[
  {
    "path": ".devcontainer/devcontainer.json",
    "content": "{\n\t\"name\": \"pip\",\n\t\"image\": \"mcr.microsoft.com/devcontainers/python:3\",\n\t\"remoteUser\": \"vscode\",\n\t\"remoteEnv\": {\n\t\t\"PATH\": \"/home/vscode/.local/bin:${containerEnv:PATH}\"\n\t},\n\t\"features\": {\n\t\t\"ghcr.io/rocker-org/devcontainer-features/apt-packages:1\": {\n\t\t\t\"packages\": \"mercurial,subversion,bzr,python3-venv\"\n\t\t}\n\t},\n\t\"postCreateCommand\": \"bash ${containerWorkspaceFolder}/.devcontainer/postCreate.sh\",\n\t\"customizations\": {\n\t\t\"vscode\": {\n\t\t\t\"extensions\": [\n\t\t\t\t\"ms-python.python\",\n\t\t\t\t\"ms-python.black-formatter\",\n\t\t\t\t\"charliermarsh.ruff\"\n\t\t\t],\n\t\t\t\"settings\": {\n\t\t\t\t\"python.testing.pytestEnabled\": true,\n\t\t\t\t\"python.testing.pytestArgs\": [\n\t\t\t\t\t\"-n\",\n\t\t\t\t\t\"auto\"\n\t\t\t\t]\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": ".devcontainer/postCreate.sh",
    "content": "#!/bin/bash\nset -Eeuo pipefail\n\n# Get the workspace directory\nWORKSPACE_DIR=\"${WORKSPACE_DIR:-/workspaces/pip}\"\ncd \"$WORKSPACE_DIR\"\n\n# Upgrade pip and install development dependencies\npython -m pip install --upgrade pip\npython -m pip install nox --group test\npython -m nox -s common-wheels\npython -m pip install -e .\n"
  },
  {
    "path": ".git-blame-ignore-revs",
    "content": "917b41d6d73535c090fc312668dff353cdaef906  # Blacken docs/html/conf.py\ned383dd8afa8fe0250dcf9b8962927ada0e21c89  # Blacken docs/pip_sphinxext.py\n228405e62451abe8a66233573035007df4be575f  # Blacken noxfile.py\nf477a9f490e978177b71c9dbaa5465c51ea21129  # Blacken setup.py\ne59ba23468390217479465019f8d78e724a23550  # Blacken src/pip/__main__.py\nd7013db084e9a52242354ee5754dc5d19ccf062e  # Blacken src/pip/_internal/build_env.py\n30e9ffacae75378fc3e3df48f754dabad037edb9  # Blacken src/pip/_internal/cache.py\n8341d56b46776a805286218ac5fb0e7850fd9341  # Blacken src/pip/_internal/cli/autocompletion.py\n3d3461ed65208656358b3595e25d8c31c5c89470  # Blacken src/pip/_internal/cli/base_command.py\nd489b0f1b104bc936b0fb17e6c33633664ebdc0e  # Blacken src/pip/_internal/cli/cmdoptions.py\n591fe4841aefe9befa0530f2a54f820c4ecbb392  # Blacken src/pip/_internal/cli/command_context.py\n9265b28ef7248ae1847a80384dbeeb8119c3e2f5  # Blacken src/pip/_internal/cli/main.py\n847a369364878c38d210c90beed2737bb6fb3a85  # Blacken src/pip/_internal/cli/main_parser.py\nec97119067041ae58b963935ff5f0e5d9fead80c  # Blacken src/pip/_internal/cli/parser.py\n6e3b8de22fa39fa3073599ecf9db61367f4b3b32  # Blacken src/pip/_internal/cli/progress_bars.py\n55405227de983c5bd5bf0858ea12dbe537d3e490  # Blacken src/pip/_internal/cli/req_command.py\nd5ca5c850cae9a0c64882a8f49d3a318699a7e2e  # Blacken src/pip/_internal/cli/spinners.py\n9747cb48f8430a7a91b36fe697dd18dbddb319f0  # Blacken src/pip/_internal/commands/__init__.py\n1c09fd6f124df08ca36bed68085ad68e89bb1957  # Blacken src/pip/_internal/commands/cache.py\n315e93d7eb87cd476afcc4eaf0f01a7b56a5037f  # Blacken src/pip/_internal/commands/check.py\n8ae3b96ed7d24fd24024ccce4840da0dcf635f26  # Blacken src/pip/_internal/commands/completion.py\n42ca4792202f26a293ee48380718743a80bbee37  # Blacken src/pip/_internal/commands/configuration.py\n790ad78fcd43d41a5bef9dca34a3c128d05eb02c  # Blacken src/pip/_internal/commands/debug.py\na6fcc8f045afe257ce321f4012fc8fcb4be01eb3  # Blacken src/pip/_internal/commands/download.py\n920e735dfc60109351fbe2f4c483c2f6ede9e52d  # Blacken src/pip/_internal/commands/freeze.py\n053004e0fcf0851238b1064fbce13aea87b24e9c  # Blacken src/pip/_internal/commands/hash.py\na6b6ae487e52c2242045b64cb8962e0a992cfd76  # Blacken src/pip/_internal/commands/help.py\n2495cf95a6c7eb61ccf1f9f0e8b8d736af914e53  # Blacken __main__.py\nc7ee560e00b85f7486b452c14ff49e4737996eda  # Blacken tools/\n8e2e1964a4f0a060f7299a96a911c9e116b2283d  # Blacken src/pip/_internal/commands/\n1bc0eef05679e87f45540ab0a294667cb3c6a88e  # Blacken src/pip/_internal/network/\n069b01932a7d64a81c708c6254cc93e1f89e6783  # Blacken src/pip/_internal/req\n1897784d59e0d5fcda2dd75fea54ddd8be3d502a  # Blacken src/pip/_internal/index\n94999255d5ede440c37137d210666fdf64302e75  # Reformat the codebase, with black\n585037a80a1177f1fa92e159a7079855782e543e  # Cleanup implicit string concatenation\n8a6f6ac19b80a6dc35900a47016c851d9fcd2ee2  # Blacken src/pip/_internal/resolution directory\nacfcae8941bb12ecfc372a05c875a7b414992604  # Reformat with Black's 2025 code style\n"
  },
  {
    "path": ".gitattributes",
    "content": "# Patches must have Unix-style line endings, even on Windows\ntools/vendoring/patches/* eol=lf\n# The CA Bundle should always use Unix-style line endings, even on Windows\nsrc/pip/_vendor/certifi/*.pem eol=lf\n"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# Contributing to pip\n\nThank you for your interest in contributing to pip! There are many ways to\ncontribute, and we appreciate all of them.\n\nAs a reminder, all contributors are expected to follow our [Code of Conduct][coc].\n\nContributors wishing to use LLM tools should be aware of, and follow, our [AI Policy][ai].\n\n[coc]: https://www.pypa.io/en/latest/code-of-conduct/\n[ai]: https://github.com/pypa/pip/blob/main/AI_POLICY.md\n\n## Development Documentation\n\nOur [development documentation](https://pip.pypa.io/en/latest/development/) contains details on how to get started with contributing to pip, and details of our development processes.\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: \"https://pypi.org/sponsor/\" # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "content": "name: Bug report\ndescription: Something is not working correctly.\nlabels: \"S: needs triage, type: bug\"\n\nbody:\n  - type: markdown\n    attributes:\n      value: >-\n        Hi there!\n\n        We'd appreciate it if you could search on pip's existing issues prior to filing\n        a bug report.\n\n        We get a lot of duplicate tickets and have limited maintainer capacity to triage\n        them. Thanks!\n\n  - type: textarea\n    attributes:\n      label: Description\n      description: >-\n        A clear and concise description of what the bug is.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Expected behavior\n      description: >-\n        A clear and concise description of what you expected to happen.\n\n  - type: input\n    attributes:\n      label: pip version\n    validations:\n      required: true\n  - type: input\n    attributes:\n      label: Python version\n    validations:\n      required: true\n  - type: input\n    attributes:\n      label: OS\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: How to Reproduce\n      description: Please provide steps to reproduce this bug.\n      placeholder: |\n        1. Get package from '...'\n        2. Then run '...'\n        3. An error occurs.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Output\n      description: >-\n        Provide the output of the steps above, including the commands\n        themselves and pip's output/traceback etc.\n\n        If you want to present output from multiple commands, please prefix\n        the line containing the command with `$ `. Please also ensure that\n        the \"How to reproduce\" section contains matching instructions for\n        reproducing this.\n\n  - type: checkboxes\n    attributes:\n      label: Code of Conduct\n      options:\n        - label: >-\n            I agree to follow the [PSF Code of Conduct](https://www.python.org/psf/conduct/).\n          required: true\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "# Documentation for this file can be found at:\n# https://help.github.com/en/github/building-a-strong-community/configuring-issue-templates-for-your-repository\n\nblank_issues_enabled: true\n# contact_links:\n#   - name: \"(maintainers only) Blank issue\"\n#     url: https://github.com/pypa/pip/issues/new\n#     about: For maintainers only.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.yml",
    "content": "name: Feature request\ndescription: Suggest an idea for this project\nlabels: \"S: needs triage, type: feature request\"\n\nbody:\n  - type: markdown\n    attributes:\n      value: >-\n        Hi there!\n\n        We'd appreciate it if you could search on pip's existing issues prior to filing\n        a feature request.\n\n        We get a lot of duplicate tickets and have limited maintainer capacity to triage\n        them. Thanks!\n\n  - type: textarea\n    attributes:\n      label: What's the problem this feature will solve?\n      description: >-\n        What are you trying to do, that you are unable to achieve with pip as it\n        currently stands?\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Describe the solution you'd like\n      description: >-\n        Clear and concise description of what you want to happen. Please use examples\n        of real world use cases that this would help with, and how it solves the\n        problem described above.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Alternative Solutions\n      description: >-\n        Have you tried to workaround the problem using pip or other tools? Or a\n        different approach to solving this issue? Please elaborate here.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Additional context\n      description: >-\n        Add any other context, links, etc. relevant to the feature request.\n    validations:\n      required: true\n\n  - type: checkboxes\n    attributes:\n      label: Code of Conduct\n      options:\n        - label: >-\n            I agree to follow the [PSF Code of Conduct](https://www.python.org/psf/conduct/).\n          required: true\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!---\nThank you for your soon to be pull request. Before you submit this, please\ndouble check to make sure that you've added a news file fragment. In pip we\ngenerate our NEWS.rst from multiple news fragment files, and all pull requests\nrequire either a news file fragment or a marker to indicate they don't require\none.\n\nTo read more about adding a news file fragment for your PR, please check out\nour documentation at: https://pip.pypa.io/en/latest/development/contributing/#news-entries\n-->\n"
  },
  {
    "path": ".github/chronographer.yml",
    "content": "branch-protection-check-name: Changelog entry\naction-hints:\n  check-title-prefix: \"Chronographer: \"\n  external-docs-url: https://pip.pypa.io/dev/news-entry-failure\n  inline-markdown: >\n    See https://pip.pypa.io/dev/news-entry-failure for details.\nenforce-name:\n  suffix: .rst\nlabels:\n  skip-changelog: skip news\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    groups:\n      github-actions:\n        patterns:\n          - \"*\"\n  - package-ecosystem: \"pip\"\n    directory: \"/build-project\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches: [main]\n    tags:\n      # Tags for all potential release numbers till 2030.\n      - \"2[0-9].[0-3]\" # 20.0 -> 29.3\n      - \"2[0-9].[0-3].[0-9]+\" # 20.0.0 -> 29.3.[0-9]+\n  pull_request:\n  schedule:\n    - cron: 0 0 * * MON # Run every Monday at 00:00 UTC\n  workflow_dispatch:\n    # allow manual runs on branches without a PR\n\nenv:\n  # The \"FORCE_COLOR\" variable, when set to 1,\n  # tells Nox to colorize itself.\n  FORCE_COLOR: \"1\"\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}\n  cancel-in-progress: true\n\njobs:\n  docs:\n    name: docs\n    runs-on: ubuntu-22.04\n\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.x\"\n      - run: pip install nox\n      - run: nox -s docs\n\n  determine-changes:\n    runs-on: ubuntu-22.04\n    outputs:\n      tests: ${{ steps.filter.outputs.tests }}\n      vendoring: ${{ steps.filter.outputs.vendoring }}\n    steps:\n      # For pull requests it's not necessary to checkout the code\n      - uses: dorny/paths-filter@v3\n        id: filter\n        with:\n          filters: |\n            vendoring:\n              # Anything that's touching \"vendored code\"\n              - \"src/pip/_vendor/**\"\n              - \"pyproject.toml\"\n              - \"noxfile.py\"\n            tests:\n              # Anything that's touching code-related stuff\n              - \".github/workflows/ci.yml\"\n              - \"src/**\"\n              - \"tests/**\"\n              - \"noxfile.py\"\n              # The test suite should also run when cutting a release\n              # (which is the only time this file is modified).\n              - \"NEWS.rst\"\n        if: github.event_name == 'pull_request'\n\n  packaging:\n    name: packaging / ${{ matrix.os }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-22.04, windows-latest]\n\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.x\"\n      - name: Set up git credentials\n        run: |\n          git config --global user.email \"pypa-dev@googlegroups.com\"\n          git config --global user.name \"pip\"\n\n      - run: pip install nox\n      - run: nox -s prepare-release -- 99.9\n      - run: nox -s build-release -- 99.9\n      - run: pipx run check-sdist\n\n  vendoring:\n    name: vendoring\n    runs-on: ubuntu-22.04\n\n    needs: [determine-changes]\n    if: >-\n      needs.determine-changes.outputs.vendoring == 'true' ||\n      github.event_name != 'pull_request'\n\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.x\"\n\n      - run: pip install nox\n      - run: nox -s vendoring\n      - run: git diff --exit-code\n\n  tests-unix:\n    name: tests / ${{ matrix.python.key || matrix.python }} / ${{ matrix.os }}\n    runs-on: ${{ matrix.os }}\n\n    needs: [determine-changes]\n    if: >-\n      needs.determine-changes.outputs.tests == 'true' ||\n      github.event_name != 'pull_request'\n\n    strategy:\n      fail-fast: true\n      matrix:\n        os: [ubuntu-22.04, macos-latest]\n        python:\n          - \"3.9\"\n          - \"3.10\"\n          - \"3.11\"\n          - \"3.12\"\n          - \"3.13\"\n          - \"3.14\"\n          - \"3.15\"\n\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: ${{ matrix.python }}\n          allow-prereleases: true\n\n      - name: Install Ubuntu dependencies\n        if: matrix.os == 'ubuntu-22.04'\n        run: |\n          sudo apt-get update\n          sudo apt-get install bzr\n\n      - name: Install MacOS dependencies\n        if: runner.os == 'macOS'\n        run: |\n          DEPS=breezy\n          if ! which svn; then\n            DEPS=\"${DEPS} subversion\"\n          fi\n          brew install ${DEPS}\n\n      - run: pip install nox\n\n      # Main check\n      - name: Run unit tests\n        run: >-\n          nox -s test-${{ matrix.python.key || matrix.python }} --\n          tests/unit\n          --verbose --numprocesses auto --showlocals\n      - name: Run integration tests\n        run: >-\n          nox -s test-${{ matrix.python.key || matrix.python }} --no-install --\n          tests/functional\n          --verbose --numprocesses auto --showlocals\n          --durations=15\n\n  tests-windows:\n    name: tests / ${{ matrix.python }} / ${{ matrix.os }} / ${{ matrix.group.number }}\n    runs-on: ${{ matrix.os }}-latest\n\n    needs: [determine-changes]\n    if: >-\n      needs.determine-changes.outputs.tests == 'true' ||\n      github.event_name != 'pull_request'\n\n    strategy:\n      fail-fast: true\n      matrix:\n        os: [Windows]\n        python:\n          - \"3.9\"\n          # Commented out, since Windows tests are expensively slow,\n          # only test the oldest and newest Python supported by pip\n          # - \"3.10\"\n          # - \"3.11\"\n          # - \"3.12\"\n          # - \"3.13\"\n          - \"3.14\"\n          - \"3.15\"\n        group:\n          - { number: 1, pytest-filter: \"not test_install\" }\n          - { number: 2, pytest-filter: \"test_install\" }\n\n    steps:\n      # The D: drive is significantly faster than the system C: drive.\n      # https://github.com/actions/runner-images/issues/8755\n      - name: Set TEMP to D:/Temp\n        run: |\n          mkdir \"D:\\\\Temp\"\n          echo \"TEMP=D:\\\\Temp\" >> $env:GITHUB_ENV\n\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: ${{ matrix.python }}\n          allow-prereleases: true\n\n      - name: Install Subversion\n        shell: pwsh\n        run: |\n          winget install --accept-source-agreements --accept-package-agreements -e --id Slik.Subversion\n          echo \"C:\\Program Files\\SlikSvn\\bin\" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append\n\n      - run: pip install nox\n\n      # Main check\n      - name: Run unit tests (group 1)\n        if: matrix.group.number == 1\n        run: >-\n          nox -s test-${{ matrix.python }} --\n          tests/unit\n          --verbose --numprocesses auto --showlocals\n\n      - name: Run integration tests (group ${{ matrix.group.number }})\n        run: >-\n          nox -s test-${{ matrix.python }} --no-install --\n          tests/functional -k \"${{ matrix.group.pytest-filter }}\"\n          --verbose --numprocesses auto --showlocals --durations=15\n\n  tests-zipapp:\n    name: tests / zipapp\n    # The macos-latest (M1) runners are the fastest available on GHA, even\n    # beating out the ubuntu-latest runners. The zipapp tests are slow by\n    # nature, and we don't care where they run, so we pick the fastest one.\n    runs-on: macos-latest\n\n    needs: [packaging, determine-changes]\n    if: >-\n      needs.determine-changes.outputs.tests == 'true' ||\n      github.event_name != 'pull_request'\n\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.10\"\n\n      - name: Install MacOS dependencies\n        run: brew install breezy subversion\n\n      - run: pip install nox\n\n      # Main check\n      - name: Run integration tests\n        run: >-\n          nox -s test-3.10 --\n          tests/functional\n          --verbose --numprocesses auto --showlocals\n          --durations=15\n          --use-zipapp\n\n  check:  # This job does nothing and is only used for the branch protection\n    if: always()\n\n    needs:\n      - determine-changes\n      - docs\n      - packaging\n      - tests-unix\n      - tests-windows\n      - tests-zipapp\n      - vendoring\n\n    runs-on: ubuntu-22.04\n\n    steps:\n      - name: Decide whether the needed jobs succeeded or failed\n        uses: re-actors/alls-green@release/v1\n        with:\n          allowed-skips: >-\n            ${{\n              (\n                needs.determine-changes.outputs.vendoring != 'true'\n                && github.event_name == 'pull_request'\n              )\n              && 'vendoring'\n              || ''\n            }}\n            ,\n            ${{\n              (\n                needs.determine-changes.outputs.tests != 'true'\n                && github.event_name == 'pull_request'\n              )\n              && '\n                tests-unix,\n                tests-windows,\n                tests-zipapp,\n                tests-importlib-metadata,\n              '\n              || ''\n            }}\n          jobs: ${{ toJSON(needs) }}\n"
  },
  {
    "path": ".github/workflows/lock-threads.yml",
    "content": "name: 'Lock Closed Threads'\n\non:\n  schedule:\n    - cron: '0 7 * * *'  # 7am UTC, daily\n  workflow_dispatch:\n\npermissions:\n  issues: write\n  pull-requests: write\n\nconcurrency:\n  group: lock\n\njobs:\n  action:\n    if: github.repository_owner == 'pypa'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: dessant/lock-threads@v6\n        with:\n          issue-inactive-days: '30'\n          pr-inactive-days: '15'\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Publish Python 🐍 distribution 📦 to PyPI\n\non:\n  push:\n    tags:\n      - \"*\"\n\njobs:\n  build:\n    name: Build distribution 📦\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@0c366fd6a839edf440554fa01a7085ccba70ac98 # v6.0.2\n        with:\n          persist-credentials: false\n      - name: Build a binary wheel and a source tarball\n        run: ./build-project/build-project.py\n      - name: Store the distribution packages\n        uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0\n        with:\n          name: python-package-distributions\n          path: dist/\n\n  publish-to-pypi:\n    name: >-\n      Publish Python 🐍 distribution 📦 to PyPI\n    needs:\n      - build\n    runs-on: ubuntu-latest\n    environment:\n      name: pypi\n      url: https://pypi.org/project/pip/${{ github.ref_name }}\n    permissions:\n      id-token: write  # IMPORTANT: mandatory for trusted publishing\n\n    steps:\n      - name: Download all the dists\n        uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n        with:\n          name: python-package-distributions\n          path: dist/\n      - name: Publish distribution 📦 to PyPI\n        uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0\n"
  },
  {
    "path": ".github/workflows/update-rtd-redirects.yml",
    "content": "name: Update documentation redirects\n\non:\n  push:\n    branches: [main]\n    paths:\n      - \".readthedocs-custom-redirects.yml\"\n      - \".readthedocs.yml\"\n  schedule:\n    - cron: 0 0 * * MON # Run every Monday at 00:00 UTC\n\nenv:\n  FORCE_COLOR: \"1\"\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}\n  cancel-in-progress: true\n\njobs:\n  update-rtd-redirects:\n    runs-on: ubuntu-latest\n    environment: RTD Deploys\n    steps:\n      - uses: actions/checkout@v6.0.2\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.11\"\n      - run: pipx run tools/update-rtd-redirects.py\n        env:\n          RTD_API_TOKEN: ${{ secrets.RTD_API_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled files\n__pycache__/\n*$py.class\n\n# Distribution / packaging\n/build/\n/dist/\n*.egg\n*.eggs\n*.egg-info/\nMANIFEST\n\n# Documentation\ndocs/build/\n\n# mypy\n.mypy_cache/\n\n# Unit test / coverage reports\n.[nt]ox/\nhtmlcov/\n.coverage\n.coverage.*\n.*cache\nnosetests.xml\ncoverage.xml\n*.cover\ntests/data/common_wheels/\n\n# Misc\n*~\n.*.sw?\n.env/\n.venv/\n\n# For IntelliJ IDEs (basically PyCharm)\n.idea/\n\n# For Visual Studio Code\n.vscode/\n\n# For Sublime Text\n*.sublime-workspace\n*.sublime-project\n\n# Scratch Pad for experiments\n.scratch/\n\n# Mac\n.DS_Store\n\n# Profiling related artifacts\n*.prof\n"
  },
  {
    "path": ".mailmap",
    "content": "Adam Wentz                                                  <awentz@theonion.com>\nAlethea Flowers     <magicalgirl@google.com>       <jjramone13@gmail.com>\nAlethea Flowers     <magicalgirl@google.com>       Thea Flowers <theaflowers@google.com>\nAlex Grönholm                                               <alex.gronholm@nextday.fi>\nAlex Grönholm       <alex.gronholm@nextday.fi>              <alex.gronholm+git@nextday.fi>\nAnatoly Techtonik                                           <techtonik@gmail.com>\nAndrey Bulgakov                                             <mail@andreiko.ru>\n                    <mail@andreiko.ru>                      <bulgakov@tranio.ru>\nAndrei Geacar       <andrei.geacar@gmail.com>      unknown  <hakaton@Anam-mbl.(none)>\nAnish Tambe         <anish.tambe@yahoo.in>                  <anish.tambe@yahoo.co.in>\nBartek Ogryczak     <b.ogryczak@gmail.com>                  <bartek@eventbrite.com>\nBen Rosser                                                  <rosser.bjr@gmail.com>\n                    <bradley.ayers@gmail.com>               <bradley.ayers@enigmainteractive.com>\n                    <carl@oddbird.net>                      <carl@dirtcircle.com>\nDaniel Holth                                                <dholth@fastmail.fm>\nDavid Black                                                 <db@d1b.org>\n                    <donald@stufft.io>                      <donald.stufft@gmail.com>\nDongweiming         <dongweiming@admaster.com.cn>           <ciici1234@hotmail.com>\nDustin Ingram       <di@di.codes>                           <di@users.noreply.github.com>\nEndoh Takanao                                               <djmchl@gmail.com>\nErik M. Bray                                                <embray@stsci.edu>\nEe Durbin                                                   <ewdurbin@gmail.com>\nGabriel de Perthuis                                         <g2p.code@gmail.com>\nHsiaoming Yang                                              <lepture@me.com>\nHugo van Kemenade   <hugovk@users.noreply.github.com>   Hugo <hugovk@users.noreply.github.com>\nHugo van Kemenade   <hugovk@users.noreply.github.com>   hugovk <hugovk@users.noreply.github.com>\nIgor Kuzmitshov     <kuzmiigo@gmail.com>                    <igor@qubit.com>\nIlya Baryshev                                               <baryshev@gmail.com>\nJakub Stasiak                                               <kuba.stasiak@gmail.com>\nJean Abou Samra                                             <jean@abou-samra.fr>\nJohn-Scott Atlakson                                         <john.scott.atlakson@gmail.com>\nJorge Niedbalski                                            <niedbalski@gmail.com>\n                    <niedbalski@gmail.com>                  <jorge@nimbic.com>\nLudovic Gasc        <gmludo@gmail.com>                      <git@gmludo.eu>\nMarkus Hametner                                             <fin+github@xbhd.org>\nMasklinn                                                    <bitbucket.org@masklinn.net>\nMatthew Iversen     <teh.ivo@gmail.com>                     <teh.ivo@gmail.com>\nOfek Lev                                                    <ofekmeister@gmail.com>\nPi Delport                                                  <pjdelport@gmail.com>\n                    <pnasrat@gmail.com>                     <pnasrat@googlemail.com>\nPradyun Gedam       <pradyunsg@gmail.com>                   <pradyunsg@users.noreply.github.com>\nPradyun Gedam       <pradyunsg@gmail.com>\nPreston Holmes                                              <preston@ptone.com>\nPrzemek Wrzos                                               <hetmankp@none>\n                    <hodgestar@gmail.com>                   <hodgestar+hg@gmail.com>\nRomuald Brunet      <romuald@chivil.com>                    <romuald@gandi.net>\nThomas Johansson    <devnull@localhost>            prencher <devnull@localhost>\nThomas Kluyver      <thomas@kluyver.me.uk>                  <takowl@gmail.com>\nStephan Erb         <github@stephanerb.eu>                  <stephan@dev.static-void.de>\nVictor Stinner      <victor.stinner@gmail.com>              <vstinner@redhat.com>\nYoval P                                                     <yoval@gmx.com>\nZhiping Deng                                                <kofreestyler@gmail.com>\ndkjsone              <221672629+dkjsone@users.noreply.github.com>   user <empty>\nMeet Vasita          <meetvasita85@gmail.com>               meet-vasita <meetvasita85@gmail.com>\nMeet Vasita          <meetvasita85@gmail.com>               Meet_Vasita <84974738+meet-vasita@users.noreply.github.com>\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "exclude: 'src/pip/_vendor/'\n\nrepos:\n- repo: https://github.com/pre-commit/pre-commit-hooks\n  rev: v6.0.0\n  hooks:\n  - id: check-builtin-literals\n  - id: check-added-large-files\n  - id: check-case-conflict\n  - id: check-toml\n  - id: check-yaml\n  - id: debug-statements\n  - id: end-of-file-fixer\n    exclude: WHEEL\n  - id: forbid-new-submodules\n  - id: trailing-whitespace\n    exclude: .patch\n\n- repo: https://github.com/psf/black-pre-commit-mirror\n  rev: 25.12.0\n  hooks:\n  - id: black\n\n- repo: https://github.com/astral-sh/ruff-pre-commit\n  rev: v0.14.10\n  hooks:\n    - id: ruff-check\n      args: [--fix]\n\n- repo: https://github.com/pre-commit/mirrors-mypy\n  rev: v1.19.1\n  hooks:\n  - id: mypy\n    exclude: tests/data\n    args:\n      - \"--pretty\"\n      - \"--show-error-codes\"\n      # Since this is only a partial mypy run, we can get false-positives\n      # for unused ignores.\n      - \"--no-warn-unused-ignores\"\n    additional_dependencies: [\n        'keyring==24.2.0',\n        'nox==2024.03.02',\n        'pytest',\n        'types-docutils==0.20.0.3',\n        'types-setuptools==68.2.0.0',\n        'types-freezegun==1.1.10',\n        'types-pyyaml==6.0.12.12',\n        'typing-extensions',\n    ]\n\n- repo: https://github.com/pre-commit/pygrep-hooks\n  rev: v1.10.0\n  hooks:\n  - id: python-no-log-warn\n  - id: python-no-eval\n  - id: rst-backticks\n    files: .*\\.rst$\n    types: [file]\n    exclude: NEWS.rst  # The errors flagged in NEWS.rst are old.\n\n- repo: https://github.com/codespell-project/codespell\n  rev: v2.4.1\n  hooks:\n    - id: codespell\n      exclude: AUTHORS.txt|tests/data\n      args: [\"--ignore-words\", tools/codespell-ignore.txt]\n\n- repo: local\n  hooks:\n  - id: news-fragment-filenames\n    name: NEWS fragment\n    language: fail\n    entry: NEWS fragment files must be named *.(process|removal|feature|bugfix|vendor|doc|trivial).rst\n    exclude: ^news/(.gitignore|.*\\.(process|removal|feature|bugfix|vendor|doc|trivial).rst)\n    files: ^news/\n\nci:\n  autofix_prs: false\n  autoupdate_commit_msg: 'pre-commit autoupdate'\n  autoupdate_schedule: monthly\n"
  },
  {
    "path": ".readthedocs-custom-redirects.yml",
    "content": "# This file is read by tools/update-rtd-redirects.py.\n# It is related to Read the Docs, but is not a file processed by the platform.\n\n/dev/news-entry-failure: >-\n  https://pip.pypa.io/en/latest/development/contributing/#news-entries\n/errors/resolution-impossible: >-\n  https://pip.pypa.io/en/stable/topics/dependency-resolution/#dealing-with-dependency-conflicts\n/surveys/backtracking: >-\n  https://forms.gle/LkZP95S4CfqBAU1N6\n/warnings/backtracking: >-\n  https://pip.pypa.io/en/stable/topics/dependency-resolution/#possible-ways-to-reduce-backtracking\n/warnings/enable-long-paths: >-\n  https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later\n/warnings/venv: >-\n  https://docs.python.org/3/tutorial/venv.html\n/reference/build-system/pyproject-toml: >-\n  https://pip.pypa.io/en/stable/reference/build-system/\n/reference/build-system/setup-py: >-\n  https://pip.pypa.io/en/stable/reference/build-system/\n"
  },
  {
    "path": ".readthedocs.yml",
    "content": "version: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.11\"\n  jobs:\n    install:\n      - pip install .\n      - pip install --group docs\n\nsphinx:\n  builder: dirhtml\n  configuration: docs/html/conf.py\n"
  },
  {
    "path": "AI_POLICY.md",
    "content": "# Generative AI / LLM Policy\n\nWe appreciate that we can't realistically police how you author your pull requests, which includes whether you employ large-language model (LLM)-based development tools.\nSo, we don't.\n\nHowever, due to both legal and human reasons, we have to establish boundaries.\n\n## Overview\n\n- We take the responsibility for this project very seriously and we expect you to take your responsibility for your contributions seriously, too.\n  This used to be a given, but it changed now that a pull request is just one prompt away.\n\n- Every contribution has to be backed by a human who unequivocally owns the copyright for all changes.\n  No LLM bots in `Co-authored-by:`s.\n\n- Repeated slop contributions are unacceptable, and will be closed without review.\n  We reserve the right to exclude contributors who continue to submit such material.\n\n- Absolutely no unsupervised agentic tools like OpenClaw.\n\n---\n\nBy submitting a pull request, you certify that:\n\n- You are the author of the contribution or have the legal right to submit it.\n- You either hold the copyright to the changes or have explicit legal authorization to contribute them under this project's license.\n- You understand the code.\n- You accept full responsibility for it.\n\n\n## Legal\n\nThere is ongoing legal uncertainty regarding the copyright status of LLM-generated works and their provenance.\nBecause of this, allowing contributions by LLMs has unpredictable consequences for the copyright status of this project – even when leaving aside possible copyright violations due to plagiarism.\n\n\n## Human\n\nAs the makers of software that is used by millions of people worldwide and with a reputation for high-quality maintenance, we take our responsibility to our users very seriously.\nNo matter what LLM vendors or boosters on LinkedIn tell you, we have to manually review every change before merging, because it's our responsibility to keep the project stable.\n\nPlease understand that by opening low-quality pull requests you're not helping anyone.\nWorse, you're [poisoning the open source ecosystem](https://lwn.net/Articles/1058266/) that was precarious even before the arrival of LLM tools.\nHaving to wade through plausible-looking-but-low-quality pull requests and trying to determine which ones are legit is extremely demoralizing and has already burned out many good maintainers.\n\nIn particular, note that [code reviews are a social process](https://blog.glyph.im/2026/03/what-is-code-review-for.html) and are *not* intended\nto catch bugs in PRs created by an LLM. If you submit a pull request, we expect you to engage with reviewers and learn from the review, not\nsimply update the prompt that generated the PR and regenerate the code.\n\nPut bluntly, we have no time or interest to become part of your vibe coding loop where you drop LLM slop at our door, we spend time and energy to review it, and you just feed it back into the LLM for another iteration.\n\nThis dynamic is especially pernicious because it poisons the well for mentoring new contributors which we are committed to.\n\n\n## Summary\n\nIn practice, this means:\n\n- Pull requests that have an LLM product listed as co-author can't be merged and will be closed without further discussion.\n  We cannot risk the copyright status of this project.\n\n  If you used LLM tools during development, you may still submit – but you must remove any LLM co-author tags and take full ownership of every line.\n\n- By submitting a pull request, you take full technical and legal responsibility for the contents of the pull request and promise that you hold the copyright for the changes submitted.\n\n  \"An LLM wrote it\" is *not* an acceptable response to questions or critique.\n  If you cannot explain and defend the changes you submit, do not submit them and open a high-quality bug report or feature request instead.\n\n- Accounts that exercise bot-like behavior – like automated mass pull requests – will be permanently banned, whether they belong to a human or not.\n\n- LLM-generated comments must be concise and accurate, and you must be prepared to stand by them.\n  Do not post summaries unless you are certain that they add value to the discussion.\n  Remember that all LLM output *looks* plausible.\n  When using these tools, it's your responsibility to ensure that the output is correct, and useful.\n\n- Remember that LLM generated content is generally easier for you to produce, but *harder* for others to read, review or interpret.\n  Prioritising your time over that of others is contrary to the project's code of conduct.\n  Verbose, repetitive, or off topic comments may be marked as spam.\n\n## Thanks\n\nThis policy was based on the policy of the `attrs` project. Many thanks to them for developing it.\n"
  },
  {
    "path": "AUTHORS.txt",
    "content": "@Switch01\nA_Rog\nAakanksha Agrawal\nAarni Koskela\nAbhinav Sagar\nABHYUDAY PRATAP SINGH\nabs51295\nAceGentile\nAdam Chainz\nAdam Tse\nAdam Turner\nAdam Wentz\nadmin\nAdolfo Ochagavía\nAdrien Morison\nAgus\nahayrapetyan\nAhilya\nAinsworthK\nAkash Srivastava\nAlan Yee\nAlbert Tugushev\nAlbert-Guan\nalbertg\nAlberto Sottile\nAleks Bunin\nAles Erjavec\nAlessandro Molina\nAlethea Flowers\nAlex Gaynor\nAlex Grönholm\nAlex Hedges\nAlex Loosley\nAlex Morega\nAlex Stachowiak\nAlexander Regueiro\nAlexander Shtyrov\nAlexandre Conrad\nAlexey Popravka\nAleš Erjavec\nAlli\nAman\nAmi Fischman\nAnanya Maiti\nAnatoly Techtonik\nAnders Kaseorg\nAndre Aguiar\nAndreas Lutro\nAndrei Geacar\nAndrew Gaul\nAndrew Shymanel\nAndrey Bienkowski\nAndrey Bulgakov\nAndrés Delfino\nAndy Freeland\nAndy Kluger\nAni Hayrapetyan\nAniruddha Basak\nAnish Tambe\nAnrs Hu\nAnthony Sottile\nAntoine Lambert\nAntoine Musso\nAnton Ovchinnikov\nAnton Patrushev\nAnton Zelenov\nAntonio Alvarado Hernandez\nAntony Lee\nAntti Kaihola\nAnubhav Patel\nAnudit Nagar\nAnuj Godase\nAQNOUCH Mohammed\nAraHaan\narena\narenasys\nArindam Choudhury\nArmin Ronacher\nArnon Yaari\nArtem\nArun Babu Neelicattu\nAshley Manton\nAshwin Ramaswami\natse\nAtsushi Odagiri\nAvinash Karhana\nAvner Cohen\nAwit (Ah-Wit) Ghirmai\nBaptiste Mispelon\nBarney Gale\nbarneygale\nBartek Ogryczak\nBastian Venthur\nBen Bodenmiller\nBen Darnell\nBen Hoyt\nBen Mares\nBen Rosser\nBence Nagy\nBenjamin Peterson\nBenjamin VanEvery\nBenoit Pierre\nBerker Peksag\nBernard\nBernard Tyers\nBernardo B. Marques\nBernhard M. Wiedemann\nBertil Hatt\nBhavam Vidyarthi\nBlazej Michalik\nBogdan Opanchuk\nBorisZZZ\nBrad Erickson\nBradley Ayers\nBradley Reynolds\nBranch Vincent\nBrandon L. Reiss\nBrandt Bucher\nBrannon Dorsey\nBrett Randall\nBrett Rosen\nBrian Cristante\nBrian Rosner\nbriantracy\nBrownTruck\nBruno Oliveira\nBruno Renié\nBruno S\nBstrdsmkr\nBuck Golemon\nburrows\nBussonnier Matthias\nbwoodsend\nc22\nCaleb Brown\nCaleb Martinez\nCalvin Smith\nCarl Meyer\nCarlos Liam\nCarol Willing\nCarter Thayer\nCass\nChandrasekhar Atina\nCharlie Marsh\ncharwick\nChih-Hsuan Yen\nChris Brinker\nChris Hunt\nChris Jerdonek\nChris Kuehl\nChris Markiewicz\nChris McDonough\nChris Pawley\nChris Pryer\nChris Wolfe\nChristian Clauss\nChristian Heimes\nChristian Oudard\nChristoph Reiter\nChristopher Hunt\nChristopher Snyder\nchrysle\ncjc7373\nClark Boylan\nClaudio Jolowicz\nClay McClure\nCody\nCody Soyland\nColin Watson\nCollin Anderson\nConnor Osborn\nCooper Lees\nCooper Ry Lees\nCory Benfield\nCory Wright\nCraig Kerstiens\nCristian Sorinel\nCristina\nCristina Muñoz\nctg123\nCurtis Doty\ncytolentino\nDaan De Meyer\nDale\nDamian\nDamian Quiroga\nDamian Shaw\nDan Black\nDan Savilonis\nDan Sully\nDane Hillard\ndaniel\nDaniel Collins\nDaniel Hahler\nDaniel Hollas\nDaniel Holth\nDaniel Jost\nDaniel Katz\nDaniel Shaulov\nDaniele Esposti\nDaniele Nicolodi\nDaniele Procida\nDaniil Konovalenko\nDanny Hermes\nDanny McClanahan\nDarren Kavanagh\nDav Clark\nDave Abrahams\nDave Jones\nDavid Aguilar\nDavid Black\nDavid Bordeynik\nDavid Caro\nDavid D Lowe\nDavid Evans\nDavid Hewitt\nDavid Linke\nDavid Poggi\nDavid Poznik\nDavid Pursehouse\nDavid Runge\nDavid Tucker\nDavid Wales\nDavidovich\nddelange\nDeepak Sharma\nDeepyaman Datta\nDenis Roussel (ACSONE)\nDenise Yu\ndependabot[bot]\nderwolfe\nDesetude\ndeveloper\nDevesh Kumar\nDevesh Kumar Singh\ndevsagul\nDiego Caraballo\nDiego Ramirez\nDiegoCaraballo\nDimitri Merejkowsky\nDimitri Papadopoulos\nDimitri Papadopoulos Orfanos\nDirk Stolle\ndkjsone\nDmitry Gladkov\nDmitry Volodin\nDomen Kožar\nDominic Davis-Foster\nDonald Stufft\nDongweiming\ndoron zarhi\nDos Moonen\nDouglas Thor\nDrFeathers\nDustin Ingram\nDustin Rodrigues\nDwayne Bailey\nEd Morley\nEdgar Ramírez\nEdgar Ramírez Mondragón\nEe Durbin\nEfflam Lemaillet\nefflamlemaillet\nEitan Adler\nekristina\nelainechan\nEli Schwartz\nElisha Hollander\nEllen Marie Dash\nEmil Burzo\nEmil Styrke\nEmmanuel Arias\nEndoh Takanao\nenoch\nErdinc Mutlu\nEric Cousineau\nEric Gillingham\nEric Hanchrow\nEric Hopper\nErik M. Bray\nErik Rose\nErwin Janssen\nEugene Vereshchagin\neverdimension\nFederico\nFelipe Peter\nFelix Yan\nfiber-space\nFilip Kokosiński\nFilipe Laíns\nFinn Womack\nfinnagin\nFlavio Amurrio\nFlorian Briand\nFlorian Rathgeber\nFrancesco\nFrancesco Montesano\nFredrik Orderud\nFredrik Roubert\nFrost Ming\nGabriel Curio\nGabriel de Perthuis\nGarry Polley\ngavin\ngdanielson\nGene Wood\nGeoffrey Sneddon\nGeorge Margaritis\nGeorge Song\nGeorgi Valkov\nGeorgy Pchelkin\nghost\nGiftlin Rajaiah\ngizmoguy1\ngkdoc\nGodefroid Chapelle\nGopinath M\nGOTO Hayato\ngousaiyang\ngpiks\nGreg Roodt\nGreg Ward\nGuido Diepen\nGuilherme Espada\nGuillaume Seguin\ngutsytechster\nGuy Rozendorn\nGuy Tuval\ngzpan123\nHanjun Kim\nHari Charan\nHarsh Vardhan\nHarsha Sai\nharupy\nHarutaka Kawamura\nHasan-8326\nhauntsaninja\nHenrich Hartzer\nHenry Schreiner\nHerbert Pfennig\nHolly Stotelmyer\nHonnix\nHsiaoming Yang\nHugo Lopes Tavares\nHugo van Kemenade\nHugues Bruant\nHynek Schlawack\niamsrp-deshaw\nIan Bicking\nIan Cordasco\nIan Lee\nIan Stapleton Cordasco\nIan Wienand\nIgor Kuzmitshov\nIgor Sobreira\nIkko Ashimine\nIlan Schnell\nIllia Volochii\nIlya Abdolmanafi\nIlya Baryshev\nInada Naoki\nIonel Cristian Mărieș\nIonel Maries Cristian\nItamar Turner-Trauring\niTrooz\nIvan Pozdeev\nJ. Nick Koston\nJacob Kim\nJacob Walls\nJaime Sanz\nJake Lishman\njakirkham\nJakub Kuczys\nJakub Stasiak\nJakub Vysoky\nJakub Wilk\nJames\nJames Cleveland\nJames Curtin\nJames Firth\nJames Gerity\nJames Polley\nJan Pokorný\nJannis Leidel\nJarek Potiuk\njarondl\nJason Curtis\nJason R. Coombs\nJasonMo\nJasonMo1\nJay Graves\nJean Abou Samra\nJean-Christophe Fillion-Robin\nJeff Barber\nJeff Dairiki\nJeff Widman\nJelmer Vernooĳ\njenix21\nJeremy Fleischman\nJeremy Stanley\nJeremy Zafran\nJesse Rittner\nJiashuo Li\nJim Fisher\nJim Garrison\nJinzhe Zeng\nJiun Bae\nJivan Amara\nJoa\nJoe Bylund\nJoe Michelini\nJohannes Altmanninger\nJohn Paton\nJohn Sirois\nJohn T. Wodder II\nJohn-Scott Atlakson\njohnthagen\nJon Banafato\nJon Dufresne\nJon Parise\nJonas Nockert\nJonathan Herbert\nJoonatan Partanen\nJoost Molenaar\nJorge Niedbalski\nJoseph Bylund\nJoseph Long\nJosh Bronson\nJosh Cannon\nJosh Hansen\nJosh Schneier\nJoshua\nJoshuaPerdue\nJost Migenda\nJuan Luis Cano Rodríguez\nJuanjo Bazán\nJudah Rand\nJulian Berman\nJulian Gethmann\nJulien Demoor\nJulien Stephan\nJuly Tikhonov\nJussi Kukkonen\nJustin van Heek\njwg4\nJyrki Pulliainen\nKai Chen\nKai Mueller\nKamal Bin Mustafa\nKarolina Surma\nkasium\nkaustav haldar\nKaz Nishimura\nkeanemind\nKeith Maxwell\nKelsey Hightower\nKenneth Belitzky\nKenneth Reitz\nKevin Burke\nKevin Carter\nKevin Frommelt\nKevin R Patterson\nKexuan Sun\nKit Randel\nKlaas van Schelven\nKOLANICH\nkonstin\nkpinc\nKrishan Bhasin\nKrishna Oza\nKumar McMillan\nKuntal Majumder\nKurt McKee\nKyle Persohn\nlakshmanaram\nLaszlo Kiss-Kollar\nLaurent Bristiel\nLaurent LAPORTE\nLaurie O\nLaurie Opperman\nlayday\nLeon Sasson\nLev Givon\nLincoln de Sousa\nLipis\nlorddavidiii\nLoren Carvalho\nLucas Cimon\nLudovic Gasc\nLuis Medel\nLukas Geiger\nLukas Juhrich\nLuke Macken\nLuo Jiebin\nluojiebin\nluz.paz\nLászló Kiss Kollár\nM00nL1ght\nMajorTanya\nMalcolm Smith\nMarc Abramowitz\nMarc Tamlyn\nMarcus Smith\nMariatta\nMark Kohler\nMark McLoughlin\nMark Williams\nMarkus Hametner\nMartey Dodoo\nMartin Fischer\nMartin Häcker\nMartin Pavlasek\nMasaki\nMasklinn\nMatej Stuchlik\nMateusz Sokół\nMathew Jennings\nMathieu Bridon\nMathieu Kniewallner\nMatt Bacchi\nMatt Good\nMatt Maker\nMatt Robenolt\nMatt Wozniski\nmatthew\nMatthew Einhorn\nMatthew Feickert\nMatthew Gilliard\nMatthew Hughes\nMatthew Iversen\nMatthew Treinish\nMatthew Trumbell\nMatthew Willson\nMatthias Bussonnier\nmattip\nMaurits van Rees\nMax W Chase\nMaxim Kurnikov\nMaxime Rouyrre\nmayeut\nmbaluna\nMd Sujauddin Sekh\nmdebi\nMeet Vasita\nmemoselyk\nmeowmeowcat\nMichael\nMichael Aquilina\nMichael E. Karpeles\nMichael Klich\nMichael Mintz\nMichael Williamson\nmichaelpacer\nMichał Górny\nMickaël Schoentgen\nMiguel Araujo Perez\nMihir Singh\nMike\nMike Hendricks\nMin RK\nMinRK\nMiro Hrončok\nMonica Baluna\nmontefra\nMonty Taylor\nmorotti\nmrKazzila\nMuha Ajjan\nMUTHUSRIHEMADHARSHINI S A\nNadav Wexler\nNahuel Ambrosini\nNate Coraor\nNate Prewitt\nNathan Houghton\nNathaniel J. Smith\nNehal J Wani\nNeil Botelho\nNguyễn Gia Phong\nNicholas Serra\nNick Coghlan\nNick Stenning\nNick Timkovich\nNicolas Bock\nNicole Harris\nNikhil Benesch\nNikhil Ladha\nNikita Chepanov\nNikolay Korolev\nNipunn Koorapati\nNitesh Sharma\nNiyas Sait\nNoah\nNoah Gorny\nNothing-991\nNowell Strite\nNtaleGrey\nnucccc\nnvdv\nOBITORASU\nOfek Lev\nofrinevo\nOleg Burnaev\nOliver Freund\nOliver Jeeves\nOliver Mannion\nOliver Tonnhofer\nOlivier Girardot\nOlivier Grisel\nOllie Rutherfurd\nOMOTO Kenji\nOmry Yadan\nonlinejudge95\nOren Held\nOscar Benjamin\noxygen dioxide\nOz N Tiram\nPachwenko\nParesh Joshi\nPatrick Dubroy\nPatrick Jenkins\nPatrick Lawson\npatricktokeeffe\nPatrik Kopkan\nPaul Ganssle\nPaul Kehrer\nPaul Moore\nPaul Nasrat\nPaul Oswald\nPaul van der Linden\nPaulus Schoutsen\nPavel Safronov\nPavithra Eswaramoorthy\nPawel Jasinski\nPaweł Szramowski\nPekka Klärck\nPeter Gessler\nPeter Lisák\nPeter Shen\nPeter Waller\nPetr Viktorin\npetr-tik\nPhaneendra Chiruvella\nPhil Elson\nPhil Freo\nPhil Pennock\nPhil Whelan\nPhilip Jägenstedt\nPhilip Molloy\nPhilippe Ombredanne\nPi Delport\nPierre-Yves Rofes\nPieter Degroote\npip\nPrabakaran Kumaresshan\nPrabhjyotsing Surjit Singh Sodhi\nPrabhu Marappan\nPradyun Gedam\nPrashant Sharma\nPratik Mallya\npre-commit-ci[bot]\nPreet Thakkar\nPreston Holmes\nPrzemek Wrzos\nPulkit Goyal\nq0w\nQiangning Hong\nQiming Xu\nqraqras\nQuentin Lee\nQuentin Pradet\nR. David Murray\nRafael Caricio\nRalf Schmitt\nRan Benita\nRandy Döring\nRazzi Abuissa\nrdb\nReece Dunham\nRemi Rampin\nRene Dudfield\nRiccardo Magliocchetti\nRiccardo Schirone\nRichard Jones\nRichard Si\nRicky Ng-Adam\nRishi\nrmorotti\nRobberPhex\nRobert Collins\nRobert McGibbon\nRobert Pollak\nRobert T. McGibbon\nrobin elisha robinson\nRodney, Tiara\nRoey Berman\nRohan Jain\nRoman Bogorodskiy\nRoman Donchenko\nRomuald Brunet\nronaudinho\nRonny Pfannschmidt\nRory McCann\nRoss Brattain\nRoy Wellington Ⅳ\nRuairidh MacLeod\nRussell Keith-Magee\nRyan Shepherd\nRyan Wooden\nryneeverett\nRyuma Asai\nS. Guliaev\nSachi King\nSalvatore Rinchiera\nsandeepkiran-js\nSander Van Balen\nSavio Jomton\nschlamar\nScott Kitterman\nSean\nseanj\nSebastian Jordan\nSebastian Schaetz\nSegev Finer\nSeongSoo Cho\nSepehr Rasouli\nsepehrrasooli\nSergey Vasilyev\nSeth Michael Larson\nSeth Woodworth\nShahar Epstein\nShantanu\nshenxianpeng\nshireenrao\nShivansh-007\nShixian Sheng\nShlomi Fish\nShovan Maity\nShubham Nagure\nSimeon Visser\nSimon Cross\nSimon Pichugin\nsinoroc\nsinscary\nsnook92\nsocketubs\nSorin Sbarnea\nSrinivas Nyayapati\nSrishti Hegde\nStavros Korokithakis\nStefan Scherfke\nStefano Rivera\nStephan Erb\nStephane Chazelas\nStephen Payne\nStephen Rosen\nstepshal\nSteve (Gadget) Barnes\nSteve Barnes\nSteve Dower\nSteve Kowalik\nSteven Myint\nSteven Silvester\nstonebig\nstudioj\nStéphane Bidoul\nStéphane Bidoul (ACSONE)\nStéphane Klein\nSumana Harihareswara\nSurbhi Sharma\nSviatoslav Sydorenko\nSviatoslav Sydorenko (Святослав Сидоренко)\nSwat009\nSylvain\nTakayuki SHIMIZUKAWA\nTaneli Hukkinen\ntbeswick\nTerrance\nThiago\nThijs Triemstra\nThomas Fenzl\nThomas Grainger\nThomas Guettler\nThomas Johansson\nThomas Kluyver\nThomas Smith\nThomas VINCENT\nTim D. Smith\nTim Gates\nTim Harder\nTim Heap\ntim smith\ntinruufu\nTobias Hermann\nTom Forbes\nTom Freudenheim\nTom V\nTomas Hrnciar\nTomas Orsava\nTomer Chachamu\nTommi Enenkel | AnB\nTomáš Hrnčiar\nTony Beswick\nTony Narlock\nTony Zhaocheng Tan\nTonyBeswick\ntoonarmycaptain\nToshio Kuratomi\ntoxinu\nTravis Swicegood\nTushar Sadhwani\nTzu-ping Chung\nValentin Haenel\nVictor Stinner\nvictorvpaulo\nVikram - Google\nViktor Szépe\nVille Skyttä\nVinay Sajip\nVincent Philippon\nVinicyus Macedo\nVipul Kumar\nVitaly Babiy\nVladimir Fokow\nVladimir Rutsky\nW. Trevor King\nWeida Hong\nWil Tan\nWilfred Hughes\nWilliam Edwards\nWilliam ML Leslie\nWilliam T Olson\nWilliam Woodruff\nWilson Mo\nwim glenn\nWinson Luk\nWolfgang Maier\nWu Zhenyu\nXAMES3\nXavier Fernandez\nXianpeng Shen\nxoviat\nxtreak\nYAMAMOTO Takashi\nYash\nYashraj\nYen Chi Hsuan\nYeray Diaz Diaz\nYoval P\nYu Jian\nYuan Jing Vincent Yan\nYuki Kobayashi\nYusuke Hayashi\nzackzack38\nZearin\nZhiping Deng\nziebam\nZvezdan Petkovic\nŁukasz Langa\nРоман Донченко\nСемён Марьясин\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "NEWS.rst",
    "content": ".. note\n\n    You should *NOT* be adding new change log entries to this file, this\n    file is managed by towncrier. You *may* edit previous change logs to\n    fix problems like typo corrections or such.\n\n    To add a new change log entry, please see\n        https://pip.pypa.io/en/latest/development/contributing/#news-entries\n\n.. towncrier release notes start\n\n26.0.1 (2026-02-04)\n===================\n\nBug Fixes\n---------\n\n- Fix ``--pre`` not being respected from the command line when a requirement file\n  includes an option e.g. ``-extra-index-url``. (`#13788 <https://github.com/pypa/pip/issues/13788>`_)\n\n26.0 (2026-01-30)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove support for non-bare project names in egg fragments. Affected users should use\n  the `Direct URL requirement syntax <https://packaging.python.org/en/latest/specifications/version-specifiers/#direct-references>`_. (`#13157 <https://github.com/pypa/pip/issues/13157>`_)\n\nFeatures\n--------\n\n- Display pip's command-line help in colour, if possible. (`#12134 <https://github.com/pypa/pip/issues/12134>`_)\n- Support installing dependencies declared with inline script metadata\n  (:pep:`723`) with ``--requirements-from-script``. (`#12891 <https://github.com/pypa/pip/issues/12891>`_)\n- Add ``--all-releases`` and ``--only-final`` options to control pre-release\n  and final release selection during package installation. (`#13221 <https://github.com/pypa/pip/issues/13221>`_)\n- Add ``--uploaded-prior-to`` option to only consider packages uploaded prior to\n  a given datetime when the ``upload-time`` field is available from a remote index. (`#13625 <https://github.com/pypa/pip/issues/13625>`_)\n- Add ``--use-feature inprocess-build-deps`` to request that build dependencies are installed\n  within the same pip install process. This new mechanism is faster, supports ``--no-clean``\n  and ``--no-cache-dir`` reliably, and supports prompting for authentication.\n\n  Enabling this feature will also enable ``--use-feature build-constraints``. This feature will\n  become the default in a future pip version. (`#9081 <https://github.com/pypa/pip/issues/9081>`_)\n- ``pip cache purge`` and ``pip cache remove`` now clean up empty directories\n  and legacy files left by older pip versions. (`#9058 <https://github.com/pypa/pip/issues/9058>`_)\n\nBug Fixes\n---------\n\n- Fix selecting pre-release versions when only pre-releases match.\n  For example, ``package>1.0`` with versions ``1.0, 2.0rc1`` now installs\n  ``2.0rc1`` instead of failing. (`#13746 <https://github.com/pypa/pip/issues/13746>`_)\n- Revisions in version control URLs now must be percent-encoded.\n  For example, use ``git+https://example.com/repo.git@issue%231`` to specify the branch ``issue#1``.\n  If you previously used a branch name containing a ``%`` character in a version control URL, you now need to replace it with ``%25`` to ensure correct percent-encoding. (`#13407 <https://github.com/pypa/pip/issues/13407>`_)\n- Preserve original casing when a path is displayed. (`#6823 <https://github.com/pypa/pip/issues/6823>`_)\n- Fix bash completion when the ``$IFS`` variable has been modified from its default. (`#13555 <https://github.com/pypa/pip/issues/13555>`_)\n- Precompute Python requirements on each candidate, reducing time of long resolutions. (`#13656 <https://github.com/pypa/pip/issues/13656>`_)\n- Skip redundant work converting version objects to strings when using the\n  ``importlib.metadata`` backend. (`#13660 <https://github.com/pypa/pip/issues/13660>`_)\n- Fix ``pip index versions`` to honor only-binary/no-binary options. (`#13682 <https://github.com/pypa/pip/issues/13682>`_)\n- Fix fallthrough logic for options, allowing overriding global options with\n  defaults from user config. (`#13703 <https://github.com/pypa/pip/issues/13703>`_)\n- Use a path-segment prefix comparison, not char-by-char. (`#13777 <https://github.com/pypa/pip/issues/13777>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.14.4\n- Upgrade certifi to 2026.1.4\n- Upgrade idna to 3.11\n- Upgrade packaging to 26.0\n- Upgrade platformdirs to 4.5.1\n\n25.3 (2025-10-24)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove support for the legacy ``setup.py develop`` editable method in setuptools\n  editable installs; setuptools >= 64 is now required. (`#11457 <https://github.com/pypa/pip/issues/11457>`_)\n- Remove the deprecated ``--global-option`` and ``--build-option``.\n  ``--config-setting`` is now the only way to pass options to the build backend. (`#11859 <https://github.com/pypa/pip/issues/11859>`_)\n- Deprecate the ``PIP_CONSTRAINT`` environment variable for specifying build\n  constraints.\n\n  Use the ``--build-constraint`` option or the ``PIP_BUILD_CONSTRAINT`` environment variable\n  instead. When build constraints are used, ``PIP_CONSTRAINT`` no longer affects isolated build\n  environments. To enable this behavior without specifying any build constraints, use\n  ``--use-feature=build-constraint``. (`#13534 <https://github.com/pypa/pip/issues/13534>`_)\n- Remove support for non-standard legacy wheel filenames. (`#13581 <https://github.com/pypa/pip/issues/13581>`_)\n- Remove support for the deprecated ``setup.py bdist_wheel`` mechanism. Consequently,\n  ``--use-pep517`` is now always on, and ``--no-use-pep517`` has been removed. (`#6334 <https://github.com/pypa/pip/issues/6334>`_)\n\nFeatures\n--------\n\n- When :pep:`658` metadata is available, full distribution files are no longer downloaded when using ``pip lock`` or ``pip install --dry-run``. (`#12603 <https://github.com/pypa/pip/issues/12603>`_)\n- Add support for installing an editable requirement written as a Direct URL (``PackageName @ URL``). (`#13495 <https://github.com/pypa/pip/issues/13495>`_)\n- Add support for build constraints via the ``--build-constraint`` option. This\n  allows constraining the versions of packages used during the build process\n  (e.g., setuptools) without affecting the final installation. (`#13534 <https://github.com/pypa/pip/issues/13534>`_)\n- On ``ResolutionImpossible`` errors, include a note about causes with no candidates. (`#13588 <https://github.com/pypa/pip/issues/13588>`_)\n- Building pip itself from source now uses flit-core instead of setuptools.\n  This does not affect how pip installs or builds packages you use. (`#13473 <https://github.com/pypa/pip/issues/13473>`_)\n\nBug Fixes\n---------\n\n- Handle malformed ``Version`` metadata entries and\n  show a sensible error message instead of crashing. (`#13443 <https://github.com/pypa/pip/issues/13443>`_)\n- Permit spaces between a filepath and extras in an install requirement. (`#13523 <https://github.com/pypa/pip/issues/13523>`_)\n- Ensure the self-check files in the cache have the same permissions as the rest of the cache. (`#13528 <https://github.com/pypa/pip/issues/13528>`_)\n- Avoid concurrency issues and improve performance when caching locally built wheels,\n  especially when the temporary build directory is on a different filesystem than the cache.\n  The wheel directory passed to the build backend is now a temporary subdirectory inside\n  the cache directory. (`#13540 <https://github.com/pypa/pip/issues/13540>`_)\n- Include relevant user-supplied constraints in logs when reporting dependency conflicts. (`#13545 <https://github.com/pypa/pip/issues/13545>`_)\n- Fix a regression in configuration parsing that was turning a single value\n  into a list and thus leading to a validation error. (`#13548 <https://github.com/pypa/pip/issues/13548>`_)\n- For Python versions that do not support :pep:`706`, pip will now raise an installation error for a\n  source distribution when it includes a symlink that points outside the source distribution archive. (`#13550 <https://github.com/pypa/pip/issues/13550>`_)\n- Prevent ``--user`` installs if ``site.ENABLE_USER_SITE`` is set to ``False``. (`#8794 <https://github.com/pypa/pip/issues/8794>`_)\n\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2025.10.5\n- Upgrade msgpack to 1.1.2\n- Upgrade platformdirs to 4.5.0\n- Upgrade requests to 2.32.5\n- Upgrade resolvelib to 1.2.1\n- Upgrade rich to 14.2.0\n- Upgrade tomli to 2.3.0\n- Upgrade truststore to 0.10.4\n\n25.2 (2025-07-30)\n=================\n\nFeatures\n--------\n\n- Declare support for Python 3.14 (`#13506 <https://github.com/pypa/pip/issues/13506>`_)\n- Automatic download resumption and retrying is enabled by default. (`#13464 <https://github.com/pypa/pip/issues/13464>`_)\n- Requires-Python error message displays version clauses in numerical order. (`#13367 <https://github.com/pypa/pip/issues/13367>`_)\n- Minor performance improvement getting the order to install a very large number of interdependent packages. (`#13424 <https://github.com/pypa/pip/issues/13424>`_)\n- Show time taken instead of ``eta 0:00:00`` at download completion. (`#13483 <https://github.com/pypa/pip/issues/13483>`_)\n- Speed up small CLI tools by removing ``import re`` from the console\n  script executable template. (`#13165 <https://github.com/pypa/pip/issues/13165>`_)\n- Remove warning when cloning from a Git reference that does not look like a commit hash. (`#12283 <https://github.com/pypa/pip/issues/12283>`_)\n\nBug Fixes\n---------\n\n- ``pip config debug`` now correctly separates options as set by the different files\n  at the same level. (`#12099 <https://github.com/pypa/pip/issues/12099>`_)\n- Ensure truststore feature remains active even when a proxy is also in use. (`#13343 <https://github.com/pypa/pip/issues/13343>`_)\n- Include sub-commands in tab completion. (`#13140 <https://github.com/pypa/pip/issues/13140>`_)\n- ``pip list`` with the ``json`` or ``freeze`` format enabled will no longer\n  crash when encountering a package with an invalid version. (`#13345 <https://github.com/pypa/pip/issues/13345>`_)\n- Provide a hint if a system error is raised involving long filenames or path segments on Windows. (`#13346 <https://github.com/pypa/pip/issues/13346>`_)\n- Resumed downloads are saved to the HTTP cache like any other normal download. (`#13441 <https://github.com/pypa/pip/issues/13441>`_)\n- Configured verbosity is consistently forwarded while calling Git during\n  VCS operations. (`#13329 <https://github.com/pypa/pip/issues/13329>`_)\n- Suppress the progress bar, when running with ``--log`` and ``--quiet``.\n\n  Consequently, a new ``auto`` mode for ``--progress-bar`` has been added.\n  ``auto`` will enable progress bars unless suppressed by ``--quiet``,\n  while ``on`` will always enable progress bars. (`#10915 <https://github.com/pypa/pip/issues/10915>`_)\n- Fix normalization of local URLs with non-``file`` schemes. (`#13509 <https://github.com/pypa/pip/issues/13509>`_)\n- Fix normalization of local file URLs on Windows in newer Python versions. (`#13510 <https://github.com/pypa/pip/issues/13510>`_)\n- Fix remaining test failures in Python 3.14 by adjusting ``path_to_url`` and similar functions. (`#13423 <https://github.com/pypa/pip/issues/13423>`_)\n- Fix missing ``network`` test markings, making the suite pass in offline\n  environments again. (`#13378 <https://github.com/pypa/pip/issues/13378>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.14.3\n- Upgrade certifi to 2025.7.14\n- Upgrade distlib to 0.4.0\n- Upgrade msgpack to 1.1.1\n- Upgrade platformdirs to 4.3.8\n- Upgrade pygments to 2.19.2\n- Upgrade requests to 2.32.4\n- Upgrade resolvelib to 1.2.0\n- Upgrade rich to 14.1.0\n- Remove vendored typing-extensions.\n\nProcess\n-------\n\n- pip's own licensing metadata now follows :pep:`639`.\n  In addition, the licenses of pip's vendored dependencies are now included\n  in the ``License-File`` metadata field and in the wheel.\n\n25.1.1 (2025-05-02)\n===================\n\nBug Fixes\n---------\n\n- Fix ``req.source_dir`` AssertionError when using the legacy resolver. (`#13353 <https://github.com/pypa/pip/issues/13353>`_)\n- Fix crash on Python 3.9.6 and lower when pip failed to compile a Python module\n  during installation. (`#13364 <https://github.com/pypa/pip/issues/13364>`_)\n- Names in dependency group includes are now normalized before lookup, which\n  fixes incorrect ``Dependency group '...' not found`` errors. (`#13372 <https://github.com/pypa/pip/issues/13372>`_)\n\nVendored Libraries\n------------------\n\n- Fix issues with using tomllib from the stdlib if available, rather than tomli\n- Upgrade dependency-groups to 1.3.1\n\n\n25.1 (2025-04-26)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Drop support for Python 3.8. (`#12989 <https://github.com/pypa/pip/issues/12989>`_)\n- On python 3.14+, the ``pkg_resources`` metadata backend cannot be used anymore. (`#13010 <https://github.com/pypa/pip/issues/13010>`_)\n- Hide ``--no-python-version-warning`` from CLI help and documentation\n  as it's useless since Python 2 support was removed. Despite being\n  formerly slated for removal, the flag will remain as a no-op to\n  avoid breakage. (`#13303 <https://github.com/pypa/pip/issues/13303>`_)\n- A warning is emitted when the deprecated ``pkg_resources`` library is used to\n  inspect and discover installed packages. This warning should only be visible to\n  users who set an undocumented environment variable to disable the default\n  ``importlib.metadata`` backend. (`#13318 <https://github.com/pypa/pip/issues/13318>`_)\n- Deprecate the legacy ``setup.py bdist_wheel`` mechanism. To silence the warning,\n  and future-proof their setup, users should enable ``--use-pep517`` or add a\n  ``pyproject.toml`` file to the projects they control. (`#13319 <https://github.com/pypa/pip/issues/13319>`_)\n\nFeatures\n--------\n\n- Suggest checking \"pip config debug\" in case of an InvalidProxyURL error. (`#12649 <https://github.com/pypa/pip/issues/12649>`_)\n- Using ``--debug`` also enables verbose logging. (`#12710 <https://github.com/pypa/pip/issues/12710>`_)\n- Display a transient progress bar during package installation. (`#12712 <https://github.com/pypa/pip/issues/12712>`_)\n- Minor performance improvement when installing packages with a large number\n  of dependencies by increasing the requirement string cache size. (`#12873 <https://github.com/pypa/pip/issues/12873>`_)\n- Add a ``--group`` option which allows installation from :pep:`735` Dependency\n  Groups. ``--group`` accepts arguments of the form ``group`` or\n  ``path:group``, where the default path is ``pyproject.toml``, and installs\n  the named Dependency Group from the provided ``pyproject.toml`` file. (`#12963 <https://github.com/pypa/pip/issues/12963>`_)\n- Add support to enable resuming incomplete downloads.\n\n  Control the number of retry attempts using the ``--resume-retries`` flag. (`#12991 <https://github.com/pypa/pip/issues/12991>`_)\n- Use :pep:`753` \"Well-known Project URLs in Metadata\" normalization rules when\n  identifying an equivalent project URL to replace a missing ``Home-Page`` field\n  in ``pip show``. (`#13135 <https://github.com/pypa/pip/issues/13135>`_)\n- Remove ``experimental`` warning from ``pip index versions`` command. (`#13188 <https://github.com/pypa/pip/issues/13188>`_)\n- Add a structured ``--json`` output to ``pip index versions`` (`#13194 <https://github.com/pypa/pip/issues/13194>`_)\n- Add a new, *experimental*, ``pip lock`` command, implementing :pep:`751`. (`#13213 <https://github.com/pypa/pip/issues/13213>`_)\n- Speed up resolution by first only considering the preference of\n  candidates that must be required to complete the resolution. (`#13253 <https://github.com/pypa/pip/issues/13253>`_)\n- Improved heuristics for determining the order of dependency resolution. (`#13273 <https://github.com/pypa/pip/issues/13273>`_)\n- Provide hint, documentation, and link to the documentation when\n  resolution too deep error occurs. (`#13282 <https://github.com/pypa/pip/issues/13282>`_)\n- Include traceback on failure to import ``setuptools`` when ``setup.py`` is being invoked directly. (`#13290 <https://github.com/pypa/pip/issues/13290>`_)\n- Support for :pep:`738` Android wheels. (`#13299 <https://github.com/pypa/pip/issues/13299>`_)\n- Display wheel build tag in ``pip list`` columns output if set. (`#5210 <https://github.com/pypa/pip/issues/5210>`_)\n- Build environment dependencies are no longer compiled to bytecode during\n  installation for a minor performance improvement. (`#7294 <https://github.com/pypa/pip/issues/7294>`_)\n\nBug Fixes\n---------\n\n- When using the ``importlib.metadata`` backend (the default on Python 3.11+),\n  ``pip list`` does not show installed egg distributions more than once anymore.\n  Additionally, egg distributions whose parent directory was in ``sys.path`` but\n  the egg themselves were not in ``sys.path`` are not detected anymore. (`#12308 <https://github.com/pypa/pip/issues/12308>`_)\n- Disable Git and SSH prompts when ``--no-input`` is passed. (`#12718 <https://github.com/pypa/pip/issues/12718>`_)\n- Gracefully handle Windows registry access errors while guessing the MIME type of a file. (`#12769 <https://github.com/pypa/pip/issues/12769>`_)\n- Support multiple global configuration paths returned by ``platformdirs`` on MacOS. (`#12903 <https://github.com/pypa/pip/issues/12903>`_)\n- Resolvelib 1.1.0 fixes a known issue where pip would report a\n  ResolutionImpossible error even though there is a valid solution.\n  However, some very complex dependency resolutions that previously\n  resolved may resolve slower or fail with an ResolutionTooDeep error. (`#13001 <https://github.com/pypa/pip/issues/13001>`_)\n- Show the correct path to the interpreter also when it's a symlink in a venv in the pip upgrade prompt. (`#13156 <https://github.com/pypa/pip/issues/13156>`_)\n- Parse wheel filenames according to `binary distribution format specification\n  <https://packaging.python.org/en/latest/specifications/binary-distribution-format/#file-format>`_.\n  When a filename doesn't match the spec a deprecation warning is emitted and the\n  filename is parsed using the old method. (`#13229 <https://github.com/pypa/pip/issues/13229>`_)\n- While resolving dependencies prefer if any of the known requirements are\n  \"direct\", e.g. points to an explicit URL. (`#13244 <https://github.com/pypa/pip/issues/13244>`_)\n- When choosing a preferred requirement for resolving dependencies\n  do not consider a specifier with a * in it, e.g. \"==1.*\", to be a\n  pinned specifier. (`#13252 <https://github.com/pypa/pip/issues/13252>`_)\n- Fix a regression that causes dependencies to be checked *before* ``Requires-Python``\n  project metadata is checked, leading to wasted cycles when the Python version is\n  unsupported. (`#13270 <https://github.com/pypa/pip/issues/13270>`_)\n- Don't require the ``wheel`` library to be installed to use ``--no-use-pep517``, any more. (`#13330 <https://github.com/pypa/pip/issues/13330>`_)\n- Fix regression that suppressed errors indicating which packages were ignored\n  due to incompatible ``requires-python`` metadata. (`#13333 <https://github.com/pypa/pip/issues/13333>`_)\n- Fix fish shell completion when commandline contains multiple commands. (`#9727 <https://github.com/pypa/pip/issues/9727>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.14.2\n- Upgrade certifi to 2025.1.31\n- Upgrade packaging to 25.0\n- Upgrade platformdirs to 4.3.7\n- Upgrade pygments to 2.19.1\n- Upgrade resolvelib to 1.1.0.\n- Upgrade rich to 14.0.0\n- Vendor tomli-w 1.2.0\n- Upgrade truststore to 0.10.1\n- Upgrade typing_extensions to 4.13.2\n\nImproved Documentation\n----------------------\n\n- Added support for building only the man pages with minimal dependencies using\n  the sphinx-build ``--tag man`` option. This enables distributors to generate man\n  pages without requiring HTML documentation dependencies. (`#13168 <https://github.com/pypa/pip/issues/13168>`_)\n\n\n25.0.1 (2025-02-09)\n===================\n\nBug Fixes\n---------\n\n- Fix an unsupported type annotation on Python 3.10 and earlier. (`#13181 <https://github.com/pypa/pip/issues/13181>`_)\n- Fix a regression where truststore would never be used while installing build dependencies. (`#13186 <https://github.com/pypa/pip/issues/13186>`_)\n\n25.0 (2025-01-26)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate the ``no-python-version-warning`` flag as it has long done nothing\n  since Python 2 support was removed in pip 21.0. (`#13154 <https://github.com/pypa/pip/issues/13154>`_)\n\nFeatures\n--------\n\n- Prefer to display :pep:`639` ``License-Expression`` in ``pip show`` if metadata version is at least 2.4. (`#13112 <https://github.com/pypa/pip/issues/13112>`_)\n- Support :pep:`639` ``License-Expression`` and ``License-File`` metadata fields in JSON\n  output. ``pip inspect`` and ``pip install --report`` now emit\n  ``license_expression`` and ``license_file`` fields in the ``metadata`` object,\n  if the corresponding fields are present in the installed ``METADATA`` file. (`#13134 <https://github.com/pypa/pip/issues/13134>`_)\n- Files in the network cache will inherit the read/write permissions of pip's cache\n  directory (in addition to the current user retaining read/write access). This\n  enables a single cache to be shared among multiple users. (`#11012 <https://github.com/pypa/pip/issues/11012>`_)\n- Return the size, along with the number, of files cleared on ``pip cache purge`` and ``pip cache remove`` (`#12176 <https://github.com/pypa/pip/issues/12176>`_)\n- Cache ``python-requires`` checks while filtering potential installation candidates. (`#13128 <https://github.com/pypa/pip/issues/13128>`_)\n- Optimize package collection by avoiding unnecessary URL parsing and other processing. (`#13132 <https://github.com/pypa/pip/issues/13132>`_)\n\nBug Fixes\n---------\n\n- Reorder the encoding detection when decoding a requirements file, relying on\n  UTF-8 over the locale encoding by default, matching the documented behaviour.\n  (`#12771 <https://github.com/pypa/pip/issues/12771>`_)\n- The pip version self check is disabled on ``EXTERNALLY-MANAGED`` environments. (`#11820 <https://github.com/pypa/pip/issues/11820>`_)\n- Fix a security bug allowing a specially crafted wheel to execute code during\n  installation. (`#13079 <https://github.com/pypa/pip/issues/13079>`_)\n- The inclusion of ``packaging`` 24.2 changes how pre-release specifiers with ``<`` and ``>``\n  behave. Including a pre-release version with these specifiers now implies\n  accepting pre-releases (e.g., ``<2.0dev`` can include ``1.0rc1``). To avoid\n  implying pre-releases, avoid specifying them (e.g., use ``<2.0``).\n  The exception is ``!=``, which never implies pre-releases. (`#13163 <https://github.com/pypa/pip/issues/13163>`_)\n- The ``--cert`` and ``--client-cert`` command-line options are now respected while\n  installing build dependencies. Consequently, the private ``_PIP_STANDALONE_CERT``\n  environment variable is no longer used. (`#5502 <https://github.com/pypa/pip/issues/5502>`_)\n- The ``--proxy`` command-line option is now respected while installing build dependencies. (`#6018 <https://github.com/pypa/pip/issues/6018>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.14.1\n- Upgrade idna to 3.10\n- Upgrade msgpack to 1.1.0\n- Upgrade packaging to 24.2\n- Upgrade platformdirs to 4.3.6\n- Upgrade pyproject-hooks to 1.2.0\n- Upgrade rich to 13.9.4\n- Upgrade tomli to 2.2.1\n\nImproved Documentation\n----------------------\n\n- Removed section about non-existing ``--force-keyring`` flag. (`#12455 <https://github.com/pypa/pip/issues/12455>`_)\n\nProcess\n-------\n\n- Started releasing to PyPI from a GitHub Actions CI/CD workflow that implements trusted publishing and bundles :pep:`740` digital attestations.\n\n24.3.1 (2024-10-27)\n===================\n\nBug Fixes\n---------\n\n- Allow multiple nested inclusions of the same requirements file again. (`#13046 <https://github.com/pypa/pip/issues/13046>`_)\n\n24.3 (2024-10-27)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate wheel filenames that are not compliant with :pep:`440`. (`#12918 <https://github.com/pypa/pip/issues/12918>`_)\n\nFeatures\n--------\n\n- Detect recursively referencing requirements files and help users identify\n  the source. (`#12653 <https://github.com/pypa/pip/issues/12653>`_)\n- Support for :pep:`730` iOS wheels. (`#12961 <https://github.com/pypa/pip/issues/12961>`_)\n\nBug Fixes\n---------\n\n- Display a better error message when an already installed package has an invalid requirement. (`#12953 <https://github.com/pypa/pip/issues/12953>`_)\n- Ignore ``PIP_TARGET`` and ``pip.conf`` ``global.target`` when preparing a build environment. (`#8438 <https://github.com/pypa/pip/issues/8438>`_)\n- Restore support for macOS 10.12 and older (via truststore). (`#12901 <https://github.com/pypa/pip/issues/12901>`_)\n- Allow installing pip in editable mode in a virtual environment on Windows. (`#12666 <https://github.com/pypa/pip/issues/12666>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2024.8.30\n- Upgrade distlib to 0.3.9\n- Upgrade truststore to 0.10.0\n- Upgrade urllib3 to 1.26.20\n\n24.2 (2024-07-28)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate ``pip install --editable`` falling back to ``setup.py develop``\n  when using a setuptools version that does not support :pep:`660`\n  (setuptools v63 and older). (`#11457 <https://github.com/pypa/pip/issues/11457>`_)\n\nFeatures\n--------\n\n- Check unsupported packages for the current platform. (`#11054 <https://github.com/pypa/pip/issues/11054>`_)\n- Use system certificates *and* certifi certificates to verify HTTPS connections on Python 3.10+.\n  Python 3.9 and earlier only use certifi.\n\n  To revert to previous behaviour, pass the flag ``--use-deprecated=legacy-certs``. (`#11647 <https://github.com/pypa/pip/issues/11647>`_)\n- Improve discovery performance of installed packages when the ``importlib.metadata``\n  backend is used to load distribution metadata (used by default under Python 3.11+). (`#12656 <https://github.com/pypa/pip/issues/12656>`_)\n- Improve performance when the same requirement string appears many times during\n  resolution, by consistently caching the parsed requirement string. (`#12663 <https://github.com/pypa/pip/issues/12663>`_)\n- Minor performance improvement of finding applicable package candidates by not\n  repeatedly calculating their versions (`#12664 <https://github.com/pypa/pip/issues/12664>`_)\n- Disable pip's self version check when invoking a pip subprocess to install\n  PEP 517 build requirements. (`#12683 <https://github.com/pypa/pip/issues/12683>`_)\n- Improve dependency resolution performance by caching platform compatibility\n  tags during wheel cache lookup. (`#12712 <https://github.com/pypa/pip/issues/12712>`_)\n- ``wheel`` is no longer explicitly listed as a build dependency of ``pip``.\n  ``setuptools`` injects this dependency in the ``get_requires_for_build_wheel()``\n  hook and no longer needs it on newer versions. (`#12728 <https://github.com/pypa/pip/issues/12728>`_)\n- Ignore ``--require-virtualenv`` for ``pip check`` and ``pip freeze`` (`#12842 <https://github.com/pypa/pip/issues/12842>`_)\n- Improve package download and install performance.\n\n  Increase chunk sizes when downloading (256 kB, up from 10 kB) and reading files (1 MB, up from 8 kB).\n  This reduces the frequency of updates to pip's progress bar. (`#12810 <https://github.com/pypa/pip/issues/12810>`_)\n- Improve pip install performance.\n\n  Files are now extracted in 1MB blocks, or in one block matching the file size for\n  smaller files. A decompressor is no longer instantiated when extracting 0 bytes files,\n  it is not necessary because there is no data to decompress. (`#12803 <https://github.com/pypa/pip/issues/12803>`_)\n\nBug Fixes\n---------\n\n- Set ``no_color`` to global ``rich.Console`` instance. (`#11045 <https://github.com/pypa/pip/issues/11045>`_)\n- Fix resolution to respect ``--python-version`` when checking ``Requires-Python``. (`#12216 <https://github.com/pypa/pip/issues/12216>`_)\n- Perform hash comparisons in a case-insensitive manner. (`#12680 <https://github.com/pypa/pip/issues/12680>`_)\n- Avoid ``dlopen`` failure for glibc detection in musl builds (`#12716 <https://github.com/pypa/pip/issues/12716>`_)\n- Avoid keyring logging crashes when pip is run in verbose mode. (`#12751 <https://github.com/pypa/pip/issues/12751>`_)\n- Fix finding hardlink targets in tar files with an ignored top-level directory. (`#12781 <https://github.com/pypa/pip/issues/12781>`_)\n- Improve pip install performance by only creating required parent\n  directories once, instead of before extracting every file in the wheel. (`#12782 <https://github.com/pypa/pip/issues/12782>`_)\n- Improve pip install performance by calculating installed packages printout\n  in linear time instead of quadratic time. (`#12791 <https://github.com/pypa/pip/issues/12791>`_)\n\nVendored Libraries\n------------------\n\n- Remove vendored tenacity.\n- Update the preload list for the ``DEBUNDLED`` case, to replace ``pep517`` that has been renamed to ``pyproject_hooks``.\n- Use tomllib from the stdlib if available, rather than tomli\n- Upgrade certifi to 2024.7.4\n- Upgrade platformdirs to 4.2.2\n- Upgrade pygments to 2.18.0\n- Upgrade setuptools to 70.3.0\n- Upgrade typing_extensions to 4.12.2\n\nImproved Documentation\n----------------------\n\n- Correct ``—-ignore-conflicts`` (including an em dash) to ``--ignore-conflicts``. (`#12851 <https://github.com/pypa/pip/issues/12851>`_)\n\n24.1.2 (2024-07-07)\n===================\n\nBug Fixes\n---------\n\n- Fix finding hardlink targets in tar files with an ignored top-level directory. (`#12781 <https://github.com/pypa/pip/issues/12781>`_)\n\n24.1.1 (2024-06-26)\n===================\n\nBug Fixes\n---------\n\n- Actually use system trust stores when the truststore feature is enabled.\n\nVendored Libraries\n------------------\n\n- Upgrade requests to 2.32.3\n\n\n24.1 (2024-06-20)\n=================\n\nVendored Libraries\n------------------\n\n- Upgrade truststore to 0.9.1.\n\n\n24.1b2 (2024-06-12)\n===================\n\nFeatures\n--------\n\n- Report informative messages about invalid requirements. (`#12713 <https://github.com/pypa/pip/issues/12713>`_)\n\nBug Fixes\n---------\n\n- Eagerly import the self version check logic to avoid crashes while upgrading or downgrading pip at the same time. (`#12675 <https://github.com/pypa/pip/issues/12675>`_)\n- Accommodate for mismatches between different sources of truth for extra names, for packages generated by ``setuptools``. (`#12688 <https://github.com/pypa/pip/issues/12688>`_)\n- Accommodate for development versions of CPython ending in ``+`` in the version string. (`#12691 <https://github.com/pypa/pip/issues/12691>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade packaging to 24.1\n- Upgrade requests to 2.32.0\n- Remove vendored colorama\n- Remove vendored six\n- Remove vendored webencodings\n- Remove vendored charset_normalizer\n\n  ``requests`` provides optional character detection support on some APIs when processing ambiguous bytes. This isn't relevant for pip to function and we're able to remove it due to recent upstream changes.\n\n24.1b1 (2024-05-06)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Drop support for EOL Python 3.7. (`#11934 <https://github.com/pypa/pip/issues/11934>`_)\n- Remove support for legacy versions and dependency specifiers.\n\n  Packages with non standard-compliant versions or dependency specifiers are now ignored by the resolver.\n  Already installed packages with non standard-compliant versions or dependency specifiers\n  must be uninstalled before upgrading them. (`#12063 <https://github.com/pypa/pip/issues/12063>`_)\n\nFeatures\n--------\n\n- Improve performance of resolution of large dependency trees, with more caching. (`#12453 <https://github.com/pypa/pip/issues/12453>`_)\n- Further improve resolution performance of large dependency trees, by caching hash calculations. (`#12657 <https://github.com/pypa/pip/issues/12657>`_)\n- Reduce startup time of commands (e.g. show, freeze) that do not access the network by 15-30%. (`#4768 <https://github.com/pypa/pip/issues/4768>`_)\n- Reword and improve presentation of uninstallation errors. (`#10421 <https://github.com/pypa/pip/issues/10421>`_)\n- Add a 'raw' progress_bar type for simple and parsable download progress reports (`#11508 <https://github.com/pypa/pip/issues/11508>`_)\n- ``pip list`` no longer performs the pip version check unless ``--outdated`` or ``--uptodate`` is given. (`#11677 <https://github.com/pypa/pip/issues/11677>`_)\n- Use the ``data_filter`` when extracting tarballs, if it's available. (`#12111 <https://github.com/pypa/pip/issues/12111>`_)\n- Display the Project-URL value under key \"Home-page\" in ``pip show`` when the Home-Page metadata field is not set.\n\n  The Project-URL key detection is case-insensitive, and ignores any dashes and underscores. (`#11221 <https://github.com/pypa/pip/issues/11221>`_)\n\nBug Fixes\n---------\n\n- Ensure ``-vv`` gets passed to any ``pip install`` build environment subprocesses. (`#12577 <https://github.com/pypa/pip/issues/12577>`_)\n- Deduplicate entries in the ``Requires`` field of ``pip show``. (`#12165 <https://github.com/pypa/pip/issues/12165>`_)\n- Fix error on checkout for subversion and bazaar with verbose mode on. (`#11050 <https://github.com/pypa/pip/issues/11050>`_)\n- Fix exception with completions when COMP_CWORD is not set (`#12401 <https://github.com/pypa/pip/issues/12401>`_)\n- Fix intermittent \"cannot locate t64.exe\" errors when upgrading pip. (`#12666 <https://github.com/pypa/pip/issues/12666>`_)\n- Remove duplication in invalid wheel error message (`#12579 <https://github.com/pypa/pip/issues/12579>`_)\n- Remove the incorrect pip3.x console entrypoint from the pip wheel. This console\n  script continues to be generated by pip when it installs itself. (`#12536 <https://github.com/pypa/pip/issues/12536>`_)\n- Gracefully skip VCS detection in pip freeze when PATH points to a non-directory path. (`#12567 <https://github.com/pypa/pip/issues/12567>`_)\n- Make the ``--proxy`` parameter take precedence over environment variables. (`#10685 <https://github.com/pypa/pip/issues/10685>`_)\n\nVendored Libraries\n------------------\n\n- Add charset-normalizer 3.3.2\n- Remove chardet\n- Remove pyparsing\n- Upgrade CacheControl to 0.14.0\n- Upgrade certifi to 2024.2.2\n- Upgrade distro to 1.9.0\n- Upgrade idna to 3.7\n- Upgrade msgpack to 1.0.8\n- Upgrade packaging to 24.0\n- Upgrade platformdirs to 4.2.1\n- Upgrade pygments to 2.17.2\n- Upgrade rich to 13.7.1\n- Upgrade setuptools to 69.5.1\n- Upgrade tenacity to 8.2.3\n- Upgrade typing_extensions to 4.11.0\n- Upgrade urllib3 to 1.26.18\n\nImproved Documentation\n----------------------\n\n- Document UX research done on pip. (`#10745 <https://github.com/pypa/pip/issues/10745>`_)\n- Fix the direct usage of zipapp showing up as ``python -m pip.pyz`` rather than ``./pip.pyz`` / ``.\\pip.pyz`` (`#12043 <https://github.com/pypa/pip/issues/12043>`_)\n- Add a warning explaining that the snippet in \"Fallback behavior\" is not a valid\n  ``pyproject.toml`` snippet for projects, and link to setuptools documentation\n  instead. (`#12122 <https://github.com/pypa/pip/issues/12122>`_)\n- The Python Support Policy has been updated. (`#12529 <https://github.com/pypa/pip/issues/12529>`_)\n- Document the environment variables that correspond with CLI options. (`#12576 <https://github.com/pypa/pip/issues/12576>`_)\n- Update architecture documentation for command line interface. (`#6831 <https://github.com/pypa/pip/issues/6831>`_)\n\nProcess\n-------\n\n- Remove ``setup.py`` since all the pip project metadata is now declared in\n  ``pyproject.toml``.\n- Move remaining pip development tools configurations to ``pyproject.toml``.\n\n24.0 (2024-02-03)\n=================\n\nFeatures\n--------\n\n- Retry on HTTP status code 502 (`#11843 <https://github.com/pypa/pip/issues/11843>`_)\n- Automatically use the setuptools PEP 517 build backend when ``--config-settings`` is\n  used for projects without ``pyproject.toml``. (`#11915 <https://github.com/pypa/pip/issues/11915>`_)\n- Make pip freeze and pip uninstall of legacy editable installs of packages whose name\n  contains ``_`` compatible with ``setuptools>=69.0.3``. (`#12477 <https://github.com/pypa/pip/issues/12477>`_)\n- Support per requirement ``--config-settings`` for editable installs. (`#12480 <https://github.com/pypa/pip/issues/12480>`_)\n\nBug Fixes\n---------\n\n- Optimized usage of ``--find-links=<path-to-dir>``, by only scanning the relevant directory once, only considering file names that are valid wheel or sdist names, and only considering files in the directory that are related to the install. (`#12327 <https://github.com/pypa/pip/issues/12327>`_)\n- Removed ``wheel`` from the ``[build-system].requires`` list fallback\n  that is used when ``pyproject.toml`` is absent. (`#12449 <https://github.com/pypa/pip/issues/12449>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade distlib to 0.3.8\n\nImproved Documentation\n----------------------\n\n- Fix explanation of how PIP_CONFIG_FILE works (`#11815 <https://github.com/pypa/pip/issues/11815>`_)\n- Fix outdated pip install argument description in documentation. (`#12417 <https://github.com/pypa/pip/issues/12417>`_)\n- Replace some links to PEPs with links to the canonical specifications on the :doc:`pypug:index` (`#12434 <https://github.com/pypa/pip/issues/12434>`_)\n- Updated the ``pyproject.toml`` document to stop suggesting\n  to depend on ``wheel`` as a build dependency directly. (`#12449 <https://github.com/pypa/pip/issues/12449>`_)\n- Update supported interpreters in development docs (`#12475 <https://github.com/pypa/pip/issues/12475>`_)\n\nProcess\n-------\n\n- Most project metadata is now defined statically via pip's ``pyproject.toml`` file.\n\n23.3.2 (2023-12-17)\n===================\n\nBug Fixes\n---------\n\n- Fix a bug in extras handling for link requirements (`#12372 <https://github.com/pypa/pip/issues/12372>`_)\n- Fix mercurial revision \"parse error\": use ``--rev={ref}`` instead of ``-r={ref}`` (`#12373 <https://github.com/pypa/pip/issues/12373>`_)\n\n\n23.3.1 (2023-10-21)\n===================\n\nBug Fixes\n---------\n\n- Handle a timezone indicator of Z when parsing dates in the self check. (`#12338 <https://github.com/pypa/pip/issues/12338>`_)\n- Fix bug where installing the same package at the same time with multiple pip processes could fail. (`#12361 <https://github.com/pypa/pip/issues/12361>`_)\n\n\n23.3 (2023-10-15)\n=================\n\nProcess\n-------\n\n- Added reference to `vulnerability reporting guidelines <https://www.python.org/dev/security/>`_ to pip's security policy.\n\nDeprecations and Removals\n-------------------------\n\n- Drop a fallback to using SecureTransport on macOS. It was useful when pip detected OpenSSL older than 1.0.1, but the current pip does not support any Python version supporting such old OpenSSL versions. (`#12175 <https://github.com/pypa/pip/issues/12175>`_)\n\nFeatures\n--------\n\n- Improve extras resolution for multiple constraints on same base package. (`#11924 <https://github.com/pypa/pip/issues/11924>`_)\n- Improve use of datastructures to make candidate selection 1.6x faster. (`#12204 <https://github.com/pypa/pip/issues/12204>`_)\n- Allow ``pip install --dry-run`` to use platform and ABI overriding options. (`#12215 <https://github.com/pypa/pip/issues/12215>`_)\n- Add ``is_yanked`` boolean entry to the installation report (``--report``) to indicate whether the requirement was yanked from the index, but was still selected by pip conform to :pep:`592`. (`#12224 <https://github.com/pypa/pip/issues/12224>`_)\n\nBug Fixes\n---------\n\n- Ignore errors in temporary directory cleanup (show a warning instead). (`#11394 <https://github.com/pypa/pip/issues/11394>`_)\n- Normalize extras according to :pep:`685` from package metadata in the resolver\n  for comparison. This ensures extras are correctly compared and merged as long\n  as the package providing the extra(s) is built with values normalized according\n  to the standard. Note, however, that this *does not* solve cases where the\n  package itself contains unnormalized extra values in the metadata. (`#11649 <https://github.com/pypa/pip/issues/11649>`_)\n- Prevent downloading sdists twice when :pep:`658` metadata is present. (`#11847 <https://github.com/pypa/pip/issues/11847>`_)\n- Include all requested extras in the install report (``--report``). (`#11924 <https://github.com/pypa/pip/issues/11924>`_)\n- Removed uses of ``datetime.datetime.utcnow`` from non-vendored code. (`#12005 <https://github.com/pypa/pip/issues/12005>`_)\n- Consistently report whether a dependency comes from an extra. (`#12095 <https://github.com/pypa/pip/issues/12095>`_)\n- Fix completion script for zsh (`#12166 <https://github.com/pypa/pip/issues/12166>`_)\n- Fix improper handling of the new onexc argument of ``shutil.rmtree()`` in Python 3.12. (`#12187 <https://github.com/pypa/pip/issues/12187>`_)\n- Filter out yanked links from the available versions error message: \"(from versions: 1.0, 2.0, 3.0)\" will not contain yanked versions conform PEP 592. The yanked versions (if any) will be mentioned in a separate error message. (`#12225 <https://github.com/pypa/pip/issues/12225>`_)\n- Fix crash when the git version number contains something else than digits and dots. (`#12280 <https://github.com/pypa/pip/issues/12280>`_)\n- Use ``-r=...`` instead of ``-r ...`` to specify references with Mercurial. (`#12306 <https://github.com/pypa/pip/issues/12306>`_)\n- Redact password from URLs in some additional places. (`#12350 <https://github.com/pypa/pip/issues/12350>`_)\n- pip uses less memory when caching large packages. As a result, there is a new on-disk cache format stored in a new directory ($PIP_CACHE_DIR/http-v2). (`#2984 <https://github.com/pypa/pip/issues/2984>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2023.7.22\n- Add truststore 0.8.0\n- Upgrade urllib3 to 1.26.17\n\nImproved Documentation\n----------------------\n\n- Document that ``pip search`` support has been removed from PyPI (`#12059 <https://github.com/pypa/pip/issues/12059>`_)\n- Clarify --prefer-binary in CLI and docs (`#12122 <https://github.com/pypa/pip/issues/12122>`_)\n- Document that using OS-provided Python can cause pip's test suite to report false failures. (`#12334 <https://github.com/pypa/pip/issues/12334>`_)\n\n\n23.2.1 (2023-07-22)\n===================\n\nBug Fixes\n---------\n\n- Disable :pep:`658` metadata fetching with the legacy resolver. (`#12156 <https://github.com/pypa/pip/issues/12156>`_)\n\n\n23.2 (2023-07-15)\n=================\n\nProcess\n-------\n\n- Deprecate support for eggs for Python 3.11 or later, when the new ``importlib.metadata`` backend is used to load distribution metadata. This only affects the egg *distribution format* (with the ``.egg`` extension); distributions using the ``.egg-info`` *metadata format* (but are not actually eggs) are not affected. For more information about eggs, see `relevant section in the setuptools documentation <https://setuptools.pypa.io/en/stable/deprecated/python_eggs.html>`__.\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate legacy version and version specifiers that don't conform to the\n  :ref:`specification <pypug:version-specifiers>`.\n  (`#12063 <https://github.com/pypa/pip/issues/12063>`_)\n- ``freeze`` no longer excludes the ``setuptools``, ``distribute``, and ``wheel``\n  from the output when running on Python 3.12 or later, where they are not\n  included in a virtual environment by default. Use ``--exclude`` if you wish to\n  exclude any of these packages. (`#4256 <https://github.com/pypa/pip/issues/4256>`_)\n\nFeatures\n--------\n\n- make rejection messages slightly different between 1 and 8, so the user can make the difference. (`#12040 <https://github.com/pypa/pip/issues/12040>`_)\n\nBug Fixes\n---------\n\n- Fix ``pip completion --zsh``. (`#11417 <https://github.com/pypa/pip/issues/11417>`_)\n- Prevent downloading files twice when :pep:`658` metadata is present (`#11847 <https://github.com/pypa/pip/issues/11847>`_)\n- Add permission check before configuration (`#11920 <https://github.com/pypa/pip/issues/11920>`_)\n- Fix deprecation warnings in Python 3.12 for usage of shutil.rmtree (`#11957 <https://github.com/pypa/pip/issues/11957>`_)\n- Ignore invalid or unreadable ``origin.json`` files in the cache of locally built wheels. (`#11985 <https://github.com/pypa/pip/issues/11985>`_)\n- Fix installation of packages with :pep:`658` metadata using non-canonicalized names (`#12038 <https://github.com/pypa/pip/issues/12038>`_)\n- Correctly parse ``dist-info-metadata`` values from JSON-format index data. (`#12042 <https://github.com/pypa/pip/issues/12042>`_)\n- Fail with an error if the ``--python`` option is specified after the subcommand name. (`#12067 <https://github.com/pypa/pip/issues/12067>`_)\n- Fix slowness when using ``importlib.metadata`` (the default way for pip to read metadata in Python 3.11+) and there is a large overlap between already installed and to-be-installed packages. (`#12079 <https://github.com/pypa/pip/issues/12079>`_)\n- Pass the ``-r`` flag to mercurial to be explicit that a revision is passed and protect\n  against ``hg`` options injection as part of VCS URLs. Users that do not have control on\n  VCS URLs passed to pip are advised to upgrade. (`#12119 <https://github.com/pypa/pip/issues/12119>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2023.5.7\n- Upgrade platformdirs to 3.8.1\n- Upgrade pygments to 2.15.1\n- Upgrade pyparsing to 3.1.0\n- Upgrade Requests to 2.31.0\n- Upgrade rich to 13.4.2\n- Upgrade setuptools to 68.0.0\n- Updated typing_extensions to 4.6.0\n- Upgrade typing_extensions to 4.7.1\n- Upgrade urllib3 to 1.26.16\n\n\n23.1.2 (2023-04-26)\n===================\n\nVendored Libraries\n------------------\n\n- Upgrade setuptools to 67.7.2\n\n\n23.1.1 (2023-04-22)\n===================\n\nBug Fixes\n---------\n\n- Revert `#11487 <https://github.com/pypa/pip/pull/11487>`_, as it causes issues with virtualenvs created by the Windows Store distribution of Python. (`#11987 <https://github.com/pypa/pip/issues/11987>`_)\n\nVendored Libraries\n------------------\n\n- Revert pkg_resources (via setuptools) back to 65.6.3\n\nImproved Documentation\n----------------------\n\n- Update documentation to reflect the new behavior of using the cache of locally\n  built wheels in hash-checking mode. (`#11967 <https://github.com/pypa/pip/issues/11967>`_)\n\n\n23.1 (2023-04-15)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove support for the deprecated ``--install-options``. (`#11358 <https://github.com/pypa/pip/issues/11358>`_)\n- ``--no-binary`` does not imply ``setup.py install`` anymore. Instead a wheel will be\n  built locally and installed. (`#11451 <https://github.com/pypa/pip/issues/11451>`_)\n- ``--no-binary`` does not disable the cache of locally built wheels anymore. It only\n  means \"don't download wheels\". (`#11453 <https://github.com/pypa/pip/issues/11453>`_)\n- Deprecate ``--build-option`` and ``--global-option``. Users are invited to switch to\n  ``--config-settings``. (`#11859 <https://github.com/pypa/pip/issues/11859>`_)\n- Using ``--config-settings`` with projects that don't have a ``pyproject.toml`` now prints\n  a deprecation warning. In the future the presence of config settings will automatically\n  enable the default build backend for legacy projects and pass the settings to it. (`#11915 <https://github.com/pypa/pip/issues/11915>`_)\n- Remove ``setup.py install`` fallback when building a wheel failed for projects without\n  ``pyproject.toml``. (`#8368 <https://github.com/pypa/pip/issues/8368>`_)\n- When the ``wheel`` package is not installed, pip now uses the default build backend\n  instead of ``setup.py install`` and ``setup.py develop`` for project without\n  ``pyproject.toml``. (`#8559 <https://github.com/pypa/pip/issues/8559>`_)\n\nFeatures\n--------\n\n- Specify egg-link location in assertion message when it does not match installed location to provide better error message for debugging. (`#10476 <https://github.com/pypa/pip/issues/10476>`_)\n- Present conflict information during installation after each choice that is rejected (pass ``-vv`` to ``pip install`` to show it) (`#10937 <https://github.com/pypa/pip/issues/10937>`_)\n- Display dependency chain on each Collecting/Processing log line. (`#11169 <https://github.com/pypa/pip/issues/11169>`_)\n- Support a per-requirement ``--config-settings`` option in requirements files. (`#11325 <https://github.com/pypa/pip/issues/11325>`_)\n- The ``--config-settings``/``-C`` option now supports using the same key multiple\n  times. When the same key is specified multiple times, all values are passed to\n  the build backend as a list, as opposed to the previous behavior, where pip would\n  only pass the last value if the same key was used multiple times. (`#11681 <https://github.com/pypa/pip/issues/11681>`_)\n- Add ``-C`` as a short version of the ``--config-settings`` option. (`#11786 <https://github.com/pypa/pip/issues/11786>`_)\n- Reduce the number of resolver rounds, since backjumping makes the resolver more efficient in finding solutions. This also makes pathological cases fail quicker. (`#11908 <https://github.com/pypa/pip/issues/11908>`_)\n- Warn if ``--hash`` is used on a line without requirement in a requirements file. (`#11935 <https://github.com/pypa/pip/issues/11935>`_)\n- Stop propagating CLI ``--config-settings`` to the build dependencies. They already did\n  not propagate to requirements provided in requirement files. To pass the same config\n  settings to several requirements, users should provide the requirements as CLI\n  arguments. (`#11941 <https://github.com/pypa/pip/issues/11941>`_)\n- Support wheel cache when using ``--require-hashes``. (`#5037 <https://github.com/pypa/pip/issues/5037>`_)\n- Add ``--keyring-provider`` flag. See the Authentication page in the documentation for more info. (`#8719 <https://github.com/pypa/pip/issues/8719>`_)\n- In the case of virtual environments, configuration files are now also included from the base installation. (`#9752 <https://github.com/pypa/pip/issues/9752>`_)\n\nBug Fixes\n---------\n\n- Fix grammar by changing \"A new release of pip available:\" to \"A new release of pip is available:\" in the notice used for indicating that. (`#11529 <https://github.com/pypa/pip/issues/11529>`_)\n- Normalize paths before checking if installed scripts are on PATH. (`#11719 <https://github.com/pypa/pip/issues/11719>`_)\n- Correct the way to decide if keyring is available. (`#11774 <https://github.com/pypa/pip/issues/11774>`_)\n- More consistent resolution backtracking by removing legacy hack related to setuptools resolution (`#11837 <https://github.com/pypa/pip/issues/11837>`_)\n- Include ``AUTHORS.txt`` in pip's wheels. (`#11882 <https://github.com/pypa/pip/issues/11882>`_)\n- The ``uninstall`` and ``install --force-reinstall`` commands no longer call\n  ``normalize_path()`` repeatedly on the same paths. Instead, these results are\n  cached for the duration of an uninstall operation, resulting in improved\n  performance, particularly on Windows. (`#11889 <https://github.com/pypa/pip/issues/11889>`_)\n- Fix and improve the parsing of hashes embedded in URL fragments. (`#11936 <https://github.com/pypa/pip/issues/11936>`_)\n- When package A depends on package B provided as a direct URL dependency including a hash\n  embedded in the link, the ``--require-hashes`` option did not warn when user supplied hashes\n  were missing for package B. (`#11938 <https://github.com/pypa/pip/issues/11938>`_)\n- Correctly report ``requested_extras`` in the installation report when extras are\n  specified for a local directory installation. (`#11946 <https://github.com/pypa/pip/issues/11946>`_)\n- When installing an archive from a direct URL or local file, populate\n  ``download_info.info.hashes`` in the installation report, in addition to the legacy\n  ``download_info.info.hash`` key. (`#11948 <https://github.com/pypa/pip/issues/11948>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade msgpack to 1.0.5\n- Patch pkg_resources to remove dependency on ``jaraco.text``.\n- Upgrade platformdirs to 3.2.0\n- Upgrade pygments to 2.14.0\n- Upgrade resolvelib to 1.0.1\n- Upgrade rich to 13.3.3\n- Upgrade setuptools to 67.6.1\n- Upgrade tenacity to 8.2.2\n- Upgrade typing_extensions to 4.5.0\n- Upgrade urllib3 to 1.26.15\n\nImproved Documentation\n----------------------\n\n- Cross-reference the ``--python`` flag from the ``--prefix`` flag,\n  and mention limitations of ``--prefix`` regarding script installation. (`#11775 <https://github.com/pypa/pip/issues/11775>`_)\n- Add SECURITY.md to make the policy official. (`#11809 <https://github.com/pypa/pip/issues/11809>`_)\n- Add username to Git over SSH example. (`#11838 <https://github.com/pypa/pip/issues/11838>`_)\n- Quote extras in the pip install docs to guard shells with default glob\n  qualifiers, like zsh. (`#11842 <https://github.com/pypa/pip/issues/11842>`_)\n- Make it clear that requirements/constraints file can be a URL (`#11954 <https://github.com/pypa/pip/issues/11954>`_)\n\n\n23.0.1 (2023-02-17)\n===================\n\nFeatures\n--------\n\n- Ignore PIP_REQUIRE_VIRTUALENV for ``pip index`` (`#11671 <https://github.com/pypa/pip/issues/11671>`_)\n- Implement ``--break-system-packages`` to permit installing packages into\n  ``EXTERNALLY-MANAGED`` Python installations. (`#11780 <https://github.com/pypa/pip/issues/11780>`_)\n\nBug Fixes\n---------\n\n- Improve handling of isolated build environments on platforms that\n  customize the Python's installation schemes, such as Debian and\n  Homebrew. (`#11740 <https://github.com/pypa/pip/issues/11740>`_)\n- Do not crash in presence of misformatted hash field in ``direct_url.json``. (`#11773 <https://github.com/pypa/pip/issues/11773>`_)\n\n\n23.0 (2023-01-30)\n=================\n\nFeatures\n--------\n\n- Change the hashes in the installation report to be a mapping. Emit the\n  ``archive_info.hashes`` dictionary in ``direct_url.json``. (`#11312 <https://github.com/pypa/pip/issues/11312>`_)\n- Implement logic to read the ``EXTERNALLY-MANAGED`` file as specified in :pep:`668`.\n  This allows a downstream Python distributor to prevent users from using pip to\n  modify the externally managed environment. (`#11381 <https://github.com/pypa/pip/issues/11381>`_)\n- Enable the use of ``keyring`` found on ``PATH``. This allows ``keyring``\n  installed using ``pipx`` to be used by ``pip``. (`#11589 <https://github.com/pypa/pip/issues/11589>`_)\n- The inspect and installation report formats are now declared stable, and their version\n  has been bumped from ``0`` to ``1``. (`#11757 <https://github.com/pypa/pip/issues/11757>`_)\n\nBug Fixes\n---------\n\n- Wheel cache behavior is restored to match previous versions, allowing the\n  cache to find existing entries. (`#11527 <https://github.com/pypa/pip/issues/11527>`_)\n- Use the \"venv\" scheme if available to obtain prefixed lib paths. (`#11598 <https://github.com/pypa/pip/issues/11598>`_)\n- Deprecated a historical ambiguity in how ``egg`` fragments in URL-style\n  requirements are formatted and handled. ``egg`` fragments that do not look\n  like :pep:`508` names now produce a deprecation warning. (`#11617 <https://github.com/pypa/pip/issues/11617>`_)\n- Fix scripts path in isolated build environment on Debian. (`#11623 <https://github.com/pypa/pip/issues/11623>`_)\n- Make ``pip show`` show the editable location if package is editable (`#11638 <https://github.com/pypa/pip/issues/11638>`_)\n- Stop checking that ``wheel`` is present when ``build-system.requires``\n  is provided without ``build-system.build-backend`` as ``setuptools``\n  (which we still check for) will inject it anyway. (`#11673 <https://github.com/pypa/pip/issues/11673>`_)\n- Fix an issue when an already existing in-memory distribution would cause\n  exceptions in ``pip install`` (`#11704 <https://github.com/pypa/pip/issues/11704>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2022.12.7\n- Upgrade chardet to 5.1.0\n- Upgrade colorama to 0.4.6\n- Upgrade distro to 1.8.0\n- Remove pep517 from vendored packages\n- Upgrade platformdirs to 2.6.2\n- Add pyproject-hooks 1.0.0\n- Upgrade requests to 2.28.2\n- Upgrade rich to 12.6.0\n- Upgrade urllib3 to 1.26.14\n\nImproved Documentation\n----------------------\n\n- Fixed the description of the option \"--install-options\" in the documentation (`#10265 <https://github.com/pypa/pip/issues/10265>`_)\n- Remove mention that editable installs are necessary for pip freeze to report the VCS\n  URL. (`#11675 <https://github.com/pypa/pip/issues/11675>`_)\n- Clarify that the egg URL fragment is only necessary for editable VCS installs, and\n  otherwise not necessary anymore. (`#11676 <https://github.com/pypa/pip/issues/11676>`_)\n\n\n22.3.1 (2022-11-05)\n===================\n\nBug Fixes\n---------\n\n- Fix entry point generation of ``pip.X``, ``pipX.Y``, and ``easy_install-X.Y``\n  to correctly account for multi-digit Python version segments (e.g. the \"11\"\n  part of 3.11). (`#11547 <https://github.com/pypa/pip/issues/11547>`_)\n\n\n22.3 (2022-10-15)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate ``--install-options`` which forces pip to use the deprecated ``install``\n  command of ``setuptools``. (`#11358 <https://github.com/pypa/pip/issues/11358>`_)\n- Deprecate installation with 'setup.py install' when no-binary is enabled for\n  source distributions without 'pyproject.toml'. (`#11452 <https://github.com/pypa/pip/issues/11452>`_)\n- Deprecate ```--no-binary`` disabling the wheel cache. (`#11454 <https://github.com/pypa/pip/issues/11454>`_)\n- Remove ``--use-feature=2020-resolver`` opt-in flag. This was supposed to be removed in 21.0, but missed during that release cycle. (`#11493 <https://github.com/pypa/pip/issues/11493>`_)\n- Deprecate installation with 'setup.py install' when the 'wheel' package is absent for\n  source distributions without 'pyproject.toml'. (`#8559 <https://github.com/pypa/pip/issues/8559>`_)\n- Remove the ability to use ``pip list --outdated`` in combination with ``--format=freeze``. (`#9789 <https://github.com/pypa/pip/issues/9789>`_)\n\nFeatures\n--------\n\n- Use ``shell=True`` for opening the editor with ``pip config edit``. (`#10716 <https://github.com/pypa/pip/issues/10716>`_)\n- Use the ``data-dist-info-metadata`` attribute from :pep:`658` to resolve distribution metadata without downloading the dist yet. (`#11111 <https://github.com/pypa/pip/issues/11111>`_)\n- Add an option to run the test suite with pip built as a zipapp. (`#11250 <https://github.com/pypa/pip/issues/11250>`_)\n- Add a ``--python`` option to allow pip to manage Python environments other\n  than the one pip is installed in. (`#11320 <https://github.com/pypa/pip/issues/11320>`_)\n- Document the new (experimental) zipapp distribution of pip. (`#11459 <https://github.com/pypa/pip/issues/11459>`_)\n- Use the much faster 'bzr co --lightweight' to obtain a copy of a Bazaar tree. (`#5444 <https://github.com/pypa/pip/issues/5444>`_)\n\nBug Fixes\n---------\n\n- Fix ``--no-index`` when ``--index-url`` or ``--extra-index-url`` is specified\n  inside a requirements file. (`#11276 <https://github.com/pypa/pip/issues/11276>`_)\n- Ensure that the candidate ``pip`` executable exists, when checking for a new version of pip. (`#11309 <https://github.com/pypa/pip/issues/11309>`_)\n- Ignore distributions with invalid ``Name`` in metadata instead of crashing, when\n  using the ``importlib.metadata`` backend. (`#11352 <https://github.com/pypa/pip/issues/11352>`_)\n- Raise RequirementsFileParseError when parsing malformed requirements options that can't be successfully parsed by shlex. (`#11491 <https://github.com/pypa/pip/issues/11491>`_)\n- Fix build environment isolation on some system Pythons. (`#6264 <https://github.com/pypa/pip/issues/6264>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2022.9.24\n- Upgrade distlib to 0.3.6\n- Upgrade idna to 3.4\n- Upgrade pep517 to 0.13.0\n- Upgrade pygments to 2.13.0\n- Upgrade tenacity to 8.1.0\n- Upgrade typing_extensions to 4.4.0\n- Upgrade urllib3 to 1.26.12\n\nImproved Documentation\n----------------------\n\n- Mention that --quiet must be used when writing the installation report to stdout. (`#11357 <https://github.com/pypa/pip/issues/11357>`_)\n\n\n22.2.2 (2022-08-03)\n===================\n\nBug Fixes\n---------\n\n- Avoid  ``AttributeError`` when removing the setuptools-provided ``_distutils_hack`` and it is missing its implementation. (`#11314 <https://github.com/pypa/pip/issues/11314>`_)\n- Fix import error when reinstalling pip in user site. (`#11319 <https://github.com/pypa/pip/issues/11319>`_)\n- Show pip deprecation warnings by default. (`#11330 <https://github.com/pypa/pip/issues/11330>`_)\n\n\n22.2.1 (2022-07-27)\n===================\n\nBug Fixes\n---------\n\n- Send the pip upgrade prompt to stderr. (`#11282 <https://github.com/pypa/pip/issues/11282>`_)\n- Ensure that things work correctly in environments where setuptools-injected\n  ``distutils`` is available by default. This is done by cooperating with\n  setuptools' injection logic to ensure that pip uses the ``distutils`` from the\n  Python standard library instead. (`#11298 <https://github.com/pypa/pip/issues/11298>`_)\n- Clarify that ``pip cache``'s wheels-related output is about locally built wheels only. (`#11300 <https://github.com/pypa/pip/issues/11300>`_)\n\n\n22.2 (2022-07-21)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove the ``html5lib`` deprecated feature flag. (`#10825 <https://github.com/pypa/pip/issues/10825>`_)\n- Remove ``--use-deprecated=backtrack-on-build-failures``. (`#11241 <https://github.com/pypa/pip/issues/11241>`_)\n\nFeatures\n--------\n\n- Add support to use `truststore <https://pypi.org/project/truststore/>`_ as an\n  alternative SSL certificate verification backend. The backend can be enabled on Python\n  3.10 and later by installing ``truststore`` into the environment, and adding the\n  ``--use-feature=truststore`` flag to various pip commands.\n\n  ``truststore`` differs from the current default verification backend (provided by\n  ``certifi``) in it uses the operating system’s trust store, which can be better\n  controlled and augmented to better support non-standard certificates. Depending on\n  feedback, pip may switch to this as the default certificate verification backend in\n  the future. (`#11082 <https://github.com/pypa/pip/issues/11082>`_)\n- Add ``--dry-run`` option to ``pip install``, to let it print what it would install but\n  not actually change anything in the target environment. (`#11096 <https://github.com/pypa/pip/issues/11096>`_)\n- Record in wheel cache entries the URL of the original artifact that was downloaded\n  to build the cached wheels. The record is named ``origin.json`` and uses the PEP 610\n  Direct URL format. (`#11137 <https://github.com/pypa/pip/issues/11137>`_)\n- Support `PEP 691 <https://peps.python.org/pep-0691/>`_. (`#11158 <https://github.com/pypa/pip/issues/11158>`_)\n- pip's deprecation warnings now subclass the built-in ``DeprecationWarning``, and\n  can be suppressed by running the Python interpreter with\n  ``-W ignore::DeprecationWarning``. (`#11225 <https://github.com/pypa/pip/issues/11225>`_)\n- Add ``pip inspect`` command to obtain the list of installed distributions and other\n  information about the Python environment, in JSON format. (`#11245 <https://github.com/pypa/pip/issues/11245>`_)\n- Significantly speed up isolated environment creation, by using the same\n  sources for pip instead of creating a standalone installation for each\n  environment. (`#11257 <https://github.com/pypa/pip/issues/11257>`_)\n- Add an experimental ``--report`` option to the install command to generate a JSON report\n  of what was installed. In combination with ``--dry-run`` and ``--ignore-installed`` it\n  can be used to resolve the requirements. (`#53 <https://github.com/pypa/pip/issues/53>`_)\n\nBug Fixes\n---------\n\n- Fix ``pip install --pre`` for packages with pre-release build dependencies defined\n  both in ``pyproject.toml``'s ``build-system.requires`` and ``setup.py``'s\n  ``setup_requires``. (`#10222 <https://github.com/pypa/pip/issues/10222>`_)\n- When pip rewrites the shebang line in a script during wheel installation,\n  update the hash and size in the corresponding ``RECORD`` file entry. (`#10744 <https://github.com/pypa/pip/issues/10744>`_)\n- Do not consider a ``.dist-info`` directory found inside a wheel-like zip file\n  as metadata for an installed distribution. A package in a wheel is (by\n  definition) not installed, and is not guaranteed to work due to how a wheel is\n  structured. (`#11217 <https://github.com/pypa/pip/issues/11217>`_)\n- Use ``importlib.resources`` to read the ``vendor.txt`` file in ``pip debug``.\n  This makes the command safe for use from a zipapp. (`#11248 <https://github.com/pypa/pip/issues/11248>`_)\n- Make the ``--use-pep517`` option of the ``download`` command apply not just\n  to the requirements specified on the command line, but to their dependencies,\n  as well. (`#9523 <https://github.com/pypa/pip/issues/9523>`_)\n\nProcess\n-------\n\n- Remove reliance on the stdlib cgi module, which is deprecated in Python 3.11.\n\nVendored Libraries\n------------------\n\n- Remove html5lib.\n- Upgrade certifi to 2022.6.15\n- Upgrade chardet to 5.0.0\n- Upgrade colorama to 0.4.5\n- Upgrade distlib to 0.3.5\n- Upgrade msgpack to 1.0.4\n- Upgrade pygments to 2.12.0\n- Upgrade pyparsing to 3.0.9\n- Upgrade requests to 2.28.1\n- Upgrade rich to 12.5.1\n- Upgrade typing_extensions to 4.3.0\n- Upgrade urllib3 to 1.26.10\n\n\n22.1.2 (2022-05-31)\n===================\n\nBug Fixes\n---------\n\n- Revert `#10979 <https://github.com/pypa/pip/issues/10979>`_ since it introduced a regression in certain edge cases. (`#10979 <https://github.com/pypa/pip/issues/10979>`_)\n- Fix an incorrect assertion in the logging logic, that prevented the upgrade prompt from being presented. (`#11136 <https://github.com/pypa/pip/issues/11136>`_)\n\n\n22.1.1 (2022-05-20)\n===================\n\nBug Fixes\n---------\n\n- Properly filter out optional dependencies (i.e. extras) when checking build environment distributions. (`#11112 <https://github.com/pypa/pip/issues/11112>`_)\n- Change the build environment dependency checking to be opt-in. (`#11116 <https://github.com/pypa/pip/issues/11116>`_)\n- Allow using a pre-release version to satisfy a build requirement. This helps\n  manually populated build environments to more accurately detect build-time\n  requirement conflicts. (`#11123 <https://github.com/pypa/pip/issues/11123>`_)\n\n\n22.1 (2022-05-11)\n=================\n\nProcess\n-------\n\n- Enable the ``importlib.metadata`` metadata implementation by default on\n  Python 3.11 (or later). The environment variable ``_PIP_USE_IMPORTLIB_METADATA``\n  can still be used to enable the implementation on 3.10 and earlier, or disable\n  it on 3.11 (by setting it to ``0`` or ``false``).\n\nBug Fixes\n---------\n\n- Revert `#9243 <https://github.com/pypa/pip/issues/9243>`_ since it introduced a regression in certain edge cases. (`#10962 <https://github.com/pypa/pip/issues/10962>`_)\n- Fix missing ``REQUESTED`` metadata when using URL constraints. (`#11079 <https://github.com/pypa/pip/issues/11079>`_)\n- ``pip config`` now normalizes names by converting underscores into dashes. (`#9330 <https://github.com/pypa/pip/issues/9330>`_)\n\n\n22.1b1 (2022-04-30)\n===================\n\nProcess\n-------\n\n- Start migration of distribution metadata implementation from ``pkg_resources``\n  to ``importlib.metadata``. The new implementation is currently not exposed in\n  any user-facing way, but included in the code base for easier development.\n\nDeprecations and Removals\n-------------------------\n\n- Drop ``--use-deprecated=out-of-tree-build``, according to deprecation message. (`#11001 <https://github.com/pypa/pip/issues/11001>`_)\n\nFeatures\n--------\n\n- Add option to install and uninstall commands to opt-out from running-as-root warning. (`#10556 <https://github.com/pypa/pip/issues/10556>`_)\n- Include Project-URLs in ``pip show`` output. (`#10799 <https://github.com/pypa/pip/issues/10799>`_)\n- Improve error message when ``pip config edit`` is provided an editor that\n  doesn't exist. (`#10812 <https://github.com/pypa/pip/issues/10812>`_)\n- Add a user interface for supplying config settings to build backends. (`#11059 <https://github.com/pypa/pip/issues/11059>`_)\n- Add support for Powershell autocompletion. (`#9024 <https://github.com/pypa/pip/issues/9024>`_)\n- Explains why specified version cannot be retrieved when *Requires-Python* is not satisfied. (`#9615 <https://github.com/pypa/pip/issues/9615>`_)\n- Validate build dependencies when using ``--no-build-isolation``. (`#9794 <https://github.com/pypa/pip/issues/9794>`_)\n\nBug Fixes\n---------\n\n- Fix conditional checks to prevent ``pip.exe`` from trying to modify itself, on Windows. (`#10560 <https://github.com/pypa/pip/issues/10560>`_)\n- Fix uninstall editable from Windows junction link. (`#10696 <https://github.com/pypa/pip/issues/10696>`_)\n- Fallback to pyproject.toml-based builds if ``setup.py`` is present in a project, but ``setuptools`` cannot be imported. (`#10717 <https://github.com/pypa/pip/issues/10717>`_)\n- When checking for conflicts in the build environment, correctly skip requirements\n  containing markers that do not match the current environment. (`#10883 <https://github.com/pypa/pip/issues/10883>`_)\n- Disable brotli import in vendored urllib3 so brotli could be uninstalled/upgraded by pip. (`#10950 <https://github.com/pypa/pip/issues/10950>`_)\n- Prioritize URL credentials over netrc. (`#10979 <https://github.com/pypa/pip/issues/10979>`_)\n- Filter available distributions using hash declarations from constraints files. (`#9243 <https://github.com/pypa/pip/issues/9243>`_)\n- Fix an error when trying to uninstall packages installed as editable from a network drive. (`#9452 <https://github.com/pypa/pip/issues/9452>`_)\n- Fix pip install issues using a proxy due to an inconsistency in how Requests is currently handling variable precedence in session. (`#9691 <https://github.com/pypa/pip/issues/9691>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.12.11\n- Upgrade distro to 1.7.0\n- Upgrade platformdirs to 2.5.2\n- Remove ``progress`` from vendored dependencies.\n- Upgrade ``pyparsing`` to 3.0.8 for startup performance improvements.\n- Upgrade rich to 12.2.0\n- Upgrade tomli to 2.0.1\n- Upgrade typing_extensions to 4.2.0\n\nImproved Documentation\n----------------------\n\n- Add more dedicated topic and reference pages to the documentation. (`#10899 <https://github.com/pypa/pip/issues/10899>`_)\n- Capitalise Y as the default for \"Proceed (y/n)?\" when uninstalling. (`#10936 <https://github.com/pypa/pip/issues/10936>`_)\n- Add ``scheme://`` requirement to ``--proxy`` option's description (`#10951 <https://github.com/pypa/pip/issues/10951>`_)\n- The wheel command now references the build interface section instead of stating the legacy\n  setuptools behavior as the default. (`#10972 <https://github.com/pypa/pip/issues/10972>`_)\n- Improved usefulness of ``pip config --help`` output. (`#11074 <https://github.com/pypa/pip/issues/11074>`_)\n\n\n22.0.4 (2022-03-06)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Drop the doctype check, that presented a warning for index pages that use non-compliant HTML 5. (`#10903 <https://github.com/pypa/pip/issues/10903>`_)\n\nVendored Libraries\n------------------\n\n- Downgrade distlib to 0.3.3.\n\n\n22.0.3 (2022-02-03)\n===================\n\nFeatures\n--------\n\n- Print the exception via ``rich.traceback``, when running with ``--debug``. (`#10791 <https://github.com/pypa/pip/issues/10791>`_)\n\nBug Fixes\n---------\n\n- Only calculate topological installation order, for packages that are going to be installed/upgraded.\n\n  This fixes an `AssertionError` that occurred when determining installation order, for a very specific combination of upgrading-already-installed-package + change of dependencies + fetching some packages from a package index. This combination was especially common in Read the Docs' builds. (`#10851 <https://github.com/pypa/pip/issues/10851>`_)\n- Use ``html.parser`` by default, instead of falling back to ``html5lib`` when ``--use-deprecated=html5lib`` is not passed. (`#10869 <https://github.com/pypa/pip/issues/10869>`_)\n\nImproved Documentation\n----------------------\n\n- Clarify that using per-requirement overrides disables the usage of wheels. (`#9674 <https://github.com/pypa/pip/issues/9674>`_)\n\n\n22.0.2 (2022-01-30)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Instead of failing on index pages that use non-compliant HTML 5, print a deprecation warning and fall back to ``html5lib``-based parsing for now. This simplifies the migration for non-compliant index pages, by letting such indexes function with a warning. (`#10847 <https://github.com/pypa/pip/issues/10847>`_)\n\n\n22.0.1 (2022-01-30)\n===================\n\nBug Fixes\n---------\n\n- Accept lowercase ``<!doctype html>`` on index pages. (`#10844 <https://github.com/pypa/pip/issues/10844>`_)\n- Properly handle links parsed by html5lib, when using ``--use-deprecated=html5lib``. (`#10846 <https://github.com/pypa/pip/issues/10846>`_)\n\n\n22.0 (2022-01-29)\n=================\n\nProcess\n-------\n\n- Completely replace :pypi:`tox` in our development workflow, with :pypi:`nox`.\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate alternative progress bar styles, leaving only ``on`` and ``off`` as available choices. (`#10462 <https://github.com/pypa/pip/issues/10462>`_)\n- Drop support for Python 3.6. (`#10641 <https://github.com/pypa/pip/issues/10641>`_)\n- Disable location mismatch warnings on Python versions prior to 3.10.\n\n  These warnings were helping identify potential issues as part of the sysconfig -> distutils transition, and we no longer need to rely on reports from older Python versions for information on the transition. (`#10840 <https://github.com/pypa/pip/issues/10840>`_)\n\nFeatures\n--------\n\n- Changed ``PackageFinder`` to parse HTML documents using the stdlib :class:`html.parser.HTMLParser` class instead of the ``html5lib`` package.\n\n  For now, the deprecated ``html5lib`` code remains and can be used with the ``--use-deprecated=html5lib`` command line option. However, it will be removed in a future pip release. (`#10291 <https://github.com/pypa/pip/issues/10291>`_)\n- Utilise ``rich`` for presenting pip's default download progress bar. (`#10462 <https://github.com/pypa/pip/issues/10462>`_)\n- Present a better error message when an invalid wheel file is encountered, providing more context where the invalid wheel file is. (`#10535 <https://github.com/pypa/pip/issues/10535>`_)\n- Documents the ``--require-virtualenv`` flag for ``pip install``. (`#10588 <https://github.com/pypa/pip/issues/10588>`_)\n- ``pip install <tab>`` autocompletes paths. (`#10646 <https://github.com/pypa/pip/issues/10646>`_)\n- Allow Python distributors to opt-out from or opt-in to the ``sysconfig`` installation scheme backend by setting ``sysconfig._PIP_USE_SYSCONFIG`` to ``True`` or ``False``. (`#10647 <https://github.com/pypa/pip/issues/10647>`_)\n- Make it possible to deselect tests requiring cryptography package on systems where it cannot be installed. (`#10686 <https://github.com/pypa/pip/issues/10686>`_)\n- Start using Rich for presenting error messages in a consistent format. (`#10703 <https://github.com/pypa/pip/issues/10703>`_)\n- Improve presentation of errors from subprocesses. (`#10705 <https://github.com/pypa/pip/issues/10705>`_)\n- Forward pip's verbosity configuration to VCS tools to control their output accordingly. (`#8819 <https://github.com/pypa/pip/issues/8819>`_)\n\nBug Fixes\n---------\n\n- Optimize installation order calculation to improve performance when installing requirements that form a complex dependency graph with a large amount of edges. (`#10557 <https://github.com/pypa/pip/issues/10557>`_)\n- When a package is requested by the user for upgrade, correctly identify that the extra-ed variant of that same package depended by another user-requested package is requesting the same package, and upgrade it accordingly. (`#10613 <https://github.com/pypa/pip/issues/10613>`_)\n- Prevent pip from installing yanked releases unless explicitly pinned via the ``==`` or ``===`` operators. (`#10617 <https://github.com/pypa/pip/issues/10617>`_)\n- Stop backtracking on build failures, by instead surfacing them to the user and aborting immediately. This behaviour provides more immediate feedback when a package cannot be built due to missing build dependencies or platform incompatibility. (`#10655 <https://github.com/pypa/pip/issues/10655>`_)\n- Silence ``Value for <location> does not match`` warning caused by an erroneous patch in Slackware-distributed Python 3.9. (`#10668 <https://github.com/pypa/pip/issues/10668>`_)\n- Fix an issue where pip did not consider dependencies with and without extras to be equal (`#9644 <https://github.com/pypa/pip/issues/9644>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.12.10\n- Upgrade certifi to 2021.10.8\n- Upgrade distlib to 0.3.4\n- Upgrade idna to 3.3\n- Upgrade msgpack to 1.0.3\n- Upgrade packaging to 21.3\n- Upgrade platformdirs to 2.4.1\n- Add pygments 2.11.2 as a vendored dependency.\n- Tree-trim unused portions of vendored pygments, to reduce the distribution size.\n- Upgrade pyparsing to 3.0.7\n- Upgrade Requests to 2.27.1\n- Upgrade resolvelib to 0.8.1\n- Add rich 11.0.0 as a vendored dependency.\n- Tree-trim unused portions of vendored rich, to reduce the distribution size.\n- Add typing_extensions 4.0.1 as a vendored dependency.\n- Upgrade urllib3 to 1.26.8\n\n\n21.3.1 (2021-10-22)\n===================\n\n\nBug Fixes\n---------\n\n\n- Always refuse installing or building projects that have no ``pyproject.toml`` nor\n  ``setup.py``. (`#10531 <https://github.com/pypa/pip/issues/10531>`_)\n- Tweak running-as-root detection, to check ``os.getuid`` if it exists, on Unix-y and non-Linux/non-MacOS machines. (`#10565 <https://github.com/pypa/pip/issues/10565>`_)\n- When installing projects with a ``pyproject.toml`` in editable mode, and the build\n  backend does not support :pep:`660`, prepare metadata using\n  ``prepare_metadata_for_build_wheel`` instead of ``setup.py egg_info``. Also, refuse\n  installing projects that only have a ``setup.cfg`` and no ``setup.py`` nor\n  ``pyproject.toml``. These restore the pre-21.3 behaviour. (`#10573 <https://github.com/pypa/pip/issues/10573>`_)\n- Restore compatibility of where configuration files are loaded from on MacOS (back to ``Library/Application Support/pip``, instead of ``Preferences/pip``). (`#10585 <https://github.com/pypa/pip/issues/10585>`_)\n\nVendored Libraries\n------------------\n\n\n- Upgrade pep517 to 0.12.0\n\n\n21.3 (2021-10-11)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Improve deprecation warning regarding the copying of source trees when installing from a local directory. (`#10128 <https://github.com/pypa/pip/issues/10128>`_)\n- Suppress location mismatch warnings when pip is invoked from a Python source\n  tree, so ``ensurepip`` does not emit warnings on CPython ``make install``. (`#10270 <https://github.com/pypa/pip/issues/10270>`_)\n- On Python 3.10 or later, the installation scheme backend has been changed to use\n  ``sysconfig``. This is to anticipate the deprecation of ``distutils`` in Python\n  3.10, and its scheduled removal in 3.12. For compatibility considerations, pip\n  installations running on Python 3.9 or lower will continue to use ``distutils``. (`#10358 <https://github.com/pypa/pip/issues/10358>`_)\n- Remove the ``--build-dir`` option and aliases, one last time. (`#10485 <https://github.com/pypa/pip/issues/10485>`_)\n- In-tree builds are now the default. ``--use-feature=in-tree-build`` is now\n  ignored. ``--use-deprecated=out-of-tree-build`` may be used temporarily to ease\n  the transition. (`#10495 <https://github.com/pypa/pip/issues/10495>`_)\n- Un-deprecate source distribution re-installation behaviour. (`#8711 <https://github.com/pypa/pip/issues/8711>`_)\n\nFeatures\n--------\n\n- Replace vendored appdirs with platformdirs. (`#10202 <https://github.com/pypa/pip/issues/10202>`_)\n- Support `PEP 610 <https://www.python.org/dev/peps/pep-0610/>`_ to detect\n  editable installs in ``pip freeze`` and  ``pip list``. The ``pip list`` column output\n  has a new ``Editable project location`` column, and the JSON output has a new\n  ``editable_project_location`` field. (`#10249 <https://github.com/pypa/pip/issues/10249>`_)\n- ``pip freeze`` will now always fallback to reporting the editable project\n  location when it encounters a VCS error while analyzing an editable\n  requirement. Before, it sometimes reported the requirement as non-editable. (`#10410 <https://github.com/pypa/pip/issues/10410>`_)\n- ``pip show`` now sorts ``Requires`` and ``Required-By`` alphabetically. (`#10422 <https://github.com/pypa/pip/issues/10422>`_)\n- Do not raise error when there are no files to remove with ``pip cache purge/remove``.\n  Instead log a warning and continue (to log that we removed 0 files). (`#10459 <https://github.com/pypa/pip/issues/10459>`_)\n- When backtracking during dependency resolution, prefer the dependencies which are involved in the most recent conflict. This can significantly reduce the amount of backtracking required. (`#10479 <https://github.com/pypa/pip/issues/10479>`_)\n- Cache requirement objects, to improve performance reducing reparses of requirement strings. (`#10550 <https://github.com/pypa/pip/issues/10550>`_)\n- Support editable installs for projects that have a ``pyproject.toml`` and use a\n  build backend that supports :pep:`660`. (`#8212 <https://github.com/pypa/pip/issues/8212>`_)\n- When a revision is specified in a Git URL, use git's partial clone feature to speed up source retrieval. (`#9086 <https://github.com/pypa/pip/issues/9086>`_)\n- Add a ``--debug`` flag, to enable a mode that doesn't log errors and propagates them to the top level instead. This is primarily to aid with debugging pip's crashes. (`#9349 <https://github.com/pypa/pip/issues/9349>`_)\n- If a host is explicitly specified as trusted by the user (via the --trusted-host option), cache HTTP responses from it in addition to HTTPS ones. (`#9498 <https://github.com/pypa/pip/issues/9498>`_)\n\nBug Fixes\n---------\n\n- Present a better error message, when a ``file:`` URL is not found. (`#10263 <https://github.com/pypa/pip/issues/10263>`_)\n- Fix the auth credential cache to allow for the case in which\n  the index url contains the username, but the password comes\n  from an external source, such as keyring. (`#10269 <https://github.com/pypa/pip/issues/10269>`_)\n- Fix double unescape of HTML ``data-requires-python`` and ``data-yanked`` attributes. (`#10378 <https://github.com/pypa/pip/issues/10378>`_)\n- New resolver: Fixes depth ordering of packages during resolution, e.g. a dependency 2 levels deep will be ordered before a dependency 3 levels deep. (`#10482 <https://github.com/pypa/pip/issues/10482>`_)\n- Correctly indent metadata preparation messages in pip output. (`#10524 <https://github.com/pypa/pip/issues/10524>`_)\n\nVendored Libraries\n------------------\n\n- Remove appdirs as a vendored dependency.\n- Upgrade distlib to 0.3.3\n- Upgrade distro to 1.6.0\n- Patch pkg_resources to use platformdirs rather than appdirs.\n- Add platformdirs as a vendored dependency.\n- Upgrade progress to 1.6\n- Upgrade resolvelib to 0.8.0\n- Upgrade urllib3 to 1.26.7\n\nImproved Documentation\n----------------------\n\n- Update links of setuptools as setuptools moved these documents. The Simple Repository link now points to PyPUG as that is the canonical place of packaging specification, and setuptools's ``easy_install`` is deprecated. (`#10430 <https://github.com/pypa/pip/issues/10430>`_)\n- Create a \"Build System Interface\" reference section, for documenting how pip interacts with build systems. (`#10497 <https://github.com/pypa/pip/issues/10497>`_)\n\n\n21.2.4 (2021-08-12)\n===================\n\nBug Fixes\n---------\n\n- Fix 3.6.0 compatibility in link comparison logic. (`#10280 <https://github.com/pypa/pip/issues/10280>`_)\n\n\n21.2.3 (2021-08-06)\n===================\n\nBug Fixes\n---------\n\n- Modify the ``sysconfig.get_preferred_scheme`` function check to be\n  compatible with CPython 3.10’s alphareleases. (`#10252 <https://github.com/pypa/pip/issues/10252>`_)\n\n\n21.2.2 (2021-07-31)\n===================\n\nBug Fixes\n---------\n\n- New resolver: When a package is specified with extras in constraints, and with\n  extras in non-constraint requirements, the resolver now correctly identifies the\n  constraint's existence and avoids backtracking. (`#10233 <https://github.com/pypa/pip/issues/10233>`_)\n\n\n21.2.1 (2021-07-25)\n===================\n\nProcess\n-------\n\n- The source distribution re-installation feature removal has been delayed to 21.3.\n\n\n21.2 (2021-07-24)\n=================\n\nProcess\n-------\n\n- ``pip freeze``, ``pip list``, and ``pip show`` no longer normalize underscore\n  (``_``) in distribution names to dash (``-``). This is a side effect of the\n  migration to ``importlib.metadata``, since the underscore-dash normalization\n  behavior is non-standard and specific to setuptools. This should not affect\n  other parts of pip (for example, when feeding the ``pip freeze`` result back\n  into ``pip install``) since pip internally performs standard PEP 503\n  normalization independently to setuptools.\n\nDeprecations and Removals\n-------------------------\n\n- Git version parsing is now done with regular expression to prepare for the\n  pending upstream removal of non-PEP-440 version parsing logic. (`#10117 <https://github.com/pypa/pip/issues/10117>`_)\n- Re-enable the \"Value for ... does not match\" location warnings to field a new\n  round of feedback for the ``distutils``-``sysconfig`` transition. (`#10151 <https://github.com/pypa/pip/issues/10151>`_)\n- Remove deprecated ``--find-links`` option in ``pip freeze`` (`#9069 <https://github.com/pypa/pip/issues/9069>`_)\n\nFeatures\n--------\n\n- New resolver: Loosen URL comparison logic when checking for direct URL reference\n  equivalency. The logic includes the following notable characteristics:\n\n  * The authentication part of the URL is explicitly ignored.\n  * Most of the fragment part, including ``egg=``, is explicitly ignored. Only\n    ``subdirectory=`` and hash values (e.g. ``sha256=``) are kept.\n  * The query part of the URL is parsed to allow ordering differences. (`#10002 <https://github.com/pypa/pip/issues/10002>`_)\n- Support TOML v1.0.0 syntax in ``pyproject.toml``. (`#10034 <https://github.com/pypa/pip/issues/10034>`_)\n- Added a warning message for errors caused due to Long Paths being disabled on Windows. (`#10045 <https://github.com/pypa/pip/issues/10045>`_)\n- Change the encoding of log file from default text encoding to UTF-8. (`#10071 <https://github.com/pypa/pip/issues/10071>`_)\n- Log the resolved commit SHA when installing a package from a Git repository. (`#10149 <https://github.com/pypa/pip/issues/10149>`_)\n- Add a warning when passing an invalid requirement to ``pip uninstall``. (`#4958 <https://github.com/pypa/pip/issues/4958>`_)\n- Add new subcommand ``pip index`` used to interact with indexes, and implement\n  ``pip index version`` to list available versions of a package. (`#7975 <https://github.com/pypa/pip/issues/7975>`_)\n- When pip is asked to uninstall a project without the dist-info/RECORD file\n  it will no longer traceback with FileNotFoundError,\n  but it will provide a better error message instead, such as::\n\n      ERROR: Cannot uninstall foobar 0.1, RECORD file not found. You might be able to recover from this via: 'pip install --force-reinstall --no-deps foobar==0.1'.\n\n  When dist-info/INSTALLER is present and contains some useful information, the info is included in the error message instead::\n\n      ERROR: Cannot uninstall foobar 0.1, RECORD file not found. Hint: The package was installed by rpm.\n\n  (`#8954 <https://github.com/pypa/pip/issues/8954>`_)\n- Add an additional level of verbosity. ``--verbose`` (and the shorthand ``-v``) now\n  contains significantly less output, and users that need complete full debug-level output\n  should pass it twice (``--verbose --verbose`` or ``-vv``). (`#9450 <https://github.com/pypa/pip/issues/9450>`_)\n- New resolver: The order of dependencies resolution has been tweaked to traverse\n  the dependency graph in a more breadth-first approach. (`#9455 <https://github.com/pypa/pip/issues/9455>`_)\n- Make \"yes\" the default choice in ``pip uninstall``'s prompt. (`#9686 <https://github.com/pypa/pip/issues/9686>`_)\n- Add a special error message when users forget the ``-r`` flag when installing. (`#9915 <https://github.com/pypa/pip/issues/9915>`_)\n- New resolver: A distribution's ``Requires-Python`` metadata is now checked\n  before its Python dependencies. This makes the resolver fail quicker when\n  there's an interpreter version conflict. (`#9925 <https://github.com/pypa/pip/issues/9925>`_)\n- Suppress \"not on PATH\" warning when ``--prefix`` is given. (`#9931 <https://github.com/pypa/pip/issues/9931>`_)\n- Include ``rustc`` version in pip's ``User-Agent``, when the system has ``rustc``. (`#9987 <https://github.com/pypa/pip/issues/9987>`_)\n\nBug Fixes\n---------\n\n- Update vendored six to 1.16.0 and urllib3 to 1.26.5 (`#10043 <https://github.com/pypa/pip/issues/10043>`_)\n- Correctly allow PEP 517 projects to be detected without warnings in ``pip freeze``. (`#10080 <https://github.com/pypa/pip/issues/10080>`_)\n- Strip leading slash from a ``file://`` URL built from an path with the Windows\n  drive notation. This fixes bugs where the ``file://`` URL cannot be correctly\n  used as requirement, constraint, or index URLs on Windows. (`#10115 <https://github.com/pypa/pip/issues/10115>`_)\n- New resolver: URL comparison logic now treats ``file://localhost/`` and\n  ``file:///`` as equivalent to conform to RFC 8089. (`#10162 <https://github.com/pypa/pip/issues/10162>`_)\n- Prefer credentials from the URL over the previously-obtained credentials from URLs of the same domain, so it is possible to use different credentials on the same index server for different ``--extra-index-url`` options. (`#3931 <https://github.com/pypa/pip/issues/3931>`_)\n- Fix extraction of files with utf-8 encoded paths from tars. (`#7667 <https://github.com/pypa/pip/issues/7667>`_)\n- Skip distutils configuration parsing on encoding errors. (`#8931 <https://github.com/pypa/pip/issues/8931>`_)\n- New resolver: Detect an unnamed requirement is user-specified (by building its\n  metadata for the project name) so it can be correctly ordered in the resolver. (`#9204 <https://github.com/pypa/pip/issues/9204>`_)\n- Fix :ref:`pip freeze` to output packages :ref:`installed from git <vcs support>`\n  in the correct ``git+protocol://git.example.com/MyProject#egg=MyProject`` format\n  rather than the old and no longer supported ``git+git@`` format. (`#9822 <https://github.com/pypa/pip/issues/9822>`_)\n- Fix warnings about install scheme selection for Python framework builds\n  distributed by Apple's Command Line Tools. (`#9844 <https://github.com/pypa/pip/issues/9844>`_)\n- Relax interpreter detection to quelch a location mismatch warning where PyPy\n  is deliberately breaking backwards compatibility. (`#9845 <https://github.com/pypa/pip/issues/9845>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2021.05.30.\n- Upgrade idna to 3.2.\n- Upgrade packaging to 21.0\n- Upgrade requests to 2.26.0.\n- Upgrade resolvelib to 0.7.1.\n- Upgrade urllib3 to 1.26.6.\n\n\n21.1.3 (2021-06-26)\n===================\n\nBug Fixes\n---------\n\n- Remove unused optional ``tornado`` import in vendored ``tenacity`` to prevent old versions of Tornado from breaking pip. (`#10020 <https://github.com/pypa/pip/issues/10020>`_)\n- Require ``setup.cfg``-only projects to be built via PEP 517, by requiring an explicit dependency on setuptools declared in pyproject.toml. (`#10031 <https://github.com/pypa/pip/issues/10031>`_)\n\n\n21.1.2 (2021-05-23)\n===================\n\nBug Fixes\n---------\n\n- New resolver: Correctly exclude an already installed package if its version is\n  known to be incompatible to stop the dependency resolution process with a clear\n  error message. (`#9841 <https://github.com/pypa/pip/issues/9841>`_)\n- Allow ZIP to archive files with timestamps earlier than 1980. (`#9910 <https://github.com/pypa/pip/issues/9910>`_)\n- Emit clearer error message when a project root does not contain either\n  ``pyproject.toml``, ``setup.py`` or ``setup.cfg``. (`#9944 <https://github.com/pypa/pip/issues/9944>`_)\n- Fix detection of existing standalone pip instance for PEP 517 builds. (`#9953 <https://github.com/pypa/pip/issues/9953>`_)\n\n\n21.1.1 (2021-04-30)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Temporarily set the new \"Value for ... does not match\" location warnings level\n  to *DEBUG*, to hide them from casual users. This prepares pip 21.1 for CPython\n  inclusion, while pip maintainers digest the first intake of location mismatch\n  issues for the ``distutils``-``sysconfig`` transition. (`#9912 <https://github.com/pypa/pip/issues/9912>`_)\n\nBug Fixes\n---------\n\n- This change fixes a bug on Python <=3.6.1 with a Typing feature added in 3.6.2 (`#9831 <https://github.com/pypa/pip/issues/9831>`_)\n- Fix compatibility between distutils and sysconfig when the project name is unknown outside of a virtual environment. (`#9838 <https://github.com/pypa/pip/issues/9838>`_)\n- Fix Python 3.6 compatibility when a PEP 517 build requirement itself needs to be\n  built in an isolated environment. (`#9878 <https://github.com/pypa/pip/issues/9878>`_)\n\n\n21.1 (2021-04-24)\n=================\n\nProcess\n-------\n\n- Start installation scheme migration from ``distutils`` to ``sysconfig``. A\n  warning is implemented to detect differences between the two implementations to\n  encourage user reports, so we can avoid breakages before they happen.\n\nFeatures\n--------\n\n- Add the ability for the new resolver to process URL constraints. (`#8253 <https://github.com/pypa/pip/issues/8253>`_)\n- Add a feature ``--use-feature=in-tree-build`` to build local projects in-place\n  when installing. This is expected to become the default behavior in pip 21.3;\n  see `Installing from local packages <https://pip.pypa.io/en/stable/user_guide/#installing-from-local-packages>`_\n  for more information. (`#9091 <https://github.com/pypa/pip/issues/9091>`_)\n- Bring back the \"(from versions: ...)\" message, that was shown on resolution failures. (`#9139 <https://github.com/pypa/pip/issues/9139>`_)\n- Add support for editable installs for project with only setup.cfg files. (`#9547 <https://github.com/pypa/pip/issues/9547>`_)\n- Improve performance when picking the best file from indexes during ``pip install``. (`#9748 <https://github.com/pypa/pip/issues/9748>`_)\n- Warn instead of erroring out when doing a PEP 517 build in presence of\n  ``--build-option``. Warn when doing a PEP 517 build in presence of\n  ``--global-option``. (`#9774 <https://github.com/pypa/pip/issues/9774>`_)\n\nBug Fixes\n---------\n\n- Fixed ``--target`` to work with ``--editable`` installs. (`#4390 <https://github.com/pypa/pip/issues/4390>`_)\n- Add a warning, discouraging the usage of pip as root, outside a virtual environment. (`#6409 <https://github.com/pypa/pip/issues/6409>`_)\n- Ignore ``.dist-info`` directories if the stem is not a valid Python distribution\n  name, so they don't show up in e.g. ``pip freeze``. (`#7269 <https://github.com/pypa/pip/issues/7269>`_)\n- Only query the keyring for URLs that actually trigger error 401.\n  This prevents an unnecessary keyring unlock prompt on every pip install\n  invocation (even with default index URL which is not password protected). (`#8090 <https://github.com/pypa/pip/issues/8090>`_)\n- Prevent packages already-installed alongside with pip to be injected into an\n  isolated build environment during build-time dependency population. (`#8214 <https://github.com/pypa/pip/issues/8214>`_)\n- Fix ``pip freeze`` permission denied error in order to display an understandable error message and offer solutions. (`#8418 <https://github.com/pypa/pip/issues/8418>`_)\n- Correctly uninstall script files (from setuptools' ``scripts`` argument), when installed with ``--user``. (`#8733 <https://github.com/pypa/pip/issues/8733>`_)\n- New resolver: When a requirement is requested both via a direct URL\n  (``req @ URL``) and via version specifier with extras (``req[extra]``), the\n  resolver will now be able to use the URL to correctly resolve the requirement\n  with extras. (`#8785 <https://github.com/pypa/pip/issues/8785>`_)\n- New resolver: Show relevant entries from user-supplied constraint files in the\n  error message to improve debuggability. (`#9300 <https://github.com/pypa/pip/issues/9300>`_)\n- Avoid parsing version to make the version check more robust against lousily\n  debundled downstream distributions. (`#9348 <https://github.com/pypa/pip/issues/9348>`_)\n- ``--user`` is no longer suggested incorrectly when pip fails with a permission\n  error in a virtual environment. (`#9409 <https://github.com/pypa/pip/issues/9409>`_)\n- Fix incorrect reporting on ``Requires-Python`` conflicts. (`#9541 <https://github.com/pypa/pip/issues/9541>`_)\n- Make wheel compatibility tag preferences more important than the build tag (`#9565 <https://github.com/pypa/pip/issues/9565>`_)\n- Fix pip to work with warnings converted to errors. (`#9779 <https://github.com/pypa/pip/issues/9779>`_)\n- **SECURITY**: Stop splitting on unicode separators in git references,\n  which could be maliciously used to install a different revision on the\n  repository. (`#9827 <https://github.com/pypa/pip/issues/9827>`_)\n\nVendored Libraries\n------------------\n\n- Update urllib3 to 1.26.4 to fix CVE-2021-28363\n- Remove contextlib2.\n- Upgrade idna to 3.1\n- Upgrade pep517 to 0.10.0\n- Upgrade vendored resolvelib to 0.7.0.\n- Upgrade tenacity to 7.0.0\n\nImproved Documentation\n----------------------\n\n- Update \"setuptools extras\" link to match upstream. (`#4822829F-6A45-4202-87BA-A80482DF6D4E <https://github.com/pypa/pip/issues/4822829F-6A45-4202-87BA-A80482DF6D4E>`_)\n- Improve SSL Certificate Verification docs and ``--cert`` help text. (`#6720 <https://github.com/pypa/pip/issues/6720>`_)\n- Add a section in the documentation to suggest solutions to the ``pip freeze`` permission denied issue. (`#8418 <https://github.com/pypa/pip/issues/8418>`_)\n- Add warning about ``--extra-index-url`` and dependency confusion (`#9647 <https://github.com/pypa/pip/issues/9647>`_)\n- Describe ``--upgrade-strategy`` and direct requirements explicitly; add a brief\n  example. (`#9692 <https://github.com/pypa/pip/issues/9692>`_)\n\n\n21.0.1 (2021-01-30)\n===================\n\nBug Fixes\n---------\n\n- commands: debug: Use packaging.version.parse to compare between versions. (`#9461 <https://github.com/pypa/pip/issues/9461>`_)\n- New resolver: Download and prepare a distribution only at the last possible\n  moment to avoid unnecessary network access when the same version is already\n  installed locally. (`#9516 <https://github.com/pypa/pip/issues/9516>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade packaging to 20.9\n\n\n21.0 (2021-01-23)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Drop support for Python 2. (`#6148 <https://github.com/pypa/pip/issues/6148>`_)\n- Remove support for legacy wheel cache entries that were created with pip\n  versions older than 20.0. (`#7502 <https://github.com/pypa/pip/issues/7502>`_)\n- Remove support for VCS pseudo URLs editable requirements. It was emitting\n  deprecation warning since version 20.0. (`#7554 <https://github.com/pypa/pip/issues/7554>`_)\n- Modernise the codebase after Python 2. (`#8802 <https://github.com/pypa/pip/issues/8802>`_)\n- Drop support for Python 3.5. (`#9189 <https://github.com/pypa/pip/issues/9189>`_)\n- Remove the VCS export feature that was used only with editable VCS\n  requirements and had correctness issues. (`#9338 <https://github.com/pypa/pip/issues/9338>`_)\n\nFeatures\n--------\n\n- Add ``--ignore-requires-python`` support to pip download. (`#1884 <https://github.com/pypa/pip/issues/1884>`_)\n- New resolver: Error message shown when a wheel contains inconsistent metadata\n  is made more helpful by including both values from the file name and internal\n  metadata. (`#9186 <https://github.com/pypa/pip/issues/9186>`_)\n\nBug Fixes\n---------\n\n- Fix a regression that made ``pip wheel`` do a VCS export instead of a VCS clone\n  for editable requirements. This broke VCS requirements that need the VCS\n  information to build correctly. (`#9273 <https://github.com/pypa/pip/issues/9273>`_)\n- Fix ``pip download`` of editable VCS requirements that need VCS information\n  to build correctly. (`#9337 <https://github.com/pypa/pip/issues/9337>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade msgpack to 1.0.2.\n- Upgrade requests to 2.25.1.\n\nImproved Documentation\n----------------------\n\n- Render the unreleased pip version change notes on the news page in docs. (`#9172 <https://github.com/pypa/pip/issues/9172>`_)\n- Fix broken email link in docs feedback banners. (`#9343 <https://github.com/pypa/pip/issues/9343>`_)\n\n\n20.3.4 (2021-01-23)\n===================\n\nFeatures\n--------\n\n- ``pip wheel`` now verifies the built wheel contains valid metadata, and can be\n  installed by a subsequent ``pip install``. This can be disabled with\n  ``--no-verify``. (`#9206 <https://github.com/pypa/pip/issues/9206>`_)\n- Improve presentation of XMLRPC errors in pip search. (`#9315 <https://github.com/pypa/pip/issues/9315>`_)\n\nBug Fixes\n---------\n\n- Fixed hanging VCS subprocess calls when the VCS outputs a large amount of data\n  on stderr. Restored logging of VCS errors that was inadvertently removed in pip\n  20.2. (`#8876 <https://github.com/pypa/pip/issues/8876>`_)\n- Fix error when an existing incompatibility is unable to be applied to a backtracked state. (`#9180 <https://github.com/pypa/pip/issues/9180>`_)\n- New resolver: Discard a faulty distribution, instead of quitting outright.\n  This implementation is taken from 20.2.2, with a fix that always makes the\n  resolver iterate through candidates from indexes lazily, to avoid downloading\n  candidates we do not need. (`#9203 <https://github.com/pypa/pip/issues/9203>`_)\n- New resolver: Discard a source distribution if it fails to generate metadata,\n  instead of quitting outright. This implementation is taken from 20.2.2, with a\n  fix that always makes the resolver iterate through candidates from indexes\n  lazily, to avoid downloading candidates we do not need. (`#9246 <https://github.com/pypa/pip/issues/9246>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade resolvelib to 0.5.4.\n\n\n20.3.3 (2020-12-15)\n===================\n\nBug Fixes\n---------\n\n- Revert \"Skip candidate not providing valid metadata\", as that caused pip to be overeager about downloading from the package index. (`#9264 <https://github.com/pypa/pip/issues/9264>`_)\n\n\n20.3.2 (2020-12-15)\n===================\n\nFeatures\n--------\n\n- New resolver: Resolve direct and pinned (``==`` or ``===``) requirements first\n  to improve resolver performance. (`#9185 <https://github.com/pypa/pip/issues/9185>`_)\n- Add a mechanism to delay resolving certain packages, and use it for setuptools. (`#9249 <https://github.com/pypa/pip/issues/9249>`_)\n\nBug Fixes\n---------\n\n- New resolver: The \"Requirement already satisfied\" log is not printed only once\n  for each package during resolution. (`#9117 <https://github.com/pypa/pip/issues/9117>`_)\n- Fix crash when logic for redacting authentication information from URLs\n  in ``--help`` is given a list of strings, instead of a single string. (`#9191 <https://github.com/pypa/pip/issues/9191>`_)\n- New resolver: Correctly implement PEP 592. Do not return yanked versions from\n  an index, unless the version range can only be satisfied by yanked candidates. (`#9203 <https://github.com/pypa/pip/issues/9203>`_)\n- New resolver: Make constraints also apply to package variants with extras, so\n  the resolver correctly avoids backtracking on them. (`#9232 <https://github.com/pypa/pip/issues/9232>`_)\n- New resolver: Discard a candidate if it fails to provide metadata from source,\n  or if the provided metadata is inconsistent, instead of quitting outright. (`#9246 <https://github.com/pypa/pip/issues/9246>`_)\n\nVendored Libraries\n------------------\n\n- Update vendoring to 20.8\n\nImproved Documentation\n----------------------\n\n- Update documentation to reflect that pip still uses legacy resolver by default in Python 2 environments. (`#9269 <https://github.com/pypa/pip/issues/9269>`_)\n\n\n20.3.1 (2020-12-03)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- The --build-dir option has been restored as a no-op, to soften the transition\n  for tools that still used it. (`#9193 <https://github.com/pypa/pip/issues/9193>`_)\n\n\n20.3 (2020-11-30)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove --unstable-feature flag as it has been deprecated. (`#9133 <https://github.com/pypa/pip/issues/9133>`_)\n\nFeatures\n--------\n\n- Add support for :pep:`600`: Future 'manylinux' Platform Tags for Portable Linux Built Distributions. (`#9077 <https://github.com/pypa/pip/issues/9077>`_)\n- The new resolver now resolves packages in a deterministic order. (`#9100 <https://github.com/pypa/pip/issues/9100>`_)\n- Add support for MacOS Big Sur compatibility tags. (`#9138 <https://github.com/pypa/pip/issues/9138>`_)\n\nBug Fixes\n---------\n\n- New Resolver: Rework backtracking and state management, to avoid getting stuck in an infinite loop. (`#9011 <https://github.com/pypa/pip/issues/9011>`_)\n- New resolver: Check version equality with ``packaging.version`` to avoid edge\n  cases if a wheel used different version normalization logic in its filename\n  and metadata. (`#9083 <https://github.com/pypa/pip/issues/9083>`_)\n- New resolver: Show each requirement in the conflict error message only once to reduce cluttering. (`#9101 <https://github.com/pypa/pip/issues/9101>`_)\n- Fix a regression that made ``pip wheel`` generate zip files of editable\n  requirements in the wheel directory. (`#9122 <https://github.com/pypa/pip/issues/9122>`_)\n- Fix ResourceWarning in VCS subprocesses (`#9156 <https://github.com/pypa/pip/issues/9156>`_)\n- Redact auth from URL in help message. (`#9160 <https://github.com/pypa/pip/issues/9160>`_)\n- New Resolver: editable installations are done, regardless of whether\n  the already-installed distribution is editable. (`#9169 <https://github.com/pypa/pip/issues/9169>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2020.11.8\n- Upgrade colorama to 0.4.4\n- Upgrade packaging to 20.7\n- Upgrade pep517 to 0.9.1\n- Upgrade requests to 2.25.0\n- Upgrade resolvelib to 0.5.3\n- Upgrade toml to 0.10.2\n- Upgrade urllib3 to 1.26.2\n\nImproved Documentation\n----------------------\n\n- Add a section to the User Guide to cover backtracking during dependency resolution. (`#9039 <https://github.com/pypa/pip/issues/9039>`_)\n- Reorder and revise installation instructions to make them easier to follow. (`#9131 <https://github.com/pypa/pip/issues/9131>`_)\n\n\n20.3b1 (2020-10-31)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- ``pip freeze`` will stop filtering the ``pip``, ``setuptools``, ``distribute`` and ``wheel`` packages from ``pip freeze`` output in a future version.\n  To keep the previous behavior, users should use the new ``--exclude`` option. (`#4256 <https://github.com/pypa/pip/issues/4256>`_)\n- Deprecate support for Python 3.5 (`#8181 <https://github.com/pypa/pip/issues/8181>`_)\n- Document that certain removals can be fast tracked. (`#8417 <https://github.com/pypa/pip/issues/8417>`_)\n- Document that Python versions are generally supported until PyPI usage falls below 5%. (`#8927 <https://github.com/pypa/pip/issues/8927>`_)\n- Deprecate ``--find-links`` option in ``pip freeze`` (`#9069 <https://github.com/pypa/pip/issues/9069>`_)\n\nFeatures\n--------\n\n- Add ``--exclude`` option to ``pip freeze`` and ``pip list`` commands to explicitly exclude packages from the output. (`#4256 <https://github.com/pypa/pip/issues/4256>`_)\n- Allow multiple values for --abi and --platform. (`#6121 <https://github.com/pypa/pip/issues/6121>`_)\n- Add option ``--format`` to subcommand ``list`` of ``pip  cache``, with ``abspath`` choice to output the full path of a wheel file. (`#8355 <https://github.com/pypa/pip/issues/8355>`_)\n- Improve error message friendliness when an environment has packages with\n  corrupted metadata. (`#8676 <https://github.com/pypa/pip/issues/8676>`_)\n- Make the ``setup.py install`` deprecation warning less noisy. We warn only\n  when ``setup.py install`` succeeded and ``setup.py bdist_wheel`` failed, as\n  situations where both fails are most probably irrelevant to this deprecation. (`#8752 <https://github.com/pypa/pip/issues/8752>`_)\n- Check the download directory for existing wheels to possibly avoid\n  fetching metadata when the ``fast-deps`` feature is used with\n  ``pip wheel`` and ``pip download``. (`#8804 <https://github.com/pypa/pip/issues/8804>`_)\n- When installing a git URL that refers to a commit that is not available locally\n  after git clone, attempt to fetch it from the remote. (`#8815 <https://github.com/pypa/pip/issues/8815>`_)\n- Include http subdirectory in ``pip cache info`` and ``pip cache purge`` commands. (`#8892 <https://github.com/pypa/pip/issues/8892>`_)\n- Cache package listings on index packages so they are guaranteed to stay stable\n  during a pip command session. This also improves performance when a index page\n  is accessed multiple times during the command session. (`#8905 <https://github.com/pypa/pip/issues/8905>`_)\n- New resolver: Tweak resolution logic to improve user experience when\n  user-supplied requirements conflict. (`#8924 <https://github.com/pypa/pip/issues/8924>`_)\n- Support Python 3.9. (`#8971 <https://github.com/pypa/pip/issues/8971>`_)\n- Log an informational message when backtracking takes multiple rounds on a specific package. (`#8975 <https://github.com/pypa/pip/issues/8975>`_)\n- Switch to the new dependency resolver by default. (`#9019 <https://github.com/pypa/pip/issues/9019>`_)\n- Remove the ``--build-dir`` option, as per the deprecation. (`#9049 <https://github.com/pypa/pip/issues/9049>`_)\n\nBug Fixes\n---------\n\n- Propagate ``--extra-index-url`` from requirements file properly to session auth,\n  so that keyring auth will work as expected. (`#8103 <https://github.com/pypa/pip/issues/8103>`_)\n- Allow specifying verbosity and quiet level via configuration files\n  and environment variables. Previously these options were treated as\n  boolean values when read from there while through CLI the level can be\n  specified. (`#8578 <https://github.com/pypa/pip/issues/8578>`_)\n- Only converts Windows path to unicode on Python 2 to avoid regressions when a\n  POSIX environment does not configure the file system encoding correctly. (`#8658 <https://github.com/pypa/pip/issues/8658>`_)\n- List downloaded distributions before exiting ``pip download``\n  when using the new resolver to make the behavior the same as\n  that on the legacy resolver. (`#8696 <https://github.com/pypa/pip/issues/8696>`_)\n- New resolver: Pick up hash declarations in constraints files and use them to\n  filter available distributions. (`#8792 <https://github.com/pypa/pip/issues/8792>`_)\n- Avoid polluting the destination directory by resolution artifacts\n  when the new resolver is used for ``pip download`` or ``pip wheel``. (`#8827 <https://github.com/pypa/pip/issues/8827>`_)\n- New resolver: If a package appears multiple times in user specification with\n  different ``--hash`` options, only hashes that present in all specifications\n  should be allowed. (`#8839 <https://github.com/pypa/pip/issues/8839>`_)\n- Tweak the output during dependency resolution in the new resolver. (`#8861 <https://github.com/pypa/pip/issues/8861>`_)\n- Correctly search for installed distributions in new resolver logic in order\n  to not miss packages (virtualenv packages from system-wide-packages for example) (`#8963 <https://github.com/pypa/pip/issues/8963>`_)\n- Do not fail in pip freeze when encountering a ``direct_url.json`` metadata file\n  with editable=True. Render it as a non-editable ``file://`` URL until modern\n  editable installs are standardized and supported. (`#8996 <https://github.com/pypa/pip/issues/8996>`_)\n\nVendored Libraries\n------------------\n\n- Fix devendoring instructions to explicitly state that ``vendor.txt`` should not be removed.\n  It is mandatory for ``pip debug`` command.\n\nImproved Documentation\n----------------------\n\n- Add documentation for '.netrc' support. (`#7231 <https://github.com/pypa/pip/issues/7231>`_)\n- Add OS tabs for OS-specific commands. (`#7311 <https://github.com/pypa/pip/issues/7311>`_)\n- Add note and example on keyring support for index basic-auth (`#8636 <https://github.com/pypa/pip/issues/8636>`_)\n- Added initial UX feedback widgets to docs. (`#8783 <https://github.com/pypa/pip/issues/8783>`_, `#8848 <https://github.com/pypa/pip/issues/8848>`_)\n- Add ux documentation (`#8807 <https://github.com/pypa/pip/issues/8807>`_)\n- Update user docs to reflect new resolver as default in 20.3. (`#9044 <https://github.com/pypa/pip/issues/9044>`_)\n- Improve migration guide to reflect changes in new resolver behavior. (`#9056 <https://github.com/pypa/pip/issues/9056>`_)\n\n\n20.2.4 (2020-10-16)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Document that certain removals can be fast tracked. (`#8417 <https://github.com/pypa/pip/issues/8417>`_)\n- Document that Python versions are generally supported until PyPI usage falls below 5%. (`#8927 <https://github.com/pypa/pip/issues/8927>`_)\n\nFeatures\n--------\n\n- New resolver: Avoid accessing indexes when the installed candidate is preferred\n  and considered good enough. (`#8023 <https://github.com/pypa/pip/issues/8023>`_)\n- Improve error message friendliness when an environment has packages with\n  corrupted metadata. (`#8676 <https://github.com/pypa/pip/issues/8676>`_)\n- Cache package listings on index packages so they are guaranteed to stay stable\n  during a pip command session. This also improves performance when a index page\n  is accessed multiple times during the command session. (`#8905 <https://github.com/pypa/pip/issues/8905>`_)\n- New resolver: Tweak resolution logic to improve user experience when\n  user-supplied requirements conflict. (`#8924 <https://github.com/pypa/pip/issues/8924>`_)\n\nBug Fixes\n---------\n\n- New resolver: Correctly respect ``Requires-Python`` metadata to reject\n  incompatible packages in ``--no-deps`` mode. (`#8758 <https://github.com/pypa/pip/issues/8758>`_)\n- New resolver: Pick up hash declarations in constraints files and use them to\n  filter available distributions. (`#8792 <https://github.com/pypa/pip/issues/8792>`_)\n- New resolver: If a package appears multiple times in user specification with\n  different ``--hash`` options, only hashes that present in all specifications\n  should be allowed. (`#8839 <https://github.com/pypa/pip/issues/8839>`_)\n\nImproved Documentation\n----------------------\n\n- Add ux documentation (`#8807 <https://github.com/pypa/pip/issues/8807>`_)\n\n\n20.2.3 (2020-09-08)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate support for Python 3.5 (`#8181 <https://github.com/pypa/pip/issues/8181>`_)\n\nFeatures\n--------\n\n- Make the ``setup.py install`` deprecation warning less noisy. We warn only\n  when ``setup.py install`` succeeded and ``setup.py bdist_wheel`` failed, as\n  situations where both fails are most probably irrelevant to this deprecation. (`#8752 <https://github.com/pypa/pip/issues/8752>`_)\n\n\n20.2.2 (2020-08-11)\n===================\n\nBug Fixes\n---------\n\n- Only attempt to use the keyring once and if it fails, don't try again.\n  This prevents spamming users with several keyring unlock prompts when they\n  cannot unlock or don't want to do so. (`#8090 <https://github.com/pypa/pip/issues/8090>`_)\n- Fix regression that distributions in system site-packages are not correctly\n  found when a virtual environment is configured with ``system-site-packages``\n  on. (`#8695 <https://github.com/pypa/pip/issues/8695>`_)\n- Disable caching for range requests, which causes corrupted wheels\n  when pip tries to obtain metadata using the feature ``fast-deps``. (`#8701 <https://github.com/pypa/pip/issues/8701>`_, `#8716 <https://github.com/pypa/pip/issues/8716>`_)\n- Always use UTF-8 to read ``pyvenv.cfg`` to match the built-in ``venv``. (`#8717 <https://github.com/pypa/pip/issues/8717>`_)\n- 2020 Resolver: Correctly handle marker evaluation in constraints and exclude\n  them if their markers do not match the current environment. (`#8724 <https://github.com/pypa/pip/issues/8724>`_)\n\n\n20.2.1 (2020-08-04)\n===================\n\nFeatures\n--------\n\n- Ignore require-virtualenv in ``pip list`` (`#8603 <https://github.com/pypa/pip/issues/8603>`_)\n\nBug Fixes\n---------\n\n- Correctly find already-installed distributions with dot (``.``) in the name\n  and uninstall them when needed. (`#8645 <https://github.com/pypa/pip/issues/8645>`_)\n- Trace a better error message on installation failure due to invalid ``.data``\n  files in wheels. (`#8654 <https://github.com/pypa/pip/issues/8654>`_)\n- Fix SVN version detection for alternative SVN distributions. (`#8665 <https://github.com/pypa/pip/issues/8665>`_)\n- New resolver: Correctly include the base package when specified with extras\n  in ``--no-deps`` mode. (`#8677 <https://github.com/pypa/pip/issues/8677>`_)\n- Use UTF-8 to handle ZIP archive entries on Python 2 according to PEP 427, so\n  non-ASCII paths can be resolved as expected. (`#8684 <https://github.com/pypa/pip/issues/8684>`_)\n\nImproved Documentation\n----------------------\n\n- Add details on old resolver deprecation and removal to migration documentation. (`#8371 <https://github.com/pypa/pip/issues/8371>`_)\n- Fix feature flag name in docs. (`#8660 <https://github.com/pypa/pip/issues/8660>`_)\n\n\n20.2 (2020-07-29)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate setup.py-based builds that do not generate an ``.egg-info`` directory. (`#6998 <https://github.com/pypa/pip/issues/6998>`_, `#8617 <https://github.com/pypa/pip/issues/8617>`_)\n- Disallow passing install-location-related arguments in ``--install-options``. (`#7309 <https://github.com/pypa/pip/issues/7309>`_)\n- Add deprecation warning for invalid requirements format \"base>=1.0[extra]\" (`#8288 <https://github.com/pypa/pip/issues/8288>`_)\n- Deprecate legacy setup.py install when building a wheel failed for source\n  distributions without pyproject.toml (`#8368 <https://github.com/pypa/pip/issues/8368>`_)\n- Deprecate -b/--build/--build-dir/--build-directory. Its current behaviour is confusing\n  and breaks in case different versions of the same distribution need to be built during\n  the resolution process. Using the TMPDIR/TEMP/TMP environment variable, possibly\n  combined with --no-clean covers known use cases. (`#8372 <https://github.com/pypa/pip/issues/8372>`_)\n- Remove undocumented and deprecated option ``--always-unzip`` (`#8408 <https://github.com/pypa/pip/issues/8408>`_)\n\nFeatures\n--------\n\n- Log debugging information about pip, in ``pip install --verbose``. (`#3166 <https://github.com/pypa/pip/issues/3166>`_)\n- Refine error messages to avoid showing Python tracebacks when an HTTP error occurs. (`#5380 <https://github.com/pypa/pip/issues/5380>`_)\n- Install wheel files directly instead of extracting them to a temp directory. (`#6030 <https://github.com/pypa/pip/issues/6030>`_)\n- Add a beta version of pip's next-generation dependency resolver.\n\n  Move pip's new resolver into beta, remove the\n  ``--unstable-feature=resolver`` flag, and enable the\n  ``--use-feature=2020-resolver`` flag. The new resolver is\n  significantly stricter and more consistent when it receives\n  incompatible instructions, and reduces support for certain kinds of\n  :ref:`Constraints Files`, so some workarounds and workflows may\n  break. More details about how to test and migrate, and how to report\n  issues, at :ref:`Resolver changes 2020` . Maintainers are preparing to\n  release pip 20.3, with the new resolver on by default, in October. (`#6536 <https://github.com/pypa/pip/issues/6536>`_)\n- Introduce a new ResolutionImpossible error, raised when pip encounters un-satisfiable dependency conflicts (`#8546 <https://github.com/pypa/pip/issues/8546>`_, `#8377 <https://github.com/pypa/pip/issues/8377>`_)\n- Add a subcommand ``debug`` to ``pip config`` to list available configuration sources and the key-value pairs defined in them. (`#6741 <https://github.com/pypa/pip/issues/6741>`_)\n- Warn if index pages have unexpected content-type (`#6754 <https://github.com/pypa/pip/issues/6754>`_)\n- Allow specifying ``--prefer-binary`` option in a requirements file (`#7693 <https://github.com/pypa/pip/issues/7693>`_)\n- Generate PEP 376 REQUESTED metadata for user supplied requirements installed\n  by pip. (`#7811 <https://github.com/pypa/pip/issues/7811>`_)\n- Warn if package url is a vcs or an archive url with invalid scheme (`#8128 <https://github.com/pypa/pip/issues/8128>`_)\n- Parallelize network operations in ``pip list``. (`#8504 <https://github.com/pypa/pip/issues/8504>`_)\n- Allow the new resolver to obtain dependency information through wheels\n  lazily downloaded using HTTP range requests.  To enable this feature,\n  invoke ``pip`` with ``--use-feature=fast-deps``. (`#8588 <https://github.com/pypa/pip/issues/8588>`_)\n- Support ``--use-feature`` in requirements files (`#8601 <https://github.com/pypa/pip/issues/8601>`_)\n\nBug Fixes\n---------\n\n- Use canonical package names while looking up already installed packages. (`#5021 <https://github.com/pypa/pip/issues/5021>`_)\n- Fix normalizing path on Windows when installing package on another logical disk. (`#7625 <https://github.com/pypa/pip/issues/7625>`_)\n- The VCS commands run by pip as subprocesses don't merge stdout and stderr anymore, improving the output parsing by subsequent commands. (`#7968 <https://github.com/pypa/pip/issues/7968>`_)\n- Correctly treat non-ASCII entry point declarations in wheels so they can be\n  installed on Windows. (`#8342 <https://github.com/pypa/pip/issues/8342>`_)\n- Update author email in config and tests to reflect decommissioning of pypa-dev list. (`#8454 <https://github.com/pypa/pip/issues/8454>`_)\n- Headers provided by wheels in .data directories are now correctly installed\n  into the user-provided locations, such as ``--prefix``, instead of the virtual\n  environment pip is running in. (`#8521 <https://github.com/pypa/pip/issues/8521>`_)\n\nVendored Libraries\n------------------\n\n- Vendored htmlib5 no longer imports deprecated xml.etree.cElementTree on Python 3.\n- Upgrade appdirs to 1.4.4\n- Upgrade certifi to 2020.6.20\n- Upgrade distlib to 0.3.1\n- Upgrade html5lib to 1.1\n- Upgrade idna to 2.10\n- Upgrade packaging to 20.4\n- Upgrade requests to 2.24.0\n- Upgrade six to 1.15.0\n- Upgrade toml to 0.10.1\n- Upgrade urllib3 to 1.25.9\n\nImproved Documentation\n----------------------\n\n- Add ``--no-input`` option to pip docs (`#7688 <https://github.com/pypa/pip/issues/7688>`_)\n- List of options supported in requirements file are extracted from source of truth,\n  instead of being maintained manually. (`#7908 <https://github.com/pypa/pip/issues/7908>`_)\n- Fix pip config docstring so that the subcommands render correctly in the docs (`#8072 <https://github.com/pypa/pip/issues/8072>`_)\n- replace links to the old pypa-dev mailing list with https://mail.python.org/mailman3/lists/distutils-sig.python.org/ (`#8353 <https://github.com/pypa/pip/issues/8353>`_)\n- Fix example for defining multiple values for options which support them (`#8373 <https://github.com/pypa/pip/issues/8373>`_)\n- Add documentation for the ResolutionImpossible error that helps the user fix dependency conflicts (`#8459 <https://github.com/pypa/pip/issues/8459>`_)\n- Add feature flags to docs (`#8512 <https://github.com/pypa/pip/issues/8512>`_)\n- Document how to install package extras from git branch and source distributions. (`#8576 <https://github.com/pypa/pip/issues/8576>`_)\n\n\n20.2b1 (2020-05-21)\n===================\n\nBug Fixes\n---------\n\n- Correctly treat wheels containing non-ASCII file contents so they can be\n  installed on Windows. (`#5712 <https://github.com/pypa/pip/issues/5712>`_)\n- Prompt the user for password if the keyring backend doesn't return one (`#7998 <https://github.com/pypa/pip/issues/7998>`_)\n\nImproved Documentation\n----------------------\n\n- Add GitHub issue template for reporting when the dependency resolver fails (`#8207 <https://github.com/pypa/pip/issues/8207>`_)\n\n20.1.1 (2020-05-19)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Revert building of local directories in place, restoring the pre-20.1\n  behaviour of copying to a temporary directory. (`#7555 <https://github.com/pypa/pip/issues/7555>`_)\n- Drop parallelization from ``pip list --outdated``. (`#8167 <https://github.com/pypa/pip/issues/8167>`_)\n\nBug Fixes\n---------\n\n- Fix metadata permission issues when umask has the executable bit set. (`#8164 <https://github.com/pypa/pip/issues/8164>`_)\n- Avoid unnecessary message about the wheel package not being installed\n  when a wheel would not have been built. Additionally, clarify the message. (`#8178 <https://github.com/pypa/pip/issues/8178>`_)\n\n\n20.1 (2020-04-28)\n=================\n\nProcess\n-------\n\n- Document that pip 21.0 will drop support for Python 2.7.\n\nFeatures\n--------\n\n- Add ``pip cache dir`` to show the cache directory. (`#7350 <https://github.com/pypa/pip/issues/7350>`_)\n\nBug Fixes\n---------\n\n- Abort pip cache commands early when cache is disabled. (`#8124 <https://github.com/pypa/pip/issues/8124>`_)\n- Correctly set permissions on metadata files during wheel installation,\n  to permit non-privileged users to read from system site-packages. (`#8139 <https://github.com/pypa/pip/issues/8139>`_)\n\n\n20.1b1 (2020-04-21)\n===================\n\nDeprecations and Removals\n-------------------------\n\n- Remove emails from AUTHORS.txt to prevent usage for spamming, and only populate names in AUTHORS.txt at time of release (`#5979 <https://github.com/pypa/pip/issues/5979>`_)\n- Remove deprecated ``--skip-requirements-regex`` option. (`#7297 <https://github.com/pypa/pip/issues/7297>`_)\n- Building of local directories is now done in place, instead of a temporary\n  location containing a copy of the directory tree. (`#7555 <https://github.com/pypa/pip/issues/7555>`_)\n- Remove unused ``tests/scripts/test_all_pip.py`` test script and the ``tests/scripts`` folder. (`#7680 <https://github.com/pypa/pip/issues/7680>`_)\n\nFeatures\n--------\n\n- pip now implements PEP 610, so ``pip freeze`` has better fidelity\n  in presence of distributions installed from Direct URL requirements. (`#609 <https://github.com/pypa/pip/issues/609>`_)\n- Add ``pip cache`` command for inspecting/managing pip's wheel cache. (`#6391 <https://github.com/pypa/pip/issues/6391>`_)\n- Raise error if ``--user`` and ``--target`` are used together in ``pip install`` (`#7249 <https://github.com/pypa/pip/issues/7249>`_)\n- Significantly improve performance when ``--find-links`` points to a very large HTML page. (`#7729 <https://github.com/pypa/pip/issues/7729>`_)\n- Indicate when wheel building is skipped, due to lack of the ``wheel`` package. (`#7768 <https://github.com/pypa/pip/issues/7768>`_)\n- Change default behaviour to always cache responses from trusted-host source. (`#7847 <https://github.com/pypa/pip/issues/7847>`_)\n- An alpha version of a new resolver is available via ``--unstable-feature=resolver``. (`#988 <https://github.com/pypa/pip/issues/988>`_)\n\nBug Fixes\n---------\n\n- Correctly freeze a VCS editable package when it is nested inside another VCS repository. (`#3988 <https://github.com/pypa/pip/issues/3988>`_)\n- Correctly handle ``%2F`` in URL parameters to avoid accidentally unescape them\n  into ``/``. (`#6446 <https://github.com/pypa/pip/issues/6446>`_)\n- Reject VCS URLs with an empty revision. (`#7402 <https://github.com/pypa/pip/issues/7402>`_)\n- Warn when an invalid URL is passed with ``--index-url`` (`#7430 <https://github.com/pypa/pip/issues/7430>`_)\n- Use better mechanism for handling temporary files, when recording metadata\n  about installed files (RECORD) and the installer (INSTALLER). (`#7699 <https://github.com/pypa/pip/issues/7699>`_)\n- Correctly detect global site-packages availability of virtual environments\n  created by PyPA’s virtualenv>=20.0. (`#7718 <https://github.com/pypa/pip/issues/7718>`_)\n- Remove current directory from ``sys.path`` when invoked as ``python -m pip <command>`` (`#7731 <https://github.com/pypa/pip/issues/7731>`_)\n- Stop failing uninstallation, when trying to remove non-existent files. (`#7856 <https://github.com/pypa/pip/issues/7856>`_)\n- Prevent an infinite recursion with ``pip wheel`` when ``$TMPDIR`` is within the source directory. (`#7872 <https://github.com/pypa/pip/issues/7872>`_)\n- Significantly speedup ``pip list --outdated`` by parallelizing index interaction. (`#7962 <https://github.com/pypa/pip/issues/7962>`_)\n- Improve Windows compatibility when detecting writability in folder. (`#8013 <https://github.com/pypa/pip/issues/8013>`_)\n\nVendored Libraries\n------------------\n\n- Update semi-supported debundling script to reflect that appdirs is vendored.\n- Add ResolveLib as a vendored dependency.\n- Upgrade certifi to 2020.04.05.1\n- Upgrade contextlib2 to 0.6.0.post1\n- Upgrade distro to 1.5.0.\n- Upgrade idna to 2.9.\n- Upgrade msgpack to 1.0.0.\n- Upgrade packaging to 20.3.\n- Upgrade pep517 to 0.8.2.\n- Upgrade pyparsing to 2.4.7.\n- Remove pytoml as a vendored dependency.\n- Upgrade requests to 2.23.0.\n- Add toml as a vendored dependency.\n- Upgrade urllib3 to 1.25.8.\n\nImproved Documentation\n----------------------\n\n- Emphasize that VCS URLs using git, git+git and git+http are insecure due to\n  lack of authentication and encryption (`#1983 <https://github.com/pypa/pip/issues/1983>`_)\n- Clarify the usage of --no-binary command. (`#3191 <https://github.com/pypa/pip/issues/3191>`_)\n- Clarify the usage of freeze command in the example of Using pip in your program (`#7008 <https://github.com/pypa/pip/issues/7008>`_)\n- Add a \"Copyright\" page. (`#7767 <https://github.com/pypa/pip/issues/7767>`_)\n- Added example of defining multiple values for options which support them (`#7803 <https://github.com/pypa/pip/issues/7803>`_)\n\n\n20.0.2 (2020-01-24)\n===================\n\nBug Fixes\n---------\n\n- Fix a regression in generation of compatibility tags. (`#7626 <https://github.com/pypa/pip/issues/7626>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade packaging to 20.1\n\n\n20.0.1 (2020-01-21)\n===================\n\nBug Fixes\n---------\n\n- Rename an internal module, to avoid ImportErrors due to improper uninstallation. (`#7621 <https://github.com/pypa/pip/issues/7621>`_)\n\n\n20.0 (2020-01-21)\n=================\n\nProcess\n-------\n\n- Switch to a dedicated CLI tool for vendoring dependencies.\n\nDeprecations and Removals\n-------------------------\n\n- Remove wheel tag calculation from pip and use ``packaging.tags``. This\n  should provide more tags ordered better than in prior releases. (`#6908 <https://github.com/pypa/pip/issues/6908>`_)\n- Deprecate setup.py-based builds that do not generate an ``.egg-info`` directory. (`#6998 <https://github.com/pypa/pip/issues/6998>`_)\n- The pip>=20 wheel cache is not retro-compatible with previous versions. Until\n  pip 21.0, pip will continue to take advantage of existing legacy cache\n  entries. (`#7296 <https://github.com/pypa/pip/issues/7296>`_)\n- Deprecate undocumented ``--skip-requirements-regex`` option. (`#7297 <https://github.com/pypa/pip/issues/7297>`_)\n- Deprecate passing install-location-related options via ``--install-option``. (`#7309 <https://github.com/pypa/pip/issues/7309>`_)\n- Use literal \"abi3\" for wheel tag on CPython 3.x, to align with PEP 384\n  which only defines it for this platform. (`#7327 <https://github.com/pypa/pip/issues/7327>`_)\n- Remove interpreter-specific major version tag e.g. ``cp3-none-any``\n  from consideration. This behavior was not documented strictly, and this\n  tag in particular is `not useful <https://snarky.ca/the-challenges-in-designing-a-library-for-pep-425/>`_.\n  Anyone with a use case can create an issue with pypa/packaging. (`#7355 <https://github.com/pypa/pip/issues/7355>`_)\n- Wheel processing no longer permits wheels containing more than one top-level\n  .dist-info directory. (`#7487 <https://github.com/pypa/pip/issues/7487>`_)\n- Support for the ``git+git@`` form of VCS requirement is being deprecated and\n  will be removed in pip 21.0. Switch to ``git+https://`` or\n  ``git+ssh://``. ``git+git://`` also works but its use is discouraged as it is\n  insecure. (`#7543 <https://github.com/pypa/pip/issues/7543>`_)\n\nFeatures\n--------\n\n- Default to doing a user install (as if ``--user`` was passed) when the main\n  site-packages directory is not writeable and user site-packages are enabled. (`#1668 <https://github.com/pypa/pip/issues/1668>`_)\n- Warn if a path in PATH starts with tilde during ``pip install``. (`#6414 <https://github.com/pypa/pip/issues/6414>`_)\n- Cache wheels built from Git requirements that are considered immutable,\n  because they point to a commit hash. (`#6640 <https://github.com/pypa/pip/issues/6640>`_)\n- Add option ``--no-python-version-warning`` to silence warnings\n  related to deprecation of Python versions. (`#6673 <https://github.com/pypa/pip/issues/6673>`_)\n- Cache wheels that ``pip wheel`` built locally, matching what\n  ``pip install`` does. This particularly helps performance in workflows where\n  ``pip wheel`` is used for `building before installing\n  <https://pip.pypa.io/en/stable/user_guide/#installing-from-local-packages>`_.\n  Users desiring the original behavior can use ``pip wheel --no-cache-dir``. (`#6852 <https://github.com/pypa/pip/issues/6852>`_)\n- Display CA information in ``pip debug``. (`#7146 <https://github.com/pypa/pip/issues/7146>`_)\n- Show only the filename (instead of full URL), when downloading from PyPI. (`#7225 <https://github.com/pypa/pip/issues/7225>`_)\n- Suggest a more robust command to upgrade pip itself to avoid confusion when the\n  current pip command is not available as ``pip``. (`#7376 <https://github.com/pypa/pip/issues/7376>`_)\n- Define all old pip console script entrypoints to prevent import issues in\n  stale wrapper scripts. (`#7498 <https://github.com/pypa/pip/issues/7498>`_)\n- The build step of ``pip wheel`` now builds all wheels to a cache first,\n  then copies them to the wheel directory all at once.\n  Before, it built them to a temporary directory and moved\n  them to the wheel directory one by one. (`#7517 <https://github.com/pypa/pip/issues/7517>`_)\n- Expand ``~`` prefix to user directory in path options, configs, and\n  environment variables. Values that may be either URL or path are not\n  currently supported, to avoid ambiguity:\n\n  * ``--find-links``\n  * ``--constraint``, ``-c``\n  * ``--requirement``, ``-r``\n  * ``--editable``, ``-e`` (`#980 <https://github.com/pypa/pip/issues/980>`_)\n\nBug Fixes\n---------\n\n- Correctly handle system site-packages, in virtual environments created with venv (PEP 405). (`#5702 <https://github.com/pypa/pip/issues/5702>`_, `#7155 <https://github.com/pypa/pip/issues/7155>`_)\n- Fix case sensitive comparison of pip freeze when used with -r option. (`#5716 <https://github.com/pypa/pip/issues/5716>`_)\n- Enforce PEP 508 requirement format in ``pyproject.toml``\n  ``build-system.requires``. (`#6410 <https://github.com/pypa/pip/issues/6410>`_)\n- Make ``ensure_dir()`` also ignore ``ENOTEMPTY`` as seen on Windows. (`#6426 <https://github.com/pypa/pip/issues/6426>`_)\n- Fix building packages which specify ``backend-path`` in pyproject.toml. (`#6599 <https://github.com/pypa/pip/issues/6599>`_)\n- Do not attempt to run ``setup.py clean`` after a ``pep517`` build error,\n  since a ``setup.py`` may not exist in that case. (`#6642 <https://github.com/pypa/pip/issues/6642>`_)\n- Fix passwords being visible in the index-url in\n  \"Downloading <url>\" message. (`#6783 <https://github.com/pypa/pip/issues/6783>`_)\n- Change method from shutil.remove to shutil.rmtree in noxfile.py. (`#7191 <https://github.com/pypa/pip/issues/7191>`_)\n- Skip running tests which require subversion, when svn isn't installed (`#7193 <https://github.com/pypa/pip/issues/7193>`_)\n- Fix not sending client certificates when using ``--trusted-host``. (`#7207 <https://github.com/pypa/pip/issues/7207>`_)\n- Make sure ``pip wheel`` never outputs pure python wheels with a\n  python implementation tag. Better fix/workaround for\n  `#3025 <https://github.com/pypa/pip/issues/3025>`_ by\n  using a per-implementation wheel cache instead of caching pure python\n  wheels with an implementation tag in their name. (`#7296 <https://github.com/pypa/pip/issues/7296>`_)\n- Include ``subdirectory`` URL fragments in cache keys. (`#7333 <https://github.com/pypa/pip/issues/7333>`_)\n- Fix typo in warning message when any of ``--build-option``, ``--global-option``\n  and ``--install-option`` is used in requirements.txt (`#7340 <https://github.com/pypa/pip/issues/7340>`_)\n- Fix the logging of cached HTTP response shown as downloading. (`#7393 <https://github.com/pypa/pip/issues/7393>`_)\n- Effectively disable the wheel cache when it is not writable, as is the\n  case with the http cache. (`#7488 <https://github.com/pypa/pip/issues/7488>`_)\n- Correctly handle relative cache directory provided via --cache-dir. (`#7541 <https://github.com/pypa/pip/issues/7541>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade CacheControl to 0.12.5\n- Upgrade certifi to 2019.9.11\n- Upgrade colorama to 0.4.1\n- Upgrade distlib to 0.2.9.post0\n- Upgrade ipaddress to 1.0.22\n- Update packaging to 20.0.\n- Upgrade pkg_resources (via setuptools) to 44.0.0\n- Upgrade pyparsing to 2.4.2\n- Upgrade six to 1.12.0\n- Upgrade urllib3 to 1.25.6\n\nImproved Documentation\n----------------------\n\n- Document that \"coding: utf-8\" is supported in requirements.txt (`#7182 <https://github.com/pypa/pip/issues/7182>`_)\n- Explain how to get pip's source code in `Getting Started <https://pip.pypa.io/en/stable/development/getting-started/>`_ (`#7197 <https://github.com/pypa/pip/issues/7197>`_)\n- Describe how basic authentication credentials in URLs work. (`#7201 <https://github.com/pypa/pip/issues/7201>`_)\n- Add more clear installation instructions (`#7222 <https://github.com/pypa/pip/issues/7222>`_)\n- Fix documentation links for index options (`#7347 <https://github.com/pypa/pip/issues/7347>`_)\n- Better document the requirements file format (`#7385 <https://github.com/pypa/pip/issues/7385>`_)\n\n\n19.3.1 (2019-10-17)\n===================\n\nFeatures\n--------\n\n- Document Python 3.8 support. (`#7219 <https://github.com/pypa/pip/issues/7219>`_)\n\nBug Fixes\n---------\n\n- Fix bug that prevented installation of PEP 517 packages without ``setup.py``. (`#6606 <https://github.com/pypa/pip/issues/6606>`_)\n\n\n19.3 (2019-10-14)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Remove undocumented support for un-prefixed URL requirements pointing\n  to SVN repositories. Users relying on this can get the original behavior\n  by prefixing their URL with ``svn+`` (which is backwards-compatible). (`#7037 <https://github.com/pypa/pip/issues/7037>`_)\n- Remove the deprecated ``--venv`` option from ``pip config``. (`#7163 <https://github.com/pypa/pip/issues/7163>`_)\n\nFeatures\n--------\n\n- Print a better error message when ``--no-binary`` or ``--only-binary`` is given\n  an argument starting with ``-``. (`#3191 <https://github.com/pypa/pip/issues/3191>`_)\n- Make ``pip show`` warn about packages not found. (`#6858 <https://github.com/pypa/pip/issues/6858>`_)\n- Support including a port number in ``--trusted-host`` for both HTTP and HTTPS. (`#6886 <https://github.com/pypa/pip/issues/6886>`_)\n- Redact single-part login credentials from URLs in log messages. (`#6891 <https://github.com/pypa/pip/issues/6891>`_)\n- Implement manylinux2014 platform tag support.  manylinux2014 is the successor\n  to manylinux2010.  It allows carefully compiled binary wheels to be installed\n  on compatible Linux platforms.  The manylinux2014 platform tag definition can\n  be found in `PEP599 <https://www.python.org/dev/peps/pep-0599/>`_. (`#7102 <https://github.com/pypa/pip/issues/7102>`_)\n\nBug Fixes\n---------\n\n- Abort installation if any archive contains a file which would be placed\n  outside the extraction location. (`#3907 <https://github.com/pypa/pip/issues/3907>`_)\n- pip's CLI completion code no longer prints a Traceback if it is interrupted. (`#3942 <https://github.com/pypa/pip/issues/3942>`_)\n- Correct inconsistency related to the ``hg+file`` scheme. (`#4358 <https://github.com/pypa/pip/issues/4358>`_)\n- Fix ``rmtree_errorhandler`` to skip non-existing directories. (`#4910 <https://github.com/pypa/pip/issues/4910>`_)\n- Ignore errors copying socket files for local source installs (in Python 3). (`#5306 <https://github.com/pypa/pip/issues/5306>`_)\n- Fix requirement line parser to correctly handle PEP 440 requirements with a URL\n  pointing to an archive file. (`#6202 <https://github.com/pypa/pip/issues/6202>`_)\n- The ``pip-wheel-metadata`` directory does not need to persist between invocations of pip, use a temporary directory instead of the current ``setup.py`` directory. (`#6213 <https://github.com/pypa/pip/issues/6213>`_)\n- Fix ``--trusted-host`` processing under HTTPS to trust any port number used\n  with the host. (`#6705 <https://github.com/pypa/pip/issues/6705>`_)\n- Switch to new ``distlib`` wheel script template. This should be functionally\n  equivalent for end users. (`#6763 <https://github.com/pypa/pip/issues/6763>`_)\n- Skip copying .tox and .nox directories to temporary build directories (`#6770 <https://github.com/pypa/pip/issues/6770>`_)\n- Fix handling of tokens (single part credentials) in URLs. (`#6795 <https://github.com/pypa/pip/issues/6795>`_)\n- Fix a regression that caused ``~`` expansion not to occur in ``--find-links``\n  paths. (`#6804 <https://github.com/pypa/pip/issues/6804>`_)\n- Fix bypassed pip upgrade warning on Windows. (`#6841 <https://github.com/pypa/pip/issues/6841>`_)\n- Fix 'm' flag erroneously being appended to ABI tag in Python 3.8 on platforms that do not provide SOABI (`#6885 <https://github.com/pypa/pip/issues/6885>`_)\n- Hide security-sensitive strings like passwords in log messages related to\n  version control system (aka VCS) command invocations. (`#6890 <https://github.com/pypa/pip/issues/6890>`_)\n- Correctly uninstall symlinks that were installed in a virtualenv,\n  by tools such as ``flit install --symlink``. (`#6892 <https://github.com/pypa/pip/issues/6892>`_)\n- Don't fail installation using pip.exe on Windows when pip wouldn't be upgraded. (`#6924 <https://github.com/pypa/pip/issues/6924>`_)\n- Use canonical distribution names when computing ``Required-By`` in ``pip show``. (`#6947 <https://github.com/pypa/pip/issues/6947>`_)\n- Don't use hardlinks for locking selfcheck state file. (`#6954 <https://github.com/pypa/pip/issues/6954>`_)\n- Ignore \"require_virtualenv\" in ``pip config`` (`#6991 <https://github.com/pypa/pip/issues/6991>`_)\n- Fix ``pip freeze`` not showing correct entry for mercurial packages that use subdirectories. (`#7071 <https://github.com/pypa/pip/issues/7071>`_)\n- Fix a crash when ``sys.stdin`` is set to ``None``, such as on AWS Lambda. (`#7118 <https://github.com/pypa/pip/issues/7118>`_, `#7119 <https://github.com/pypa/pip/issues/7119>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2019.9.11\n- Add contextlib2 0.6.0 as a vendored dependency.\n- Remove Lockfile as a vendored dependency.\n- Upgrade msgpack to 0.6.2\n- Upgrade packaging to 19.2\n- Upgrade pep517 to 0.7.0\n- Upgrade pyparsing to 2.4.2\n- Upgrade pytoml to 0.1.21\n- Upgrade setuptools to 41.4.0\n- Upgrade urllib3 to 1.25.6\n\nImproved Documentation\n----------------------\n\n- Document caveats for UNC paths in uninstall and add .pth unit tests. (`#6516 <https://github.com/pypa/pip/issues/6516>`_)\n- Add architectural overview documentation. (`#6637 <https://github.com/pypa/pip/issues/6637>`_)\n- Document that ``--ignore-installed`` is dangerous. (`#6794 <https://github.com/pypa/pip/issues/6794>`_)\n\n\n19.2.3 (2019-08-25)\n===================\n\nBug Fixes\n---------\n\n- Fix 'm' flag erroneously being appended to ABI tag in Python 3.8 on platforms that do not provide SOABI (`#6885 <https://github.com/pypa/pip/issues/6885>`_)\n\n\n19.2.2 (2019-08-11)\n===================\n\nBug Fixes\n---------\n\n- Fix handling of tokens (single part credentials) in URLs. (`#6795 <https://github.com/pypa/pip/issues/6795>`_)\n- Fix a regression that caused ``~`` expansion not to occur in ``--find-links``\n  paths. (`#6804 <https://github.com/pypa/pip/issues/6804>`_)\n\n\n19.2.1 (2019-07-23)\n===================\n\nBug Fixes\n---------\n\n- Fix a ``NoneType`` ``AttributeError`` when evaluating hashes and no hashes\n  are provided. (`#6772 <https://github.com/pypa/pip/issues/6772>`_)\n\n\n19.2 (2019-07-22)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Drop support for EOL Python 3.4. (`#6685 <https://github.com/pypa/pip/issues/6685>`_)\n- Improve deprecation messages to include the version in which the functionality will be removed. (`#6549 <https://github.com/pypa/pip/issues/6549>`_)\n\nFeatures\n--------\n\n- Credentials will now be loaded using `keyring` when installed. (`#5948 <https://github.com/pypa/pip/issues/5948>`_)\n- Fully support using ``--trusted-host`` inside requirements files. (`#3799 <https://github.com/pypa/pip/issues/3799>`_)\n- Update timestamps in pip's ``--log`` file to include milliseconds. (`#6587 <https://github.com/pypa/pip/issues/6587>`_)\n- Respect whether a file has been marked as \"yanked\" from a simple repository\n  (see `PEP 592 <https://www.python.org/dev/peps/pep-0592/>`__ for details). (`#6633 <https://github.com/pypa/pip/issues/6633>`_)\n- When choosing candidates to install, prefer candidates with a hash matching\n  one of the user-provided hashes. (`#5874 <https://github.com/pypa/pip/issues/5874>`_)\n- Improve the error message when ``METADATA`` or ``PKG-INFO`` is None when\n  accessing metadata. (`#5082 <https://github.com/pypa/pip/issues/5082>`_)\n- Add a new command ``pip debug`` that can display e.g. the list of compatible\n  tags for the current Python. (`#6638 <https://github.com/pypa/pip/issues/6638>`_)\n- Display hint on installing with --pre when search results include pre-release versions. (`#5169 <https://github.com/pypa/pip/issues/5169>`_)\n- Report to Warehouse that pip is running under CI if the ``PIP_IS_CI`` environment variable is set. (`#5499 <https://github.com/pypa/pip/issues/5499>`_)\n- Allow ``--python-version`` to be passed as a dotted version string (e.g.\n  ``3.7`` or ``3.7.3``). (`#6585 <https://github.com/pypa/pip/issues/6585>`_)\n- Log the final filename and SHA256 of a ``.whl`` file when done building a\n  wheel. (`#5908 <https://github.com/pypa/pip/issues/5908>`_)\n- Include the wheel's tags in the log message explanation when a candidate\n  wheel link is found incompatible. (`#6121 <https://github.com/pypa/pip/issues/6121>`_)\n- Add a ``--path`` argument to ``pip freeze`` to support ``--target``\n  installations. (`#6404 <https://github.com/pypa/pip/issues/6404>`_)\n- Add a ``--path`` argument to ``pip list`` to support ``--target``\n  installations. (`#6551 <https://github.com/pypa/pip/issues/6551>`_)\n\nBug Fixes\n---------\n\n- Set ``sys.argv[0]`` to the underlying ``setup.py`` when invoking ``setup.py``\n  via the setuptools shim so setuptools doesn't think the path is ``-c``. (`#1890 <https://github.com/pypa/pip/issues/1890>`_)\n- Update ``pip download`` to respect the given ``--python-version`` when checking\n  ``\"Requires-Python\"``. (`#5369 <https://github.com/pypa/pip/issues/5369>`_)\n- Respect ``--global-option`` and ``--install-option`` when installing from\n  a version control url (e.g. ``git``). (`#5518 <https://github.com/pypa/pip/issues/5518>`_)\n- Make the \"ascii\" progress bar really be \"ascii\" and not Unicode. (`#5671 <https://github.com/pypa/pip/issues/5671>`_)\n- Fail elegantly when trying to set an incorrectly formatted key in config. (`#5963 <https://github.com/pypa/pip/issues/5963>`_)\n- Prevent DistutilsOptionError when prefix is indicated in the global environment and `--target` is used. (`#6008 <https://github.com/pypa/pip/issues/6008>`_)\n- Fix ``pip install`` to respect ``--ignore-requires-python`` when evaluating\n  links. (`#6371 <https://github.com/pypa/pip/issues/6371>`_)\n- Fix a debug log message when freezing an editable, non-version controlled\n  requirement. (`#6383 <https://github.com/pypa/pip/issues/6383>`_)\n- Extend to Subversion 1.8+ the behavior of calling Subversion in\n  interactive mode when pip is run interactively. (`#6386 <https://github.com/pypa/pip/issues/6386>`_)\n- Prevent ``pip install <url>`` from permitting directory traversal if e.g.\n  a malicious server sends a ``Content-Disposition`` header with a filename\n  containing ``../`` or ``..\\\\``. (`#6413 <https://github.com/pypa/pip/issues/6413>`_)\n- Hide passwords in output when using ``--find-links``. (`#6489 <https://github.com/pypa/pip/issues/6489>`_)\n- Include more details in the log message if ``pip freeze`` can't generate a\n  requirement string for a particular distribution. (`#6513 <https://github.com/pypa/pip/issues/6513>`_)\n- Add the line number and file location to the error message when reading an\n  invalid requirements file in certain situations. (`#6527 <https://github.com/pypa/pip/issues/6527>`_)\n- Prefer ``os.confstr`` to ``ctypes`` when extracting glibc version info. (`#6543 <https://github.com/pypa/pip/issues/6543>`_, `#6675 <https://github.com/pypa/pip/issues/6675>`_)\n- Improve error message printed when an invalid editable requirement is provided. (`#6648 <https://github.com/pypa/pip/issues/6648>`_)\n- Improve error message formatting when a command errors out in a subprocess. (`#6651 <https://github.com/pypa/pip/issues/6651>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2019.6.16\n- Upgrade distlib to 0.2.9.post0\n- Upgrade msgpack to 0.6.1\n- Upgrade requests to 2.22.0\n- Upgrade urllib3 to 1.25.3\n- Patch vendored html5lib, to prefer using `collections.abc` where possible.\n\nImproved Documentation\n----------------------\n\n- Document how Python 2.7 support will be maintained. (`#6726 <https://github.com/pypa/pip/issues/6726>`_)\n- Upgrade Sphinx version used to build documentation. (`#6471 <https://github.com/pypa/pip/issues/6471>`_)\n- Fix generation of subcommand manpages. (`#6724 <https://github.com/pypa/pip/issues/6724>`_)\n- Mention that pip can install from git refs. (`#6512 <https://github.com/pypa/pip/issues/6512>`_)\n- Replace a failing example of pip installs with extras with a working one. (`#4733 <https://github.com/pypa/pip/issues/4733>`_)\n\n19.1.1 (2019-05-06)\n===================\n\nFeatures\n--------\n\n- Restore ``pyproject.toml`` handling to how it was with pip 19.0.3 to prevent\n  the need to add ``--no-use-pep517`` when installing in editable mode. (`#6434 <https://github.com/pypa/pip/issues/6434>`_)\n\nBug Fixes\n---------\n\n- Fix a regression that caused `@` to be quoted in pypiserver links.\n  This interfered with parsing the revision string from VCS urls. (`#6440 <https://github.com/pypa/pip/issues/6440>`_)\n\n\n19.1 (2019-04-23)\n=================\n\nFeatures\n--------\n\n- Configuration files may now also be stored under ``sys.prefix`` (`#5060 <https://github.com/pypa/pip/issues/5060>`_)\n- Avoid creating an unnecessary local clone of a Bazaar branch when exporting. (`#5443 <https://github.com/pypa/pip/issues/5443>`_)\n- Include in pip's User-Agent string whether it looks like pip is running\n  under CI. (`#5499 <https://github.com/pypa/pip/issues/5499>`_)\n- A custom (JSON-encoded) string can now be added to pip's User-Agent\n  using the ``PIP_USER_AGENT_USER_DATA`` environment variable. (`#5549 <https://github.com/pypa/pip/issues/5549>`_)\n- For consistency, passing ``--no-cache-dir`` no longer affects whether wheels\n  will be built.  In this case, a temporary directory is used. (`#5749 <https://github.com/pypa/pip/issues/5749>`_)\n- Command arguments in ``subprocess`` log messages are now quoted using\n  ``shlex.quote()``. (`#6290 <https://github.com/pypa/pip/issues/6290>`_)\n- Prefix warning and error messages in log output with `WARNING` and `ERROR`. (`#6298 <https://github.com/pypa/pip/issues/6298>`_)\n- Using ``--build-options`` in a PEP 517 build now fails with an error,\n  rather than silently ignoring the option. (`#6305 <https://github.com/pypa/pip/issues/6305>`_)\n- Error out with an informative message if one tries to install a\n  ``pyproject.toml``-style (PEP 517) source tree using ``--editable`` mode. (`#6314 <https://github.com/pypa/pip/issues/6314>`_)\n- When downloading a package, the ETA and average speed now only update once per second for better legibility. (`#6319 <https://github.com/pypa/pip/issues/6319>`_)\n\nBug Fixes\n---------\n\n- The stdout and stderr from VCS commands run by pip as subprocesses (e.g.\n  ``git``, ``hg``, etc.) no longer pollute pip's stdout. (`#1219 <https://github.com/pypa/pip/issues/1219>`_)\n- Fix handling of requests exceptions when dependencies are debundled. (`#4195 <https://github.com/pypa/pip/issues/4195>`_)\n- Make pip's self version check avoid recommending upgrades to prereleases if the currently-installed version is stable. (`#5175 <https://github.com/pypa/pip/issues/5175>`_)\n- Fixed crash when installing a requirement from a URL that comes from a dependency without a URL. (`#5889 <https://github.com/pypa/pip/issues/5889>`_)\n- Improve handling of file URIs: correctly handle `file://localhost/...` and don't try to use UNC paths on Unix. (`#5892 <https://github.com/pypa/pip/issues/5892>`_)\n- Fix ``utils.encoding.auto_decode()`` ``LookupError`` with invalid encodings.\n  ``utils.encoding.auto_decode()`` was broken when decoding Big Endian BOM\n  byte-strings on Little Endian or vice versa. (`#6054 <https://github.com/pypa/pip/issues/6054>`_)\n- Fix incorrect URL quoting of IPv6 addresses. (`#6285 <https://github.com/pypa/pip/issues/6285>`_)\n- Redact the password from the extra index URL when using ``pip -v``. (`#6295 <https://github.com/pypa/pip/issues/6295>`_)\n- The spinner no longer displays a completion message after subprocess calls\n  not needing a spinner. It also no longer incorrectly reports an error after\n  certain subprocess calls to Git that succeeded. (`#6312 <https://github.com/pypa/pip/issues/6312>`_)\n- Fix the handling of editable mode during installs when ``pyproject.toml`` is\n  present but PEP 517 doesn't require the source tree to be treated as\n  ``pyproject.toml``-style. (`#6370 <https://github.com/pypa/pip/issues/6370>`_)\n- Fix ``NameError`` when handling an invalid requirement. (`#6419 <https://github.com/pypa/pip/issues/6419>`_)\n\nVendored Libraries\n------------------\n\n- Updated certifi to 2019.3.9\n- Updated distro to 1.4.0\n- Update progress to 1.5\n- Updated pyparsing to 2.4.0\n- Updated pkg_resources to 41.0.1 (via setuptools)\n\nImproved Documentation\n----------------------\n\n- Make dashes render correctly when displaying long options like\n  ``--find-links`` in the text. (`#6422 <https://github.com/pypa/pip/issues/6422>`_)\n\n\n19.0.3 (2019-02-20)\n===================\n\nBug Fixes\n---------\n\n- Fix an ``IndexError`` crash when a legacy build of a wheel fails. (`#6252 <https://github.com/pypa/pip/issues/6252>`_)\n- Fix a regression introduced in 19.0.2 where the filename in a RECORD file\n  of an installed file would not be updated when installing a wheel. (`#6266 <https://github.com/pypa/pip/issues/6266>`_)\n\n\n19.0.2 (2019-02-09)\n===================\n\nBug Fixes\n---------\n\n- Fix a crash where PEP 517-based builds using ``--no-cache-dir`` would fail in\n  some circumstances with an ``AssertionError`` due to not finalizing a build\n  directory internally. (`#6197 <https://github.com/pypa/pip/issues/6197>`_)\n- Provide a better error message if attempting an editable install of a\n  directory with a ``pyproject.toml`` but no ``setup.py``. (`#6170 <https://github.com/pypa/pip/issues/6170>`_)\n- The implicit default backend used for projects that provide a ``pyproject.toml``\n  file without explicitly specifying ``build-backend`` now behaves more like direct\n  execution of ``setup.py``, and hence should restore compatibility with projects\n  that were unable to be installed with ``pip`` 19.0. This raised the minimum\n  required version of ``setuptools`` for such builds to 40.8.0. (`#6163 <https://github.com/pypa/pip/issues/6163>`_)\n- Allow ``RECORD`` lines with more than three elements, and display a warning. (`#6165 <https://github.com/pypa/pip/issues/6165>`_)\n- ``AdjacentTempDirectory`` fails on unwritable directory instead of locking up the uninstall command. (`#6169 <https://github.com/pypa/pip/issues/6169>`_)\n- Make failed uninstalls roll back more reliably and better at avoiding naming conflicts. (`#6194 <https://github.com/pypa/pip/issues/6194>`_)\n- Ensure the correct wheel file is copied when building PEP 517 distribution is built. (`#6196 <https://github.com/pypa/pip/issues/6196>`_)\n- The Python 2 end of life warning now only shows on CPython, which is the\n  implementation that has announced end of life plans. (`#6207 <https://github.com/pypa/pip/issues/6207>`_)\n\nImproved Documentation\n----------------------\n\n- Re-write README and documentation index (`#5815 <https://github.com/pypa/pip/issues/5815>`_)\n\n\n19.0.1 (2019-01-23)\n===================\n\nBug Fixes\n---------\n\n- Fix a crash when using --no-cache-dir with PEP 517 distributions (`#6158 <https://github.com/pypa/pip/issues/6158>`_, `#6171 <https://github.com/pypa/pip/issues/6171>`_)\n\n\n19.0 (2019-01-22)\n=================\n\nDeprecations and Removals\n-------------------------\n\n- Deprecate support for Python 3.4 (`#6106 <https://github.com/pypa/pip/issues/6106>`_)\n- Start printing a warning for Python 2.7 to warn of impending Python 2.7 End-of-life and\n  prompt users to start migrating to Python 3. (`#6148 <https://github.com/pypa/pip/issues/6148>`_)\n- Remove the deprecated ``--process-dependency-links`` option. (`#6060 <https://github.com/pypa/pip/issues/6060>`_)\n- Remove the deprecated SVN editable detection based on dependency links\n  during freeze. (`#5866 <https://github.com/pypa/pip/issues/5866>`_)\n\nFeatures\n--------\n\n- Implement PEP 517 (allow projects to specify a build backend via pyproject.toml). (`#5743 <https://github.com/pypa/pip/issues/5743>`_)\n- Implement manylinux2010 platform tag support.  manylinux2010 is the successor\n  to manylinux1.  It allows carefully compiled binary wheels to be installed\n  on compatible Linux platforms. (`#5008 <https://github.com/pypa/pip/issues/5008>`_)\n- Improve build isolation: handle ``.pth`` files, so namespace packages are correctly supported under Python 3.2 and earlier. (`#5656 <https://github.com/pypa/pip/issues/5656>`_)\n- Include the package name in a freeze warning if the package is not installed. (`#5943 <https://github.com/pypa/pip/issues/5943>`_)\n- Warn when dropping an ``--[extra-]index-url`` value that points to an existing local directory. (`#5827 <https://github.com/pypa/pip/issues/5827>`_)\n- Prefix pip's ``--log`` file lines with their timestamp. (`#6141 <https://github.com/pypa/pip/issues/6141>`_)\n\nBug Fixes\n---------\n\n- Avoid creating excessively long temporary paths when uninstalling packages. (`#3055 <https://github.com/pypa/pip/issues/3055>`_)\n- Redact the password from the URL in various log messages. (`#4746 <https://github.com/pypa/pip/issues/4746>`_, `#6124 <https://github.com/pypa/pip/issues/6124>`_)\n- Avoid creating excessively long temporary paths when uninstalling packages. (`#3055 <https://github.com/pypa/pip/issues/3055>`_)\n- Avoid printing a stack trace when given an invalid requirement. (`#5147 <https://github.com/pypa/pip/issues/5147>`_)\n- Present 401 warning if username/password do not work for URL (`#4833 <https://github.com/pypa/pip/issues/4833>`_)\n- Handle ``requests.exceptions.RetryError`` raised in ``PackageFinder`` that was causing pip to fail silently when some indexes were unreachable. (`#5270 <https://github.com/pypa/pip/issues/5270>`_, `#5483 <https://github.com/pypa/pip/issues/5483>`_)\n- Handle a broken stdout pipe more gracefully (e.g. when running ``pip list | head``). (`#4170 <https://github.com/pypa/pip/issues/4170>`_)\n- Fix crash from setting ``PIP_NO_CACHE_DIR=yes``. (`#5385 <https://github.com/pypa/pip/issues/5385>`_)\n- Fix crash from unparsable requirements when checking installed packages. (`#5839 <https://github.com/pypa/pip/issues/5839>`_)\n- Fix content type detection if a directory named like an archive is used as a package source. (`#5838 <https://github.com/pypa/pip/issues/5838>`_)\n- Fix listing of outdated packages that are not dependencies of installed packages in ``pip list --outdated --not-required`` (`#5737 <https://github.com/pypa/pip/issues/5737>`_)\n- Fix sorting ``TypeError`` in ``move_wheel_files()`` when installing some packages. (`#5868 <https://github.com/pypa/pip/issues/5868>`_)\n- Fix support for invoking pip using ``python src/pip ...``. (`#5841 <https://github.com/pypa/pip/issues/5841>`_)\n- Greatly reduce memory usage when installing wheels containing large files. (`#5848 <https://github.com/pypa/pip/issues/5848>`_)\n- Editable non-VCS installs now freeze as editable. (`#5031 <https://github.com/pypa/pip/issues/5031>`_)\n- Editable Git installs without a remote now freeze as editable. (`#4759 <https://github.com/pypa/pip/issues/4759>`_)\n- Canonicalize sdist file names so they can be matched to a canonicalized package name passed to ``pip install``. (`#5870 <https://github.com/pypa/pip/issues/5870>`_)\n- Properly decode special characters in SVN URL credentials. (`#5968 <https://github.com/pypa/pip/issues/5968>`_)\n- Make ``PIP_NO_CACHE_DIR`` disable the cache also for truthy values like ``\"true\"``, ``\"yes\"``, ``\"1\"``, etc. (`#5735 <https://github.com/pypa/pip/issues/5735>`_)\n\nVendored Libraries\n------------------\n\n- Include license text of vendored 3rd party libraries. (`#5213 <https://github.com/pypa/pip/issues/5213>`_)\n- Update certifi to 2018.11.29\n- Update colorama to 0.4.1\n- Update distlib to 0.2.8\n- Update idna to 2.8\n- Update packaging to 19.0\n- Update pep517 to 0.5.0\n- Update pkg_resources to 40.6.3 (via setuptools)\n- Update pyparsing to 2.3.1\n- Update pytoml to 0.1.20\n- Update requests to 2.21.0\n- Update six to 1.12.0\n- Update urllib3 to 1.24.1\n\nImproved Documentation\n----------------------\n\n- Include the Vendoring Policy in the documentation. (`#5958 <https://github.com/pypa/pip/issues/5958>`_)\n- Add instructions for running pip from source to Development documentation. (`#5949 <https://github.com/pypa/pip/issues/5949>`_)\n- Remove references to removed ``#egg=<name>-<version>`` functionality (`#5888 <https://github.com/pypa/pip/issues/5888>`_)\n- Fix omission of command name in HTML usage documentation (`#5984 <https://github.com/pypa/pip/issues/5984>`_)\n\n\n18.1 (2018-10-05)\n=================\n\nFeatures\n--------\n\n- Allow PEP 508 URL requirements to be used as dependencies.\n\n  As a security measure, pip will raise an exception when installing packages from\n  PyPI if those packages depend on packages not also hosted on PyPI.\n  In the future, PyPI will block uploading packages with such external URL dependencies directly. (`#4187 <https://github.com/pypa/pip/issues/4187>`_)\n- Allows dist options (--abi, --python-version, --platform, --implementation) when installing with --target (`#5355 <https://github.com/pypa/pip/issues/5355>`_)\n- Support passing ``svn+ssh`` URLs with a username to ``pip install -e``. (`#5375 <https://github.com/pypa/pip/issues/5375>`_)\n- pip now ensures that the RECORD file is sorted when installing from a wheel file. (`#5525 <https://github.com/pypa/pip/issues/5525>`_)\n- Add support for Python 3.7. (`#5561 <https://github.com/pypa/pip/issues/5561>`_)\n- Malformed configuration files now show helpful error messages, instead of tracebacks. (`#5798 <https://github.com/pypa/pip/issues/5798>`_)\n\nBug Fixes\n---------\n\n- Checkout the correct branch when doing an editable Git install. (`#2037 <https://github.com/pypa/pip/issues/2037>`_)\n- Run self-version-check only on commands that may access the index, instead of\n  trying on every run and failing to do so due to missing options. (`#5433 <https://github.com/pypa/pip/issues/5433>`_)\n- Allow a Git ref to be installed over an existing installation. (`#5624 <https://github.com/pypa/pip/issues/5624>`_)\n- Show a better error message when a configuration option has an invalid value. (`#5644 <https://github.com/pypa/pip/issues/5644>`_)\n- Always revalidate cached simple API pages instead of blindly caching them for up to 10\n  minutes. (`#5670 <https://github.com/pypa/pip/issues/5670>`_)\n- Avoid caching self-version-check information when cache is disabled. (`#5679 <https://github.com/pypa/pip/issues/5679>`_)\n- Avoid traceback printing on autocomplete after flags in the CLI. (`#5751 <https://github.com/pypa/pip/issues/5751>`_)\n- Fix incorrect parsing of egg names if pip needs to guess the package name. (`#5819 <https://github.com/pypa/pip/issues/5819>`_)\n\nVendored Libraries\n------------------\n\n- Upgrade certifi to 2018.8.24\n- Upgrade packaging to 18.0\n- Upgrade pyparsing to 2.2.1\n- Add pep517 version 0.2\n- Upgrade pytoml to 0.1.19\n- Upgrade pkg_resources to 40.4.3 (via setuptools)\n\nImproved Documentation\n----------------------\n\n- Fix \"Requirements Files\" reference in User Guide (`#user_guide_fix_requirements_file_ref <https://github.com/pypa/pip/issues/user_guide_fix_requirements_file_ref>`_)\n\n\n18.0 (2018-07-22)\n=================\n\nProcess\n-------\n\n- Switch to a Calendar based versioning scheme.\n- Formally document our deprecation process as a minimum of 6 months of deprecation\n  warnings.\n- Adopt and document NEWS fragment writing style.\n- Switch to releasing a new, non-bug fix version of pip every 3 months.\n\nDeprecations and Removals\n-------------------------\n\n- Remove the legacy format from pip list. (#3651, #3654)\n- Dropped support for Python 3.3. (#3796)\n- Remove support for cleaning up #egg fragment postfixes. (#4174)\n- Remove the shim for the old get-pip.py location. (#5520)\n\n  For the past 2 years, it's only been redirecting users to use the newer\n  https://bootstrap.pypa.io/get-pip.py location.\n\nFeatures\n--------\n\n- Introduce a new --prefer-binary flag, to prefer older wheels over newer source packages. (#3785)\n- Improve autocompletion function on file name completion after options\n  which have ``<file>``, ``<dir>`` or ``<path>`` as metavar. (#4842, #5125)\n- Add support for installing PEP 518 build dependencies from source. (#5229)\n- Improve status message when upgrade is skipped due to only-if-needed strategy. (#5319)\n\nBug Fixes\n---------\n\n- Update pip's self-check logic to not use a virtualenv specific file and honor cache-dir. (#3905)\n- Remove compiled pyo files for wheel packages. (#4471)\n- Speed up printing of newly installed package versions. (#5127)\n- Restrict install time dependency warnings to directly-dependant packages. (#5196, #5457)\n\n  Warning about the entire package set has resulted in users getting confused as\n  to why pip is printing these warnings.\n- Improve handling of PEP 518 build requirements: support environment markers and extras. (#5230, #5265)\n- Remove username/password from log message when using index with basic auth. (#5249)\n- Remove trailing os.sep from PATH directories to avoid false negatives. (#5293)\n- Fix \"pip wheel pip\" being blocked by the \"don't use pip to modify itself\" check. (#5311, #5312)\n- Disable pip's version check (and upgrade message) when installed by a different package manager. (#5346)\n\n  This works better with Linux distributions where pip's upgrade message may\n  result in users running pip in a manner that modifies files that should be\n  managed by the OS's package manager.\n- Check for file existence and unlink first when clobbering existing files during a wheel install. (#5366)\n- Improve error message to be more specific when no files are found as listed in as listed in PKG-INFO. (#5381)\n- Always read ``pyproject.toml`` as UTF-8. This fixes Unicode handling on Windows and Python 2. (#5482)\n- Fix a crash that occurs when PATH not set, while generating script location warning. (#5558)\n- Disallow packages with ``pyproject.toml`` files that have an empty build-system table. (#5627)\n\nVendored Libraries\n------------------\n\n- Update CacheControl to 0.12.5.\n- Update certifi to 2018.4.16.\n- Update distro to 1.3.0.\n- Update idna to 2.7.\n- Update ipaddress to 1.0.22.\n- Update pkg_resources to 39.2.0 (via setuptools).\n- Update progress to 1.4.\n- Update pytoml to 0.1.16.\n- Update requests to 2.19.1.\n- Update urllib3 to 1.23.\n\nImproved Documentation\n----------------------\n\n- Document how to use pip with a proxy server. (#512, #5574)\n- Document that the output of pip show is in RFC-compliant mail header format. (#5261)\n\n\n10.0.1 (2018-04-19)\n===================\n\nFeatures\n--------\n\n- Switch the default repository to the new \"PyPI 2.0\" running at\n  https://pypi.org/. (#5214)\n\nBug Fixes\n---------\n\n- Fix a bug that made get-pip.py unusable on Windows without renaming. (#5219)\n- Fix a TypeError when loading the cache on older versions of Python 2.7.\n  (#5231)\n- Fix and improve error message when EnvironmentError occurs during\n  installation. (#5237)\n- A crash when reinstalling from VCS requirements has been fixed. (#5251)\n- Fix PEP 518 support when pip is installed in the user site. (#5524)\n\nVendored Libraries\n------------------\n\n- Upgrade distlib to 0.2.7\n\n\n10.0.0 (2018-04-14)\n===================\n\nBug Fixes\n---------\n\n- Prevent false-positive installation warnings due to incomplete name\n  normalization. (#5134)\n- Fix issue where installing from Git with a short SHA would fail. (#5140)\n- Accept pre-release versions when checking for conflicts with pip check or pip\n  install. (#5141)\n- ``ioctl(fd, termios.TIOCGWINSZ, ...)`` needs 8 bytes of data (#5150)\n- Do not warn about script location when installing to the directory containing\n  sys.executable. This is the case when 'pip install'ing without activating a\n  virtualenv. (#5157)\n- Fix PEP 518 support. (#5188)\n- Don't warn about script locations if ``--target`` is specified. (#5203)\n\n\n10.0.0b2 (2018-04-02)\n=====================\n\nBug Fixes\n---------\n\n- Fixed line endings in CA Bundle - 10.0.0b1 was inadvertently released with Windows\n  line endings. (#5131)\n\n\n10.0.0b1 (2018-03-31)\n=====================\n\nDeprecations and Removals\n-------------------------\n\n- Removed the deprecated ``--egg`` parameter to ``pip install``. (#1749)\n- Removed support for uninstalling projects which have been installed using\n  distutils. distutils installed projects do not include metadata indicating\n  what files belong to that install and thus it is impossible to *actually*\n  uninstall them rather than just remove the metadata saying they've been\n  installed while leaving all of the actual files behind. (#2386)\n- Removed the deprecated ``--download`` option to ``pip install``. (#2643)\n- Removed the deprecated --(no-)use-wheel flags to ``pip install`` and ``pip\n  wheel``. (#2699)\n- Removed the deprecated ``--allow-external``, ``--allow-all-external``, and\n  ``--allow-unverified`` options. (#3070)\n- Switch the default for ``pip list`` to the columns format, and deprecate the\n  legacy format. (#3654, #3686)\n- Deprecate support for Python 3.3. (#3796)\n- Removed the deprecated ``--default-vcs`` option. (#4052)\n- Removed the ``setup.py test`` support from our sdist as it wasn't being\n  maintained as a supported means to run our tests. (#4203)\n- Dropped support for Python 2.6. (#4343)\n- Removed the --editable flag from pip download, as it did not make sense\n  (#4362)\n- Deprecate SVN detection based on dependency links in ``pip freeze``. (#4449)\n- Move all of pip's APIs into the pip._internal package, properly reflecting\n  the fact that pip does not currently have any public APIs. (#4696, #4700)\n\nFeatures\n--------\n\n- Add `--progress-bar <progress_bar>` to ``pip download``, ``pip install`` and\n  ``pip wheel`` commands, to allow selecting a specific progress indicator or,\n  to completely suppress, (for example in a CI environment) use\n  ``--progress-bar off```. (#2369, #2756)\n- Add `--no-color` to `pip`. All colored output is disabled if this flag is\n  detected. (#2449)\n- pip uninstall now ignores the absence of a requirement and prints a warning.\n  (#3016, #4642)\n- Improved the memory and disk efficiency of the HTTP cache. (#3515)\n- Support for packages specifying build dependencies in pyproject.toml (see\n  `PEP 518 <https://www.python.org/dev/peps/pep-0518/>`__). Packages which\n  specify one or more build dependencies this way will be built into wheels in\n  an isolated environment with those dependencies installed. (#3691)\n- pip now supports environment variable expansion in requirement files using\n  only ``${VARIABLE}`` syntax on all platforms. (#3728)\n- Allowed combinations of -q and -v to act sanely. Then we don't need warnings\n  mentioned in the issue. (#4008)\n- Add `--exclude-editable` to ``pip freeze`` and ``pip list`` to exclude\n  editable packages from installed package list. (#4015, #4016)\n- Improve the error message for the common ``pip install ./requirements.txt``\n  case. (#4127)\n- Add support for the new ``@ url`` syntax from PEP 508. (#4175)\n- Add setuptools version to the statistics sent to BigQuery. (#4209)\n- Report the line which caused the hash error when using requirement files.\n  (#4227)\n- Add a pip config command for managing configuration files. (#4240)\n- Allow ``pip download`` to be used with a specific platform when ``--no-deps``\n  is set. (#4289)\n- Support build-numbers in wheel versions and support sorting with\n  build-numbers. (#4299)\n- Change pip outdated to use PackageFinder in order to do the version lookup so\n  that local mirrors in Environments that do not have Internet connections can\n  be used as the Source of Truth for latest version. (#4336)\n- pip now retries on more HTTP status codes, for intermittent failures.\n  Previously, it only retried on the standard 503. Now, it also retries on 500\n  (transient failures on AWS S3), 520 and 527 (transient failures on\n  Cloudflare). (#4473)\n- pip now displays where it is looking for packages, if non-default locations\n  are used. (#4483)\n- Display a message to run the right command for modifying pip on Windows\n  (#4490)\n- Add Man Pages for pip (#4491)\n- Make uninstall command less verbose by default (#4493)\n- Switch the default upgrade strategy to be 'only-if-needed' (#4500)\n- Installing from a local directory or a VCS URL now builds a wheel to install,\n  rather than running ``setup.py install``. Wheels from these sources are not\n  cached. (#4501)\n- Don't log a warning when installing a dependency from Git if the name looks\n  like a commit hash. (#4507)\n- pip now displays a warning when it installs scripts from a wheel outside the\n  PATH. These warnings can be suppressed using a new --no-warn-script-location\n  option. (#4553)\n- Local Packages can now be referenced using forward slashes on Windows.\n  (#4563)\n- pip show learnt a new Required-by field that lists currently installed\n  packages that depend on the shown package (#4564)\n- The command-line autocompletion engine ``pip show`` now autocompletes\n  installed distribution names. (#4749)\n- Change documentation theme to be in line with Python Documentation (#4758)\n- Add auto completion of short options. (#4954)\n- Run 'setup.py develop' inside pep518 build environment. (#4999)\n- pip install now prints an error message when it installs an incompatible\n  version of a dependency. (#5000)\n- Added a way to distinguish between pip installed packages and those from the\n  system package manager in 'pip list'. Specifically, 'pip list -v' also shows\n  the installer of package if it has that meta data. (#949)\n- Show install locations when list command ran with \"-v\" option. (#979)\n\nBug Fixes\n---------\n\n- Allow pip to work if the ``GIT_DIR`` and ``GIT_WORK_TREE`` environment\n  variables are set. (#1130)\n- Make ``pip install --force-reinstall`` not require passing ``--upgrade``.\n  (#1139)\n- Return a failing exit status when `pip install`, `pip download`, or `pip\n  wheel` is called with no requirements. (#2720)\n- Interactive setup.py files will no longer hang indefinitely. (#2732, #4982)\n- Correctly reset the terminal if an exception occurs while a progress bar is\n  being shown. (#3015)\n- \"Support URL-encoded characters in URL credentials.\" (#3236)\n- Don't assume sys.__stderr__.encoding exists (#3356)\n- Fix ``pip uninstall`` when ``easy-install.pth`` lacks a trailing newline.\n  (#3741)\n- Keep install options in requirements.txt from leaking. (#3763)\n- pip no longer passes global options from one package to later packages in the\n  same requirement file. (#3830)\n- Support installing from Git refs (#3876)\n- Use pkg_resources to parse the entry points file to allow names with colons.\n  (#3901)\n- ``-q`` specified once correctly sets logging level to WARNING, instead of\n  CRITICAL. Use `-qqq` to have the previous behavior back. (#3994)\n- Shell completion scripts now use correct executable names (e.g., ``pip3``\n  instead of ``pip``) (#3997)\n- Changed vendored encodings from ``utf8`` to ``utf-8``. (#4076)\n- Fixes destination directory of data_files when ``pip install --target`` is\n  used. (#4092)\n- Limit the disabling of requests' pyopenssl to Windows only. Fixes\n  \"SNIMissingWarning / InsecurePlatformWarning not fixable with pip 9.0 /\n  9.0.1\" (for non-Windows) (#4098)\n- Support the installation of wheels with non-PEP 440 version in their\n  filenames. (#4169)\n- Fall back to sys.getdefaultencoding() if locale.getpreferredencoding()\n  returns None in `pip.utils.encoding.auto_decode`. (#4184)\n- Fix a bug where `SETUPTOOLS_SHIM` got called incorrectly for relative path\n  requirements by converting relative paths to absolute paths prior to calling\n  the shim. (#4208)\n- Return the latest version number in search results. (#4219)\n- Improve error message on permission errors (#4233)\n- Fail gracefully when ``/etc/image_version`` (or another distro version file)\n  appears to exists but is not readable. (#4249)\n- Avoid importing setuptools in the parent pip process, to avoid a race\n  condition when upgrading one of setuptools dependencies. (#4264)\n- Fix for an incorrect ``freeze`` warning message due to a package being\n  included in multiple requirements files that were passed to ``freeze``.\n  Instead of warning incorrectly that the package is not installed, pip now\n  warns that the package was declared multiple times and lists the name of each\n  requirements file that contains the package in question. (#4293)\n- Generalize help text for ``compile``/``no-compile`` flags. (#4316)\n- Handle the case when ``/etc`` is not readable by the current user by using a\n  hardcoded list of possible names of release files. (#4320)\n- Fixed a ``NameError`` when attempting to catch ``FileNotFoundError`` on\n  Python 2.7. (#4322)\n- Ensure USER_SITE is correctly initialised. (#4437)\n- Reinstalling an editable package from Git no longer assumes that the\n  ``master`` branch exists. (#4448)\n- This fixes an issue where when someone who tries to use git with pip but pip\n  can't because git is not in the path environment variable. This clarifies the\n  error given to suggest to the user what might be wrong. (#4461)\n- Improve handling of text output from build tools (avoid Unicode errors)\n  (#4486)\n- Fix a \"No such file or directory\" error when using --prefix. (#4495)\n- Allow commands to opt out of --require-venv. This allows pip help to work\n  even when the environment variable PIP_REQUIRE_VIRTUALENV is set. (#4496)\n- Fix warning message on mismatched versions during installation. (#4655)\n- pip now records installed files in a deterministic manner improving\n  reproducibility. (#4667)\n- Fix an issue where ``pip install -e`` on a Git url would fail to update if a\n  branch or tag name is specified that happens to match the prefix of the\n  current ``HEAD`` commit hash. (#4675)\n- Fix an issue where a variable assigned in a try clause was accessed in the\n  except clause, resulting in an undefined variable error in the except clause.\n  (#4811)\n- Use log level `info` instead of `warning` when ignoring packages due to\n  environment markers. (#4876)\n- Replaced typo mistake in subversion support. (#4908)\n- Terminal size is now correctly inferred when using Python 3 on Windows.\n  (#4966)\n- Abort if reading configuration causes encoding errors. (#4976)\n- Add a ``--no-user`` option and use it when installing build dependencies.\n  (#5085)\n\nVendored Libraries\n------------------\n\n- Upgraded appdirs to 1.4.3.\n- Upgraded CacheControl to 0.12.3.\n- Vendored certifi at 2017.7.27.1.\n- Vendored chardet at 3.0.4.\n- Upgraded colorama to 0.3.9.\n- Upgraded distlib to 0.2.6.\n- Upgraded distro to 1.2.0.\n- Vendored idna at idna==2.6.\n- Upgraded ipaddress to 1.0.18.\n- Vendored msgpack-python at 0.4.8.\n- Removed the vendored ordereddict.\n- Upgraded progress to 1.3.\n- Upgraded pyparsing to 2.2.0.\n- Upgraded pytoml to 0.1.14.\n- Upgraded requests to 2.18.4.\n- Upgraded pkg_resources (via setuptools) to 36.6.0.\n- Upgraded six to 1.11.0.\n- Vendored urllib3 at 1.22.\n- Upgraded webencodings to 0.5.1.\n\nImproved Documentation\n----------------------\n\n- Added documentation on usage of --build command line option (#4262)\n-  (#4358)\n- Document how to call pip from your code, including the fact that we do not\n  provide a Python API. (#4743)\n\n\n9.0.3 (2018-03-21)\n==================\n\n- Fix an error where the vendored requests was not correctly containing itself\n  to only the internal vendored prefix.\n- Restore compatibility with 2.6.\n\n\n9.0.2 (2018-03-16)\n==================\n\n- Fallback to using SecureTransport on macOS when the linked OpenSSL is too old\n  to support TLSv1.2.\n\n\n9.0.1 (2016-11-06)\n==================\n\n- Correct the deprecation message when not specifying a --format so that it\n  uses the correct setting name (``format``) rather than the incorrect one\n  (``list_format``). (#4058)\n- Fix ``pip check`` to check all available distributions and not just the\n  local ones. (#4083)\n- Fix a crash on non ASCII characters from `lsb_release`. (#4062)\n- Fix an SyntaxError in an unused module of a vendored dependency. (#4059)\n- Fix UNC paths on Windows. (#4064)\n\n\n9.0.0 (2016-11-02)\n==================\n\n- **BACKWARD INCOMPATIBLE** Remove the attempted autodetection of requirement\n  names from URLs, URLs must include a name via ``#egg=``.\n- **DEPRECATION** ``pip install --egg`` have been deprecated and will be\n  removed in the future. This \"feature\" has a long list of drawbacks which\n  break nearly all of pip's other features in subtle and hard-to-diagnose\n  ways.\n- **DEPRECATION** ``--default-vcs`` option. (#4052)\n- **WARNING** pip 9 cache can break forward compatibility with previous pip\n  versions if your package repository allows chunked responses. (#4078)\n- Add an ``--upgrade-strategy`` option to ``pip install``, to control how\n  dependency upgrades are managed. (#3972)\n- Add a ``pip check`` command to check installed packages dependencies. (#3750)\n- Add option allowing user to abort pip operation if file/directory exists\n- Add Appveyor CI\n- Uninstall existing packages when performing an editable installation of\n  the same packages. (#1548)\n- ``pip show`` is less verbose by default. ``--verbose`` prints multiline\n  fields. (#3858)\n- Add optional column formatting to ``pip list``. (#3651)\n- Add ``--not-required`` option to ``pip list``, which lists packages that are\n  not dependencies of other packages.\n- Fix builds on systems with symlinked ``/tmp`` directory for custom\n  builds such as numpy. (#3701)\n- Fix regression in ``pip freeze``: when there is more than one git remote,\n  priority is given to the remote named ``origin``. (#3708, #3616).\n- Fix crash when calling ``pip freeze`` with invalid requirement installed.\n  (#3704, #3681)\n- Allow multiple ``--requirement`` files in ``pip freeze``. (#3703)\n- Implementation of pep-503 ``data-requires-python``. When this field is\n  present for a release link, pip will ignore the download when\n  installing to a Python version that doesn't satisfy the requirement.\n- ``pip wheel`` now works on editable packages too (it was only working on\n  editable dependencies before); this allows running ``pip wheel`` on the result\n  of ``pip freeze`` in presence of editable requirements. (#3695, #3291)\n- Load credentials from ``.netrc`` files. (#3715, #3569)\n- Add ``--platform``, ``--python-version``, ``--implementation`` and ``--abi``\n  parameters to ``pip download``. These allow utilities and advanced users to\n  gather distributions for interpreters other than the one pip is being run on.\n  (#3760)\n- Skip scanning virtual environments, even when venv/bin/python is a dangling\n  symlink.\n- Added ``pip completion`` support for the ``fish`` shell.\n- Fix problems on Windows on Python 2 when username or hostname contains\n  non-ASCII characters. (#3463, #3970, #4000)\n- Use ``git fetch --tags`` to fetch tags in addition to everything else that\n  is normally fetched; this is necessary in case a git requirement url\n  points to a tag or commit that is not on a branch. (#3791)\n- Normalize package names before using in ``pip show`` (#3976)\n- Raise when Requires-Python do not match the running version and add\n  ``--ignore-requires-python`` option as escape hatch. (#3846)\n- Report the correct installed version when performing an upgrade in some\n  corner cases. (#2382\n- Add ``-i`` shorthand for ``--index`` flag in ``pip search``.\n- Do not optionally load C dependencies in requests. (#1840, #2930, #3024)\n- Strip authentication from SVN url prior to passing it to ``svn``.\n  (#3697, #3209)\n- Also install in platlib with ``--target`` option. (#3694, #3682)\n- Restore the ability to use inline comments in requirements files passed to\n  ``pip freeze``. (#3680)\n\n\n8.1.2 (2016-05-10)\n==================\n\n- Fix a regression on systems with uninitialized locale. (#3575)\n- Use environment markers to filter packages before determining if a required\n  wheel is supported. (#3254)\n- Make glibc parsing for `manylinux1` support more robust for the variety of\n  glibc versions found in the wild. (#3588)\n- Update environment marker support to fully support legacy and PEP 508 style\n  environment markers. (#3624)\n- Always use debug logging to the ``--log`` file. (#3351)\n- Don't attempt to wrap search results for extremely narrow terminal windows.\n  (#3655)\n\n\n8.1.1 (2016-03-17)\n==================\n\n- Fix regression with non-ascii requirement files on Python 2 and add support\n  for encoding headers in requirement files. (#3548, #3547)\n\n\n8.1.0 (2016-03-05)\n==================\n\n- Implement PEP 513, which adds support for the manylinux1 platform tag,\n  allowing carefully compiled binary wheels to be installed on compatible Linux\n  platforms.\n- Allow wheels which are not specific to a particular Python interpreter but\n  which are specific to a particular platform. (#3202)\n- Fixed an issue where ``call_subprocess`` would crash trying to print debug\n  data on child process failure. (#3521, #3522)\n- Exclude the wheel package from the `pip freeze` output (like pip and\n  setuptools). (#2989)\n- Allow installing modules from a subdirectory of a vcs repository in\n  non-editable mode. (#3217, #3466)\n- Make pip wheel and pip download work with vcs urls with subdirectory option.\n  (#3466)\n- Show classifiers in ``pip show``.\n- Show PEP376 Installer in ``pip show``. (#3517)\n- Unhide completion command. (#1810)\n- Show latest version number in ``pip search`` results. (#1415)\n- Decode requirement files according to their BOM if present. (#3485, #2865)\n- Fix and deprecate package name detection from url path. (#3523, #3495)\n- Correct the behavior where interpreter specific tags (such as cp34) were\n  being used on later versions of the same interpreter instead of only for that\n  specific interpreter. (#3472)\n- Fix an issue where pip would erroneously install a 64 bit wheel on a 32 bit\n  Python running on a 64 bit macOS machine.\n- Do not assume that all git repositories have an origin remote.\n- Correctly display the line to add to a requirements.txt for an URL based\n  dependency when ``--require-hashes`` is enabled.\n\n\n8.0.3 (2016-02-25)\n==================\n\n- Make ``install --quiet`` really quiet. (#3418)\n- Fix a bug when removing packages in python 3: disable INI-style parsing of the\n  entry_point.txt file to allow entry point names with colons. (#3434)\n- Normalize generated script files path in RECORD files. (#3448)\n- Fix bug introduced in 8.0.0 where subcommand output was not shown,\n  even when the user specified ``-v`` / ``--verbose``. (#3486)\n- Enable python -W with respect to PipDeprecationWarning. (#3455)\n- Upgrade distlib to 0.2.2.\n- Improved support for Jython when quoting executables in output scripts.\n  (#3467)\n- Add a `--all` option to `pip freeze` to include usually skipped package\n  (like pip, setuptools and wheel) to the freeze output. (#1610)\n\n\n8.0.2 (2016-01-21)\n==================\n\n- Stop attempting to trust the system CA trust store because it's extremely\n  common for them to be broken, often in incompatible ways. (#3416)\n\n\n8.0.1 (2016-01-21)\n==================\n\n- Detect CAPaths in addition to CAFiles on platforms that provide them.\n- Installing argparse or wsgiref will no longer warn or error - pip will allow\n  the installation even though it may be useless (since the installed thing\n  will be shadowed by the standard library).\n- Upgrading a distutils installed item that is installed outside of a virtual\n  environment, while inside of a virtual environment will no longer warn or\n  error.\n- Fix a bug where pre-releases were showing up in ``pip list --outdated``\n  without the ``--pre`` flag.\n- Switch the SOABI emulation from using RuntimeWarnings to debug logging.\n- Rollback the removal of the ability to uninstall distutils installed items\n  until a future date.\n\n\n8.0.0 (2016-01-19)\n==================\n\n- **BACKWARD INCOMPATIBLE** Drop support for Python 3.2.\n- **BACKWARD INCOMPATIBLE** Remove the ability to find any files other than the\n  ones directly linked from the index or find-links pages.\n- **BACKWARD INCOMPATIBLE** Remove the ``--download-cache`` which had been\n  deprecated and no-op'd in 6.0.\n- **BACKWARD INCOMPATIBLE** Remove the ``--log-explicit-levels`` which had been\n  deprecated in 6.0.\n- **BACKWARD INCOMPATIBLE** Change pip wheel --wheel-dir default path from\n  <cwd>/wheelhouse to <cwd>.\n- Deprecate and no-op the ``--allow-external``, ``--allow-all-external``, and\n  ``--allow-unverified`` functionality that was added as part of PEP 438. With\n  changes made to the repository protocol made in PEP 470, these options are no\n  longer functional.\n- Allow ``--trusted-host`` within a requirements file. (#2822)\n- Allow ``--process-dependency-links`` within a requirements file. (#1274)\n- Allow ``--pre`` within a requirements file. (#1273)\n- Allow repository URLs with secure transports to count as trusted. (E.g.,\n  \"git+ssh\" is okay.) (#2811)\n- Implement a top-level ``pip download`` command and deprecate\n  ``pip install --download``.\n- When uninstalling, look for the case of paths containing symlinked\n  directories (#3141, #3154)\n- When installing, if building a wheel fails, clear up the build directory\n  before falling back to a source install. (#3047)\n- Fix user directory expansion when ``HOME=/``. Workaround for Python bug\n  https://bugs.python.org/issue14768. (#2996)\n- Correct reporting of requirements file line numbers. (#3009, #3125)\n- Fixed Exception(IOError) for ``pip freeze`` and ``pip list`` commands with\n  subversion >= 1.7. (#1062, #3346)\n- Provide a spinner showing that progress is happening when installing or\n  building a package via ``setup.py``. This will alleviate concerns that\n  projects with unusually long build times have with pip appearing to stall.\n- Include the functionality of ``peep`` into pip, allowing hashes to be baked\n  into a requirements file and ensuring that the packages being downloaded\n  match one of those hashes. This is an additional, opt-in security measure\n  that, when used, removes the need to trust the repository.\n- Fix a bug causing pip to not select a wheel compiled against an OSX SDK later\n  than what Python itself was compiled against when running on a newer version\n  of OSX.\n- Add a new ``--prefix`` option for ``pip install`` that supports wheels and\n  sdists. (#3252)\n- Fixed issue regarding wheel building with setup.py using a different encoding\n  than the system. (#2042)\n- Drop PasteScript specific egg_info hack. (#3270)\n- Allow combination of pip list options --editable with --outdated/--uptodate.\n  (#933)\n- Gives VCS implementations control over saying whether a project is under\n  their control. (#3258)\n- Git detection now works when ``setup.py`` is not at the Git repo root\n  and when ``package_dir`` is used, so ``pip freeze`` works in more\n  cases. (#3258)\n- Correctly freeze Git develop packages in presence of the &subdirectory\n  option (#3258)\n- The detection of editable packages now relies on the presence of ``.egg-link``\n  instead of looking for a VCS, so ``pip list -e`` is more reliable. (#3258)\n- Add the ``--prefix`` flag to ``pip install`` which allows specifying a root\n  prefix to use instead of ``sys.prefix``. (#3252)\n- Allow duplicate specifications in the case that only the extras differ, and\n  union all specified extras together. (#3198)\n- Fix the detection of the user's current platform on OSX when determining the\n  OSX SDK version. (#3232)\n- Prevent the automatically built wheels from mistakenly being used across\n  multiple versions of Python when they may not be correctly configured for\n  that by making the wheel specific to a specific version of Python and\n  specific interpreter. (#3225)\n- Emulate the SOABI support in wheels from Python 2.x on Python 2.x as closely\n  as we can with the information available within the interpreter. (#3075)\n- Don't roundtrip to the network when git is pinned to a specific commit hash\n  and that hash already exists locally. (#3066)\n- Prefer wheels built against a newer SDK to wheels built against an older SDK\n  on OSX. (#3163)\n- Show entry points for projects installed via wheel. (#3122)\n- Improve message when an unexisting path is passed to --find-links option.\n  (#2968)\n- pip freeze does not add the VCS branch/tag name in the #egg=... fragment\n  anymore. (#3312)\n- Warn on installation of editable if the provided #egg=name part does not\n  match the metadata produced by `setup.py egg_info`. (#3143)\n- Add support for .xz files for python versions supporting them (>= 3.3). (#722)\n\n\n7.1.2 (2015-08-22)\n==================\n\n- Don't raise an error if pip is not installed when checking for the latest pip\n  version.\n\n\n7.1.1 (2015-08-20)\n==================\n\n- Check that the wheel cache directory is writable before we attempt to write\n  cached files to them.\n- Move the pip version check until *after* any installs have been performed,\n  thus removing the extraneous warning when upgrading pip.\n- Added debug logging when using a cached wheel.\n- Respect platlib by default on platforms that have it separated from purelib.\n- Upgrade packaging to 15.3.\n  - Normalize post-release spellings for rev/r prefixes.\n- Upgrade distlib to 0.2.1.\n  - Updated launchers to decode shebangs using UTF-8. This allows non-ASCII\n  pathnames to be correctly handled.\n  - Ensured that the executable written to shebangs is normcased.\n  - Changed ScriptMaker to work better under Jython.\n- Upgrade ipaddress to 1.0.13.\n\n\n7.1.0 (2015-06-30)\n==================\n\n- Allow constraining versions globally without having to know exactly what will\n  be installed by the pip command. (#2731)\n- Accept --no-binary and --only-binary via pip.conf. (#2867)\n- Allow ``--allow-all-external`` within a requirements file.\n- Fixed an issue where ``--user`` could not be used when ``--prefix`` was used\n  in a distutils configuration file.\n- Fixed an issue where the SOABI tags were not correctly being generated on\n  Python 3.5.\n- Fixed an issue where we were advising windows users to upgrade by directly\n  executing pip, when that would always fail on Windows.\n- Allow ``~`` to be expanded within a cache directory in all situations.\n\n\n7.0.3 (2015-06-01)\n==================\n\n- Fixed a regression where ``--no-cache-dir`` would raise an exception. (#2855)\n\n\n7.0.2 (2015-06-01)\n==================\n\n- **BACKWARD INCOMPATIBLE** Revert the change (released in v7.0.0) that\n  required quoting in requirements files around specifiers containing\n  environment markers. (#2841)\n- **BACKWARD INCOMPATIBLE** Revert the accidental introduction of support for\n  options interleaved with requirements, version specifiers etc in\n  ``requirements`` files. (#2841)\n- Expand ``~`` in the cache directory when caching wheels. (#2816)\n- Use ``python -m pip`` instead of ``pip`` when recommending an upgrade command\n  to Windows users.\n\n\n7.0.1 (2015-05-22)\n==================\n\n- Don't build and cache wheels for non-editable installations from VCSs.\n- Allow ``--allow-all-external`` inside of a requirements.txt file, fixing a\n  regression in 7.0.\n\n\n7.0.0 (2015-05-21)\n==================\n\n- **BACKWARD INCOMPATIBLE** Removed the deprecated ``--mirror``,\n  ``--use-mirrors``, and ``-M`` options.\n- **BACKWARD INCOMPATIBLE** Removed the deprecated ``zip`` and ``unzip``\n  commands.\n- **BACKWARD INCOMPATIBLE** Removed the deprecated ``--no-install`` and\n  ``--no-download`` options.\n- **BACKWARD INCOMPATIBLE** No longer implicitly support an insecure origin\n  origin, and instead require insecure origins be explicitly trusted with the\n  ``--trusted-host`` option.\n- **BACKWARD INCOMPATIBLE** Removed the deprecated link scraping that attempted\n  to parse HTML comments for a specially formatted comment.\n- **BACKWARD INCOMPATIBLE** Requirements in requirements files containing\n  markers must now be quoted due to parser changes.  For example, use\n  ``\"SomeProject; python_version < '2.7'\"``, not simply\n  ``SomeProject; python_version < '2.7'`` (#2697, #2725)\n- `get-pip.py` now installs the \"wheel\" package, when it's not already\n  installed. (#2800)\n- Ignores bz2 archives if Python wasn't compiled with bz2 support. (#497)\n- Support ``--install-option`` and ``--global-option`` per requirement in\n  requirement files. (#2537)\n- Build Wheels prior to installing from sdist, caching them in the pip cache\n  directory to speed up subsequent installs. (#2618)\n- Allow fine grained control over the use of wheels and source builds. (#2699)\n- ``--no-use-wheel`` and ``--use-wheel`` are deprecated in favour of new\n  options ``--no-binary`` and ``--only-binary``. The equivalent of\n  ``--no-use-wheel`` is ``--no-binary=:all:``. (#2699)\n- The use of ``--install-option``, ``--global-option`` or ``--build-option``\n  disable the use of wheels, and the autobuilding of wheels. (#2711, #2677)\n- Improve logging when a requirement marker doesn't match your environment.\n  (#2735)\n- Removed the temporary modifications (that began in pip v1.4 when distribute\n  and setuptools merged) that allowed distribute to be considered a conflict to\n  setuptools. ``pip install -U setuptools`` will no longer upgrade \"distribute\"\n  to \"setuptools\".  Instead, use ``pip install -U distribute``. (#2767)\n- Only display a warning to upgrade pip when the newest version is a final\n  release and it is not a post release of the version we already have\n  installed. (#2766)\n- Display a warning when attempting to access a repository that uses HTTPS when\n  we don't have Python compiled with SSL support. (#2761)\n- Allowing using extras when installing from a file path without requiring the\n  use of an editable. (#2785)\n- Fix an infinite loop when the cache directory is stored on a file system\n  which does not support hard links. (#2796)\n- Remove the implicit debug log that was written on every invocation, instead\n  users will need to use ``--log`` if they wish to have one. (#2798)\n\n\n6.1.1 (2015-04-07)\n==================\n\n- No longer ignore dependencies which have been added to the standard library,\n  instead continue to install them.\n\n\n6.1.0 (2015-04-07)\n==================\n\n- Fixes upgrades failing when no potential links were found for dependencies\n  other than the current installation. (#2538, #2502)\n- Use a smoother progress bar when the terminal is capable of handling it,\n  otherwise fallback to the original ASCII based progress bar.\n- Display much less output when `pip install` succeeds, because on success,\n  users probably don't care about all the nitty gritty details of compiling and\n  installing. When `pip install` fails, display the failed install output once\n  instead of twice, because once is enough. (#2487)\n- Upgrade the bundled copy of requests to 2.6.0, fixing CVE-2015-2296.\n- Display format of latest package when using ``pip list --outdated``. (#2475)\n- Don't use pywin32 as ctypes should always be available on Windows, using\n  pywin32 prevented uninstallation of pywin32 on Windows. (:pr:`2467`)\n- Normalize the ``--wheel-dir`` option, expanding out constructs such as ``~``\n  when used. (#2441)\n- Display a warning when an undefined extra has been requested. (#2142)\n- Speed up installing a directory in certain cases by creating a sdist instead\n  of copying the entire directory. (#2535)\n- Don't follow symlinks when uninstalling files (#2552)\n- Upgrade the bundled copy of cachecontrol from 0.11.1 to 0.11.2. (#2481, #2595)\n- Attempt to more smartly choose the order of installation to try and install\n  dependencies before the projects that depend on them. (#2616)\n- Skip trying to install libraries which are part of the standard library.\n  (#2636, #2602)\n- Support arch specific wheels that are not tied to a specific Python ABI.\n  (#2561)\n- Output warnings and errors to stderr instead of stdout. (#2543)\n- Adjust the cache dir file checks to only check ownership if the effective\n  user is root. (#2396)\n- Install headers into a per project name directory instead of all of them into\n  the root directory when inside of a virtual environment. (#2421)\n\n\n6.0.8 (2015-02-04)\n==================\n\n- Fix an issue where the ``--download`` flag would cause pip to no longer use\n  randomized build directories.\n- Fix an issue where pip did not properly unquote quoted URLs which contain\n  characters like PEP 440's epoch separator (``!``).\n- Fix an issue where distutils installed projects were not actually uninstalled\n  and deprecate attempting to uninstall them altogether.\n- Retry deleting directories in case a process like an antivirus is holding the\n  directory open temporarily.\n- Fix an issue where pip would hide the cursor on Windows but would not reshow\n  it.\n\n\n6.0.7 (2015-01-28)\n==================\n\n- Fix a regression where Numpy requires a build path without symlinks to\n  properly build.\n- Fix a broken log message when running ``pip wheel`` without a requirement.\n- Don't mask network errors while downloading the file as a hash failure.\n- Properly create the state file for the pip version check so it only happens\n  once a week.\n- Fix an issue where switching between Python 3 and Python 2 would evict cached\n  items.\n- Fix a regression where pip would be unable to successfully uninstall a\n  project without a normalized version.\n\n\n6.0.6 (2015-01-03)\n==================\n\n- Continue the regression fix from 6.0.5 which was not a complete fix.\n\n\n6.0.5 (2015-01-03)\n==================\n\n- Fix a regression with 6.0.4 under Windows where most commands would raise an\n  exception due to Windows not having the ``os.geteuid()`` function.\n\n\n6.0.4 (2015-01-03)\n==================\n\n- Fix an issue where ANSI escape codes would be used on Windows even though the\n  Windows shell does not support them, causing odd characters to appear with\n  the progress bar.\n- Fix an issue where using -v would cause an exception saying\n  ``TypeError: not all arguments converted during string formatting``.\n- Fix an issue where using -v with dependency links would cause an exception\n  saying ``TypeError: 'InstallationCandidate' object is not iterable``.\n- Fix an issue where upgrading distribute would cause an exception saying\n  ``TypeError: expected string or buffer``.\n- Show a warning and disable the use of the cache directory when the cache\n  directory is not owned by the current user, commonly caused by using ``sudo``\n  without the ``-H`` flag.\n- Update PEP 440 support to handle the latest changes to PEP 440, particularly\n  the changes to ``>V`` and ``<V`` so that they no longer imply ``!=V.*``.\n- Document the default cache directories for each operating system.\n- Create the cache directory when the pip version check needs to save to it\n  instead of silently logging an error.\n- Fix a regression where the ``-q`` flag would not properly suppress the\n  display of the progress bars.\n\n\n6.0.3 (2014-12-23)\n==================\n\n- Fix an issue where the implicit version check new in pip 6.0 could cause pip\n  to block for up to 75 seconds if PyPI was not accessible.\n- Make ``--no-index`` imply ``--disable-pip-version-check``.\n\n\n6.0.2 (2014-12-23)\n==================\n\n- Fix an issue where the output saying that a package was installed would\n  report the old version instead of the new version during an upgrade.\n- Fix left over merge conflict markers in the documentation.\n- Document the backwards incompatible PEP 440 change in the 6.0.0 changelog.\n\n\n6.0.1 (2014-12-22)\n==================\n\n- Fix executable file permissions for Wheel files when using the distutils\n  scripts option.\n- Fix a confusing error message when an exceptions was raised at certain\n  points in pip's execution.\n- Fix the missing list of versions when a version cannot be found that matches\n  the specifiers.\n- Add a warning about the possibly problematic use of > when the given\n  specifier doesn't match anything.\n- Fix an issue where installing from a directory would not copy over certain\n  directories which were being excluded, however some build systems rely on\n  them.\n\n\n6.0 (2014-12-22)\n================\n\n- **PROCESS** Version numbers are now simply ``X.Y`` where the leading ``1``\n  has been dropped.\n- **BACKWARD INCOMPATIBLE** Dropped support for Python 3.1.\n- **BACKWARD INCOMPATIBLE** Removed the bundle support which was deprecated in\n  1.4. (#1806)\n- **BACKWARD INCOMPATIBLE** File lists generated by `pip show -f` are now\n  rooted at the location reported by show, rather than one (unstated)\n  directory lower. (#1933)\n- **BACKWARD INCOMPATIBLE** The ability to install files over the FTP protocol\n  was accidentally lost in pip 1.5 and it has now been decided to not restore\n  that ability.\n- **BACKWARD INCOMPATIBLE** PEP 440 is now fully implemented, this means that\n  in some cases versions will sort differently or version specifiers will be\n  interpreted differently than previously. The common cases should all function\n  similarly to before.\n- **DEPRECATION** ``pip install --download-cache`` and\n  ``pip wheel --download-cache`` command line flags have been deprecated and\n  the functionality removed. Since pip now automatically configures and uses\n  it's internal HTTP cache which supplants the ``--download-cache`` the\n  existing options have been made non functional but will still be accepted\n  until their removal in pip v8.0. For more information please see\n  https://pip.pypa.io/en/stable/reference/pip_install.html#caching\n- **DEPRECATION** ``pip install --build`` and ``pip install --no-clean`` are now\n  *NOT* deprecated.  This reverses the deprecation that occurred in v1.5.3.\n  (#906)\n- **DEPRECATION** Implicitly accessing URLs which point to an origin which is\n  not a secure origin, instead requiring an opt-in for each host using the new\n  ``--trusted-host`` flag (``pip install --trusted-host example.com foo``).\n- Allow the new ``--trusted-host`` flag to also disable TLS verification for\n  a particular hostname.\n- Added a ``--user`` flag to ``pip freeze`` and ``pip list`` to check the\n  user site directory only.\n- Silence byte compile errors when installation succeed. (#1873)\n- Added a virtualenv-specific configuration file. (#1364)\n- Added site-wide configuration files. (1978)\n- Added an automatic check to warn if there is an updated version of pip\n  available. (#2049)\n- `wsgiref` and `argparse` (for >py26) are now excluded from `pip list` and\n  `pip freeze`. (#1606, #1369)\n- Add ``--client-cert`` option for SSL client certificates. (#1424)\n- `pip show --files` was broken for wheel installs. (#1635, #1484)\n- install_lib should take precedence when reading distutils config.\n  (#1642, #1641)\n- Send `Accept-Encoding: identity` when downloading files in an attempt to\n  convince some servers who double compress the downloaded file to stop doing\n  so. (#1688)\n- Stop breaking when given pip commands in uppercase (#1559, #1725)\n- pip no longer adds duplicate logging consumers, so it won't create duplicate\n  output when being called multiple times. (#1618, #1723)\n- `pip wheel` now returns an error code if any wheels fail to build. (#1769)\n- `pip wheel` wasn't building wheels for dependencies of editable requirements.\n  (#1775)\n- Allow the use of ``--no-use-wheel`` within a requirements file. (#1859)\n- Attempt to locate system TLS certificates to use instead of the included\n  CA Bundle if possible. (#1680, #1866)\n- Allow use of Zip64 extension in Wheels and other zip files. (#1319, #1868)\n- Properly handle an index or --find-links target which has a <base> without a\n  href attribute. (#1101, #1869)\n- Properly handle extras when a project is installed via Wheel. (#1885, #1896)\n- Added support to respect proxies in ``pip search``.\n  (#1180, #932, #1104, #1902)\n- `pip install --download` works with vcs links. (#798, #1060, #1926)\n- Disabled warning about insecure index host when using localhost. Based off of\n  Guy Rozendorn's work in #1718. (#1456, #1967)\n- Allow the use of OS standard user configuration files instead of ones simply\n  based around ``$HOME``. (#2021)\n- When installing directly from wheel paths or urls, previous versions were not\n  uninstalled. (#1825, #804, #1838)\n- Detect the location of the ``.egg-info`` directory by looking for any file\n  located inside of it instead of relying on the record file listing a\n  directory. (#2075, #2076)\n- Use a randomized and secure default build directory when possible.\n  (#1964, #1935, #676, #2122, CVE-2014-8991)\n- Support environment markers in requirements.txt files. (#1433, #2134)\n- Automatically retry failed HTTP requests by default. (#1444, #2147)\n- Handle HTML Encoding better using a method that is more similar to how\n  browsers handle it. (#1100, #1874)\n- Reduce the verbosity of the pip command by default. (#2175, #2177, #2178)\n- Fixed :issue:`2031` - Respect sys.executable on OSX when installing from\n  Wheels.\n- Display the entire URL of the file that is being downloaded when downloading\n  from a non PyPI repository. (#2183)\n- Support setuptools style environment markers in a source distribution. (#2153)\n\n\n1.5.6 (2014-05-16)\n==================\n\n- Upgrade requests to 2.3.0 to fix an issue with proxies on Python 3.4.1.\n  (#1821)\n\n\n1.5.5 (2014-05-03)\n==================\n\n- Uninstall issues on debianized pypy, specifically issues with setuptools\n  upgrades. (#1632, #1743)\n- Update documentation to point at https://bootstrap.pypa.io/get-pip.py for\n  bootstrapping pip.\n- Update docs to point to https://pip.pypa.io/\n- Upgrade the bundled projects (distlib==0.1.8, html5lib==1.0b3, six==1.6.1,\n  colorama==0.3.1, setuptools==3.4.4).\n\n\n1.5.4 (2014-02-21)\n==================\n\n- Correct deprecation warning for ``pip install --build`` to only notify when\n  the `--build` value is different than the default.\n\n\n1.5.3 (2014-02-20)\n==================\n\n- **DEPRECATION** ``pip install --build`` and ``pip install --no-clean`` are now\n  deprecated. (#906)\n- Fixed being unable to download directly from wheel paths/urls, and when wheel\n  downloads did occur using requirement specifiers, dependencies weren't\n  downloaded. (#1112, #1527)\n- ``pip wheel`` was not downloading wheels that already existed. (#1320, #1524)\n- ``pip install --download`` was failing using local ``--find-links``.\n  (#1111, #1524)\n- Workaround for Python bug https://bugs.python.org/issue20053. (#1544)\n- Don't pass a unicode __file__ to setup.py on Python 2.x. (#1583)\n- Verify that the Wheel version is compatible with this pip. (#1569)\n\n\n1.5.2 (2014-01-26)\n==================\n\n- Upgraded the vendored ``pkg_resources`` and ``_markerlib`` to setuptools 2.1.\n- Fixed an error that prevented accessing PyPI when pyopenssl, ndg-httpsclient,\n  and pyasn1 are installed.\n- Fixed an issue that caused trailing comments to be incorrectly included as\n  part of the URL in a requirements file.\n\n\n1.5.1 (2014-01-20)\n==================\n\n- pip now only requires setuptools (any setuptools, not a certain version) when\n  installing distributions from src (i.e. not from wheel). (#1434)\n- `get-pip.py` now installs setuptools, when it's not already installed. (#1475)\n- Don't decode downloaded files that have a ``Content-Encoding`` header. (#1435)\n- Fix to correctly parse wheel filenames with single digit versions. (#1445)\n- If `--allow-unverified` is used assume it also means `--allow-external`.\n  (#1457)\n\n\n1.5 (2014-01-01)\n================\n\n- **BACKWARD INCOMPATIBLE** pip no longer supports the ``--use-mirrors``,\n  ``-M``, and ``--mirrors`` flags. The mirroring support has been removed. In\n  order to use a mirror specify it as the primary index with ``-i`` or\n  ``--index-url``, or as an additional index with ``--extra-index-url``.\n  (#1098, CVE-2013-5123)\n- **BACKWARD INCOMPATIBLE** pip no longer will scrape insecure external urls by\n  default nor will it install externally hosted files by default. Users may opt\n  into installing externally hosted or insecure files or urls using\n  ``--allow-external PROJECT`` and ``--allow-unverified PROJECT``. (#1055)\n- **BACKWARD INCOMPATIBLE** pip no longer respects dependency links by default.\n  Users may opt into respecting them again using ``--process-dependency-links``.\n- **DEPRECATION** ``pip install --no-install`` and ``pip install\n  --no-download`` are now formally deprecated.  See #906 for discussion on\n  possible alternatives, or lack thereof, in future releases.\n- **DEPRECATION** ``pip zip`` and ``pip unzip`` are now formally deprecated.\n- pip will now install Mac OSX platform wheels from PyPI. (:pr:`1278`)\n- pip now generates the appropriate platform-specific console scripts when\n  installing wheels. (#1251)\n- pip now confirms a wheel is supported when installing directly from a path or\n  url. (#1315)\n- ``--ignore-installed`` now behaves again as designed, after it was\n  unintentionally broke in v0.8.3 when fixing #14. (#1097, #1352)\n- Fixed a bug where global scripts were being removed when uninstalling --user\n  installed packages. (#1353)\n- ``--user`` wasn't being respected when installing scripts from wheels.\n  (#1163, #1176)\n- Assume '_' means '-' in versions from wheel filenames. (#1150, #1158)\n- Error when using --log with a failed install. (#219, #1205)\n- Fixed logging being buffered and choppy in Python 3. (#1131)\n- Don't ignore --timeout. (#70, #1202)\n- Fixed an error when setting PIP_EXISTS_ACTION. (#772, #1201)\n- Added colors to the logging output in order to draw attention to important\n  warnings and errors. (#1109)\n- Added warnings when using an insecure index, find-link, or dependency link.\n  (#1121)\n- Added support for installing packages from a subdirectory using the\n  ``subdirectory`` editable option. (#1082)\n- Fixed \"TypeError: bad operand type for unary\" in some cases when installing\n  wheels using --find-links. (#1192, #1218)\n- Archive contents are now written based on system defaults and umask (i.e.\n  permissions are not preserved), except that regular files with any execute\n  permissions have the equivalent of \"chmod +x\" applied after being written.\n  (#1133, #317, #1146)\n- PreviousBuildDirError now returns a non-zero exit code and prevents the\n  previous build dir from being cleaned in all cases. (#1162)\n- Renamed --allow-insecure to --allow-unverified, however the old name will\n  continue to work for a period of time. (#1257)\n- Fixed an error when installing local projects with symlinks in Python 3.\n  (#1006, #1311)\n- The previously hidden ``--log-file`` option, is now shown as a general option.\n  (#1316)\n\n\n1.4.1 (2013-08-07)\n==================\n\n- **New Signing Key** Release 1.4.1 is using a different key than normal with\n  fingerprint: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA\n- Fixed issues with installing from pybundle files. (#1116)\n- Fixed error when sysconfig module throws an exception. (#1095)\n- Don't ignore already installed pre-releases. (#1076)\n- Fixes related to upgrading setuptools. (#1092)\n- Fixes so that --download works with wheel archives. (#1113)\n- Fixes related to recognizing and cleaning global build dirs. (#1080)\n\n\n1.4 (2013-07-23)\n================\n\n- **BACKWARD INCOMPATIBLE** pip now only installs stable versions by default,\n  and offers a new ``--pre`` option to also find pre-release and development\n  versions. (#834)\n- **BACKWARD INCOMPATIBLE** Dropped support for Python 2.5. The minimum\n  supported Python version for pip 1.4 is Python 2.6.\n- Added support for installing and building wheel archives. Thanks Daniel Holth,\n  Marcus Smith, Paul Moore, and Michele Lacchia (#845)\n- Applied security patch to pip's ssl support related to certificate DNS\n  wildcard matching (https://bugs.python.org/issue17980).\n- To satisfy pip's setuptools requirement, pip now recommends setuptools>=0.8,\n  not distribute. setuptools and distribute are now merged into one project\n  called 'setuptools'. (#1003)\n- pip will now warn when installing a file that is either hosted externally to\n  the index or cannot be verified with a hash. In the future pip will default\n  to not installing them and will require the flags --allow-external NAME, and\n  --allow-insecure NAME respectively. (#985)\n- If an already-downloaded or cached file has a bad hash, re-download it rather\n  than erroring out. (#963)\n- ``pip bundle`` and support for installing from pybundle files is now\n  considered deprecated and will be removed in pip v1.5.\n- Fix a number of issues related to cleaning up and not reusing build\n  directories. (#413, #709, #634, #602, #939, #865, #948)\n- Added a User Agent so that pip is identifiable in logs. (#901)\n- Added ssl and --user support to get-pip.py. Thanks Gabriel de Perthuis.\n  (#895)\n- Fixed the proxy support, which was broken in pip 1.3.x (#840)\n- Fixed pip failing when server does not send content-type header. Thanks\n  Hugo Lopes Tavares and Kelsey Hightower. (#32, #872)\n- \"Vendorized\" distlib as pip.vendor.distlib (https://distlib.readthedocs.io/).\n- Fixed git VCS backend with git 1.8.3. (#967)\n\n\n1.3.1 (2013-03-08)\n==================\n\n- Fixed a major backward incompatible change of parsing URLs to externally\n  hosted packages that got accidentally included in 1.3.\n\n\n1.3 (2013-03-07)\n================\n\n- SSL Cert Verification; Make https the default for PyPI access. Thanks\n  James Cleveland, Giovanni Bajo, Marcus Smith and many others.\n  (#791, CVE-2013-1629)\n- Added \"pip list\" for listing installed packages and the latest version\n  available. Thanks Rafael Caricio, Miguel Araujo, Dmitry Gladkov. (#752)\n- Fixed security issues with pip's use of temp build directories.\n  Thanks David (d1b) and Thomas Guttler. (#780, CVE-2013-1888)\n- Improvements to sphinx docs and cli help. (#773)\n- Fixed an issue dealing with macOS temp dir handling, which was causing global\n  NumPy installs to fail. (#707, #768)\n- Split help output into general vs command-specific option groups.\n  Thanks Georgi Valkov. (#744, #721)\n- Fixed dependency resolution when installing from archives with uppercase\n  project names. (#724)\n- Fixed problem where re-installs always occurred when using file:// find-links.\n  (#683, #702)\n- \"pip install -v\" now shows the full download url, not just the archive name.\n  Thanks Marc Abramowitz (#687)\n- Fix to prevent unnecessary PyPI redirects. Thanks Alex Gronholm (#695)\n- Fixed an install failure under Python 3 when the same version of a package is\n  found under 2 different URLs. Thanks Paul Moore (#670, #671)\n- Fix git submodule recursive updates. Thanks Roey Berman. (#674)\n- Explicitly ignore rel='download' links while looking for html pages. Thanks\n  Maxime R. (#677)\n- --user/--upgrade install options now work together. Thanks 'eevee' for\n  discovering the problem. (#705)\n- Added check in ``install --download`` to prevent re-downloading if the target\n  file already exists. Thanks Andrey Bulgakov. (#669)\n- Added support for bare paths (including relative paths) as argument to\n  `--find-links`. Thanks Paul Moore for draft patch.\n- Added support for --no-index in requirements files.\n- Added \"pip show\" command to get information about an installed package.\n  Thanks Kelsey Hightower and Rafael Caricio. (#131)\n- Added `--root` option for \"pip install\" to specify root directory. Behaves\n  like the same option in distutils but also plays nice with pip's egg-info.\n  Thanks Przemek Wrzos. (#253, #693)\n\n\n1.2.1 (2012-09-06)\n==================\n\n- Fixed a regression introduced in 1.2 about raising an exception when\n  not finding any files to uninstall in the current environment. Thanks for\n  the fix, Marcus Smith.\n\n\n1.2 (2012-09-01)\n================\n\n- **Dropped support for Python 2.4** The minimum supported Python version is\n  now Python 2.5.\n- Fixed PyPI mirror support being broken on some DNS responses. Thanks\n  philwhin. (#605)\n- Fixed pip uninstall removing files it didn't install. Thanks pjdelport.\n  (#355)\n- Fixed a number of issues related to improving support for the user\n  installation scheme. Thanks Marcus Smith. (#493, #494, #440, #573)\n- Write failure log to temp file if default location is not writable. Thanks\n  andreigc.\n- Pull in submodules for git editable checkouts. Thanks Hsiaoming Yang and\n  Markus Hametner. (#289, #421)\n- Use a temporary directory as the default build location outside of a\n  virtualenv. Thanks Ben Rosser. (#339, #381)\n- Added support for specifying extras with local editables. Thanks Nick\n  Stenning.\n- Added ``--egg`` flag to request egg-style rather than flat installation.\n  Thanks Kamal Bin Mustafa. (#3)\n- Prevent e.g. ``gmpy2-2.0.tar.gz`` from matching a request to\n  ``pip install gmpy``; sdist filename must begin with full project name\n  followed by a dash. Thanks casevh for the report. (#510)\n- Allow package URLS to have querystrings. Thanks W. Trevor King. (#504)\n- pip freeze now falls back to non-editable format rather than blowing up if it\n  can't determine the origin repository of an editable. Thanks Rory McCann.\n  (#58)\n- Added a `__main__.py` file to enable `python -m pip` on Python versions\n  that support it. Thanks Alexey Luchko.\n- Fixed upgrading from VCS url of project that does exist on index. Thanks\n  Andrew Knapp for the report. (#487)\n- Fix upgrade from VCS url of project with no distribution on index.\n  Thanks Andrew Knapp for the report. (#486)\n- Add a clearer error message on a malformed VCS url. Thanks Thomas Fenzl.\n  (#427)\n- Added support for using any of the built in guaranteed algorithms in\n  ``hashlib`` as a checksum hash.\n- Raise an exception if current working directory can't be found or accessed.\n  (#321)\n- Removed special casing of the user directory and use the Python default\n  instead. (#82)\n- Only warn about version conflicts if there is actually one. This re-enables\n  using ``==dev`` in requirements files. (#436)\n- Moved tests to be run on Travis CI: https://travis-ci.org/pypa/pip\n- Added a better help formatter.\n\n\n1.1 (2012-02-16)\n================\n\n- Don't crash when a package's setup.py emits UTF-8 and then fails. Thanks\n  Marc Abramowitz. (#326)\n- Added ``--target`` option for installing directly to arbitrary directory.\n  Thanks Stavros Korokithakis.\n- Added support for authentication with Subversion repositories. Thanks\n  Qiangning Hong.\n- ``--download`` now downloads dependencies as well. Thanks Qiangning Hong.\n  (#315)\n- Errors from subprocesses will display the current working directory.\n  Thanks Antti Kaihola.\n- Fixed  compatibility with Subversion 1.7. Thanks Qiangning Hong. Note that\n  setuptools remains incompatible with Subversion 1.7; to get the benefits of\n  pip's support you must use Distribute rather than setuptools. (#369)\n- Ignore py2app-generated macOS mpkg zip files in finder. Thanks Rene Dudfield.\n  (#57)\n- Log to ~/Library/Logs/ by default on macOS framework installs. Thanks\n  Dan Callahan for report and patch. (#182)\n- Understand version tags without minor version (\"py3\") in sdist filenames.\n  Thanks Stuart Andrews for report and Olivier Girardot for patch. (#310)\n- pip now supports optionally installing setuptools \"extras\" dependencies; e.g.\n  \"pip install Paste[openid]\". Thanks Matt Maker and Olivier Girardot. (#7)\n- freeze no longer borks on requirements files with --index-url or --find-links.\n  Thanks Herbert Pfennig. (#391)\n- Handle symlinks properly. Thanks lebedov for the patch. (#288)\n- pip install -U no longer reinstalls the same versions of packages. Thanks\n  iguananaut for the pull request. (#49)\n- Removed ``-E``/``--environment`` option and ``PIP_RESPECT_VIRTUALENV``;\n  both use a restart-in-venv mechanism that's broken, and neither one is\n  useful since every virtualenv now has pip inside it.  Replace ``pip -E\n  path/to/venv install Foo`` with ``virtualenv path/to/venv &&\n  path/to/venv/pip install Foo``.\n- Fixed pip throwing an IndexError when it calls `scraped_rel_links`. (#366)\n- pip search should set and return a useful shell status code. (#22)\n- Added global ``--exists-action`` command line option to easier script file\n  exists conflicts, e.g. from editable requirements from VCS that have a\n  changed repo URL. (#351, #365)\n\n\n1.0.2 (2011-07-16)\n==================\n\n- Fixed docs issues.\n- Reinstall a package when using the ``install -I`` option. (#295)\n- Finds a Git tag pointing to same commit as origin/master. (#283)\n- Use absolute path for path to docs in setup.py. (#279)\n- Correctly handle exceptions on Python3. (#314)\n- Correctly parse ``--editable`` lines in requirements files. (#320)\n\n\n1.0.1 (2011-04-30)\n==================\n\n- Start to use git-flow.\n- `find_command` should not raise AttributeError. (#274)\n- Respect Content-Disposition header. Thanks Bradley Ayers. (#273)\n- pathext handling on Windows. (#233)\n- svn+svn protocol. (#252)\n- multiple CLI searches. (#44)\n- Current working directory when running setup.py clean. (#266)\n\n\n1.0 (2011-04-04)\n================\n\n- Added Python 3 support! Huge thanks to Vinay Sajip, Vitaly Babiy, Kelsey\n  Hightower, and Alex Gronholm, among others.\n- Download progress only shown on a real TTY. Thanks Alex Morega.\n- Fixed finding of VCS binaries to not be fooled by same-named directories.\n  Thanks Alex Morega.\n- Fixed uninstall of packages from system Python for users of Debian/Ubuntu\n  python-setuptools package (workaround until fixed in Debian and Ubuntu).\n- Added `get-pip.py <https://raw.github.com/pypa/pip/master/contrib/get-pip.py>`_\n  installer. Simply download and execute it, using the Python interpreter of\n  your choice::\n\n    $ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py\n    $ python get-pip.py\n\n  This may have to be run as root.\n\n  .. note::\n\n      Make sure you have `distribute <http://pypi.python.org/pypi/distribute>`_\n      installed before using the installer!\n\n\n0.8.3\n=====\n\n- Moved main repository to GitHub: https://github.com/pypa/pip\n- Transferred primary maintenance from Ian to Jannis Leidel, Carl Meyer,\n  Brian Rosner\n- Fixed no uninstall-on-upgrade with URL package. Thanks Oliver Tonnhofer.\n  (#14)\n- Fixed egg name not properly resolving. Thanks Igor Sobreira. (#163)\n- Fixed Non-alphabetical installation of requirements. Thanks Igor Sobreira.\n  (#178)\n- Fixed documentation mentions --index instead of --index-url. Thanks\n  Kelsey Hightower (#199)\n- rmtree undefined in mercurial.py. Thanks Kelsey Hightower. (#204)\n- Fixed bug in Git vcs backend that would break during reinstallation.\n- Fixed bug in Mercurial vcs backend related to pip freeze and branch/tag\n  resolution.\n- Fixed bug in version string parsing related to the suffix \"-dev\".\n\n\n0.8.2\n=====\n\n- Avoid redundant unpacking of bundles (from pwaller)\n- Fixed checking out the correct tag/branch/commit when updating an editable\n  Git requirement. (#32, #150, #161)\n- Added ability to install version control requirements without making them\n  editable, e.g.::\n\n    pip install git+https://github.com/pypa/pip/\n\n  (#49)\n- Correctly locate build and source directory on macOS. (#175)\n- Added ``git+https://`` scheme to Git VCS backend.\n\n\n0.8.1\n=====\n\n- Added global --user flag as shortcut for --install-option=\"--user\". From\n  Ronny Pfannschmidt.\n- Added support for `PyPI mirrors <http://pypi.python.org/mirrors>`_ as\n  defined in `PEP 381 <https://www.python.org/dev/peps/pep-0381/>`_, from\n  Jannis Leidel.\n- Fixed git revisions being ignored. Thanks John-Scott Atlakson. (#138)\n- Fixed initial editable install of github package from a tag failing. Thanks\n  John-Scott Atlakson. (#95)\n- Fixed installing if a directory in cwd has the same name as the package\n  you're installing. (#107)\n- --install-option=\"--prefix=~/.local\" ignored with -e. Thanks\n  Ronny Pfannschmidt and Wil Tan. (#39)\n\n\n0.8\n===\n\n- Track which ``build/`` directories pip creates, never remove directories\n  it doesn't create.  From Hugo Lopes Tavares.\n- pip now accepts file:// index URLs. Thanks Dave Abrahams.\n- Various cleanup to make test-running more consistent and less fragile.\n  Thanks Dave Abrahams.\n- Real Windows support (with passing tests). Thanks Dave Abrahams.\n- ``pip-2.7`` etc. scripts are created (Python-version specific scripts)\n- ``contrib/build-standalone`` script creates a runnable ``.zip`` form of\n  pip, from Jannis Leidel\n- Editable git repos are updated when reinstalled\n- Fix problem with ``--editable`` when multiple ``.egg-info/`` directories\n  are found.\n- A number of VCS-related fixes for ``pip freeze``, from Hugo Lopes Tavares.\n- Significant test framework changes, from Hugo Lopes Tavares.\n\n\n0.7.2\n=====\n\n- Set zip_safe=False to avoid problems some people are encountering where\n  pip is installed as a zip file.\n\n\n0.7.1\n=====\n\n- Fixed opening of logfile with no directory name. Thanks Alexandre Conrad.\n- Temporary files are consistently cleaned up, especially after\n  installing bundles, also from Alex Conrad.\n- Tests now require at least ScriptTest 1.0.3.\n\n\n0.7\n===\n\n- Fixed uninstallation on Windows\n- Added ``pip search`` command.\n- Tab-complete names of installed distributions for ``pip uninstall``.\n- Support tab-completion when there is a global-option before the\n  subcommand.\n- Install header files in standard (scheme-default) location when installing\n  outside a virtualenv. Install them to a slightly more consistent\n  non-standard location inside a virtualenv (since the standard location is\n  a non-writable symlink to the global location).\n- pip now logs to a central location by default (instead of creating\n  ``pip-log.txt`` all over the place) and constantly overwrites the\n  file in question. On Unix and macOS this is ``'$HOME/.pip/pip.log'``\n  and on Windows it's ``'%HOME%\\\\pip\\\\pip.log'``. You are still able to\n  override this location with the ``$PIP_LOG_FILE`` environment variable.\n  For a complete (appended) logfile use the separate ``'--log'`` command line\n  option.\n- Fixed an issue with Git that left an editable package as a checkout of a\n  remote branch, even if the default behaviour would have been fine, too.\n- Fixed installing from a Git tag with older versions of Git.\n- Expand \"~\" in logfile and download cache paths.\n- Speed up installing from Mercurial repositories by cloning without\n  updating the working copy multiple times.\n- Fixed installing directly from directories (e.g.\n  ``pip install path/to/dir/``).\n- Fixed installing editable packages with ``svn+ssh`` URLs.\n- Don't print unwanted debug information when running the freeze command.\n- Create log file directory automatically. Thanks Alexandre Conrad.\n- Make test suite easier to run successfully. Thanks Dave Abrahams.\n- Fixed \"pip install .\" and \"pip install ..\"; better error for directory\n  without setup.py. Thanks Alexandre Conrad.\n- Support Debian/Ubuntu \"dist-packages\" in zip command. Thanks duckx.\n- Fix relative --src folder. Thanks Simon Cross.\n- Handle missing VCS with an error message. Thanks Alexandre Conrad.\n- Added --no-download option to install; pairs with --no-install to separate\n  download and installation into two steps. Thanks Simon Cross.\n- Fix uninstalling from requirements file containing -f, -i, or\n  --extra-index-url.\n- Leftover build directories are now removed. Thanks Alexandre Conrad.\n\n\n0.6.3\n=====\n\n- Fixed import error on Windows with regard to the backwards compatibility\n  package\n\n0.6.2\n=====\n\n- Fixed uninstall when /tmp is on a different filesystem.\n- Fixed uninstallation of distributions with namespace packages.\n\n\n0.6.1\n=====\n\n- Added support for the ``https`` and ``http-static`` schemes to the\n  Mercurial and ``ftp`` scheme to the Bazaar backend.\n- Fixed uninstallation of scripts installed with easy_install.\n- Fixed an issue in the package finder that could result in an\n  infinite loop while looking for links.\n- Fixed issue with ``pip bundle`` and local files (which weren't being\n  copied into the bundle), from Whit Morriss.\n\n\n0.6\n===\n\n- Add ``pip uninstall`` and uninstall-before upgrade (from Carl Meyer).\n- Extended configurability with config files and environment variables.\n- Allow packages to be upgraded, e.g., ``pip install Package==0.1``\n  then ``pip install Package==0.2``.\n- Allow installing/upgrading to Package==dev (fix \"Source version does not\n  match target version\" errors).\n- Added command and option completion for bash and zsh.\n- Extended integration with virtualenv by providing an option to\n  automatically use an active virtualenv and an option to warn if no active\n  virtualenv is found.\n- Fixed a bug with pip install --download and editable packages, where\n  directories were being set with 0000 permissions, now defaults to 755.\n- Fixed uninstallation of easy_installed console_scripts.\n- Fixed uninstallation on macOS Framework layout installs\n- Fixed bug preventing uninstall of editables with source outside venv.\n- Creates download cache directory if not existing.\n\n\n0.5.1\n=====\n\n- Fixed a couple little bugs, with git and with extensions.\n\n\n0.5\n===\n\n- Added ability to override the default log file name (``pip-log.txt``)\n  with the environmental variable ``$PIP_LOG_FILE``.\n- Made the freeze command print installed packages to stdout instead of\n  writing them to a file. Use simple redirection (e.g.\n  ``pip freeze > stable-req.txt``) to get a file with requirements.\n- Fixed problem with freezing editable packages from a Git repository.\n- Added support for base URLs using ``<base href='...'>`` when parsing\n  HTML pages.\n- Fixed installing of non-editable packages from version control systems.\n- Fixed issue with Bazaar's bzr+ssh scheme.\n- Added --download-dir option to the install command to retrieve package\n  archives. If given an editable package it will create an archive of it.\n- Added ability to pass local file and directory paths to ``--find-links``,\n  e.g. ``--find-links=file:///path/to/my/private/archive``\n- Reduced the amount of console log messages when fetching a page to find a\n  distribution was problematic. The full messages can be found in pip-log.txt.\n- Added ``--no-deps`` option to install ignore package dependencies\n- Added ``--no-index`` option to ignore the package index (PyPI) temporarily\n- Fixed installing editable packages from Git branches.\n- Fixes freezing of editable packages from Mercurial repositories.\n- Fixed handling read-only attributes of build files, e.g. of Subversion and\n  Bazaar on Windows.\n- When downloading a file from a redirect, use the redirected\n  location's extension to guess the compression (happens specifically\n  when redirecting to a bitbucket.org tip.gz file).\n- Editable freeze URLs now always use revision hash/id rather than tip or\n  branch names which could move.\n- Fixed comparison of repo URLs so incidental differences such as\n  presence/absence of final slashes or quoted/unquoted special\n  characters don't trigger \"ignore/switch/wipe/backup\" choice.\n- Fixed handling of attempt to checkout editable install to a\n  non-empty, non-repo directory.\n\n\n0.4\n===\n\n- Make ``-e`` work better with local hg repositories\n- Construct PyPI URLs the exact way easy_install constructs URLs (you\n  might notice this if you use a custom index that is\n  slash-sensitive).\n- Improvements on Windows (from `Ionel Maries Cristian\n  <https://ionelmc.wordpress.com/>`_).\n- Fixed problem with not being able to install private git repositories.\n- Make ``pip zip`` zip all its arguments, not just the first.\n- Fix some filename issues on Windows.\n- Allow the ``-i`` and ``--extra-index-url`` options in requirements\n  files.\n- Fix the way bundle components are unpacked and moved around, to make\n  bundles work.\n- Adds ``-s`` option to allow the access to the global site-packages if a\n  virtualenv is to be created.\n- Fixed support for Subversion 1.6.\n\n\n0.3.1\n=====\n\n- Improved virtualenv restart and various path/cleanup problems on win32.\n- Fixed a regression with installing from svn repositories (when not\n  using ``-e``).\n- Fixes when installing editable packages that put their source in a\n  subdirectory (like ``src/``).\n- Improve ``pip -h``\n\n\n0.3\n===\n\n- Added support for editable packages created from Git, Mercurial and Bazaar\n  repositories and ability to freeze them. Refactored support for version\n  control systems.\n- Do not use ``sys.exit()`` from inside the code, instead use a\n  return.  This will make it easier to invoke programmatically.\n- Put the install record in ``Package.egg-info/installed-files.txt``\n  (previously they went in\n  ``site-packages/install-record-Package.txt``).\n- Fix a problem with ``pip freeze`` not including ``-e svn+`` when an\n  svn structure is peculiar.\n- Allow ``pip -E`` to work with a virtualenv that uses a different\n  version of Python than the parent environment.\n- Fixed Win32 virtualenv (``-E``) option.\n- Search the links passed in with ``-f`` for packages.\n- Detect zip files, even when the file doesn't have a ``.zip``\n  extension and it is served with the wrong Content-Type.\n- Installing editable from existing source now works, like ``pip\n  install -e some/path/`` will install the package in ``some/path/``.\n  Most importantly, anything that package requires will also be\n  installed by pip.\n- Add a ``--path`` option to ``pip un/zip``, so you can avoid zipping\n  files that are outside of where you expect.\n- Add ``--simulate`` option to ``pip zip``.\n\n\n0.2.1\n=====\n\n- Fixed small problem that prevented using ``pip.py`` without actually\n  installing pip.\n- Fixed ``--upgrade``, which would download and appear to install\n  upgraded packages, but actually just reinstall the existing package.\n- Fixed Windows problem with putting the install record in the right\n  place, and generating the ``pip`` script with Setuptools.\n- Download links that include embedded spaces or other unsafe\n  characters (those characters get %-encoded).\n- Fixed use of URLs in requirement files, and problems with some blank\n  lines.\n- Turn some tar file errors into warnings.\n\n\n0.2\n===\n\n- Renamed to ``pip``, and to install you now do ``pip install\n  PACKAGE``\n- Added command ``pip zip PACKAGE`` and ``pip unzip PACKAGE``.  This\n  is particularly intended for Google App Engine to manage libraries\n  to stay under the 1000-file limit.\n- Some fixes to bundles, especially editable packages and when\n  creating a bundle using unnamed packages (like just an svn\n  repository without ``#egg=Package``).\n\n\n0.1.4\n=====\n\n- Added an option ``--install-option`` to pass options to pass\n  arguments to ``setup.py install``\n- ``.svn/`` directories are no longer included in bundles, as these\n  directories are specific to a version of svn -- if you build a\n  bundle on a system with svn 1.5, you can't use the checkout on a\n  system with svn 1.4.  Instead a file ``svn-checkout.txt`` is\n  included that notes the original location and revision, and the\n  command you can use to turn it back into an svn checkout.  (Probably\n  unpacking the bundle should, maybe optionally, recreate this\n  information -- but that is not currently implemented, and it would\n  require network access.)\n- Avoid ambiguities over project name case, where for instance\n  MyPackage and mypackage would be considered different packages.\n  This in particular caused problems on Macs, where ``MyPackage/`` and\n  ``mypackage/`` are the same directory.\n- Added support for an environmental variable\n  ``$PIP_DOWNLOAD_CACHE`` which will cache package downloads, so\n  future installations won't require large downloads.  Network access\n  is still required, but just some downloads will be avoided when\n  using this.\n\n\n0.1.3\n=====\n\n- Always use ``svn checkout`` (not ``export``) so that\n  ``tag_svn_revision`` settings give the revision of the package.\n- Don't update checkouts that came from ``.pybundle`` files.\n\n\n0.1.2\n=====\n\n- Improve error text when there are errors fetching HTML pages when\n  seeking packages.\n- Improve bundles: include empty directories, make them work with\n  editable packages.\n- If you use ``-E env`` and the environment ``env/`` doesn't exist, a\n  new virtual environment will be created.\n- Fix ``dependency_links`` for finding packages.\n\n\n0.1.1\n=====\n\n- Fixed a NameError exception when running pip outside of a virtualenv\n  environment.\n- Added HTTP proxy support (from Prabhu Ramachandran)\n- Fixed use of ``hashlib.md5`` on python2.5+ (also from Prabhu Ramachandran)\n\n\n0.1\n===\n\n- Initial release\n"
  },
  {
    "path": "README.rst",
    "content": "pip - The Python Package Installer\n==================================\n\n.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg\n   :target: https://pypi.org/project/pip/\n   :alt: PyPI\n\n.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip\n   :target: https://pypi.org/project/pip\n   :alt: PyPI - Python Version\n\n.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest\n   :target: https://pip.pypa.io/en/latest\n   :alt: Documentation\n\n|pypi-version| |python-versions| |docs-badge|\n\npip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.\n\nPlease take a look at our documentation for how to install and use pip:\n\n* `Installation`_\n* `Usage`_\n\nWe release updates regularly, with a new version every 3 months. Find more details in our documentation:\n\n* `Release notes`_\n* `Release process`_\n\nIf you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:\n\n* `Issue tracking`_\n* `Discourse channel`_\n* `User IRC`_\n\nIf you want to get involved, head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:\n\n* `GitHub page`_\n* `Development documentation`_\n* `Development IRC`_\n\nCode of Conduct\n---------------\n\nEveryone interacting in the pip project's codebases, issue trackers, chat\nrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.\n\n.. _package installer: https://packaging.python.org/guides/tool-recommendations/\n.. _Python Package Index: https://pypi.org\n.. _Installation: https://pip.pypa.io/en/stable/installation/\n.. _Usage: https://pip.pypa.io/en/stable/\n.. _Release notes: https://pip.pypa.io/en/stable/news.html\n.. _Release process: https://pip.pypa.io/en/latest/development/release-process/\n.. _GitHub page: https://github.com/pypa/pip\n.. _Development documentation: https://pip.pypa.io/en/latest/development\n.. _Issue tracking: https://github.com/pypa/pip/issues\n.. _Discourse channel: https://discuss.python.org/c/packaging\n.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa\n.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev\n.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Reporting a Vulnerability\n\nPlease read the guidelines on reporting security issues [on the\nofficial website](https://www.python.org/dev/security/) for\ninstructions on how to report a security-related problem to\nthe Python Security Response Team responsibly.\n\nTo reach the response team, email `security at python dot org`.\n"
  },
  {
    "path": "build-project/.python-version",
    "content": "3.12\n"
  },
  {
    "path": "build-project/build-project.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Build pip using pinned build requirements.\"\"\"\n\nimport subprocess\nimport tempfile\nimport venv\nfrom os import PathLike\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Union\n\n\nclass EnvBuilder(venv.EnvBuilder):\n    \"\"\"A subclass of venv.EnvBuilder that exposes the python executable command.\"\"\"\n\n    def ensure_directories(\n        self, env_dir: Union[str, bytes, \"PathLike[str]\", \"PathLike[bytes]\"]\n    ) -> SimpleNamespace:\n        context = super().ensure_directories(env_dir)\n        self.env_exec_cmd = context.env_exec_cmd\n        return context\n\n\ndef get_git_head_timestamp() -> str:\n    return subprocess.run(\n        [\n            \"git\",\n            \"log\",\n            \"-1\",\n            \"--pretty=format:%ct\",\n        ],\n        text=True,\n        stdout=subprocess.PIPE,\n    ).stdout.strip()\n\n\ndef main() -> None:\n    with tempfile.TemporaryDirectory() as build_env:\n        env_builder = EnvBuilder(with_pip=True)\n        # If this venv creation step fails, you may be hitting\n        # https://github.com/astral-sh/python-build-standalone/issues/381\n        # Try running with a another Python distribution.\n        env_builder.create(build_env)\n        subprocess.run(\n            [\n                env_builder.env_exec_cmd,\n                \"-Im\",\n                \"pip\",\n                \"install\",\n                \"--no-deps\",\n                \"--only-binary=:all:\",\n                \"--require-hashes\",\n                \"-r\",\n                Path(__file__).parent / \"build-requirements.txt\",\n            ],\n            check=True,\n        )\n        subprocess.run(\n            [\n                env_builder.env_exec_cmd,\n                \"-Im\",\n                \"build\",\n                \"--no-isolation\",\n            ],\n            check=True,\n            env={\"SOURCE_DATE_EPOCH\": get_git_head_timestamp()},\n            cwd=Path(__file__).parent.parent,\n        )\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "build-project/build-requirements.in",
    "content": "build\nflit-core\n"
  },
  {
    "path": "build-project/build-requirements.txt",
    "content": "#\n# This file is autogenerated by pip-compile with Python 3.12\n# by the following command:\n#\n#    pip-compile --allow-unsafe --generate-hashes build-requirements.in\n#\nbuild==1.4.0 \\\n    --hash=sha256:6a07c1b8eb6f2b311b96fcbdbce5dab5fe637ffda0fd83c9cac622e927501596 \\\n    --hash=sha256:f1b91b925aa322be454f8330c6fb48b465da993d1e7e7e6fa35027ec49f3c936\n    # via -r build-requirements.in\nflit-core==3.12.0 \\\n    --hash=sha256:18f63100d6f94385c6ed57a72073443e1a71a4acb4339491615d0f16d6ff01b2 \\\n    --hash=sha256:e7a0304069ea895172e3c7bb703292e992c5d1555dd1233ab7b5621b5b69e62c\n    # via -r build-requirements.in\npackaging==25.0 \\\n    --hash=sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484 \\\n    --hash=sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f\n    # via build\npyproject-hooks==1.2.0 \\\n    --hash=sha256:1e859bd5c40fae9448642dd871adf459e5e2084186e8d2c2a79a824c970da1f8 \\\n    --hash=sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913\n    # via build\n"
  },
  {
    "path": "docs/html/cli/index.md",
    "content": "# Commands\n\nThe general options that apply to all the commands listed below can be\nfound [under the `pip` page in this section](pip).\n\n```{toctree}\n:maxdepth: 1\n:hidden:\n\npip\n```\n\n```{toctree}\n:maxdepth: 1\n:caption: Environment Management and Introspection\n\npip_install\npip_uninstall\npip_inspect\npip_list\npip_show\npip_freeze\npip_check\n```\n\n```{toctree}\n:maxdepth: 1\n:caption: Resolving dependencies\n\npip_lock\n```\n\n```{toctree}\n:maxdepth: 1\n:caption: Handling Distribution Files\n\npip_download\npip_wheel\npip_hash\n```\n\n```{toctree}\n:maxdepth: 1\n:caption: Package Index information\n\npip_search\npip_index\n```\n\n```{toctree}\n:maxdepth: 1\n:caption: Managing pip itself\n\npip_cache\npip_config\npip_debug\n```\n"
  },
  {
    "path": "docs/html/cli/pip.rst",
    "content": "===\npip\n===\n\n\nUsage\n*****\n\n.. tab:: Unix/macOS\n\n    .. code-block:: shell\n\n        python -m pip <command> [options]\n\n.. tab:: Windows\n\n    .. code-block:: shell\n\n        py -m pip <command> [options]\n\nDescription\n***********\n\n\n.. _`Logging`:\n\n\nLogging\n=======\n\nConsole logging\n~~~~~~~~~~~~~~~\n\npip offers :ref:`-v, --verbose <--verbose>` and :ref:`-q, --quiet <--quiet>`\nto control the console log level. By default, some messages (error and warnings)\nare colored in the terminal. If you want to suppress the colored output use\n:ref:`--no-color <--no-color>`.\n\n\n.. _`FileLogging`:\n\nFile logging\n~~~~~~~~~~~~\n\npip offers the :ref:`--log <--log>` option for specifying a file where a maximum\nverbosity log will be kept.  This option is empty by default. This log appends\nto previous logging.\n\nLike all pip options, ``--log`` can also be set as an environment variable, or\nplaced into the pip config file. See the :doc:`../topics/configuration` section.\n\n.. _`exists-action`:\n\n--exists-action option\n======================\n\nThis option specifies default behavior when path already exists.\nPossible cases: downloading files or checking out repositories for installation,\ncreating archives. If ``--exists-action`` is not defined, pip will prompt\nwhen decision is needed.\n\n*(s)witch*\n    Only relevant to VCS checkout. Attempt to switch the checkout\n    to the appropriate URL and/or revision.\n*(i)gnore*\n    Abort current operation (e.g. don't copy file, don't create archive,\n    don't modify a checkout).\n*(w)ipe*\n    Delete the file or VCS checkout before trying to create, download, or checkout a new one.\n*(b)ackup*\n    Rename the file or checkout to ``{name}{'.bak' * n}``, where n is some number\n    of ``.bak`` extensions, such that the file didn't exist at some point.\n    So the most recent backup will be the one with the largest number after ``.bak``.\n*(a)bort*\n    Abort pip and return non-zero exit status.\n\n.. _`2-build-system-interface`:\n.. rubric:: Build System Interface\n\nThis is now covered in :doc:`../reference/build-system`.\n\n.. _`General Options`:\n\nGeneral Options\n***************\n\n.. pip-general-options::\n"
  },
  {
    "path": "docs/html/cli/pip_cache.rst",
    "content": "\n.. _`pip cache`:\n\npip cache\n---------\n\n\nUsage\n*****\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: cache \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: cache \"py -m pip\"\n\nDescription\n***********\n\n.. pip-command-description:: cache\n\nOptions\n*******\n\n.. pip-command-options:: cache\n"
  },
  {
    "path": "docs/html/cli/pip_check.rst",
    "content": ".. _`pip check`:\n\n=========\npip check\n=========\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: check \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: check \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: check\n\n\nExamples\n========\n\n#. If all dependencies are compatible:\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip check\n         No broken requirements found.\n         $ echo $?\n         0\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip check\n         No broken requirements found.\n         C:\\> echo %errorlevel%\n         0\n\n#. If a package is missing:\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip check\n         pyramid 1.5.2 requires WebOb, which is not installed.\n         $ echo $?\n         1\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip check\n         pyramid 1.5.2 requires WebOb, which is not installed.\n         C:\\> echo %errorlevel%\n         1\n\n#. If a package has the wrong version:\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip check\n         pyramid 1.5.2 has requirement WebOb>=1.3.1, but you have WebOb 0.8.\n         $ echo $?\n         1\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip check\n         pyramid 1.5.2 has requirement WebOb>=1.3.1, but you have WebOb 0.8.\n         C:\\> echo %errorlevel%\n         1\n"
  },
  {
    "path": "docs/html/cli/pip_config.rst",
    "content": "\n.. _`pip config`:\n\n==========\npip config\n==========\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: config \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: config \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: config\n\n\nOptions\n=======\n\n.. pip-command-options:: config\n"
  },
  {
    "path": "docs/html/cli/pip_debug.rst",
    "content": ".. _`pip debug`:\n\n=========\npip debug\n=========\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: debug \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: debug \"py -m pip\"\n\n\n.. warning::\n\n    This command is only meant for debugging.\n    Its options and outputs are provisional and may change without notice.\n\n\nDescription\n===========\n\n.. pip-command-description:: debug\n\n\nOptions\n=======\n\n.. pip-command-options:: debug\n"
  },
  {
    "path": "docs/html/cli/pip_download.rst",
    "content": "\n.. _`pip download`:\n\n============\npip download\n============\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: download \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: download \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: download\n\nOverview\n--------\n\n``pip download`` does the same resolution and downloading as ``pip install``,\nbut instead of installing the dependencies, it collects the downloaded\ndistributions into the directory provided (defaulting to the current\ndirectory). This directory can later be passed as the value to ``pip install\n--find-links`` to facilitate offline or locked down package installation.\n\n``pip download`` with the ``--platform``, ``--python-version``,\n``--implementation``, and ``--abi`` options provides the ability to fetch\ndependencies for an interpreter and system other than the ones that pip is\nrunning on. ``--only-binary=:all:`` or ``--no-deps`` is required when using any\nof these options. It is important to note that these options all default to the\ncurrent system/interpreter, and not to the most restrictive constraints (e.g.\nplatform any, abi none, etc). To avoid fetching dependencies that happen to\nmatch the constraint of the current interpreter (but not your target one), it\nis recommended to specify all of these options if you are specifying one of\nthem. Generic dependencies (e.g. universal wheels, or dependencies with no\nplatform, abi, or implementation constraints) will still match an over-\nconstrained download requirement. If some of your dependencies are not\navailable as binaries, you can build them manually for your target platform\nand let pip download know where to find them using ``--find-links``.\n\n.. note::\n\n   To determine the appropriate values for ``--python-version`` and ``--platform``, you can query the target system using the following commands:\n\n   - For the Python version, use :func:`sysconfig.get_python_version() <sysconfig.get_python_version>`.\n   - For the platform, use :func:`packaging.tags.platform_tags() <packaging.tags.platform_tags>`.\n\nOptions\n=======\n\n.. pip-command-options:: download\n\n.. pip-index-options:: download\n\n.. pip-package-selection-options:: download\n\n\nExamples\n========\n\n#. Download a package and all of its dependencies\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip download SomePackage\n         python -m pip download -d . SomePackage  # equivalent to above\n         python -m pip download --no-index --find-links=/tmp/wheelhouse -d /tmp/otherwheelhouse SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip download SomePackage\n         py -m pip download -d . SomePackage  # equivalent to above\n         py -m pip download --no-index --find-links=/tmp/wheelhouse -d /tmp/otherwheelhouse SomePackage\n\n\n#. Download a package and all of its dependencies with OSX specific interpreter constraints.\n   This forces OSX 10.10 or lower compatibility. Since OSX deps are forward compatible,\n   this will also match ``macosx_10_9_x86_64``, ``macosx_10_8_x86_64``, ``macosx_10_8_intel``,\n   etc.\n   It will also match deps with platform ``any``. Also force the interpreter version to ``27``\n   (or more generic, i.e. ``2``) and implementation to ``cp`` (or more generic, i.e. ``py``).\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip download \\\n            --only-binary=:all: \\\n            --platform macosx_10_10_x86_64 \\\n            --python-version 27 \\\n            --implementation cp \\\n            SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip download ^\n            --only-binary=:all: ^\n            --platform macosx_10_10_x86_64 ^\n            --python-version 27 ^\n            --implementation cp ^\n            SomePackage\n\n#. Download a package and its dependencies with linux specific constraints.\n   Force the interpreter to be any minor version of py3k, and only accept\n   ``cp34m`` or ``none`` as the abi.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip download \\\n            --only-binary=:all: \\\n            --platform linux_x86_64 \\\n            --python-version 3 \\\n            --implementation cp \\\n            --abi cp34m \\\n            SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip download ^\n            --only-binary=:all: ^\n            --platform linux_x86_64 ^\n            --python-version 3 ^\n            --implementation cp ^\n            --abi cp34m ^\n            SomePackage\n\n#. Force platform, implementation, and abi agnostic deps.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip download \\\n            --only-binary=:all: \\\n            --platform any \\\n            --python-version 3 \\\n            --implementation py \\\n            --abi none \\\n            SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip download ^\n            --only-binary=:all: ^\n            --platform any ^\n            --python-version 3 ^\n            --implementation py ^\n            --abi none ^\n            SomePackage\n\n#. Even when overconstrained, this will still correctly fetch the pip universal wheel.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip download \\\n            --only-binary=:all: \\\n            --platform linux_x86_64 \\\n            --python-version 33 \\\n            --implementation cp \\\n            --abi cp34m \\\n            pip>=8\n\n      .. code-block:: console\n\n         $ ls pip-8.1.1-py2.py3-none-any.whl\n         pip-8.1.1-py2.py3-none-any.whl\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip download ^\n            --only-binary=:all: ^\n            --platform linux_x86_64 ^\n            --python-version 33 ^\n            --implementation cp ^\n            --abi cp34m ^\n            pip>=8\n\n      .. code-block:: console\n\n         C:\\> dir pip-8.1.1-py2.py3-none-any.whl\n         pip-8.1.1-py2.py3-none-any.whl\n\n#. Download a package supporting one of several ABIs and platforms.\n   This is useful when fetching wheels for a well-defined interpreter, whose\n   supported ABIs and platforms are known and fixed, different than the one pip is\n   running under.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip download \\\n            --only-binary=:all: \\\n            --platform manylinux1_x86_64 --platform linux_x86_64 --platform any \\\n            --python-version 36 \\\n            --implementation cp \\\n            --abi cp36m --abi cp36 --abi abi3 --abi none \\\n            SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:> py -m pip download ^\n            --only-binary=:all: ^\n            --platform manylinux1_x86_64 --platform linux_x86_64 --platform any ^\n            --python-version 36 ^\n            --implementation cp ^\n            --abi cp36m --abi cp36 --abi abi3 --abi none ^\n            SomePackage\n"
  },
  {
    "path": "docs/html/cli/pip_freeze.rst",
    "content": "\n.. _`pip freeze`:\n\n==========\npip freeze\n==========\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: freeze \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: freeze \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: freeze\n\n.. note::\n   By default, ``pip freeze`` omits bootstrap packaging tools so the output\n   focuses on your project’s dependencies. On Python **3.11 and earlier**\n   this excludes ``pip``, ``setuptools``, ``wheel`` and ``distribute``; on\n   Python **3.12 and later** only ``pip`` is excluded. Use ``--all`` to\n   include those packages when you need a complete environment snapshot.\n   ``pip freeze`` reports what is installed; it does **not** compute a\n   lockfile or a solver result.\n\n\nOptions\n=======\n\n.. pip-command-options:: freeze\n\n\nExamples\n========\n\n#. Generate output suitable for a requirements file.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip freeze\n         docutils==0.11\n         Jinja2==2.7.2\n         MarkupSafe==0.19\n         Pygments==1.6\n         Sphinx==1.2.2\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip freeze\n         docutils==0.11\n         Jinja2==2.7.2\n         MarkupSafe==0.19\n         Pygments==1.6\n         Sphinx==1.2.2\n\n#. Generate a requirements file and then install from it in another environment.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         env1/bin/python -m pip freeze > requirements.txt\n         env2/bin/python -m pip install -r requirements.txt\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         env1\\bin\\python -m pip freeze > requirements.txt\n         env2\\bin\\python -m pip install -r requirements.txt\n\n\nFixing \"Permission denied:\" errors\n==================================\n\nThe purpose of this section of documentation is to provide practical\nsuggestions to users seeing a `\"Permission denied\" error <https://github.com/pypa/pip/issues/8418>`__ on ``pip freeze``.\n\nThis error occurs, for instance, when the command is installed only for another\nuser, and the current user doesn't have the permission to execute the other\nuser's command.\n\nTo solve that issue, you can try one of the following:\n\n- Install the command for yourself (e.g. in your home directory).\n- Ask the system admin to allow this command for all users.\n- Check and correct the PATH variable of your own environment.\n- Check the `ACL (Access-Control List) <https://en.wikipedia.org/wiki/Access-control_list>`_ for this command.\n"
  },
  {
    "path": "docs/html/cli/pip_hash.rst",
    "content": ".. _`pip hash`:\n\n========\npip hash\n========\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: hash \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: hash \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: hash\n\nOverview\n--------\n\n``pip hash`` is a convenient way to get a hash digest for use with\n:ref:`hash-checking mode`, especially for packages with multiple archives. The\nerror message from ``pip install --require-hashes ...`` will give you one\nhash, but, if there are multiple archives (like source and binary ones), you\nwill need to manually download and compute a hash for the others. Otherwise, a\nspurious hash mismatch could occur when :ref:`pip install` is passed a\ndifferent set of options, like :ref:`--no-binary <install_--no-binary>`.\n\n\nOptions\n=======\n\n.. pip-command-options:: hash\n\n\nExample\n=======\n\nCompute the hash of a downloaded archive:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip download SomePackage\n      Collecting SomePackage\n         Downloading SomePackage-2.2.tar.gz\n         Saved ./pip_downloads/SomePackage-2.2.tar.gz\n      Successfully downloaded SomePackage\n      $ python -m pip hash ./pip_downloads/SomePackage-2.2.tar.gz\n      ./pip_downloads/SomePackage-2.2.tar.gz:\n      --hash=sha256:93e62e05c7ad3da1a233def6731e8285156701e3419a5fe279017c429ec67ce0\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip download SomePackage\n      Collecting SomePackage\n         Downloading SomePackage-2.2.tar.gz\n         Saved ./pip_downloads/SomePackage-2.2.tar.gz\n      Successfully downloaded SomePackage\n      C:\\> py -m pip hash ./pip_downloads/SomePackage-2.2.tar.gz\n      ./pip_downloads/SomePackage-2.2.tar.gz:\n      --hash=sha256:93e62e05c7ad3da1a233def6731e8285156701e3419a5fe279017c429ec67ce0\n"
  },
  {
    "path": "docs/html/cli/pip_index.rst",
    "content": ".. _`pip index`:\n\n===========\npip index\n===========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: index \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: index \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: index\n\n\n\nOptions\n=======\n\n.. pip-command-options:: index\n\n.. pip-index-options:: index\n\n.. pip-package-selection-options:: index\n\n\nExamples\n========\n\n#. Search for \"peppercorn\" versions\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip index versions peppercorn\n         peppercorn (0.6)\n         Available versions: 0.6, 0.5, 0.4, 0.3, 0.2, 0.1\n\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip index peppercorn\n         peppercorn (0.6)\n         Available versions: 0.6, 0.5, 0.4, 0.3, 0.2, 0.1\n"
  },
  {
    "path": "docs/html/cli/pip_inspect.rst",
    "content": ".. _`pip inspect`:\n\n===========\npip inspect\n===========\n\n.. versionadded:: 22.2\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: inspect \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: inspect \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: inspect\n\nThe format of the JSON output is described in :doc:`../reference/inspect-report`.\n\n\nOptions\n=======\n\n.. pip-command-options:: inspect\n"
  },
  {
    "path": "docs/html/cli/pip_install.rst",
    "content": ".. _`pip install`:\n\n===========\npip install\n===========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: install 'python -m pip'\n\n.. tab:: Windows\n\n   .. pip-command-usage:: install \"py -m pip\"\n\n\n\nDescription\n===========\n\n.. pip-command-description:: install\n\nOverview\n--------\n\npip install has several stages:\n\n1. Identify the base requirements. The user supplied arguments are processed\n   here.\n2. Resolve dependencies. What will be installed is determined here.\n3. Build wheels. All the dependencies that can be are built into wheels.\n4. Install the packages (and uninstall anything being upgraded/replaced).\n\nNote that ``pip install`` prefers to leave the installed version as-is\nunless ``--upgrade`` is specified.\n\nArgument Handling\n-----------------\n\nWhen looking at the items to be installed, pip checks what type of item\neach is, in the following order:\n\n1. Project or archive URL.\n2. Local directory (which must contain a ``pyproject.toml`` or ``setup.py``,\n   otherwise pip will report an error).\n3. Local file (a sdist or wheel format archive, following the naming\n   conventions for those formats).\n4. A :ref:`version specifier <pypug:version-specifiers>`.\n\nEach item identified is added to the set of requirements to be satisfied by\nthe install.\n\nWorking Out the Name and Version\n--------------------------------\n\nFor each candidate item, pip needs to know the project name and version. For\nwheels (identified by the ``.whl`` file extension) this can be obtained from\nthe filename, as per the Wheel spec. For local directories, or explicitly\nspecified sdist files, the ``setup.py egg_info`` command is used to determine\nthe project metadata. For sdists located via an index, the filename is parsed\nfor the name and project version (this is in theory slightly less reliable\nthan using the ``egg_info`` command, but avoids downloading and processing\nunnecessary numbers of files).\n\nThe :ref:`Direct URL requirement syntax <pypug:dependency-specifiers>` can be used\nto explicitly state the project name (see :doc:`../topics/vcs-support`).\n\nSatisfying Requirements\n-----------------------\n\nOnce pip has the set of requirements to satisfy, it chooses which version of\neach requirement to install using the simple rule that the latest version that\nsatisfies the given constraints will be installed (but see :ref:`here <Pre Release Versions>`\nfor an exception regarding pre-release versions). Where more than one source of\nthe chosen version is available, it is assumed that any source is acceptable\n(as otherwise the versions would differ).\n\nObtaining information about what was installed\n----------------------------------------------\n\nThe install command has a ``--report`` option that will generate a JSON report of what\npip has installed. In combination with the ``--dry-run`` and ``--ignore-installed`` it\ncan be used to *resolve* a set of requirements without actually installing them.\n\nThe report can be written to a file, or to standard output (using ``--report -`` in\ncombination with ``--quiet``).\n\nThe format of the JSON report is described in :doc:`../reference/installation-report`.\n\nInstallation Order\n------------------\n\n.. note::\n\n   This section is only about installation order of runtime dependencies, and\n   does not apply to build dependencies (those are specified using the\n   :ref:`[build-system] table <pypug:pyproject-build-system-table>`).\n\nAs of v6.1.0, pip installs dependencies before their dependents, i.e. in\n\"topological order.\"  This is the only commitment pip currently makes related\nto order.  While it may be coincidentally true that pip will install things in\nthe order of the install arguments or in the order of the items in a\nrequirements file, this is not a promise.\n\nIn the event of a dependency cycle (aka \"circular dependency\"), the current\nimplementation (which might possibly change later) has it such that the first\nencountered member of the cycle is installed last.\n\nFor instance, if quux depends on foo which depends on bar which depends on baz,\nwhich depends on foo:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install quux\n      ...\n      Installing collected packages baz, bar, foo, quux\n\n      $ python -m pip install bar\n      ...\n      Installing collected packages foo, baz, bar\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install quux\n      ...\n      Installing collected packages baz, bar, foo, quux\n\n      C:\\> py -m pip install bar\n      ...\n      Installing collected packages foo, baz, bar\n\n\nPrior to v6.1.0, pip made no commitments about install order.\n\nThe decision to install topologically is based on the principle that\ninstallations should proceed in a way that leaves the environment usable at each\nstep. This has two main practical benefits:\n\n1. Concurrent use of the environment during the install is more likely to work.\n2. A failed install is less likely to leave a broken environment.  Although pip\n   would like to support failure rollbacks eventually, in the mean time, this is\n   an improvement.\n\nAlthough the new install order is not intended to replace (and does not replace)\nthe use of ``setup_requires`` to declare build dependencies, it may help certain\nprojects install from sdist (that might previously fail) that fit the following\nprofile:\n\n1. They have build dependencies that are also declared as install dependencies\n   using ``install_requires``.\n2. ``python setup.py egg_info`` works without their build dependencies being\n   installed.\n3. For whatever reason, they don't or won't declare their build dependencies using\n   ``setup_requires``.\n\n.. _`0-requirements-file-format`:\n.. rubric:: Requirements File Format\n\nThis section has been moved to :doc:`../reference/requirements-file-format`.\n\n.. _`0-requirement-specifiers`:\n.. rubric:: Requirement Specifiers\n\nThis section has been moved to :doc:`../reference/requirement-specifiers`.\n\n.. _`0-per-requirement-overrides`:\n.. rubric:: Per-requirement Overrides\n\nThis is now covered in :doc:`../reference/requirements-file-format`.\n\n.. _`Pre Release Versions`:\n\nPre-release Versions\n--------------------\n\nStarting with v1.4, pip will only install stable versions as specified by\n`pre-releases`_ by default. If a version cannot be parsed as a\n:ref:`compliant <pypug:version-specifiers>` version then it is assumed to be\na pre-release.\n\nIf a Requirement specifier includes a pre-release or development version\n(e.g. ``>=0.0.dev0``) then pip will allow pre-release and development versions\nfor that requirement. This does not include the != flag.\n\nThe ``pip install`` command also supports a :ref:`--pre <install_--pre>` flag\nthat enables installation of pre-releases and development releases.\n\n\n.. _pre-releases: https://www.python.org/dev/peps/pep-0440/#handling-of-pre-releases\n\n.. _`0-vcs-support`:\n.. rubric:: VCS Support\n\nThis is now covered in :doc:`../topics/vcs-support`.\n\nFinding Packages\n----------------\n\npip searches for packages on `PyPI`_ using the\n`HTTP simple interface <https://pypi.org/simple/>`_,\nwhich is documented `here <https://packaging.python.org/specifications/simple-repository-api/>`_\nand `there <https://www.python.org/dev/peps/pep-0503/>`_.\n\npip offers a number of package index options for modifying how packages are\nfound.\n\npip looks for packages in a number of places: on PyPI (or the index given as\n``--index-url``, if not disabled via ``--no-index``), in the local filesystem,\nand in any additional repositories specified via ``--find-links`` or\n``--extra-index-url``. There is no priority in the locations that are searched.\nRather they are all checked, and the \"best\" match for the requirements (in\nterms of version number - see the\n:ref:`specification <pypug:version-specifiers>` for details) is selected.\n\nSee the :ref:`pip install Examples<pip install Examples>`.\n\n.. _`0-ssl certificate verification`:\n.. rubric:: SSL Certificate Verification\n\nThis is now covered in :doc:`../topics/https-certificates`.\n\n.. _`0-caching`:\n.. rubric:: Caching\n\nThis is now covered in :doc:`../topics/caching`.\n\n.. _`0-wheel-cache`:\n.. rubric:: Wheel Cache\n\nThis is now covered in :doc:`../topics/caching`.\n\n.. _`0-hash-checking-mode`:\n.. rubric:: Hash checking mode\n\nThis is now covered in :doc:`../topics/secure-installs`.\n\n.. _`0-local-project-installs`:\n.. rubric:: Local Project Installs\n\nThis is now covered in :doc:`../topics/local-project-installs`.\n\n.. _`0-editable-installs`:\n.. rubric:: Editable installs\n\nThis is now covered in :doc:`../topics/local-project-installs`.\n\n.. _`0-build-system-interface`:\n.. rubric:: Build System Interface\n\nThis is now covered in :doc:`../reference/build-system`.\n\n.. _`pip install Options`:\n\nOptions\n=======\n\n.. pip-command-options:: install\n\n.. pip-index-options:: install\n\n.. pip-package-selection-options:: install\n\n.. _`pip install Examples`:\n\n\nExamples\n========\n\n#. Install ``SomePackage`` and its dependencies from `PyPI`_ using :ref:`Requirement Specifiers`\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install SomePackage            # latest version\n         python -m pip install 'SomePackage==1.0.4'   # specific version\n         python -m pip install 'SomePackage>=1.0.4'   # minimum version\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install SomePackage            # latest version\n         py -m pip install \"SomePackage==1.0.4\"   # specific version\n         py -m pip install \"SomePackage>=1.0.4\"   # minimum version\n\n\n#. Install a list of requirements specified in a file.  See the :ref:`Requirements files <Requirements Files>`.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install -r requirements.txt\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install -r requirements.txt\n\n\n#. Upgrade an already installed ``SomePackage`` to the latest from PyPI.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install --upgrade SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install --upgrade SomePackage\n\n   .. note::\n\n      This will guarantee an update to ``SomePackage`` as it is a direct\n      requirement, and possibly upgrade dependencies if their installed\n      versions do not meet the minimum requirements of ``SomePackage``.\n      Any non-requisite updates of its dependencies (indirect requirements)\n      will be affected by the ``--upgrade-strategy`` command.\n\n#. Install a local project in \"editable\" mode. See the section on :ref:`Editable Installs <editable-installs>`.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install -e .                # project in current directory\n         python -m pip install -e path/to/project  # project in another directory\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install -e .                 # project in current directory\n         py -m pip install -e path/to/project   # project in another directory\n\n\n#. Install a project from VCS\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install 'SomeProject@git+https://git.repo/some_pkg.git@1.3.1'\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install \"SomeProject@git+https://git.repo/some_pkg.git@1.3.1\"\n\n\n#. Install a project from VCS in \"editable\" mode. See the sections on :doc:`../topics/vcs-support` and :ref:`Editable Installs <editable-installs>`.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install -e 'SomePackage @ git+https://git.repo/some_pkg.git'          # from git\n         python -m pip install -e 'SomePackage @ hg+https://hg.repo/some_pkg.git'            # from mercurial\n         python -m pip install -e 'SomePackage @ svn+svn://svn.repo/some_pkg/trunk/'         # from svn\n         python -m pip install -e 'SomePackage @ git+https://git.repo/some_pkg.git@feature'  # from 'feature' branch\n         python -m pip install -e 'SomePackage @ git+https://git.repo/some_repo.git#subdirectory=subdir_path' # install a python package from a repo subdirectory\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install -e \"SomePackage @ git+https://git.repo/some_pkg.git\"          # from git\n         py -m pip install -e \"SomePackage @ hg+https://hg.repo/some_pkg.git\"            # from mercurial\n         py -m pip install -e \"SomePackage @ svn+svn://svn.repo/some_pkg/trunk/\"         # from svn\n         py -m pip install -e \"SomePackage @ git+https://git.repo/some_pkg.git@feature\"  # from 'feature' branch\n         py -m pip install -e \"SomePackage @ git+https://git.repo/some_repo.git#subdirectory=subdir_path\" # install a python package from a repo subdirectory\n\n#. Install a package with extras, i.e., optional dependencies\n   (:ref:`specification <pypug:dependency-specifiers>`).\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install 'SomePackage[PDF]'\n         python -m pip install 'SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path'\n         python -m pip install '.[PDF]'  # project in current directory\n         python -m pip install 'SomePackage[PDF]==3.0'\n         python -m pip install 'SomePackage[PDF,EPUB]'  # multiple extras\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install \"SomePackage[PDF]\"\n         py -m pip install \"SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path\"\n         py -m pip install \".[PDF]\"  # project in current directory\n         py -m pip install \"SomePackage[PDF]==3.0\"\n         py -m pip install \"SomePackage[PDF,EPUB]\"  # multiple extras\n\n#. Install a particular source archive file.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install './downloads/SomePackage-1.0.4.tar.gz'\n         python -m pip install 'http://my.package.repo/SomePackage-1.0.4.zip'\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install \"./downloads/SomePackage-1.0.4.tar.gz\"\n         py -m pip install \"http://my.package.repo/SomePackage-1.0.4.zip\"\n\n#. Install a particular source archive file following direct references\n   (:ref:`specification <pypug:dependency-specifiers>`).\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install 'SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'\n         python -m pip install 'SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'\n         python -m pip install 'SomeProject@http://my.package.repo/1.2.3.tar.gz'\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install \"SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl\"\n         py -m pip install \"SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl\"\n         py -m pip install \"SomeProject@http://my.package.repo/1.2.3.tar.gz\"\n\n#. Install from alternative package repositories.\n\n   Install from a different index, and not `PyPI`_\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install --index-url http://my.package.repo/simple/ SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install --index-url http://my.package.repo/simple/ SomePackage\n\n   Install from a local flat directory containing archives (and don't scan indexes):\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install --no-index --find-links=file:///local/dir/ SomePackage\n         python -m pip install --no-index --find-links=/local/dir/ SomePackage\n         python -m pip install --no-index --find-links=relative/dir/ SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install --no-index --find-links=file:///local/dir/ SomePackage\n         py -m pip install --no-index --find-links=/local/dir/ SomePackage\n         py -m pip install --no-index --find-links=relative/dir/ SomePackage\n\n   Search an additional index during install, in addition to `PyPI`_\n\n   .. warning::\n\n       Using the ``--extra-index-url`` option to search for packages which are\n       not in the main repository (for example, private packages) is unsafe.\n       This is a class of security issue known as `dependency confusion <https://azure.microsoft.com/en-us/resources/3-ways-to-mitigate-risk-using-private-package-feeds/>`_: an\n       attacker can publish a package with the same name to a public index,\n       which may then be chosen instead of your private package.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install --extra-index-url http://my.package.repo/simple SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install --extra-index-url http://my.package.repo/simple SomePackage\n\n\n#. Find pre-release and development versions, in addition to stable versions.  By default, pip only finds stable versions.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install --pre SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install --pre SomePackage\n\n\n#. Install packages from source.\n\n   Do not use any binary packages\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install SomePackage1 SomePackage2 --no-binary :all:\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install SomePackage1 SomePackage2 --no-binary :all:\n\n   Specify ``SomePackage1`` to be installed from source:\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1\n\n.. _PyPI: https://pypi.org/\n"
  },
  {
    "path": "docs/html/cli/pip_list.rst",
    "content": ".. _`pip list`:\n\n========\npip list\n========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: list \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: list \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: list\n\n\nOptions\n=======\n\n.. pip-command-options:: list\n\n.. pip-index-options:: list\n\n.. pip-package-selection-options:: list\n\n\nExamples\n========\n\n#. List installed packages (with the default column formatting).\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list\n         Package Version\n         ------- -------\n         docopt  0.6.2\n         idlex   1.13\n         jedi    0.9.0\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list\n         Package Version\n         ------- -------\n         docopt  0.6.2\n         idlex   1.13\n         jedi    0.9.0\n\n#. List outdated packages with column formatting.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list --outdated --format columns\n         Package    Version Latest Type\n         ---------- ------- ------ -----\n         retry      0.8.1   0.9.1  wheel\n         setuptools 20.6.7  21.0.0 wheel\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list --outdated --format columns\n         Package    Version Latest Type\n         ---------- ------- ------ -----\n         retry      0.8.1   0.9.1  wheel\n         setuptools 20.6.7  21.0.0 wheel\n\n#. List packages that are not dependencies of other packages. Can be combined with\n   other options.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list --outdated --not-required\n         Package  Version Latest Type\n         -------- ------- ------ -----\n         docutils 0.14    0.17.1 wheel\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list --outdated --not-required\n         Package  Version Latest Type\n         -------- ------- ------ -----\n         docutils 0.14    0.17.1 wheel\n\n#. Use json formatting\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list --format=json\n         [{'name': 'colorama', 'version': '0.3.7'}, {'name': 'docopt', 'version': '0.6.2'}, ...\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list --format=json\n         [{'name': 'colorama', 'version': '0.3.7'}, {'name': 'docopt', 'version': '0.6.2'}, ...\n\n#. Use freeze formatting\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list --format=freeze\n         colorama==0.3.7\n         docopt==0.6.2\n         idlex==1.13\n         jedi==0.9.0\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list --format=freeze\n         colorama==0.3.7\n         docopt==0.6.2\n         idlex==1.13\n         jedi==0.9.0\n\n#. List packages installed in editable mode\n\n   When some packages are installed in editable mode, ``pip list`` outputs an\n   additional column that shows the directory where the editable project is\n   located (i.e. the directory that contains the ``pyproject.toml`` or\n   ``setup.py`` file).\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list\n         Package          Version  Editable project location\n         ---------------- -------- -------------------------------------\n         pip              21.2.4\n         pip-test-package 0.1.1    /home/you/.venv/src/pip-test-package\n         setuptools       57.4.0\n         wheel            0.36.2\n\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list\n         Package          Version  Editable project location\n         ---------------- -------- ----------------------------------------\n         pip              21.2.4\n         pip-test-package 0.1.1    C:\\Users\\You\\.venv\\src\\pip-test-package\n         setuptools       57.4.0\n         wheel            0.36.2\n\n   The json format outputs an additional ``editable_project_location`` field.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip list --format=json | python -m json.tool\n         [\n           {\n             \"name\": \"pip\",\n             \"version\": \"21.2.4\",\n           },\n           {\n             \"name\": \"pip-test-package\",\n             \"version\": \"0.1.1\",\n             \"editable_project_location\": \"/home/you/.venv/src/pip-test-package\"\n           },\n           {\n             \"name\": \"setuptools\",\n             \"version\": \"57.4.0\"\n           },\n           {\n             \"name\": \"wheel\",\n             \"version\": \"0.36.2\"\n           }\n         ]\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip list --format=json | py -m json.tool\n         [\n           {\n             \"name\": \"pip\",\n             \"version\": \"21.2.4\",\n           },\n           {\n             \"name\": \"pip-test-package\",\n             \"version\": \"0.1.1\",\n             \"editable_project_location\": \"C:\\Users\\You\\.venv\\src\\pip-test-package\"\n           },\n           {\n             \"name\": \"setuptools\",\n             \"version\": \"57.4.0\"\n           },\n           {\n             \"name\": \"wheel\",\n             \"version\": \"0.36.2\"\n           }\n         ]\n\n.. note::\n\n   Contrary to the ``freeze``  command, ``pip list --format=freeze`` will not\n   report editable install information, but the version of the package at the\n   time it was installed.\n"
  },
  {
    "path": "docs/html/cli/pip_lock.rst",
    "content": "\n.. _`pip lock`:\n\n========\npip lock\n========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: lock \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: lock \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: lock\n\nOptions\n=======\n\n.. pip-command-options:: lock\n\n.. pip-index-options:: lock\n\n.. pip-package-selection-options:: lock\n\n\nExamples\n========\n\n#. Emit a ``pylock.toml`` for the project in the current directory\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip lock -e .\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip lock -e .\n"
  },
  {
    "path": "docs/html/cli/pip_search.rst",
    "content": ".. _`pip search`:\n\n==========\npip search\n==========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: search \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: search \"py -m pip\"\n\n\nDescription\n===========\n\n.. attention::\n    PyPI no longer supports ``pip search`` (or XML-RPC search). Please use https://pypi.org/search (via a browser)\n    instead. See https://warehouse.pypa.io/api-reference/xml-rpc.html#deprecated-methods for more information.\n\n    However, XML-RPC search (and this command) may still be supported by indexes other than PyPI.\n\n.. pip-command-description:: search\n\n\nOptions\n=======\n\n.. pip-command-options:: search\n\n\nExamples\n========\n\n#. Search for \"peppercorn\"\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip search peppercorn\n         pepperedform    - Helpers for using peppercorn with formprocess.\n         peppercorn      - A library for converting a token stream into [...]\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip search peppercorn\n         pepperedform    - Helpers for using peppercorn with formprocess.\n         peppercorn      - A library for converting a token stream into [...]\n"
  },
  {
    "path": "docs/html/cli/pip_show.rst",
    "content": ".. _`pip show`:\n\n========\npip show\n========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: show \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: show \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: show\n\n\nOptions\n=======\n\n.. pip-command-options:: show\n\n\nExamples\n========\n\n#. Show information about a package:\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip show sphinx\n         Name: Sphinx\n         Version: 1.4.5\n         Summary: Python documentation generator\n         Home-page: http://sphinx-doc.org/\n         Author: Georg Brandl\n         Author-email: georg@python.org\n         License: BSD\n         Location: /my/env/lib/python2.7/site-packages\n         Requires: docutils, snowballstemmer, alabaster, Pygments, imagesize, Jinja2, babel, six\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip show sphinx\n         Name: Sphinx\n         Version: 1.4.5\n         Summary: Python documentation generator\n         Home-page: http://sphinx-doc.org/\n         Author: Georg Brandl\n         Author-email: georg@python.org\n         License: BSD\n         Location: /my/env/lib/python2.7/site-packages\n         Requires: docutils, snowballstemmer, alabaster, Pygments, imagesize, Jinja2, babel, six\n\n#. Show all information about a package\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip show --verbose sphinx\n         Name: Sphinx\n         Version: 1.4.5\n         Summary: Python documentation generator\n         Home-page: http://sphinx-doc.org/\n         Author: Georg Brandl\n         Author-email: georg@python.org\n         License: BSD\n         Location: /my/env/lib/python2.7/site-packages\n         Requires: docutils, snowballstemmer, alabaster, Pygments, imagesize, Jinja2, babel, six\n         Metadata-Version: 2.0\n         Installer:\n         Classifiers:\n            Development Status :: 5 - Production/Stable\n            Environment :: Console\n            Environment :: Web Environment\n            Intended Audience :: Developers\n            Intended Audience :: Education\n            License :: OSI Approved :: BSD License\n            Operating System :: OS Independent\n            Programming Language :: Python\n            Programming Language :: Python :: 2\n            Programming Language :: Python :: 3\n            Framework :: Sphinx\n            Framework :: Sphinx :: Extension\n            Framework :: Sphinx :: Theme\n            Topic :: Documentation\n            Topic :: Documentation :: Sphinx\n            Topic :: Text Processing\n            Topic :: Utilities\n         Entry-points:\n            [console_scripts]\n            sphinx-apidoc = sphinx.apidoc:main\n            sphinx-autogen = sphinx.ext.autosummary.generate:main\n            sphinx-build = sphinx:main\n            sphinx-quickstart = sphinx.quickstart:main\n            [distutils.commands]\n            build_sphinx = sphinx.setup_command:BuildDoc\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip show --verbose sphinx\n         Name: Sphinx\n         Version: 1.4.5\n         Summary: Python documentation generator\n         Home-page: http://sphinx-doc.org/\n         Author: Georg Brandl\n         Author-email: georg@python.org\n         License: BSD\n         Location: /my/env/lib/python2.7/site-packages\n         Requires: docutils, snowballstemmer, alabaster, Pygments, imagesize, Jinja2, babel, six\n         Metadata-Version: 2.0\n         Installer:\n         Classifiers:\n            Development Status :: 5 - Production/Stable\n            Environment :: Console\n            Environment :: Web Environment\n            Intended Audience :: Developers\n            Intended Audience :: Education\n            License :: OSI Approved :: BSD License\n            Operating System :: OS Independent\n            Programming Language :: Python\n            Programming Language :: Python :: 2\n            Programming Language :: Python :: 3\n            Framework :: Sphinx\n            Framework :: Sphinx :: Extension\n            Framework :: Sphinx :: Theme\n            Topic :: Documentation\n            Topic :: Documentation :: Sphinx\n            Topic :: Text Processing\n            Topic :: Utilities\n         Entry-points:\n            [console_scripts]\n            sphinx-apidoc = sphinx.apidoc:main\n            sphinx-autogen = sphinx.ext.autosummary.generate:main\n            sphinx-build = sphinx:main\n            sphinx-quickstart = sphinx.quickstart:main\n            [distutils.commands]\n            build_sphinx = sphinx.setup_command:BuildDoc\n"
  },
  {
    "path": "docs/html/cli/pip_uninstall.rst",
    "content": ".. _`pip uninstall`:\n\n=============\npip uninstall\n=============\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: uninstall \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: uninstall \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: uninstall\n\n\nOptions\n=======\n\n.. pip-command-options:: uninstall\n\n\nExamples\n========\n\n#. Uninstall a package.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: console\n\n         $ python -m pip uninstall simplejson\n         Uninstalling simplejson:\n            /home/me/env/lib/python3.9/site-packages/simplejson\n            /home/me/env/lib/python3.9/site-packages/simplejson-2.2.1-py3.9.egg-info\n         Proceed (Y/n)? y\n            Successfully uninstalled simplejson\n\n   .. tab:: Windows\n\n      .. code-block:: console\n\n         C:\\> py -m pip uninstall simplejson\n         Uninstalling simplejson:\n            /home/me/env/lib/python3.9/site-packages/simplejson\n            /home/me/env/lib/python3.9/site-packages/simplejson-2.2.1-py3.9.egg-info\n         Proceed (Y/n)? y\n            Successfully uninstalled simplejson\n"
  },
  {
    "path": "docs/html/cli/pip_wheel.rst",
    "content": "\n.. _`pip wheel`:\n\n=========\npip wheel\n=========\n\n\n\nUsage\n=====\n\n.. tab:: Unix/macOS\n\n   .. pip-command-usage:: wheel \"python -m pip\"\n\n.. tab:: Windows\n\n   .. pip-command-usage:: wheel \"py -m pip\"\n\n\nDescription\n===========\n\n.. pip-command-description:: wheel\n\n\n.. _`1-build-system-interface`:\n.. rubric:: Build System Interface\n\nThis is now covered in :doc:`../reference/build-system`.\n\nDifferences to ``build``\n------------------------\n\n`build <https://pypi.org/project/build/>`_ is a simple tool which can among other things build\nwheels for projects using the standard ``pyproject.toml``-based build interface. It\nis comparable to the execution of ``pip wheel --no-deps .``.\nIt can also build source distributions which is not possible with ``pip``.\n``pip wheel`` covers the wheel scope of ``build`` but offers many additional features.\n\nOptions\n=======\n\n.. pip-command-options:: wheel\n\n.. pip-index-options:: wheel\n\n.. pip-package-selection-options:: wheel\n\n\nExamples\n========\n\n#. Build wheels for a requirement (and all its dependencies), and then install\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip wheel --wheel-dir=/tmp/wheelhouse SomePackage\n         python -m pip install --no-index --find-links=/tmp/wheelhouse SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip wheel --wheel-dir=/tmp/wheelhouse SomePackage\n         py -m pip install --no-index --find-links=/tmp/wheelhouse SomePackage\n\n#. Build a wheel for a package from source\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip wheel --no-binary SomePackage SomePackage\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip wheel --no-binary SomePackage SomePackage\n"
  },
  {
    "path": "docs/html/conf.py",
    "content": "\"\"\"Sphinx configuration file for pip's documentation.\"\"\"\n\nimport glob\nimport os\nimport pathlib\nimport re\nimport sys\n\n# Add the docs/ directory to sys.path, because pip_sphinxext.py is there.\ndocs_dir = os.path.dirname(os.path.dirname(__file__))\nsys.path.insert(0, docs_dir)\n\n# -- General configuration ------------------------------------------------------------\n\nextensions = [\n    # extensions common to all builds\n    \"pip_sphinxext\",\n]\n\n# 'tags' is a injected by sphinx\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-tags\nif \"man\" not in tags:  # type: ignore[name-defined] # noqa: F821\n    # extensions not needed for building man pages\n    extensions.extend(\n        (\n            # first-party extensions\n            \"sphinx.ext.autodoc\",\n            \"sphinx.ext.todo\",\n            \"sphinx.ext.intersphinx\",\n            # third-party extensions\n            \"myst_parser\",\n            \"sphinx_copybutton\",\n            \"sphinx_inline_tabs\",\n            \"sphinxcontrib.towncrier\",\n            \"sphinx_issues\",\n        ),\n    )\n\n# General information about the project.\nproject = \"pip\"\ncopyright = \"The pip developers\"\n\n# Find the version and release information.\n# We have a single source of truth for our version number: pip's __init__.py file.\n# This next bit of code reads from it.\nfile_with_version = os.path.join(docs_dir, \"..\", \"src\", \"pip\", \"__init__.py\")\nwith open(file_with_version) as f:\n    for line in f:\n        m = re.match(r'__version__ = \"(.*)\"', line)\n        if m:\n            __version__ = m.group(1)\n            # The short X.Y version.\n            version = \".\".join(__version__.split(\".\")[:2])\n            # The full version, including alpha/beta/rc tags.\n            release = __version__\n            break\n    else:  # AKA no-break\n        version = release = \"dev\"\n\nprint(\"pip version:\", version)\nprint(\"pip release:\", release)\n\n# -- Options for myst-parser ----------------------------------------------------------\n\nmyst_enable_extensions = [\"deflist\"]\nmyst_heading_anchors = 3\n\n# -- Options for smartquotes ----------------------------------------------------------\n\n# Disable the conversion of dashes so that long options like \"--find-links\" won't\n# render as \"-find-links\" if included in the text.The default of \"qDe\" converts normal\n# quote characters ('\"' and \"'\"), en and em dashes (\"--\" and \"---\"), and ellipses \"...\"\nsmartquotes_action = \"qe\"\n\n# -- Options for intersphinx ----------------------------------------------------------\n\nintersphinx_mapping = {\n    \"python\": (\"https://docs.python.org/3\", None),\n    \"pypug\": (\"https://packaging.python.org\", None),\n    \"packaging\": (\"https://packaging.pypa.io/en/stable/\", None),\n}\n\n# -- Options for towncrier_draft extension --------------------------------------------\n\ntowncrier_draft_autoversion_mode = \"draft\"  # or: 'sphinx-release', 'sphinx-version'\ntowncrier_draft_include_empty = True\ntowncrier_draft_working_directory = pathlib.Path(docs_dir).parent\n# Not yet supported: towncrier_draft_config_path = 'pyproject.toml'  # relative to cwd\n\n# -- Options for HTML -----------------------------------------------------------------\n\nhtml_theme = \"furo\"\nhtml_title = f\"{project} documentation v{release}\"\n\n# Disable the generation of the various indexes\nhtml_use_modindex = False\nhtml_use_index = False\n\n# -- Options for Manual Pages ---------------------------------------------------------\n\n\n# List of manual pages generated\ndef determine_man_pages() -> list[tuple[str, str, str, str, int]]:\n    \"\"\"Determine which man pages need to be generated.\"\"\"\n\n    def to_document_name(path: str, base_dir: str) -> str:\n        \"\"\"Convert a provided path to a Sphinx \"document name\".\"\"\"\n        relative_path = os.path.relpath(path, base_dir)\n        root, _ = os.path.splitext(relative_path)\n        return root.replace(os.sep, \"/\")\n\n    # Crawl the entire man/commands/ directory and list every file with appropriate\n    # name and details.\n    man_dir = os.path.join(docs_dir, \"man\")\n    raw_subcommands = glob.glob(os.path.join(man_dir, \"commands/*.rst\"))\n    if not raw_subcommands:\n        raise FileNotFoundError(\n            \"The individual subcommand manpages could not be found!\"\n        )\n\n    retval = [\n        (\"index\", \"pip\", \"package manager for Python packages\", \"pip developers\", 1),\n    ]\n    for fname in raw_subcommands:\n        fname_base = to_document_name(fname, man_dir)\n        outname = \"pip-\" + fname_base.split(\"/\")[1]\n        description = \"description of {} command\".format(outname.replace(\"-\", \" \"))\n\n        retval.append((fname_base, outname, description, \"pip developers\", 1))\n\n    return retval\n\n\nman_pages = determine_man_pages()\n\n# -- Options for sphinx_copybutton ----------------------------------------------------\n\ncopybutton_prompt_text = r\"\\$ | C\\:\\> \"\ncopybutton_prompt_is_regexp = True\ncopybutton_only_copy_prompt_lines = False\n\n# -- Options for sphinx_issues --------------------------------------------------------\n\nissues_default_group_project = \"pypa/pip\"\n"
  },
  {
    "path": "docs/html/copyright.rst",
    "content": ":orphan:\n\n=========\nCopyright\n=========\n\npip and this documentation is:\n\nCopyright © 2008-2020 The pip developers (see `AUTHORS.txt <https://github.com/pypa/pip/blob/main/AUTHORS.txt>`_ file). All rights reserved.\n"
  },
  {
    "path": "docs/html/development/architecture/anatomy.rst",
    "content": ".. note::\n\n    This section of the documentation is currently being written. pip\n    developers welcome your help to complete this documentation. If you're\n    interested in helping out, please let us know in the `tracking issue`_.\n\n****************************************\nRepository anatomy & directory structure\n****************************************\n\n``pip``’s codebase (`GitHub repository`_) is structured as a standard Python package.\n\n\nRoot and tools\n==============\n\nThe ``README``, license, ``pyproject.toml``, and so on are in the top level.\n\n* ``AUTHORS.txt``\n* ``LICENSE.txt``\n* ``NEWS.rst``\n* ``pyproject.toml``\n* ``README.rst``\n* ``noxfile.py`` -- ``pip`` uses Nox, an automation tool, configured by this file. ``noxfile.py`` describes a few environments ``pip`` uses during development for simplifying how tests are run (complicated situation there). Example: ``nox -s lint``, ``nox -s test-3.10``. We can run tests for different versions of Python by changing “3.10” to “3.7” or similar.\n* ``.gitattributes``\n* ``.gitignore``\n* ``.mailmap``\n* ``docs/`` *[documentation, built with Sphinx]*\n\n  * ``html/`` *[sources to HTML documentation avail. online]*\n  * ``man/`` has man pages the distros can use by running ``man pip``\n  * ``pip_sphinxext.py`` *[an extension -- pip-specific plugins to Sphinx that do not apply to other packages]*\n\n* ``news/`` *[pip stores news fragments… Every time pip makes a user-facing change, a file is added to this directory (usually a short note referring to a GitHub issue) with the right extension & name so it gets included in changelog…. So every release the maintainers will be deleting old files in this directory? Yes - we use the towncrier automation to generate a NEWS file, and auto-delete old stuff. There’s more about this in the contributor documentation!]*\n\n  * ``template.rst`` *[template for changelog -- this is a file towncrier uses…. Is this jinja? I don’t know, check towncrier docs]*\n\n* ``src/`` *[source; see below]*\n* ``tools/`` *[misc development workflow tools, like requirements files & CI files & helpers. For instance, automating the release.]*\n* ``tests/`` -- contains tests you can run. There are instructions in :doc:`../getting-started`.\n\n  * ``__init__.py``\n  * ``conftest.py``\n  * ``data/`` *[test data for running tests -- pseudo package index in it!  Lots of small packages that are invalid or are valid. Test fixtures.  Used by functional tests]*\n  * ``functional/`` *[functional tests of pip’s CLI -- end-to-end, invoke pip in subprocess & check results of execution against desired result. This also is what makes test suite slow]*\n  * ``lib/`` *[helpers for tests]*\n  * ``unit/`` *[unit tests -- fast and small and nice!]*\n\n* ``.github``\n\n\nsrc directory\n=============\n\nIn the root directory, the ``src/`` directory contains pip's core\nsource code. Within ``src/pip/``, ``_internal/`` has the pip code\nthat's written by pip maintainers, and ``_vendor/`` is pip's\ndependencies (code from other packages).\n\nWithin ``src/``:\n\n* ``pip/``\n\n  * ``__init__.py``\n  * ``__main__.py``\n  * ``_internal/`` *[where all the pip code lives that’s written by pip maintainers -- underscore means private. pip is not a library -- it’s a command line tool! A very important distinction! People who want to install stuff with pip should not use the internals -- they should use the CLI. There’s a note on this in the docs.]*\n\n    * ``__init__.py``\n    * ``build_env.py``\n    * ``cache.py`` *[has all the info for how to handle caching within pip -- cache-handling stuff. Uses cachecontrol from PyPI, vendored into pip]*\n    * ``cli/`` *[subpackage containing helpers & additional code for managing the command line interface. Uses argparse from stdlib]*\n    * ``commands/`` *[literally - each file is the name of the command on the pip CLI. Each has a class that defines what’s needed to set it up, what happens]*\n    * ``configuration.py``\n    * ``download.py``\n    * ``exceptions.py``\n    * ``index/``\n    * ``locations/``\n    * ``main.py`` *[legacy entry point]*\n    * ``models/`` *[in-process refactoring! Goal: improve how pip internally models representations it has for data -- data representation. General overall cleanup. Data reps are spread throughout codebase….link is defined in a class in 1 file, and then another file imports Link from that file. Sometimes cyclic dependency?!?! To prevent future situations like this, etc., Pradyun started moving these into a models directory.]*\n    * ``operations/`` -- a bit of a weird directory….. ``Freeze.py`` used to be in there. Freeze is an operation -- there was an operations.freeze. Then “prepare” got added (the operation of preparing a pkg). Then “check” got added for checking the state of an env.] [what’s a command vs an operation? Command is on CLI; an operation would be an internal bit of code that actually does some subset of the operation the command says. ``install`` command uses bits of ``check`` and ``prepare``, for instance. In the long run, Pradyun’s goal: ``prepare.py`` goes away (gets refactored into other files) such that ``operations`` is just ``check`` and ``freeze``..... … Pradyun plans to refactor this. [how does this compare to ``utils``?]\n\n      * ``install/`` -- for modules related to installing projects of various kinds\n\n        * ``wheel.py`` is a file that manages installation of a wheel file. This handles unpacking wheels -- “unpack and spread”. There is a package on PyPI called ``wheel`` that builds wheels -- do not confuse it with this.\n\n    * ``pep425tags.py`` -- getting refactored into packaging.tags (a library on PyPI) which is external to pip (but vendored by pip). :pep:`425` tags: turns out lots of people want this! Compatibility tags for built distributions -> e.g., platform, Python version, etc.\n    * ``pyproject.py`` -- ``pyproject.toml`` is a new standard (:pep:`518` and :pep:`517`). This file reads pyproject.toml and passes that info elsewhere. The rest of the processing happens in a different file. All the handling for 517 and 518 is in a different file.\n    * ``req/`` *[*\\ **A DIRECTORY THAT NEEDS REFACTORING. A LOT**\\ *\\ …… Remember Step 3? Dependency resolution etc.? This is that step! Each file represents … have the entire flow of installing & uninstalling, getting info about packages…. Some files here are more than 1,000 lines long! (used to be longer?!) Refactor will deeply improve developer experience. Also, we're `improving the pip dependency resolver`_ in 2020 so a bunch of this is changing.]*\n    * ``utils/`` *[everything that is not “operationally” pip ….. Misc functions and files get dumped. There’s some organization here. There’s a models.py here which needs refactoring. Deprecation.py is useful, as are other things, but some things do not belong here. There ought to be some GitHub issues for refactoring some things here. Maybe a few issues with checkbox lists.]*\n    * ``vcs/`` *[stands for Version Control System. Where pip handles all version control stuff -- one of the ``pip install`` arguments you can use is a version control link. Are any of these commands vendored? No, via subprocesses. For performance, it makes sense (we think) to do this instead of pygitlib2 or similar -- and has to be pure Python, can’t include C libraries, because you can’t include compiled C stuff, because you might not have it for the platform you are running on.]*\n\n  * ``_vendor/`` *[code from other packages -- pip’s own dependencies…. Has them in its own source tree, because pip cannot depend on pip being installed on the machine already!]*\n\n.. _`tracking issue`: https://github.com/pypa/pip/issues/6831\n.. _GitHub repository: https://github.com/pypa/pip/\n.. _improving the pip dependency resolver: https://github.com/pypa/pip/issues/988\n"
  },
  {
    "path": "docs/html/development/architecture/command-line-interface.rst",
    "content": "======================\nCommand Line Interface\n======================\n\nThe ``pip._internal.cli`` package is responsible for processing and providing\npip's command line interface. This package handles:\n\n* CLI option definition and parsing\n* autocompletion\n* dispatching to the various commands\n* utilities like progress bars and spinners\n\n.. note::\n\n    This section of the documentation is currently being written. pip\n    developers welcome your help to complete this documentation. If you're\n    interested in helping out, please let us know in the\n    `tracking issue <https://github.com/pypa/pip/issues/6831>`_.\n\n\n.. _cli-overview:\n\nOverview\n========\n\nA ``ConfigOptionParser`` instance is used as the \"main parser\",\nfor parsing top level args.\n\n``Command`` then uses another ``ConfigOptionParser`` instance, to parse command-specific args.\n\nCommand structure\n-----------------\n\nThis section shows the class hierarchy from which every command's class will inherit\nfrom.\n\n`base_command.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/base_command.py>`_\ndefines the base ``Command`` class, from which every other command will inherit directly or\nindirectly (see the *command tree* at the end of this section).\n\nUsing the ``ConfigOptionParser`` (see `Configuration and CLI \"blend\" <Configuration and CLI \"blend\"_>`_),\nthis class adds the general options and instantiates the *cmd_opts* group, where every other specific\noption will be added if needed on each command's class. For those commands that define specific\noptions, like ``--dry-run`` on ``pip install`` command, the options must be added to *cmd_opts*\nthis is the job of *add_options* method), which will be automatically called on ``Command``'s initialization.\n\nThe base ``Command`` has the following methods:\n\n.. py:class:: Command\n\n  .. py:method:: main()\n\n    Main method of the class, it's always called (as can be seen in main.py's\n    `main <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/main.py#L46>`_).\n    It's in charge of calling the specific ``run`` method of the class and handling the possible errors.\n\n  .. py:method:: run()\n\n    Abstract method where the actual action of a command is defined.\n\n  .. py:method:: add_options()\n\n    Optional method to insert additional options on a class, called on ``Command`` initialization.\n\nSome commands have more specialized behavior, (see for example ``pip index``).\nThese commands instead will inherit from ``IndexGroupCommand``, which inherits from ``Command``\nand  ``SessionCommandMixin`` to build build the pip session for the corresponding requests.\n\nLastly, ``RequirementCommand``, which inherits from ``IndexGroupCommand`` is the base class\nfor those commands which make use of requirements in any form, like ``pip install``.\n\nIn addition to the previous classes, a last mixin class must be mentioned, from which\n``Command`` as well as ``SessionCommandMixin`` inherit: ``CommandContextMixIn``, in\ncharge of the command's context.\n\nIn the following command tree we can see the hierarchy defined for the different pip\ncommands, where each command is defined under the base class it inherits from:\n\n| ``Command``\n|  ├─ ``cache``, ``check``, ``completion``, ``configuration``, ``debug``, ``freeze``, ``hash``, ``help``, ``inspect``, ``show``, ``search``, ``uninstall``\n|  └─ ``IndexGroupCommand``\n|      ├─ ``index``, ``list``\n|      └─ ``RequirementCommand``\n|           └─ ``wheel``, ``download``, ``install``\n\n\nOption definition\n-----------------\n\nThe set of shared options are defined in `cmdoptions.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/cmdoptions.py>`_\nmodule, as well as the *general options* and *package index options* groups of options\nwe see when we call a command's help, or the ``pip index``'s help message respectively.\nAll options are defined in terms of functions that return `optparse.Option <https://docs.python.org/3/library/optparse.html#optparse.Option>`_\ninstances once called, while specific groups of options, like *Config Options* for\n``pip config`` are defined in each specific command file (see for example the\n`configuration.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/commands/configuration.py>`_).\n\nArgument parsing\n----------------\n\nThe main entrypoint for the application is defined in the ``main`` function in the\n`main.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/main.py>`_ module.\nThis function is in charge of the `autocompletion <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/autocompletion.py>`_,\ncalling the ``parse_command`` function and creating and running the subprograms\nvia ``create_command``, on which the ``main`` method is called.\n\nThe ``parse_command`` is defined in the `main_parser.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/main_parser.py>`_\nmodule, which defines the following two functions:\n\n.. py:function:: parse_command()\n\n  Function in charge of the initial parse of ``pip``'s program. Creates the main parser (see\n  the next function ``create_main_parser``) to extract the general options\n  and the remaining arguments. For example, running ``pip --timeout=5 install --user INITools``\n  will split ``['--timeout=5']`` as general option and  ``['install', '--user', 'INITools']``\n  as the remainder.\n\n  At this step the program deals with the options ``--python``, ``--version``, ``pip``\n  or ``pip help``. If neither of the previous options is found, it tries to extract the command\n  name and arguments.\n\n.. py:function:: create_main_parser()\n\n  Creates the main parser (type ``pip`` in the console to see the description of the\n  program). The internal parser (`ConfigOptionParser <Configuration and CLI \"blend\"_>`_),\n  adds the general option group and the list of commands coming from ``cmdoptions.py``\n  at this point.\n\nAfter the initial parsing is done, ``create_command`` is in charge of creating the appropriate\ncommand using the information stored in `commands_dict <https://github.com/pypa/pip/blob/main/src/pip/_internal/commands/__init__.py>`_\nvariable, and calling its ``main`` method (see `Command structure <Command structure>`_).\n\nA second argument parsing is done at each specific command (defined in the base ``Command`` class),\nagain using the ``ConfigOptionParser``.\n\nArgument access\n---------------\n\nTo access all the options and arguments, ``Command.run()`` takes\nthe options as `optparse.Values <https://docs.python.org/3/library/optparse.html#optparse.Values>`_\nand a list of strings for the arguments (parsed in ``Command.main()``). The internal methods of\nthe base ``Command`` class are in charge of passing these variables after ``parse_args`` is\ncalled for a specific command.\n\nConfiguration and CLI \"blend\"\n-----------------------------\n\nThe base ``Command`` instantiates the class `ConfigOptionParser <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/parser.py>`_\nwhich is in charge of the parsing process (via its parent class\n`optparse.OptionParser <https://docs.python.org/3/library/optparse.html#optparse.OptionParser>`_).\nIts main addition consists of the following function:\n\n.. py:class:: ConfigOptionParser(OptionParser)\n\n  .. py:method:: get_default_values()\n\n    Overrides the original method to allow updating the defaults after the instantiation of the\n    option parser.\n\nIt allows overriding the default options and arguments using the ``Configuration`` class\n(more information can be found on :ref:`Configuration`) to include environment variables and\nsettings from configuration files.\n\nProgress bars and spinners\n--------------------------\n\nThere are two more modules in the ``cli`` subpackage in charge of showing the state of the\nprogram.\n\n* `progress_bars.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/progress_bars.py>`_\n\n  This module contains the following function:\n\n  .. py:function:: get_download_progress_renderer()\n\n    It uses `rich <https://rich.readthedocs.io/en/stable/reference/progress.html#module-rich.progress>`_\n    functionalities to render the download progress.\n\n  This function (used in `download.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/network/download.py>`_,\n  inside the ``Downloader`` class), allows watching the download process when running\n  ``pip install`` on *big* packages.\n\n* `spinner.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/cli/spinners.py>`_\n\n  The main function of this module is:\n\n  .. py:function:: open_spinner()\n\n    It yields the appropriate type of spinner, which is used in ``call_subprocess``\n    function, inside `subprocess.py <https://github.com/pypa/pip/blob/main/src/pip/_internal/utils/subprocess.py>`_\n    module, so the user can see there is a program running.\n\n* TODO: quirks / standard practices / broad ideas.\n  (avoiding lists in option def'n, special cased option value types,\n  )\n\n\nFuture Refactoring Ideas\n========================\n\n* Change option definition to be a more declarative, consistent, static\n  data-structure, replacing the current ``partial(Option, ...)`` form\n* Move progress bar and spinner to a ``cli.ui`` subpackage\n* Move all ``Command`` classes into a ``cli.commands`` subpackage\n  (including base classes)\n"
  },
  {
    "path": "docs/html/development/architecture/configuration-files.rst",
    "content": "===========================\nConfiguration File Handling\n===========================\n\nThe ``pip._internal.configuration`` module is responsible for handling\n(eg. loading from and saving values to) configuration files that are used by\npip. The module's functionality is largely exposed through and coordinated by\nthe module's ``Configuration`` class.\n\n.. note::\n\n    This section of the documentation is currently being written. pip\n    developers welcome your help to complete this documentation. If you're\n    interested in helping out, please let us know in the\n    `tracking issue <https://github.com/pypa/pip/issues/6831>`_.\n\n\n.. _configuration-overview:\n\nOverview\n========\n\npip stores configuration files in standard OS-appropriate locations, which are\ndetermined by ``appdirs``. These files are in the INI format and are processed\nwith ``RawConfigParser``.\n\npip uses configuration files in two operations:\n\n* During processing of command line options.\n\n  * Reading from *all* configuration sources\n\n* As part of ``pip config`` command.\n\n  * Reading from *all* configuration sources\n  * Manipulating a single configuration file\n\nBoth of these operations utilize functionality provided the ``Configuration``\nobject, which encapsulates all the logic for handling configuration files and\nprovides APIs for the same.\n\nThe remainder of this section documents the ``Configuration`` class, and\ndiscusses potential future refactoring ideas.\n\n\n.. _configuration-class:\n\n``Configuration`` class\n=======================\n\n``Configuration`` loads configuration values from sources in the local\nenvironment: a combination of configuration files and environment variables.\n\nIt can be used in two \"modes\", for reading all the values from the local\nenvironment and for manipulating a single configuration file. It differentiates\nbetween these two modes using the ``load_only`` attribute, which can be None or\nrepresent the :ref:`kind <config-kinds>` of the configuration file to be\nmanipulated.\n\nThe ``isolated`` attribute determines which sources are used when loading the\nconfiguration. If ``isolated`` is ``True``, user-specific configuration files\nand environment variables are not used.\n\nReading from local environment\n------------------------------\n\n``Configuration`` can be used to read from all configuration sources in the\nlocal environment and access the values, as per the precedence logic described\nin the :ref:`Config Precedence <config-precedence>` section.\n\nFor this use case, the ``Configuration.load_only`` attribute would be ``None``,\nand the methods used would be:\n\n.. py:class:: Configuration\n\n  .. py:method:: load()\n\n    Handles all the interactions with the environment, to load all the\n    configuration data into objects in memory.\n\n  .. py:method:: items()\n\n    Provides key-value pairs (like ``dict.items()``) from the loaded-in-memory\n    information, handling all of the override ordering logic.\n\n  .. py:method:: get_value(key)\n\n    Provides the value of the given key from the loaded configuration.\n    The loaded configuration may have ``load_only`` be None or non-None.\n    This uses the same underlying mechanism as ``Configuration.items()`` and\n    does follow the precedence logic described in :ref:`Config Precedence\n    <config-precedence>`.\n\nAt the time of writing, the parts of the codebase that use ``Configuration``\nin this manner are: ``ConfigOptionParser``, to transparently include\nconfiguration handling as part of the command line processing logic,\nand ``pip config get``, for printing the entire configuration when no\n:ref:`kind <config-kinds>` is specified via the CLI.\n\nManipulating a single configuration file\n----------------------------------------\n\n``Configuration`` can be used to manipulate a single configuration file,\nsuch as to add, change or remove certain key-value pairs.\n\nFor this use case, the ``load_only`` attribute would be non-None, and would\nrepresent the :ref:`kind <config-kinds>` of the configuration file to be\nmanipulated. In addition to the methods discussed in the previous section,\nthe methods used would be:\n\n.. py:class:: Configuration\n  :noindex:\n\n  .. py:method:: get_file_to_edit()\n\n    Provides the \"highest priority\" file, for the :ref:`kind <config-kinds>` of\n    configuration file specified by ``load_only``. This requires ``load_only``\n    to be non-None.\n\n  .. py:method:: set_value(key, value)\n\n    Provides a way to add/change a single key-value pair, in the file specified\n    by ``Configuration.get_file_to_edit()``.\n\n  .. py:method:: unset_value(key)\n\n    Provides a way to remove a single key-value pair, in the file specified\n    by ``Configuration.get_file_to_edit()``.\n\n  .. py:method:: save()\n\n    Saves the in-memory state of to the original files, saving any modifications\n    made to the ``Configuration`` object back into the local environment.\n\n.. _config-kinds:\n\nkinds\n=====\n\nThis is an enumeration that provides values to represent a \"source\" for\nconfiguration. This includes environment variables and various types of\nconfiguration files (global, site-specific, user_specific, specified via\n``PIP_CONFIG_FILE``).\n\nFuture Refactoring Ideas\n========================\n\n* Break up the ``Configuration`` class into 2 smaller classes, by use case\n    * ``Command`` use-case (read only) -- ``ConfigurationReader``\n    * ``pip config`` use-case (read / write) -- ``ConfigurationModifier`` (inherit from ``ConfigurationReader``)\n* Eagerly populate ``Configuration._dictionary`` on load.\n"
  },
  {
    "path": "docs/html/development/architecture/index.rst",
    "content": ".. _architecture-pip-internals:\n\n===============================\nArchitecture of pip's internals\n===============================\n\n.. note::\n\n    This section of the documentation is currently being written. pip\n    developers welcome your help to complete this documentation. If\n    you're interested in helping out, please let us know in the\n    `tracking issue`_, or just go ahead and submit a pull request and\n    mention it in that tracking issue.\n\n.. note::\n\n    Direct use of pip's internals is *not supported*, and these internals\n    can change at any time. For more details, see :ref:`Using pip from\n    your program`.\n\n\n.. toctree::\n    :maxdepth: 2\n\n    overview\n    anatomy\n    configuration-files\n    package-finding\n    command-line-interface\n    upgrade-options\n\n\n.. _`tracking issue`: https://github.com/pypa/pip/issues/6831\n"
  },
  {
    "path": "docs/html/development/architecture/overview.rst",
    "content": ".. note::\n\n    This section of the documentation is currently being written. pip\n    developers welcome your help to complete this documentation. If you're\n    interested in helping out, please let us know in the `tracking issue`_.\n\n\n****************************\nBroad functionality overview\n****************************\n\npip is a package installer.\n\npip does a lot more than installation; it also has a cache, and it has\nconfiguration, and it has a CLI, which has its own quirks. But mainly:\n\nThings pip does:\n\n1. | Manages the building of packages (offloads package building to a\n     backend) when that’s necessary (a source distribution package --\n     this is not necessary if the package is a wheel).\n\n   1. | By default, pip delegates package-building to setuptools, for\n           backwards compatibility reasons. But thing with setuptools:\n           has a ``setup.py`` file that it invokes to …… get info?\n\n2. Decides where to install stuff. Once the package is built, the resulting\n   artifact is then installed to the system in its appropriate place. :pep:`517`\n   defines the interface between the build backend & installer.\n\nBroad overview of flow\n======================\n\nIn sequence, what does pip do?:\n\n1. Get user input (user-supplied string saying what package they want)\n2. Figure out what that means: exactly what the user requested --\n   translate to a thing pip can operate on (user input to requirements)\n3. CORE OF THE WHOLE PROCESS, MAYBE? Once you have a set of reqs from\n   Step 2, you have to expand those into a concrete “things to install”\n   -- Figure out what other requirements it has to install based on\n   user-given requirements, and where to get them from.\n\n   a. this step is convoluted - also exploratory, involves dependency\n      resolution -- we need to get to the index, see what versions\n      are available\n\n   b. Sometimes you need to build the package itself in order to get\n      dependency information, which means fetching the package from\n      package index, which means knowing whether it exists. For a\n      single package,\n\n4. Install the actual items to be installed.\n\nWhy? pip installs from places other than PyPI! But also, we’ve never had\nguarantees of PyPI’s JSON API before now, so no one has been getting\nmetadata from PyPI separate from downloading the package itself.\n\nIn terms of flow of the install process:\n\n1. For 1 package: Get abstract requirement(s) for that package, and\n   try and see what that means (this abstract requirement can take\n   various forms). Define abstract dependencies.\n\n2. Once we have a set of \"this package, get it from here, this is that\n   version of that package\",\n\n3. Modify the environment to install those things (which means: place\n   the files in the right place). For example: if you already have\n   version 6.0 of a requirement and you are installing 7.2, uninstall\n   6.0 and install 7.2.\n\nDownload process\n----------------\n\nWhat happens in an install? Well, a subset of ``install``, a process\npip usually does during a ``pip install``, is ``download`` (also\navailable to the user as the :ref:`pip download` command). And we\ndownload and INSPECT packages to get manifests. For any given package\nname, we need to know what files are available and what their\nfilenames are.\n\npip can download from a Python package repository, where packages are\nstored in a structured format so an installer like pip can find them.\n\n:pep:`503` defines the API we use to talk to a Python package repository.\n\nPyPI\n^^^^\n\nWhat happens if we run ``pip download somepackage`` with no other\narguments?  By default we look at `PyPI`_, which is where pip knows\nwhere to look to get more info for what the package index knows about\n``somepackage``.\n\n``pip`` then knows: what files are available, and what their filenames\nare.\n\nIN OTHER WORDS\n\nWhile all dependencies have not been resolved, do the following:\n\n1.  Following the API defined in :pep:`503`, fetch the index page from\n    `https://{pypi_index}/simple/{package_name} <https://pypi.org/simple/{package_name}>`_\n2.  Parse all of the file links from the page.\n3.  Select a single file to download from the list of links.\n4.  Extract the metadata from the downloaded package.\n5.  Update the dependency tree based on the metadata.\n\nThe package index gives pip a list of files for that package (via the existing PyPI API). The files have the version and some other info that helps pip decide whether that's something pip ought to download.\n\npip chooses from the list a single file to download.\n\nIt may go back and choose another file to download.\n\nWhen pip looks at the package index, the place where it looks has\nbasically a link. The link’s text is the name of the file.\n\nThis is the `PyPI Simple API`_ (PyPI has several APIs, some are being\ndeprecated). pip looks at Simple API, documented initially at :pep:`503` --\npackaging.python.org has PyPA specifications with more details for\nSimple Repository API.\n\nFor this package name -- this is the list of files available.\n\nLooks there for:\n\n* The list of filenames\n* Other info\n\nOnce it has those, it selects one file and downloads it.\n\n(Question: If I want to ``pip install flask``, I think the whole list of filenames\ncannot….should not be …. ? I want only the Flask …. Why am I getting the\nwhole list?\n\nAnswer: It's not every file, just files of Flask. No API for getting all\nfiles on PyPI. It’s for getting all files of Flask.)\n\n.. _`tracking issue`: https://github.com/pypa/pip/issues/6831\n.. _PyPI: https://pypi.org/\n.. _PyPI Simple API: https://warehouse.readthedocs.io/api-reference/legacy/\n"
  },
  {
    "path": "docs/html/development/architecture/package-finding.rst",
    "content": "Finding and choosing files (``index`` and ``PackageFinder``)\n---------------------------------------------------------------\n\nThe ``pip._internal.index`` sub-package in pip is responsible for deciding\nwhat file to download and from where, given a requirement for a project. The\npackage's functionality is largely exposed through and coordinated by the\npackage's ``PackageFinder`` class.\n\n\n.. _index-overview:\n\nOverview\n********\n\nHere is a rough description of the process that pip uses to choose what\nfile to download for a package, given a requirement:\n\n1. Collect together the various network and file system locations containing\n   project package files. These locations are derived, for example, from pip's\n   :ref:`--index-url <install_--index-url>` (with default\n   https://pypi.org/simple/ ) setting and any configured\n   :ref:`--extra-index-url <install_--extra-index-url>` locations. Each of the\n   project page URL's is an HTML page of anchor links, as defined in\n   `PEP 503`_, the \"Simple Repository API.\"\n2. For each project page URL, fetch the HTML and parse out the anchor links,\n   creating a ``Link`` object from each one. The :ref:`LinkCollector\n   <link-collector-class>` class is responsible for both the previous step\n   and fetching the HTML over the network.\n3. Determine which of the links are minimally relevant, using the\n   :ref:`LinkEvaluator <link-evaluator-class>` class.  Create an\n   ``InstallationCandidate`` object (aka candidate for install) for each\n   of these relevant links.\n4. Further filter the collection of ``InstallationCandidate`` objects (using\n   the :ref:`CandidateEvaluator <candidate-evaluator-class>` class) to a\n   collection of \"applicable\" candidates.\n5. If there are applicable candidates, choose the best candidate by sorting\n   them (again using the :ref:`CandidateEvaluator\n   <candidate-evaluator-class>` class).\n\nThe remainder of this section is organized by documenting some of the\nclasses inside the ``index`` package, in the following order:\n\n* the main :ref:`PackageFinder <package-finder-class>` class,\n* the :ref:`LinkCollector <link-collector-class>` class,\n* the :ref:`LinkEvaluator <link-evaluator-class>` class,\n* the :ref:`CandidateEvaluator <candidate-evaluator-class>` class,\n* the :ref:`CandidatePreferences <candidate-preferences-class>` class, and\n* the :ref:`BestCandidateResult <best-candidate-result-class>` class.\n\n\n.. _package-finder-class:\n\nThe ``PackageFinder`` class\n***************************\n\nThe ``PackageFinder`` class is the primary way through which code in pip\ninteracts with ``index`` package. It is an umbrella class that encapsulates and\ngroups together various package-finding functionality.\n\nThe ``PackageFinder`` class is responsible for searching the network and file\nsystem for what versions of a package pip can install, and also for deciding\nwhich version is most preferred, given the user's preferences, target Python\nenvironment, etc.\n\nThe pip commands that use the ``PackageFinder`` class are:\n\n* :ref:`pip download`\n* :ref:`pip install`\n* :ref:`pip list`\n* :ref:`pip wheel`\n\nThe pip commands requiring use of the ``PackageFinder`` class generally\ninstantiate ``PackageFinder`` only once for the whole pip invocation. In\nfact, pip creates this ``PackageFinder`` instance when command options\nare first parsed.\n\nWith the exception of :ref:`pip list`, each of the above commands is\nimplemented as a ``Command`` class inheriting from ``RequirementCommand``\n(for example :ref:`pip download` is implemented by ``DownloadCommand``), and\nthe ``PackageFinder`` instance is created by calling the\n``RequirementCommand`` class's ``_build_package_finder()`` method. ``pip\nlist``, on the other hand, constructs its ``PackageFinder`` instance by\ncalling the ``ListCommand`` class's ``_build_package_finder()``. (This\ndifference may simply be historical and may not actually be necessary.)\n\nEach of these commands also uses the ``PackageFinder`` class for pip's\n\"self-check,\" (i.e. to check whether a pip upgrade is available). In this\ncase, the ``PackageFinder`` instance is created by the\n``self_outdated_check.py`` module's ``pip_self_version_check()`` function.\n\nThe ``PackageFinder`` class is responsible for doing all of the things listed\nin the :ref:`Overview <index-overview>` section like fetching and parsing\n`PEP 503`_ simple repository HTML pages, evaluating which links in the simple\nrepository pages are relevant for each requirement, and further filtering and\nsorting by preference the candidates for install coming from the relevant\nlinks.\n\nOne of ``PackageFinder``'s main top-level methods is\n``find_best_candidate()``. This method does the following two things:\n\n1. Calls its ``find_all_candidates()`` method, which gathers all\n   possible package links by reading and parsing the index URL's and\n   locations provided by the user (the :ref:`LinkCollector\n   <link-collector-class>` class's ``collect_sources()`` method), constructs a\n   :ref:`LinkEvaluator <link-evaluator-class>` object to filter out some of\n   those links, and then returns a list of ``InstallationCandidates`` (aka\n   candidates for install). This corresponds to steps 1-3 of the\n   :ref:`Overview <index-overview>` above.\n2. Constructs a ``CandidateEvaluator`` object and uses that to determine\n   the best candidate. It does this by calling the ``CandidateEvaluator``\n   class's ``compute_best_candidate()`` method on the return value of\n   ``find_all_candidates()``. This corresponds to steps 4-5 of the Overview.\n\n``PackageFinder`` also has a ``process_project_url()`` method (called by\n``find_best_candidate()``) to process a `PEP 503`_ \"simple repository\"\nproject page. This method fetches and parses the HTML from a PEP 503 project\npage URL, extracts the anchor elements and creates ``Link`` objects from\nthem, and then evaluates those links.\n\n\n.. _link-collector-class:\n\nThe ``LinkCollector`` class\n***************************\n\nThe :ref:`LinkCollector <link-collector-class>` class is the class\nresponsible for collecting the raw list of \"links\" to package files\n(represented as ``Link`` objects) from file system locations, as well as the\n`PEP 503`_ project page URL's that ``PackageFinder`` should access.\n\nThe ``LinkCollector`` class takes into account the user's :ref:`--find-links\n<install_--find-links>`, :ref:`--extra-index-url <install_--extra-index-url>`,\nand related options when deciding which locations to collect links from. The\nclass's main method is the ``collect_sources()`` method. The :ref:`PackageFinder\n<package-finder-class>` class invokes this method as the first step of its\n``find_all_candidates()`` method.\n\n``LinkCollector`` also has a ``fetch_page()`` method to fetch the HTML from a\nproject page URL. This method is \"unintelligent\" in that it doesn't parse the\nHTML.\n\nThe ``LinkCollector`` class is the only class in the ``index`` sub-package that\nmakes network requests and is the only class in the sub-package that depends\ndirectly on ``PipSession``, which stores pip's configuration options and\nstate for making requests.\n\n\n.. _link-evaluator-class:\n\nThe ``LinkEvaluator`` class\n***************************\n\nThe ``LinkEvaluator`` class contains the business logic for determining\nwhether a link (e.g. in a simple repository page) satisfies minimal\nconditions to be a candidate for install (resulting in an\n``InstallationCandidate`` object). When making this determination, the\n``LinkEvaluator`` instance uses information like the target Python\ninterpreter as well as user preferences like whether binary files are\nallowed or preferred, etc.\n\nSpecifically, the ``LinkEvaluator`` class has an ``evaluate_link()`` method\nthat returns whether a link is a candidate for install.\n\nInstances of this class are created by the ``PackageFinder`` class's\n``make_link_evaluator()`` on a per-requirement basis.\n\n\n.. _candidate-evaluator-class:\n\nThe ``CandidateEvaluator`` class\n********************************\n\nThe ``CandidateEvaluator`` class contains the business logic for evaluating\nwhich ``InstallationCandidate`` objects should be preferred. This can be\nviewed as a determination that is finer-grained than that performed by the\n``LinkEvaluator`` class.\n\nIn particular, the ``CandidateEvaluator`` class uses the whole set of\n``InstallationCandidate`` objects when making its determinations, as opposed\nto evaluating each candidate in isolation, as ``LinkEvaluator`` does. For\nexample, whether a pre-release is eligible for selection or whether a file\nwhose hash doesn't match is eligible depends on properties of the collection\nas a whole.\n\nThe ``CandidateEvaluator`` class uses information like the list of\n:ref:`platform tags <pypug:platform-compatibility-tags>`\ncompatible with the target Python interpreter, hashes provided by the\nuser, and other user preferences, etc.\n\nSpecifically, the class has a ``get_applicable_candidates()`` method.\nThis accepts the ``InstallationCandidate`` objects resulting from the links\naccepted by the ``LinkEvaluator`` class's ``evaluate_link()`` method, filters\nthem to a list of \"applicable\" candidates and orders them by preference.\n\nThe ``CandidateEvaluator`` class also has a ``sort_best_candidate()`` method\nthat returns the best (i.e. most preferred) candidate.\n\nFinally, the class has a ``compute_best_candidate()`` method that calls\n``get_applicable_candidates()`` followed by ``sort_best_candidate()``, and\nthen returning a :ref:`BestCandidateResult <best-candidate-result-class>`\nobject encapsulating both the intermediate and final results of the decision.\n\nInstances of ``CandidateEvaluator`` are created by the ``PackageFinder``\nclass's ``make_candidate_evaluator()`` method on a per-requirement basis.\n\n\n.. _candidate-preferences-class:\n\nThe ``CandidatePreferences`` class\n**********************************\n\nThe ``CandidatePreferences`` class is a simple container class that groups\ntogether some of the user preferences that ``PackageFinder`` uses to\nconstruct ``CandidateEvaluator`` objects (via the ``PackageFinder`` class's\n``make_candidate_evaluator()`` method).\n\nA ``PackageFinder`` instance has a ``_candidate_prefs`` attribute whose value\nis a ``CandidatePreferences`` instance. Since ``PackageFinder`` has a number\nof responsibilities and options that control its behavior, grouping the\npreferences specific to ``CandidateEvaluator`` helps maintainers know which\nattributes are needed only for ``CandidateEvaluator``.\n\n\n.. _best-candidate-result-class:\n\nThe ``BestCandidateResult`` class\n*********************************\n\nThe ``BestCandidateResult`` class is a convenience \"container\" class that\nencapsulates the result of finding the best candidate for a requirement.\n(By \"container\" we mean an object that simply contains data and has no\nbusiness logic or state-changing methods of its own.) It stores not just the\nfinal result but also intermediate values used to determine the result.\n\nThe class is the return type of both the ``CandidateEvaluator`` class's\n``compute_best_candidate()`` method and the ``PackageFinder`` class's\n``find_best_candidate()`` method.\n\n\n.. _`PEP 503`: https://www.python.org/dev/peps/pep-0503/\n"
  },
  {
    "path": "docs/html/development/architecture/upgrade-options.rst",
    "content": "=============================================\nOptions that control the installation process\n=============================================\n\nWhen installing packages, pip chooses a distribution file, and\ninstalls it in the user's environment. There are many choices (which\nare `still evolving`_) involved in deciding which file to install, and\nthese are controlled by a variety of options.\n\n.. note::\n\n    This section of the documentation needs to be updated per\n    :ref:`Resolver changes 2020`.\n\nControlling what gets installed\n===============================\n\nThese options directly affect how the resolver uses the list of available\ndistribution files to decide which one to install. So these modify the\nresolution algorithm itself, rather than the input to that algorithm.\n\n``--upgrade``\n\nAllow installing a newer version of an installed package. In principle, this\noption actually affects \"what gets considered\", in the sense that it allows\nthe resolver to see other versions of installed packages. Without\n``--upgrade``, the resolver will only see the installed version as a\ncandidate.\n\n``--upgrade-strategy``\n\nThis option affects which packages are allowed to be installed. It is only\nrelevant if ``--upgrade`` is specified (except for the ``to-satisfy-only``\noption mentioned below). The base behaviour is to allow\npackages specified on pip's command line to be upgraded. This option controls\nwhat *other* packages can be upgraded:\n\n* ``eager`` - all packages will be upgraded to the latest possible version.\n  It should be noted here that pip's current resolution algorithm isn't even\n  aware of packages other than those specified on the command line, and\n  those identified as dependencies. This may or may not be true of the new\n  resolver.\n* ``only-if-needed`` - packages are only upgraded if they are named in the\n  pip command or a requirement file (i.e, they are direct requirements), or\n  an upgraded parent needs a later version of the dependency than is\n  currently installed.\n* ``to-satisfy-only`` (**undocumented, please avoid**) - packages are not\n  upgraded (not even direct requirements) unless the currently installed\n  version fails to satisfy a requirement (either explicitly specified or a\n  dependency).\n\n  * This is actually the \"default\" upgrade strategy when ``--upgrade`` is\n    *not set*, i.e. ``pip install AlreadyInstalled`` and\n    ``pip install --upgrade --upgrade-strategy=to-satisfy-only AlreadyInstalled``\n    yield the same behavior.\n\n``--force-reinstall``\n\nDoesn't affect resolution, but if the resolved result is the same as what is\ncurrently installed, uninstall and reinstall it rather than leaving the\ncurrent version in place. This occurs even if ``--upgrade`` is not set.\n\n``--ignore-installed``\n\nAct as if the currently installed version isn't there - so don't care about\n``--upgrade``, and don't uninstall before (re-)installing.\n\n\nControlling what gets considered\n================================\n\nThese options affect the list of distribution files that the resolver will\nconsider as candidates for installation. As such, they affect the data that\nthe resolver has to work with, rather than influencing what pip does with the\nresolution result.\n\nPrereleases\n\n``--pre``\n\nSource vs Binary\n\n``--no-binary``\n\n``--only-binary``\n\n``--prefer-binary``\n\nWheel tag specification\n\n``--platform``\n\n``--implementation``\n\n``--abi``\n\nIndex options\n\n``--index-url``\n\n``--extra-index-url``\n\n``--no-index``\n\n``--find-links``\n\n\nControlling dependency data\n===========================\n\nThese options control what dependency data the resolver sees for any given\npackage (or, in the case of ``--python-version``, the environment information\nthe resolver uses to *check* the dependency).\n\n``--no-deps``\n\n``--python-version``\n\n``--ignore-requires-python``\n\n\nSpecial cases\n=============\n\nThese need further investigation. They affect the install process, but not\nnecessarily resolution or what gets installed.\n\n``--require-hashes``\n\n``--constraint``\n\n``--editable <LOCATION>``\n\n\n.. _still evolving: https://github.com/pypa/pip/issues/8115\n"
  },
  {
    "path": "docs/html/development/ci.rst",
    "content": ".. note::\n\n    This section of the documentation is currently out of date.\n\n    pip developers welcome your help to update this documentation. If\n    you're interested in helping out, please let us know in the\n    `tracking issue`_, or just submit a pull request and mention it in\n    that tracking issue.\n\n.. _`tracking issue`: https://github.com/pypa/pip/issues/7279\n\n======================\nContinuous Integration\n======================\n\nSupported interpreters\n======================\n\npip support a variety of Python interpreters:\n\n- CPython 3.9\n- CPython 3.10\n- CPython 3.11\n- CPython 3.12\n- CPython 3.13\n- CPython 3.14\n- Latest PyPy3\n\non different operating systems:\n\n- Linux\n- Windows\n- macOS\n\nand on different architectures:\n\n- x64\n- x86\n- arm64 (macOS only)\n\nso 56 hypothetical interpreters.\n\n\nChecks\n======\n\n``pip`` CI runs different kind of tests:\n\n- lint (defined in ``.pre-commit-config.yaml``)\n- docs\n- vendoring (is the ``src/_internal/_vendor`` directory cleanly vendored)\n- unit tests (present in ``tests/unit``)\n- \"integration\" tests (mostly present in ``tests/functional``)\n- package (test the packaging steps)\n\nSince lint, docs, vendoring and package tests only need to run on a pip\ndeveloper/contributor machine, they only need to be tested on the x64 variant\nof the 3 different operating systems, and when an interpreter needs to be\nspecified it's ok to require the latest CPython interpreter.\n\nSo only unit tests and integration tests would need to be run with the different\ninterpreters.\n\n\nServices\n========\n\npip test suite and checks are distributed on `GitHub Actions`_ which provides\nfree executors for open source packages.\n\n.. _`GitHub Actions`: https://github.com/features/actions\n\n\nCurrent run tests\n=================\n\nDeveloper tasks\n---------------\n\n======== =============== ================ ================== =============\n   OS          docs            lint           vendoring        packaging\n======== =============== ================ ================== =============\nLinux         GitHub           GitHub           GitHub           GitHub\nWindows       GitHub           GitHub           GitHub           GitHub\nmacOS         GitHub           GitHub           GitHub           GitHub\n======== =============== ================ ================== =============\n\nActual testing\n--------------\n\n+------------------------------+---------------+-----------------+\n|       **interpreter**        |   **unit**    | **integration** |\n+-----------+----------+-------+---------------+-----------------+\n|           |   x86    | CP3.9 |               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n|  Windows  +----------+-------+---------------+-----------------+\n|           |   x64    | CP3.9 |   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n+-----------+----------+-------+---------------+-----------------+\n|           |   x86    | CP3.9 |               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|               |                 |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n|   Linux   +----------+-------+---------------+-----------------+\n|           |   x64    | CP3.9 |   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n+-----------+----------+-------+---------------+-----------------+\n|           |  arm64   | CP3.9 |   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n|   macOS   +----------+-------+---------------+-----------------+\n|           |   x64    | CP3.9 |   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.10|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.11|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.12|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.13|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | CP3.14|   GitHub      |   GitHub        |\n|           |          +-------+---------------+-----------------+\n|           |          | PyPy3 |               |                 |\n+-----------+----------+-------+---------------+-----------------+\n"
  },
  {
    "path": "docs/html/development/contributing.rst",
    "content": "============\nContributing\n============\n\nPip's internals\n===============\n\nWe have an in-progress guide to the\n:ref:`architecture-pip-internals`. It might be helpful as you dive in.\n\nAI Policy\n=========\n\nWhile we do not dictate what tools contributors use to create pull requests,\nLLM (Large Language Model) tools are often used to generate code that the\nhuman contributor does not fully understand, and may not even be legally\nconsidered the owner of. Therefore, contributors wishing to use LLM tools\nshould read and follow the project [AI policy](https://github.com/pypa/pip/blob/main/.github/AI_POLICY.md).\n\nSubmitting Pull Requests\n========================\n\nSubmit pull requests against the ``main`` branch, providing a good\ndescription of what you're doing and why. You must have legal permission to\ndistribute any code you contribute to pip and it must be available under the\nMIT License.\n\nProvide tests that cover your changes and run the tests locally first. pip\n:ref:`supports <compatibility-requirements>` multiple Python versions and\noperating systems. Any pull request must consider and work on all these\nplatforms.\n\nPull requests should be small to facilitate easier review. Keep them\nself-contained, and limited in scope. `Studies have shown`_ that review quality\nfalls off as patch size grows. Sometimes this will result in many small PRs to\nland a single large feature. In particular, pull requests must not be treated\nas \"feature branches\", with ongoing development work happening within the PR.\nInstead, the feature should be broken up into smaller, independent parts which\ncan be reviewed and merged individually.\n\nAdditionally, avoid including \"cosmetic\" changes to code that\nis unrelated to your change, as these make reviewing the PR more difficult.\nExamples include re-flowing text in comments or documentation, or adding or\nremoving blank lines or whitespace within lines. Such changes can be made\nseparately, as a \"formatting cleanup\" PR, if needed.\n\n.. attention::\n\n   While contributors may use whatever tools they like when developing a pull\n   request, it is the contributor's responsibility to ensure that submitted\n   code meets the project requirements, and that they understand the submitted\n   code well enough to respond to review comments.\n\nAutomated Testing\n=================\n\nAll pull requests and merges to 'main' branch are tested using `GitHub\nActions`_ based on our `.github/workflows`_ files. More details about pip's\nContinuous Integration can be found in the `CI Documentation`_\n\n\nYou can find the status and results to the CI runs for your PR on GitHub's web\nUI for the pull request. You can also find links to the CI services' pages for\nthe specific builds in the form of \"Details\" links, in case the CI run fails\nand you wish to view the output.\n\nTo trigger CI to run again for a pull request, you can close and open the pull\nrequest or submit another change to the pull request. If needed, project\nmaintainers can manually trigger a restart of a job/build.\n\nTo understand the broader software architecture around dependency\nresolution in pip, and how we automatically test this functionality,\nsee `Testing the next-gen pip dependency resolver`_.\n\nNEWS Entries\n============\n\nThe ``NEWS.rst`` file is managed using `towncrier`_ and all non trivial changes\nmust be accompanied by a news entry.\n\nTo add an entry to the news file, first you need to have created an issue\ndescribing the change you want to make. A Pull Request itself *may* function as\nsuch, but it is preferred to have a dedicated issue (for example, in case the\nPR ends up rejected due to code quality reasons).\n\nOnce you have an issue or pull request, you take the number and you create a\nfile inside of the ``news/`` directory, named after that issue number with a\n\"type\" of ``removal``, ``feature``, ``bugfix``, or ``doc`` associated with it.\n\nIf your issue or PR number is ``1234`` and this change is fixing a bug,\nthen you would create a file ``news/1234.bugfix.rst``. PRs can span multiple\ncategories by creating multiple files (for instance, if you added a feature and\ndeprecated/removed the old feature at the same time, you would create\n``news/NNNN.feature.rst`` and ``news/NNNN.removal.rst``).\n\nIf a PR touches multiple issues/PRs, you may create a file for each of them\nwith the exact same contents and Towncrier will deduplicate them.\n\nContents of a NEWS entry\n------------------------\n\nThe contents of this file are reStructuredText formatted text that\nwill be used as the content of the news file entry. You do not need to\nreference the issue or PR numbers in the entry, since ``towncrier``\nwill automatically add a reference to all of the affected issues when\nrendering the NEWS file. There must be a newline at the end of the file.\n\nIn order to maintain a consistent style in the ``NEWS.rst`` file, it is\npreferred to keep the news entry to the point, in sentence case, shorter than\n80 characters and in an imperative tone -- an entry should complete the sentence\n\"This change will ...\". In rare cases, where one line is not enough, use a\nsummary line in an imperative tone followed by a blank line separating it\nfrom a description of the feature/change in one or more paragraphs, each wrapped\nat 80 characters. Remember that a news entry is meant for end users and should\nonly contain details relevant to an end user.\n\n.. _`choosing-news-entry-type`:\n\nChoosing the type of NEWS entry\n-------------------------------\n\nA trivial change is anything that does not warrant an entry in the news file.\nSome examples are: Code refactors that don't change anything as far as the\npublic is concerned, typo fixes, white space modification, etc. To mark a PR\nas trivial a contributor simply needs to add a randomly named, empty file to\nthe ``news/`` directory with the extension of ``.trivial.rst``. If you are on a\nPOSIX like operating system, one can be added by running\n``touch news/$(uuidgen).trivial.rst``. On Windows, the same result can be\nachieved in Powershell using ``New-Item \"news/$([guid]::NewGuid()).trivial.rst\"``.\nCore committers may also add a \"skip news\" label to the PR which will accomplish\nthe same thing.\n\nUpgrading, removing, or adding a new vendored library gets a special mention\nusing a ``news/<library>.vendor.rst`` file. This is in addition to any features,\nbugfixes, or other kinds of news that pulling in this library may have. This\nuses the library name as the key so that updating the same library twice doesn't\nproduce two news file entries.\n\nChanges to the processes, policies, or other non code related changed that are\notherwise notable can be done using a ``news/<name>.process.rst`` file. This is\nnot typically used, but can be used for things like changing version schemes,\nupdating deprecation policy, etc.\n\n\nUpdating your branch\n====================\n\nAs you work, you might need to update your local main branch up-to-date with\nthe ``main`` branch in the main pip repository, which moves forward as the\nmaintainers merge pull requests. Most people working on the project use the\nfollowing workflow.\n\nThis assumes that you have Git configured so that when you run the following\ncommand:\n\n.. code-block:: console\n\n    git remote -v\n\nYour output looks like this:\n\n.. code-block:: console\n\n    origin  https://github.com/USERNAME/pip.git (fetch)\n    origin  https://github.com/USERNAME/pip.git (push)\n    upstream  https://github.com/pypa/pip.git (fetch)\n    upstream  https://github.com/pypa/pip.git (push)\n\nIn the example above, ``USERNAME`` is your username on GitHub.\n\nFirst, fetch the latest changes from the main pip repository, ``upstream``:\n\n.. code-block:: console\n\n    git fetch upstream\n\nThen, check out your local ``main`` branch, and rebase the changes on top of\nit:\n\n.. code-block:: console\n\n    git checkout main\n    git rebase upstream/main\n\nAt this point, you might have to `resolve merge conflicts`_. Once this is done,\npush the updates you have just made to your local ``main`` branch to your\n``origin`` repository on GitHub:\n\n.. code-block:: console\n\n    git checkout main\n    git push origin main\n\nNow your local ``main`` branch and the ``main`` branch in your ``origin``\nrepo have been updated with the most recent changes from the main pip\nrepository.\n\nTo keep your branches updated, the process is similar:\n\n.. code-block:: console\n\n    git checkout awesome-feature\n    git fetch upstream\n    git rebase upstream/main\n\nNow your branch has been updated with the latest changes from the\n``main`` branch on the upstream pip repository.\n\nIt's good practice to back up your branches by pushing them to your\n``origin`` on GitHub as you are working on them. To push a branch,\nrun this command:\n\n.. code-block:: console\n\n    git push origin awesome-feature\n\nIn this example, ``<awesome-feature>`` is the name of your branch. This\nwill push the branch you are working on to GitHub, but will not\ncreate a PR.\n\nOnce you have pushed your branch to your ``origin``, if you need to\nupdate it again, you will have to force push your changes by running the\nfollowing command:\n\n.. code-block:: console\n\n    git push -f origin awesome-feature\n\nThe ``-f`` (or ``--force``) flag after ``push`` forces updates from your local\nbranch to update your ``origin`` branch. If you have a PR open on your\nbranch, force pushing will update your PR. (This is a useful command\nwhen someone requests changes on a PR.)\n\nIf you get an error message like this:\n\n.. code-block:: console\n\n    ! [rejected]        awesome-feature -> awesome-feature (non-fast-forward)\n    error: failed to push some refs to 'https://github.com/USERNAME/pip.git'\n    hint: Updates were rejected because the tip of your current branch is behind\n    hint: its remote counterpart. Integrate the remote changes (e.g.\n    hint: 'git pull ...') before pushing again.\n    hint: See the 'Note about fast-forwards' in 'git push --help' for details.\n\nTry force-pushing your branch with ``push -f``.\n\nThe ``main`` branch in the main pip repository gets updated frequently, so\nyou might have to update your branch at least once while you are working on it.\n\nThank you for your contribution!\n\n\nBecoming a maintainer\n=====================\n\nIf you want to become an official maintainer, start by helping out.\n\nAs a first step, we welcome you to triage issues on pip's issue\ntracker. pip maintainers provide triage abilities to contributors once\nthey have been around for some time (probably at least 2-3 months) and\ncontributed positively to the project. This is optional and highly\nrecommended for becoming a pip maintainer.\n\nLater, when you think you're ready (probably at least 5 months after\nstarting to triage), get in touch with one of the maintainers and they\nwill initiate a vote among the existing maintainers.\n\n.. note::\n\n    Upon becoming a maintainer, a person should be given access to various\n    pip-related tooling across multiple platforms. These are noted here for\n    future reference by the maintainers:\n\n    - GitHub Push Access\n    - PyPI Publishing Access\n    - CI Administration capabilities\n    - ReadTheDocs Administration capabilities\n\n.. _`Studies have shown`: https://smartbear.com/learn/code-review/best-practices-for-peer-code-review/\n.. _`resolve merge conflicts`: https://help.github.com/articles/resolving-a-merge-conflict-using-the-command-line\n.. _`GitHub Actions`: https://github.com/features/actions\n.. _`.github/workflows`: https://github.com/pypa/pip/blob/main/.github/workflows\n.. _`CI Documentation`: https://pip.pypa.io/en/latest/development/ci/\n.. _`towncrier`: https://pypi.org/project/towncrier/\n.. _`Testing the next-gen pip dependency resolver`: https://pradyunsg.me/blog/2020/03/27/pip-resolver-testing/\n"
  },
  {
    "path": "docs/html/development/conventions.rst",
    "content": ":orphan:\n\n=========================\nDocumentation Conventions\n=========================\n\nThis document describes the conventions used in pip's documentation. We\nexpect it to evolve over time as additional conventions are identified\nand past conventions are rendered obsolete.\n\n.. note::\n\n   Currently, these conventions are not enforced automatically, and\n   need to be verified manually during code review. We are interested\n   in linters that can help us enforce these conventions automatically.\n\n\nFiles\n=====\n\nNaming\n------\n\nFolder names should be a single word, all lowercase.\n\nFile names must use the kebab-case style (all lowercase, hyphen for\nseparating words) and have the extension ``.rst``.\n\nEncoding\n--------\n\nAll files in our documentation must use UTF-8 encoding.\n\nLine Length\n-----------\n\nLimit all lines to a maximum of 72 characters, where possible. This may\nbe exceeded when it does not make sense to abide by it (eg. long links,\ncode blocks).\n\nHeadings\n========\n\nUse the following symbols to create headings:\n\n#. ``=`` with overline\n#. ``=``\n#. ``-``\n#. ``^``\n#. ``'``\n#. ``*``\n\nFor visual separation from the rest of the content, all other headings\nmust have one empty line before and after. Heading 2 (``=``) should have\ntwo empty lines before, for indicating the end of the section prior to\nit.\n\n::\n\n   =========\n   Heading 1\n   =========\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n\n   Heading 2\n   =========\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n   Heading 3\n   ---------\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n   Heading 4\n   ^^^^^^^^^\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n   Heading 5\n   '''''''''\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n   Heading 6\n   *********\n\n   Lorem ipsum dolor sit amet consectetur adipisicing elit.\n\n\nWriting\n=======\n\n.. note::\n\n   We're still discussing *how* pip should be capitalized in prose. The\n   current statement here is tentative.\n\npip is a proper noun, and spelt all lowercase. Do not capitalize pip as\n\"Pip\" at the start of a sentence.\n\nAvoid using phrases such as \"easy\", \"just\", \"simply\" etc, which imply\nthat the task is trivial. If it were trivial, the user wouldn't be\nreading the documentation for it.\n"
  },
  {
    "path": "docs/html/development/getting-started.rst",
    "content": "===============\nGetting Started\n===============\n\nWe’re pleased that you are interested in working on pip.\n\nThis document is meant to get you setup to work on pip and to act as a guide and\nreference to the development setup. If you face any issues during this\nprocess, please `open an issue`_ about it on the issue tracker.\n\n\nGet the source code\n===================\n\nTo work on pip, you first need to get the source code of pip. The source code is\navailable on `GitHub`_.\n\n.. code-block:: console\n\n    $ git clone https://github.com/pypa/pip\n    $ cd pip\n\n\nDevelopment Environment\n=======================\n\npip is a command line application written in Python. For developing pip,\nyou should `install Python`_ on your computer.\n\nFor developing pip, you need to install :pypi:`nox`. The full development setup would then be:\n\n.. tab:: Unix/macOS\n\n    .. code-block:: shell\n\n        python -m venv .venv\n        source .venv/bin/activate\n        python -m pip install nox\n\n.. tab:: Windows\n\n    .. code-block:: shell\n\n        py -m venv .venv\n        .venv\\Scripts\\activate\n        py -m pip install nox\n\nRunning pip From Source Tree\n============================\n\nTo run the pip executable from your source tree during development, install pip\nlocally using editable installation (inside a virtualenv).\nYou can then invoke your local source tree pip normally (be sure virtualenv is active).\n\n.. tab:: Unix/macOS\n\n    .. code-block:: shell\n\n        python -m pip install -e .\n        python -m pip --version\n\n.. tab:: Windows\n\n    .. code-block:: shell\n\n        py -m pip install -e .\n        py -m pip --version\n\nRunning Tests\n=============\n\npip's tests are written using the :pypi:`pytest` test framework and\n:mod:`unittest.mock`. :pypi:`nox` is used to automate the setup and execution\nof pip's tests.\n\nIt is preferable to run the tests in parallel for a better experience during development,\nsince the tests can take a long time to finish when run sequentially.\n\nTo run tests:\n\n.. code-block:: console\n\n    $ nox -s test-3.10 -- -n auto\n\nTo run tests without parallelization, run:\n\n.. code-block:: console\n\n    $ nox -s test-3.10\n\nThe example above runs tests against Python 3.10. You can also use other\nversions like ``3.9`` and ``pypy3``.\n\n``nox`` has been configured to forward any additional arguments it is given to\n``pytest``. This enables the use of pytest's `rich CLI`_. As an example, you\ncan select tests using the various ways that pytest provides:\n\n.. code-block:: console\n\n    $ # Using file name\n    $ nox -s test-3.10 -- tests/functional/test_install.py\n    $ # Using markers\n    $ nox -s test-3.10 -- -m unit\n    $ # Using keywords\n    $ nox -s test-3.10 -- -k \"install and not wheel\"\n\n.. note::\n\n    When running pip's tests with OS distribution Python versions, be aware that some\n    functional tests may fail due to potential patches introduced by the distribution.\n    For all tests to pass consider:\n\n    - Installing Python from `python.org`_ or compile from source\n    - Or, using `pyenv`_ to assist with source compilation\n\nRunning pip's entire test suite requires supported version control tools\n(subversion, bazaar, git, and mercurial) to be installed. If you are missing\nany of these VCS, those tests should be skipped automatically. You can also\nexplicitly tell pytest to skip those tests:\n\n.. code-block:: console\n\n    $ nox -s test-3.10 -- -k \"not svn\"\n    $ nox -s test-3.10 -- -k \"not (svn or git)\"\n\n.. _python.org: https://www.python.org/downloads/\n.. _pyenv: https://github.com/pyenv/pyenv\n\n\nRunning Linters\n===============\n\npip uses :pypi:`pre-commit` for managing linting of the codebase.\n``pre-commit`` performs various checks on all files in pip and uses tools that\nhelp follow a consistent code style within the codebase.\n\nTo use linters locally, run:\n\n.. code-block:: console\n\n    $ nox -s lint\n\n.. note::\n\n    Avoid using ``# noqa`` comments to suppress linter warnings - wherever\n    possible, warnings should be fixed instead. ``# noqa`` comments are\n    reserved for rare cases where the recommended style causes severe\n    readability problems.\n\n\nRunning pip under a debugger\n============================\n\nIn order to debug pip's behavior, you can run it under a debugger like so:\n\n.. code-block:: console\n\n    $ python -m pdb -m pip --debug ...\n\n\nReplace the ``...`` with arguments you'd like to run pip with. Give PDB the\n``c`` (\"continue\") command afterwards, to run the process.\n\nThe ``--debug`` flag disables pip's exception handler, which would normally\ncatch all unhandled exceptions. With this flag, pip will let these exceptions\npropagate outside of its main subroutine, letting them get caught by the\ndebugger. This way you'll be able to debug an exception post-mortem via PDB.\n\n\nBuilding Documentation\n======================\n\npip's documentation is built using :pypi:`Sphinx`. The documentation is written\nin reStructuredText.\n\nTo build it locally, run:\n\n.. code-block:: console\n\n    $ nox -s docs\n\nThe built documentation can be found in the ``docs/build`` folder.\n\nFor each Pull Request made the documentation is deployed following this link:\n\n.. code-block:: none\n\n    https://pip--<PR-NUMBER>.org.readthedocs.build/en/<PR-NUMBER>\n\n\nWhat Next?\n==========\n\nThe following pages may be helpful for new contributors on where to look next\nin order to start contributing.\n\n* Some `good first issues`_ on GitHub for new contributors\n* A deep dive into `pip's architecture`_\n* A guide on `triaging issues`_ for issue tracker\n* Getting started with Git\n\n  - `Hello World for Git`_\n  - `Understanding the GitHub flow`_\n  - `Start using Git on the command line`_\n\n\n.. _`open an issue`: https://github.com/pypa/pip/issues/new?title=Trouble+with+pip+development+environment\n.. _`install Python`: https://realpython.com/installing-python/\n.. _`rich CLI`: https://docs.pytest.org/en/latest/how-to/usage.html#specifying-which-tests-to-run\n.. _`GitHub`: https://github.com/pypa/pip\n.. _`good first issues`: https://github.com/pypa/pip/labels/good%20first%20issue\n.. _`pip's architecture`: https://pip.pypa.io/en/latest/development/architecture/\n.. _`triaging issues`: https://pip.pypa.io/en/latest/development/issue-triage/\n.. _`Hello World for Git`: https://guides.github.com/activities/hello-world/\n.. _`Understanding the GitHub flow`: https://guides.github.com/introduction/flow/\n.. _`Start using Git on the command line`: https://docs.gitlab.com/ee/topics/git/\n"
  },
  {
    "path": "docs/html/development/index.rst",
    "content": "===========\nDevelopment\n===========\n\npip is a volunteer maintained open source project and we welcome contributions\nof all forms. The sections below will help you get started with development,\ntesting, and documentation.\n\nYou can also join ``#pypa`` (general packaging discussion and user support) and\n``#pypa-dev`` (discussion about development of packaging tools) `on Libera.chat`_,\nor the ``#pip`` channel on the `PyPA Discord`_, to ask questions or get involved.\n\n.. toctree::\n    :maxdepth: 2\n\n    getting-started\n    contributing\n    ci\n    issue-triage\n    architecture/index\n    release-process\n    vendoring-policy\n\n.. note::\n\n    pip's development documentation has been rearranged and some older\n    references might be broken.\n\n.. _`on Libera.chat`: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev\n.. _`PyPA Discord`: https://discord.gg/pypa\n"
  },
  {
    "path": "docs/html/development/issue-triage.md",
    "content": "```{note}\nThis section of the documentation is currently being written. pip\ndevelopers welcome your help to complete this documentation. If\nyou're interested in helping out, please let us know in the\n[tracking issue](https://github.com/pypa/pip/issues/6583), or\njust submit a pull request and mention it in that tracking issue.\n```\n\n# Issue Triage\n\nThis serves as an introduction to issue tracking in pip as well as\nhow to help triage reported issues.\n\n## Issue Tracker\n\nThe [pip issue tracker](https://github.com/pypa/pip/issues) is hosted on\nGitHub alongside the project.\n\nCurrently, the issue tracker is used for bugs, feature requests, and general\nuser support.\n\nIn the pip issue tracker, we make use of labels and milestones to organize and\ntrack work.\n\n### Labels\n\nIssue labels are used to:\n\n1. Categorize issues\n2. Provide status information for contributors and reporters\n3. Help contributors find tasks to work on\n\nThe current set of labels are divided into several categories identified by\nprefix:\n\n**C - Category**\n: which area of `pip` functionality a feature request or issue is related to\n\n**K - Kind**\n**O - Operating System**\n: for issues that are OS-specific\n\n**P - Project/Platform**\n: related to something external to `pip`\n\n**R - Resolution**\n: no more discussion is really needed, an action has been identified and the\nissue is waiting or closed\n\n**S - State**\n: for some automatic labels and other indicators that work is needed\n\n**type**\n: the role or flavor of an issue\n\nThe specific labels falling into each category have a description that can be\nseen on the [Labels](https://github.com/pypa/pip/labels) page.\n\nIn addition, there are several standalone labels:\n\n**good first issue**\n: this label marks an issue as beginner-friendly and shows up in banners that\nGitHub displays for first-time visitors to the repository\n\n**triage**\n: default label given to issues when they are created\n\n**trivial**\n: special label for pull requests that removes the\n{ref}`news file requirement <choosing-news-entry-type>`\n\n**needs rebase or merge**\n\n: this is a special label used by BrownTruck to mark PRs that have merge\nconflicts\n\n### Automation\n\nThere are several helpers to manage issues and pull requests.\n\nIssues created on the issue tracker are automatically given the\n`triage` label by the\n[triage-new-issues](https://github.com/apps/triage-new-issues)\nbot. The label is automatically removed when another label is added.\n\nWhen an issue needs feedback from the author we can label it with\n`S: awaiting response`. When the author responds, the\n[no-response](https://github.com/apps/no-response) bot removes the label.\n\nAfter an issue has been closed for 30 days, the\n[lock](https://github.com/apps/lock) bot locks the issue and adds the\n`S: auto-locked` label. This allows us to avoid monitoring existing closed\nissues, but unfortunately prevents and references to issues from showing up as\nlinks on the closed issue.\n\n## Triage Issues\n\nUsers can make issues for a number of reasons:\n\n1. Suggestions about pip features that could be added or improved\n2. Problems using pip\n3. Concerns about pip usability\n4. General packaging problems to be solved with pip\n5. Problems installing or using Python packages\n6. Problems managing virtual environments\n7. Problems managing Python installations\n\nTo triage issues means to identify what kind of issue is happening and\n\n- confirm bugs\n- provide support\n- discuss and design around the uses of the tool\n\nSpecifically, to address an issue:\n\n1. Read issue title\n2. Scan issue description\n3. Ask questions\n4. If time is available, try to reproduce\n5. Search for or remember related issues and link to them\n6. Identify an appropriate area of concern (if applicable)\n\nKeep in mind that all communication is happening with other people and\nshould be done with respect per the\n[Code of Conduct](https://www.pypa.io/en/latest/code-of-conduct/).\n\nThe lifecycle of an issue (bug or support) generally looks like:\n\n1. waiting for triage (marked with label `triage`)\n\n2. confirming issue - some discussion with the user, gathering\n   details, trying to reproduce the issue (may be marked with a specific\n   category, `S: awaiting-response`, `S: discussion-needed`, or\n   `S: need-repro`)\n\n3. confirmed - the issue is pretty consistently reproducible in a\n   straightforward way, or a mechanism that could be causing the issue has been\n   identified\n\n4. awaiting fix - the fix is identified and no real discussion on the issue\n   is needed, should be marked `R: awaiting PR`\n\n5. closed - can be for several reasons\n\n   - fixed\n   - could not be reproduced, no more details could be obtained, and no\n     progress can be made\n   - actual issue was with another project or related to system\n     configuration and pip cannot (or will not) be adapted for it\n\n### Requesting information\n\nRequesting more information to better understand the context and environment\nthat led to the issue. Examples of specific information that may be useful\ndepending on the situation:\n\n- pip debug: `pip debug`\n- pip version: `pip -V`\n- Python version: `python -VV`\n- Python path: `python -c 'import sys; print(sys.executable)'`\n- `python` on `PATH`: Unix: `which python`; Windows: `where python`\n- Python as resolved by the shell: `type python`\n- Origin of pip (get-pip.py, OS-level package manager, ensurepip, manual\n  installation)\n- Using a virtual environment (with `--system-site-packages`?)\n- Using a conda environment\n- `PATH` environment variable\n- Network situation (e.g. airgapped environment, firewalls)\n- `--verbose` output of a failing command\n- (Unix) `strace` output from a failing command (be careful not to output\n  into the same directory as a package that's being installed, otherwise pip\n  will loop forever copying the log file...)\n- (Windows)\n  [procmon](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon)\n  output during a failing command\n  ([example request](https://github.com/pypa/pip/issues/6814#issuecomment-516611389))\n- Listing of files relevant to the issue (e.g. `ls -l venv/lib/pythonX.Y/problem-package.dist-info/`)\n- whether the unexpected behavior ever worked as expected - if so then what\n  were the details of the setup (same information as above)\n\nGenerally, information is good to request if it can help confirm or rule out\npossible sources of error. We shouldn't request information that does not\nimprove our understanding of the situation.\n\n### Reproducing issues\n\nWhenever an issue happens and the cause isn't obvious, it is important\nthat we be able to reproduce it independently. This serves several purposes:\n\n1. If it is a pip bug, then any fix will need tests - a good reproducer\n   is most of the way towards that.\n2. If it is not reproducible using the provided instructions, that helps\n   rule out a lot of possible causes.\n3. A clear set of instructions is an easy way to get on the same page as\n   someone reporting an issue.\n\nThe best way to reproduce an issue is with a script.\n\nA script can be copied into a file and executed, whereas shell output\nhas to be manually copied a line at a time.\n\nScripts to reproduce issues should be:\n\n- portable (few/no assumptions about the system, other that it being Unix or Windows as applicable)\n- non-destructive\n- convenient\n- require little/no setup on the part of the runner\n\nExamples:\n\n- creating and installing multiple wheels with different versions\n  ([link](https://github.com/pypa/pip/issues/4331#issuecomment-520156471))\n- using a small web server for authentication errors\n  ([link](https://github.com/pypa/pip/issues/2920#issuecomment-508953118))\n- using docker to test system or global configuration-related issues\n  ([link](https://github.com/pypa/pip/issues/5533#issuecomment-520159896))\n- using docker to test special filesystem permission/configurations\n  ([link](https://github.com/pypa/pip/issues/6364#issuecomment-507074729))\n- using docker for global installation with get-pip\n  ([link](https://github.com/pypa/pip/issues/6498#issuecomment-513501112))\n- get-pip on system with no `/usr/lib64`\n  ([link](https://github.com/pypa/pip/issues/5379#issuecomment-515270576))\n- reproducing with `pip` from current development branch\n  ([link](https://github.com/pypa/pip/issues/6707#issue-467770959))\n\n### Reaching resolution\n\nSome user support questions are more related to system configuration than pip.\nIt's important to treat these issues with the same care and attention as\nothers, specifically:\n\n1. Unless the issue is very old and the user doesn't seem active, wait for\n   confirmation before closing the issue\n\n2. Direct the user to the most appropriate forum for their questions:\n\n   - For Ubuntu, [askubuntu](https://askubuntu.com/)\n   - For Other linuxes/unixes, [serverfault](https://serverfault.com/)\n   - For network connectivity issues,\n     [serverfault](https://serverfault.com/)\n\n3. Just because a user support question is best solved using some other forum\n   doesn't mean that we can't make things easier. Try to extract and\n   understand from the user query how things could have been made easier for\n   them or you, for example with better warning or error messages. If an issue\n   does not exist covering that case then create one. If an issue does exist then\n   make sure to reference that issue before closing this one.\n\n4. A user may be having trouble installing a package, where the package\n   `setup.py` or build-backend configuration is non-trivial. In these cases we\n   can help to troubleshoot but the best advice is going to be to direct them\n   to the support channels for the related projects.\n\n5. Do not be hasty to assume it is one cause or another. What looks like\n   someone else's problem may still be an issue in pip or at least something\n   that could be improved.\n\n6. For general discussion on Python packaging:\n\n   - [pypa/packaging](https://github.com/pypa/packaging-problems)\n   - [discuss.python.org/packaging](https://discuss.python.org/c/packaging)\n\n### Closing issues\n\nAn issue may be considered resolved and closed when:\n\n- for each possible improvement or problem represented in the issue\n  discussion:\n\n  - Consensus has been reached on a specific action and the actions\n    appear to be external to the project, with no follow up needed\n    in the project afterwards.\n\n    - PEP updates (with a corresponding issue in\n      [python/peps](https://github.com/python/peps))\n    - already tracked by another issue\n\n  - A project-specific issue has been identified and the issue no\n    longer occurs as of the latest commit on the main branch.\n\n- An enhancement or feature request no longer has a proponent and the maintainers\n  don't think it's worth keeping open.\n\n- An issue has been identified as a duplicate, and it is clearly a duplicate (i.e. the\n  original report was very good and points directly to the issue)\n\n- The issue has been fixed, and can be independently validated as no longer being an\n  issue. If this is with code then the specific change/PR that led to it should be\n  identified and posted for tracking.\n\n## Common issues\n\n1. network-related issues - any issue involving retries, address lookup, or\n   anything like that are typically network issues.\n\n2. issues related to having multiple Python versions, or an OS package\n   manager-managed pip/python installation (specifically with Debian/Ubuntu).\n   These typically present themselves as:\n\n   1. Not being able to find installed packages\n   2. basic libraries not able to be found, fundamental OS components missing\n   3. In these situations you will want to make sure that we know how they got\n      their Python and pip. Knowing the relevant package manager commands can\n      help, e.g. `dpkg -S`.\n\n## For issues caused by changes by redistributors\n\nCertain issues are caused by patches that redistributors of Python/pip\nmake to Python/pip.\n\nCertain redistributors have shared preferred wording to redirect users\nto their issue trackers.\n\nFedora, RHEL, CentOS (and probably other derivatives – Rocky, Scientific, CloudLinux):\n\n```\nThis issue looks like it's caused by changes that Fedora or Red Hat\nmade in their pip packaging. Please file a Fedora bug at\nhttps://bugzilla.redhat.com/enter_bug.cgi?product=Fedora&component=python-pip\n\ncc @encukou @hroncok\n```\n\nDebian:\n\n```\nThis issue looks like it's caused by changes that Debian made in\ntheir pip packaging. Please file a bug with Debian, with\n`reportbug python3-pip` [Docs](https://www.debian.org/Bugs/Reporting).\nYou can link to this issue in your bug report.\n\nIn the meantime, you may be able to work-around your issue by upgrading\npip inside your virtualenv: `python -m pip install -U pip`\n```\n\nUbuntu:\n\n```\nThis issue looks like it's caused by changes that Ubuntu made in\ntheir pip packaging. Please file a bug with Ubuntu, with\n`ubuntu-bug python3-pip` [Docs](https://help.ubuntu.com/community/ReportingBugs).\nYou can link to this issue in your bug report.\n\nIn the meantime, you may be able to work-around your issue by upgrading\npip inside your virtualenv: `python -m pip install -U pip`\n```\n"
  },
  {
    "path": "docs/html/development/release-process.rst",
    "content": "===============\nRelease process\n===============\n\n.. _`Release Cadence`:\n\nRelease Cadence\n===============\n\nThe pip project has a release cadence of releasing whatever is on ``main``\nevery 3 months. This gives users a predictable pattern for when releases\nare going to happen and prevents locking up improvements for fixes for long\nperiods of time, while still preventing massively fracturing the user base\nwith version numbers.\n\nOur release months are January, April, July, October. The release date within\nthat month will be up to the release manager for that release. If there are\nno changes, then that release month is skipped and the next release will be\n3 months later.\n\nThe version number of pip is ``YY.N``, where ``YY`` is the year of the release\nand ``N`` identifies the quarter of the year (0-3).\n\nThe release manager may, at their discretion, choose whether or not there\nwill be a pre-release period for a release, and if there is may extend that\nperiod into the next month if needed.\n\nBecause releases are made direct from the ``main`` branch, it is essential\nthat ``main`` is always in a releasable state. It is acceptable to merge\nPRs that partially implement a new feature, but only if the partially\nimplemented version is usable in that state (for example, with reduced\nfunctionality or disabled by default). In the case where a merged PR is found\nto need extra work before being released, the release manager always has the\noption to back out the partial change prior to a release. The PR can then be\nreworked and resubmitted for the next release.\n\nVendoring updates will be picked up from the ``main`` branch, as for any other\nupdate. Ideally, vendoring updates should be merged between releases, just like\nany other change. If there are outstanding updates to vendored packages, the\nrelease manager *may* at their discretion choose to do a vendoring update\nbefore the release. However this is *not* a requirement and in particular,\nupdates to vendored packages that fix issues in pip should be merged\nproactively, to ensure that they will be present in the next release.\n\n\n.. _`Deprecation Policy`:\n\nDeprecation Policy\n==================\n\nAny change to pip that removes or significantly alters user-visible behavior\nthat is described in the pip documentation will be deprecated for a minimum of\n6 months before the change occurs.\n\nCertain changes may be fast tracked and have a deprecation period of 3 months.\nThis requires at least two members of the pip team to be in favor of doing so,\nand no pip maintainers opposing.\n\nDeprecation will take the form of a warning being issued by pip when the\nfeature is used. Longer deprecation periods, or deprecation warnings for\nbehavior changes that would not normally be covered by this policy, are also\npossible depending on circumstances, but this is at the discretion of the pip\nmaintainers.\n\nNote that the documentation is the sole reference for what counts as agreed\nbehavior. If something isn't explicitly mentioned in the documentation, it can\nbe changed without warning, or any deprecation period, in a pip release.\nHowever, we are aware that the documentation isn't always complete - PRs that\ndocument existing behavior with the intention of covering that behavior with\nthe above deprecation process are always acceptable, and will be considered on\ntheir merits.\n\n.. note::\n\n  pip has a helper function for making deprecation easier for pip maintainers.\n  The supporting documentation can be found in the source code of\n  ``pip._internal.utils.deprecation.deprecated``. The function is not a part of\n  pip's public API.\n\nSupported Versions\n==================\n\nThe latest version of the pip is the only supported version, previous\nversions should be considered unsupported. Users are encouraged to make\nregular updates to their version of pip in order to remain supported.\n\n.. _`Python 2 Support`:\n\nPython 2 Support\n----------------\n\npip 20.3 was the last version of pip that supported Python 2. Bugs reported\nwith pip which only occur on Python 2.7 will likely be closed as \"won't fix\"\nissues by pip's maintainers.\n\nPython Support Policy\n---------------------\n\npip supports `CPython versions that are not end-of-life`_. Older versions of CPython may\nbe supported at the discretion of pip maintainers (based on criteria such as download\nstatistics on PyPI, Python versions supported by the vendored dependencies and\nmaintenance burden).\n\npip maintainers accept pull requests to support other Python implementations, but the\npip CI does not test for compatibility with them.\n\n.. _`Feature Flags`:\n\nFeature Flags\n=============\n\n``--use-deprecated``\n--------------------\n\nExample: ``--use-deprecated=legacy-resolver``\n\nUse for features that will be deprecated. Deprecated features should remain\navailable behind this flag for at least six months, as per the deprecation\npolicy.\n\nFeatures moved behind this flag should always include a warning that indicates\nwhen the feature is scheduled to be removed.\n\nOnce the feature is removed, users who use the flag should be shown an error.\n\n``--use-feature``\n-----------------\n\nExample: ``--use-feature=2020-resolver``\n\nUse for new features that users can test before they become pip's default\nbehaviour (e.g. alpha or beta releases).\n\nOnce the feature becomes the default behaviour, this flag can remain in place,\nbut should issue a warning telling the user that it is no longer necessary.\n\nRelease Process\n===============\n\nCreating a new release\n----------------------\n\n#. Ensure you have the latest ``nox`` installed.\n#. Create a new ``release/YY.N`` branch off ``main`` and switch to it.\n#. Prepare for release using ``nox -s prepare-release -- YY.N``.\n   This will update the relevant files and tag the correct commit.\n#. Submit the ``release/YY.N`` branch as a pull request and ensure CI passes.\n   Merge the changes back into ``main`` and pull them back locally.\n#. Push the tag created by ``prepare-release``. This will trigger the release\n   workflow on GitHub.\n#. Go to https://github.com/pypa/pip/actions, find the latest ``Publish Python\n   🐍 distribution 📦 to PyPI`` workflow run, open it, wait for the build step\n   to complete, then approve the PyPI environment to let the publishing step\n   run. If you desire, you have the possibility to download and inspect the\n   artifacts before approving.\n#. Regenerate the ``get-pip.py`` script in the `get-pip repository`_ (as\n   documented there) and commit the results.\n#. Submit a Pull Request to `CPython`_ adding the new version of pip\n   to ``Lib/ensurepip/_bundled``, removing the existing version, and\n   adjusting the versions listed in ``Lib/ensurepip/__init__.py``.\n\n\n.. note::\n\n  If the release dropped the support of an obsolete Python version ``M.m``,\n  a new ``M.m/get-pip.py`` needs to be published: update the ``all`` task from\n  ``tasks/generate.py`` in `get-pip repository`_ and make a pull request to\n  `psf-salt repository`_ to add the new ``get-pip.py`` (and its directory) to\n  ``salt/pypa/bootstrap/init.sls``.\n\n\n.. note::\n\n  If the ``get-pip.py`` script needs to be updated due to changes in pip internals\n  and if the last ``M.m/get-pip.py`` published still uses the default template, make\n  sure to first duplicate ``templates/default.py`` as ``templates/pre-YY.N.py``\n  before updating it and specify in ``tasks/generate.py`` that ``M.m/get-pip.py``\n  now needs to use ``templates/pre-YY.N.py``.\n\n\nCreating a bug-fix release\n--------------------------\n\nSometimes we need to release a bugfix release of the form ``YY.N.Z+1``. In\norder to create one of these the changes should already be merged into the\n``main`` branch.\n\nNote that this process is only needed when there are changes on the main branch\nthat you do *not* want to include in the bugfix release. For a bugfix release\nthat will include everything that is on the ``main`` branch, the above process\nfor creating a new release can be used, simply changing the version number.\n\n#. Create a new ``release/YY.N.Z+1`` branch off of the ``YY.N`` tag using the\n   command ``git checkout -b release/YY.N.Z+1 YY.N``.\n#. Cherry pick the fixed commits off of the ``main`` branch, fixing any\n   conflicts.\n#. Run ``nox -s prepare-release -- YY.N.Z+1``.\n#. Merge main into your release branch and drop the news files that have been\n   included in your release (otherwise they would also appear in the ``YY.N+1``\n   changelog)\n#. Push the ``release/YY.N.Z+1`` branch to github and submit a PR for it against\n   the ``main`` branch and wait for the tests to run.\n#. Once tests run, merge the ``release/YY.N.Z+1`` branch into ``main``, and\n   follow the above release process starting with step 5.\n\n.. _`get-pip repository`: https://github.com/pypa/get-pip\n.. _`psf-salt repository`: https://github.com/python/psf-salt\n.. _`CPython`: https://github.com/python/cpython\n.. _`CPython versions that are not end-of-life`: https://devguide.python.org/versions/\n"
  },
  {
    "path": "docs/html/development/vendoring-policy.rst",
    "content": ".. include:: ../../../src/pip/_vendor/README.rst\n"
  },
  {
    "path": "docs/html/getting-started.md",
    "content": "# Getting Started\n\nTo get started with using pip, you should [install Python] on your system.\n\n[install Python]: https://realpython.com/installing-python/\n\n## Ensure you have a working pip\n\nAs a first step, you should check that you have a working Python with pip\ninstalled. This can be done by running the following commands and making\nsure that the output looks similar.\n\n```{pip-cli}\n$ python --version\nPython 3.N.N\n$ pip --version\npip X.Y.Z from ... (python 3.N.N)\n```\n\nIf that worked, congratulations! You have a working pip in your environment.\n\nIf you got output that does not look like the sample above, please read\nthe {doc}`installation` page. It provides guidance on how to install pip\nwithin a Python environment that doesn't have it.\n\n## Common tasks\n\n### Install a package\n\n```{pip-cli}\n$ pip install sampleproject\n[...]\nSuccessfully installed sampleproject\n```\n\nBy default, pip will fetch packages from [Python Package Index][PyPI], a\nrepository of software for the Python programming language where anyone can\nupload packages.\n\n[PyPI]: https://pypi.org/\n\n### Install a package from GitHub\n\n```{pip-cli}\n$ pip install git+https://github.com/pypa/sampleproject.git@main\n[...]\nSuccessfully installed sampleproject\n```\n\nSee {doc}`topics/vcs-support` for more information about this syntax.\n\n### Install a package from a distribution file\n\npip can install directly from distribution files as well. They come in 2 forms:\n\n- {term}`source distribution <Source Distribution (or \"sdist\")>` (usually shortened to \"sdist\")\n- {term}`wheel distribution <Wheel>` (usually shortened to \"wheel\")\n\n```{pip-cli}\n$ pip install sampleproject-1.0.tar.gz\n[...]\nSuccessfully installed sampleproject\n$ pip install sampleproject-1.0-py3-none-any.whl\n[...]\nSuccessfully installed sampleproject\n```\n\n### Install multiple packages using a requirements file\n\nMany Python projects use {file}`requirements.txt` files, to specify the\nlist of packages that need to be installed for the project to run. To install\nthe packages listed in that file, you can run:\n\n```{pip-cli}\n$ pip install -r requirements.txt\n[...]\nSuccessfully installed sampleproject\n```\n\n### Upgrade a package\n\n```{pip-cli}\n$ pip install --upgrade sampleproject\n   [...]\nSuccessfully installed sampleproject\n```\n\n### Uninstall a package\n\n```{pip-cli}\n$ pip uninstall sampleproject\nUninstalling sampleproject:\n   [...]\nProceed (Y/n)? y\nSuccessfully uninstalled sampleproject\n```\n\n## Next Steps\n\nIt is recommended to learn about what virtual environments are and how to use\nthem. This is covered in the {doc}`Installing Packages <pypug:tutorials/installing-packages>`\ntutorial on packaging.python.org.\n"
  },
  {
    "path": "docs/html/index.md",
    "content": "---\nhide-toc: true\n---\n\n# pip\n\npip is the [package installer for Python][recommended]. You can use it to\ninstall packages from the [Python Package Index][pypi] and other indexes.\n\n```{toctree}\n:hidden:\n\ngetting-started\ninstallation\nuser_guide\ntopics/index\nreference/index\ncli/index\n```\n\n```{toctree}\n:caption: Project\n:hidden:\n\ndevelopment/index\nux-research-design/index\nnews\nCode of Conduct <https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md>\nGitHub <https://github.com/pypa/pip>\n```\n\nIf you want to learn about how to use pip, check out the following resources:\n\n- [Getting Started](getting-started)\n- [Python Packaging User Guide](https://packaging.python.org)\n\nIf you find bugs, need help, or want to talk to the developers, use our mailing\nlists or chat rooms:\n\n- [GitHub Issues][issue-tracker]\n- [Discourse channel][packaging-discourse]\n- [User IRC][irc-pypa]\n- [Development IRC][irc-pypa-dev]\n\n[recommended]: https://packaging.python.org/guides/tool-recommendations/\n[pypi]: https://pypi.org/\n[issue-tracker]: https://github.com/pypa/pip/issues/\n[packaging-discourse]: https://discuss.python.org/c/packaging/14\n[irc-pypa]: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa\n[irc-pypa-dev]: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev\n\nIf you find any security issues, please report to [security@python.org](mailto:security@python.org)\n\n## Privacy Notice\n\nPip does not collect any telemetry, however, it will send\nnon-identifying environment information (Python version, OS, etc.) to any remote indices\nused, who may choose to retain such information. Please consult PyPI's privacy\npolicy for their data collection and retention practices.\n"
  },
  {
    "path": "docs/html/installation.md",
    "content": "# Installation\n\nUsually, pip is automatically installed if you are:\n\n- working in a\n  {ref}`virtual environment <pypug:Creating and using Virtual Environments>`\n- using Python downloaded from [python.org](https://www.python.org)\n- using Python that has not been modified by a redistributor to remove\n  {mod}`ensurepip`\n\n## Supported Methods\n\nIf your Python environment does not have pip installed, there are 2 mechanisms\nto install pip supported directly by pip's maintainers:\n\n- [`ensurepip`](#ensurepip)\n- [`get-pip.py`](#get-pippy)\n\n### `ensurepip`\n\nPython comes with an {mod}`ensurepip` module[^python], which can install pip in\na Python environment.\n\n```{pip-cli}\n$ python -m ensurepip --upgrade\n```\n\nMore details about how {mod}`ensurepip` works and how it can be used, is\navailable in the standard library documentation.\n\n### `get-pip.py`\n\nThis is a Python script that uses some bootstrapping logic to install\npip.\n\n- Download the script, from <https://bootstrap.pypa.io/get-pip.py>.\n- Open a terminal/command prompt, `cd` to the folder containing the\n  `get-pip.py` file and run:\n\n  ```{pip-cli}\n  $ python get-pip.py\n  ```\n\nMore details about this script can be found in [pypa/get-pip]'s README.\n\n[pypa/get-pip]: https://github.com/pypa/get-pip\n\n### Standalone zip application\n\n```{note}\nThe zip application is currently experimental. We test that pip runs correctly\nin this form, but it is possible that there could be issues in some situations.\nWe will accept bug reports in such cases, but for now the zip application should\nnot be used in production environments.\n```\n\nIn addition to installing pip in your environment, pip is available as a\nstandalone [zip application](https://docs.python.org/3.11/library/zipapp.html).\nThis can be downloaded from <https://bootstrap.pypa.io/pip/pip.pyz>. There are\nalso zip applications for specific pip versions, named `pip-X.Y.Z.pyz`.\n\nThe zip application can be run using any supported version of Python:\n\n```{pip-cli}\n$ python pip.pyz --help\n```\n\nIf run directly:\n\n````{tab} Linux\n```console\n$ chmod +x ./pip.pyz\n$ ./pip.pyz\n```\n\nthen the currently active Python interpreter will be used.\n````\n\n````{tab} MacOS\n```console\n$ chmod +x ./pip.pyz\n$ ./pip.pyz\n```\n\nthen the currently active Python interpreter will be used.\n````\n\n````{tab} Windows\n```doscon\nC:> .\\pip.pyz\n```\n\nthen the currently active Python interpreter will be used.\n\nYou may need to configure your system to recognise the ``.pyz`` extension\nbefore this will work.\n````\n\n## Alternative Methods\n\nDepending on how you installed Python, there might be other mechanisms\navailable to you for installing pip such as\n{ref}`using Linux package managers <pypug:installing pip/setuptools/wheel with linux package managers>`.\n\nThese mechanisms are provided by redistributors of pip, who may have modified\npip to change its behaviour. This has been a frequent source of user confusion,\nsince it causes a mismatch between documented behaviour in this documentation\nand how pip works after those modifications.\n\nIf you face issues when using Python and pip installed using these mechanisms,\nit is recommended to request for support from the relevant provider (eg: Linux\ndistro community, cloud provider support channels, etc).\n\n## Upgrading `pip`\n\nUpgrade your `pip` by running:\n\n```{pip-cli}\n$ pip install --upgrade pip\n```\n\n(compatibility-requirements)=\n\n## Compatibility\n\nThe current version of pip works on:\n\n- Windows, Linux and macOS.\n- CPython 3.9, 3.10, 3.11, 3.12, 3.13, and latest PyPy3.\n\npip is tested to work on the latest patch version of the Python interpreter,\nfor each of the minor versions listed above. Previous patch versions are\nsupported on a best effort approach.\n\nOther operating systems and Python versions are not supported by pip's\nmaintainers.\n\nUsers who are on unsupported platforms should be aware that if they hit issues, they may have to resolve them for themselves. If they received pip from a source which provides support for their platform, they should request pip support from that source.\n\n[^python]: The `ensurepip` module was added to the Python standard library in Python 3.4.\n"
  },
  {
    "path": "docs/html/installing.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../installation/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`installation`\n"
  },
  {
    "path": "docs/html/news.rst",
    "content": "=========\nChangelog\n=========\n\n.. attention::\n\n    Major and minor releases of pip also include changes listed within\n    prior beta releases.\n\n.. towncrier-draft-entries:: Not yet released\n\n.. pip-news-include:: ../../NEWS.rst\n"
  },
  {
    "path": "docs/html/quickstart.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../getting-started/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`getting-started`\n"
  },
  {
    "path": "docs/html/reference/build-system.md",
    "content": "(build-interface)=\n\n# Build System Interface\n\nWhen dealing with installable source distributions of a package, pip does not\ndirectly handle the build process for the package. This responsibility is\ndelegated to \"build backends\" -- also known as \"build systems\". This means\nthat pip needs an interface, to interact with these build backends.\n\nModern Python packages can contain a `pyproject.toml` file, first introduced in\n{pep}`518` and later expanded in {pep}`517`, {pep}`621` and {pep}`660`.\nThis file contains build system requirements and information, which are used by\npip to build the package.\n\n## Build process\n\nThe overall process for building a package is:\n\n- Create an isolated build environment.\n- Populate the build environment with build dependencies.\n- Generate the package's metadata, if necessary and possible.\n- Generate a wheel for the package.\n\nThe wheel can then be used to perform an installation, if necessary.\n\n### Build Isolation\n\nFor building packages using this interface, pip uses an _isolated environment_.\nThat is, pip will install build-time Python dependencies in a temporary\ndirectory which will be added to `sys.path` for the build commands. This ensures\nthat build requirements are handled independently of the user's runtime\nenvironment.\n\nFor example, a project that needs an older version of setuptools to build can\nstill be installed, even if the user has a newer version installed (and\nwithout silently replacing that version).\n\n### Build-time dependencies\n\nIntroduced in {pep}`518`, the `build-system.requires` key in the\n`pyproject.toml` file is a list of requirement specifiers for build-time\ndependencies of a package.\n\n```toml\n[build-system]\nrequires = [\"setuptools ~= 58.0\", \"cython ~= 0.29.0\"]\n```\n\nIt is also possible for a build backend to provide dynamically calculated\nbuild dependencies, using {pep}`517`'s `get_requires_for_build_wheel` hook. This\nhook will be called by pip, and dependencies it describes will also be installed\nin the build environment. For example, newer versions of setuptools expose the\ncontents of `setup_requires` to pip via this hook.\n\nBuild-time requirement specifiers follow {pep}`508`, so it's possible to\nreference packages with URLs. For example:\n\n```toml\n[build-system]\nrequires = [\"setuptools @ git+https://github.com/pypa/setuptools.git@main\"]\n```\n\n### Metadata Generation\n\n```{versionadded} 19.0\n\n```\n\nOnce the build environment has been created and populated with build-time\ndependencies, `pip` will usually need metadata about a package (name, version,\ndependencies, and more).\n\nIf {pep}`517`'s `prepare_metadata_for_build_wheel` hook is provided by the\nbuild backend, that will be used to generate the packages' metadata. Otherwise,\na wheel will be generated (as described below) and the metadata contained\nwithin such a wheel will be used.\n\n### Wheel Generation\n\n```{versionadded} 19.0\n\n```\n\nFor generating a wheel, pip uses the {pep}`517` `build_wheel` hook that has\nto be provided by the build backend. The build backend will generate a wheel,\nwhich may involve compiling extension code written in C/C++ (or other\nlanguages).\n\nWheels generated using this mechanism can be [cached](wheel-caching) for reuse,\nto speed up future installations.\n\n### Editable Installation\n\n```{versionadded} 21.3\n\n```\n\nFor performing editable installs, pip will use {pep}`660`\n`build_wheel_for_editable` hook that has to be provided by the build backend.\nThe wheels generated using this mechanism are not cached.\n\n### Backend Configuration\n\nBuild backends have the ability to accept configuration settings, which can\nchange the way the build is handled. These settings take the form of a\nseries of `key=value` pairs. The user can supply configuration settings\nusing the `--config-settings` command line option (which can be supplied\nmultiple times, in order to specify multiple settings).\n\nThe supplied configuration settings are passed to every backend hook call.\n\nConfiguration settings provided via `--config-settings` command line options (or the\nequivalent environment variables or configuration file entries) are passed to the build\nof requirements explicitly provided as pip command line arguments. They are not passed\nto the build of dependencies, or to the build of requirements provided in requirement\nfiles.\n\n## Build output\n\nIt is the responsibility of the build backend to ensure that the output is\nin the correct encoding, as described in {pep}`517`.\n\n## Fallback Behaviour\n\n```{warning}\nThe following snippet merely describes the fallback behavior. For valid\nexamples of `pyproject.toml` to use with setuptools, please refer to\n[the setuptools documentation](\nhttps://setuptools.pypa.io/en/stable/userguide/quickstart.html#basic-use).\n```\n\nIf a project does not have a `pyproject.toml` file containing a `build-system`\nsection, and contains a `setup.py` it will be assumed to have the following\nbackend settings:\n\n```toml\n[build-system]\nrequires = [\"setuptools>=40.8.0\"]\nbuild-backend = \"setuptools.build_meta:__legacy__\"\n```\n\nIf a project has a `build-system` section but no `build-backend`, then:\n\n- It is expected to include `setuptools` as a build requirement. An\n  error is reported if the available version of `setuptools` is not recent\n  enough.\n\n- The `setuptools.build_meta:__legacy__` build backend will be used.\n\n## Disabling build isolation\n\nThis can be disabled using the `--no-build-isolation` flag -- users supplying\nthis flag are responsible for ensuring the build environment is managed\nappropriately, including ensuring that all required build-time dependencies are\ninstalled, since pip does not manage build-time dependencies when this flag is\npassed.\n\n## Historical notes\n\n```{versionadded} 10.0\n\n```\n\nAs this feature was incrementally rolled out, there have been various notable\nchanges and improvements in it.\n\nSetuptools 40.8.0 is the first version of setuptools that offers a\n{pep}`517` backend that closely mimics directly executing `setup.py`.\n\n```{versionadded} 18.0\nPrior to pip 18.0, pip only supports installing build requirements from\nwheels, and does not support the use of environment markers and extras (only\nversion specifiers are respected).\n```\n\n```{versionadded} 18.1\nPrior to pip 18.1, build dependencies using `.pth` files are not properly\nsupported; as a result namespace packages do not work under Python 3.2 and\nearlier.\n```\n\n```{versionchanged} 23.1\nThe legacy interface where pip could invoke `setup.py install`\nin some circumstances was removed,\nin favor of the fallback behavior described above.\n```\n\n```{versionchanged} 25.3\nThe legacy interface where pip could invoke `setup.py build_wheel` or\n`setup.py develop` in some circumstances was removed,\nin favor of the fallback behavior described above.\n```\n"
  },
  {
    "path": "docs/html/reference/index.md",
    "content": "# Reference\n\nReference provides information about various file formats, interfaces and\ninteroperability standards that pip utilises/implements.\n\n```{toctree}\n:titlesonly:\n\nbuild-system\nrequirement-specifiers\nrequirements-file-format\ninstallation-report\ninspect-report\n```\n"
  },
  {
    "path": "docs/html/reference/inspect-report.md",
    "content": "# `pip inspect` JSON output specification\n\n```{versionadded} 22.2\n```\n\n```{versionchanged} 23.0\n``version`` has been bumped to ``1`` and the format declared stable.\n```\n\nThe `pip inspect` command produces a detailed JSON report of the Python\nenvironment, including installed distributions.\n\n## Specification\n\nThe report is a JSON object with the following properties:\n\n- `version`: the string `1`. It will change only if\n  and when backward incompatible changes are introduced, such as removing mandatory\n  fields or changing the semantics or data type of existing fields. The introduction of\n  backward incompatible changes will follow the usual pip processes such as the\n  deprecation cycle or feature flags. Tools must check this field to ensure they support\n  the corresponding version.\n\n- `pip_version`: a string with the version of pip used to produce the report.\n\n- `installed`: an array of [`InspectReportItem`](InspectReportItem) representing the\n  distribution packages that are installed.\n\n- `environment`: an object describing the environment where the installation report was\n  generated. See the section on environment markers in the {ref}`pypug:dependency-specifiers`\n  specification for more information. Values have a string type.\n\n(InspectReportItem)=\n\nAn `InspectReportItem` is an object describing an installed distribution package with\nthe following properties:\n\n- `metadata`: the metadata of the distribution, converted to a JSON object according to\n  the [PEP 566\n  transformation](https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata).\n\n- `metadata_location`: the location of the metadata of the installed distribution. Most\n  of the time this is the `.dist-info` directory. For legacy installs it is the\n  `.egg-info` directory.\n\n  ```{warning}\n  This field may not necessarily point to a directory, for instance, in the case of older\n  `.egg` installs.\n  ```\n\n- `direct_url`: Information about the direct URL that was used for installation, if any,\n  using the [direct URL data\n  structure](https://packaging.python.org/en/latest/specifications/direct-url-data-structure/).\n  In most case, this field corresponds to the\n  [`direct_url.json`](https://packaging.python.org/en/latest/specifications/direct-url)\n  metadata, except for legacy editable installs, where it is emulated.\n\n- `requested`: `true` if the `REQUESTED` metadata is present, `false` otherwise. This\n  field is only present for modern `.dist-info` installations.\n\n  ```{note}\n  The `REQUESTED` metadata may not be generated by all installers.\n  It is generated by pip since version 20.2.\n  ```\n\n- `installer`: the content of the `INSTALLER` metadata, if present and not empty.\n\n## Example\n\nRunning the ``pip inspect`` command, in an environment where `pip` is installed in\neditable mode and `packaging` is installed as well, will produce an output similar to\nthis (metadata abriged for brevity):\n\n```json\n{\n  \"version\": \"1\",\n  \"pip_version\": \"22.2.dev0\",\n  \"installed\": [\n    {\n      \"metadata\": {\n        \"metadata_version\": \"2.1\",\n        \"name\": \"pyparsing\",\n        \"version\": \"3.0.9\",\n        \"summary\": \"pyparsing module - Classes and methods to define and execute parsing grammars\",\n        \"description_content_type\": \"text/x-rst\",\n        \"author_email\": \"Paul McGuire <ptmcg.gm+pyparsing@gmail.com>\",\n        \"classifier\": [\n          \"Development Status :: 5 - Production/Stable\",\n          \"Intended Audience :: Developers\",\n          \"Intended Audience :: Information Technology\",\n          \"License :: OSI Approved :: MIT License\",\n          \"Operating System :: OS Independent\",\n          \"Programming Language :: Python\",\n          \"Programming Language :: Python :: 3\",\n          \"Programming Language :: Python :: 3.6\",\n          \"Programming Language :: Python :: 3.7\",\n          \"Programming Language :: Python :: 3.8\",\n          \"Programming Language :: Python :: 3.9\",\n          \"Programming Language :: Python :: 3.10\",\n          \"Programming Language :: Python :: 3 :: Only\",\n          \"Programming Language :: Python :: Implementation :: CPython\",\n          \"Programming Language :: Python :: Implementation :: PyPy\",\n          \"Typing :: Typed\"\n        ],\n        \"requires_dist\": [\n          \"railroad-diagrams ; extra == \\\"diagrams\\\"\",\n          \"jinja2 ; extra == \\\"diagrams\\\"\"\n        ],\n        \"requires_python\": \">=3.6.8\",\n        \"project_url\": [\n          \"Homepage, https://github.com/pyparsing/pyparsing/\"\n        ],\n        \"provides_extra\": [\n          \"diagrams\"\n        ],\n        \"description\": \"...\"\n      },\n      \"metadata_location\": \"/home/me/.virtualenvs/demoenv/lib/python3.8/site-packages/pyparsing-3.0.9.dist-info\",\n      \"installer\": \"pip\",\n      \"requested\": false\n    },\n    {\n      \"metadata\": {\n        \"metadata_version\": \"2.1\",\n        \"name\": \"packaging\",\n        \"version\": \"21.3\",\n        \"platform\": [\n          \"UNKNOWN\"\n        ],\n        \"summary\": \"Core utilities for Python packages\",\n        \"description_content_type\": \"text/x-rst\",\n        \"home_page\": \"https://github.com/pypa/packaging\",\n        \"author\": \"Donald Stufft and individual contributors\",\n        \"author_email\": \"donald@stufft.io\",\n        \"license\": \"BSD-2-Clause or Apache-2.0\",\n        \"classifier\": [\n          \"Development Status :: 5 - Production/Stable\",\n          \"Intended Audience :: Developers\",\n          \"License :: OSI Approved :: Apache Software License\",\n          \"License :: OSI Approved :: BSD License\",\n          \"Programming Language :: Python\",\n          \"Programming Language :: Python :: 3\",\n          \"Programming Language :: Python :: 3 :: Only\",\n          \"Programming Language :: Python :: 3.6\",\n          \"Programming Language :: Python :: 3.7\",\n          \"Programming Language :: Python :: 3.8\",\n          \"Programming Language :: Python :: 3.9\",\n          \"Programming Language :: Python :: 3.10\",\n          \"Programming Language :: Python :: Implementation :: CPython\",\n          \"Programming Language :: Python :: Implementation :: PyPy\"\n        ],\n        \"requires_dist\": [\n          \"pyparsing (!=3.0.5,>=2.0.2)\"\n        ],\n        \"requires_python\": \">=3.6\",\n        \"description\": \"...\"\n      },\n      \"metadata_location\": \"/home/me/.virtualenvs/demoenv/lib/python3.8/site-packages/packaging-21.3.dist-info\",\n      \"installer\": \"pip\",\n      \"requested\": true\n    },\n    {\n      \"metadata\": {\n        \"metadata_version\": \"2.1\",\n        \"name\": \"pip\",\n        \"version\": \"22.2.dev0\",\n        \"summary\": \"The PyPA recommended tool for installing Python packages.\",\n        \"home_page\": \"https://pip.pypa.io/\",\n        \"author\": \"The pip developers\",\n        \"author_email\": \"distutils-sig@python.org\",\n        \"license\": \"MIT\",\n        \"classifier\": [\n          \"Development Status :: 5 - Production/Stable\",\n          \"Intended Audience :: Developers\",\n          \"License :: OSI Approved :: MIT License\",\n          \"Topic :: Software Development :: Build Tools\",\n          \"Programming Language :: Python\",\n          \"Programming Language :: Python :: 3\",\n          \"Programming Language :: Python :: 3 :: Only\",\n          \"Programming Language :: Python :: 3.7\",\n          \"Programming Language :: Python :: 3.8\",\n          \"Programming Language :: Python :: 3.9\",\n          \"Programming Language :: Python :: 3.10\",\n          \"Programming Language :: Python :: Implementation :: CPython\",\n          \"Programming Language :: Python :: Implementation :: PyPy\"\n        ],\n        \"requires_python\": \">=3.7\",\n        \"project_url\": [\n          \"Documentation, https://pip.pypa.io\",\n          \"Source, https://github.com/pypa/pip\",\n          \"Changelog, https://pip.pypa.io/en/stable/news/\"\n        ],\n        \"description\": \"...\"\n      },\n      \"metadata_location\": \"/home/me/pip/src/pip.egg-info\",\n      \"direct_url\": {\n        \"url\": \"file:///home/me/pip/src\",\n        \"dir_info\": {\n          \"editable\": true\n        }\n      }\n    }\n  ],\n  \"environment\": {\n    \"implementation_name\": \"cpython\",\n    \"implementation_version\": \"3.8.10\",\n    \"os_name\": \"posix\",\n    \"platform_machine\": \"x86_64\",\n    \"platform_release\": \"5.13-generic\",\n    \"platform_system\": \"Linux\",\n    \"platform_version\": \"...\",\n    \"python_full_version\": \"3.8.10\",\n    \"platform_python_implementation\": \"CPython\",\n    \"python_version\": \"3.8\",\n    \"sys_platform\": \"linux\"\n  }\n}\n```\n"
  },
  {
    "path": "docs/html/reference/installation-report.md",
    "content": "# Installation Report\n\n```{versionadded} 22.2\n```\n\n```{versionchanged} 23.0\n``version`` has been bumped to ``1`` and the format declared stable.\n```\n\nThe `--report` option of the pip install command produces a detailed JSON report of what\nit did install (or what it would have installed, if used with the `--dry-run` option).\n\n```{note}\nWhen considering use cases, please bear in mind that\n\n- while the `--report` option may be used to implement requirement locking tools (among\n  other use cases), this format is *not* meant to be a lock file format as such;\n- there is no plan for pip to accept an installation report as input for the `install`,\n  `download` or `wheel` commands;\n- while the `--report` option and this format is a supported pip feature,\n  it is *not* a PyPA interoperability standard and as such its evolution is governed by\n  the pip processes and not the PyPA standardization processes.\n```\n\n## Specification\n\nThe report is a JSON object with the following properties:\n\n- `version`: the string `1`. It will change only if\n  and when backward incompatible changes are introduced, such as removing mandatory\n  fields or changing the semantics or data type of existing fields. The introduction of\n  backward incompatible changes will follow the usual pip processes such as the\n  deprecation cycle or feature flags. Tools must check this field to ensure they support\n  the corresponding version.\n\n- `pip_version`: a string with the version of pip used to produce the report.\n\n- `install`: an array of [`InstallationReportItem`](InstallationReportItem) representing\n  the distribution packages (to be) installed.\n\n- `environment`: an object describing the environment where the installation report was\n  generated. See [PEP 508 environment\n  markers](https://peps.python.org/pep-0508/#environment-markers) for more information.\n  Values have a string type.\n\n(InstallationReportItem)=\n\nAn `InstallationReportItem` is an object describing a (to be) installed distribution\npackage with the following properties:\n\n- `metadata`: the metadata of the distribution, converted to a JSON object according to\n  the [PEP 566\n  transformation](https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata).\n\n- `is_direct`: `true` if the requirement was provided as, or constrained to, a direct\n  URL reference. `false` if the requirements was provided as a name and version\n  specifier.\n\n- `is_yanked`: `true` if the requirement was yanked from the index, but was still\n  selected by pip conform to [PEP 592](https://peps.python.org/pep-0592/#installers).\n\n- `download_info`: Information about the artifact (to be) downloaded for installation,\n  using the [direct URL data\n  structure](https://packaging.python.org/en/latest/specifications/direct-url-data-structure/).\n  When `is_direct` is `true`, this field is the same as the\n  [`direct_url.json`](https://packaging.python.org/en/latest/specifications/direct-url)\n  metadata, otherwise it represents the URL of the artifact obtained from the index or\n  `--find-links`.\n\n  ```{note}\n  For source archives, `download_info.archive_info.hashes` may\n  be absent when the requirement was installed from the wheel cache\n  and the cache entry was populated by an older pip version that did not\n  record the origin URL of the downloaded artifact.\n  ```\n\n- `requested`: `true` if the requirement was explicitly provided by the user, either\n  directly via a command line argument or indirectly via a requirements file. `false`\n  if the requirement was installed as a dependency of another requirement.\n\n- `requested_extras`: extras requested by the user. This field is only present when the\n  `requested` field is true.\n\n## Example\n\nThe following command:\n\n```console\npip install \\\n  --ignore-installed --dry-run --quiet \\\n  --report - \\\n  \"pydantic>=1.9\" git+https://github.com/pypa/packaging@main\n```\n\nwill produce an output similar to this (metadata abriged for brevity):\n\n```json\n{\n  \"version\": \"1\",\n  \"pip_version\": \"22.2\",\n  \"install\": [\n    {\n      \"download_info\": {\n        \"url\": \"https://files.pythonhosted.org/packages/a4/0c/fbaa7319dcb5eecd3484686eb5a5c5702a6445adb566f01aee6de3369bc4/pydantic-1.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\",\n        \"archive_info\": {\n          \"hashes\": {\n            \"sha256\": \"18f3e912f9ad1bdec27fb06b8198a2ccc32f201e24174cec1b3424dda605a310\"\n          }\n        }\n      },\n      \"is_direct\": false,\n      \"is_yanked\": false,\n      \"requested\": true,\n      \"metadata\": {\n        \"name\": \"pydantic\",\n        \"version\": \"1.9.1\",\n        \"requires_dist\": [\n          \"typing-extensions (>=3.7.4.3)\",\n          \"dataclasses (>=0.6) ; python_version < \\\"3.7\\\"\",\n          \"python-dotenv (>=0.10.4) ; extra == 'dotenv'\",\n          \"email-validator (>=1.0.3) ; extra == 'email'\"\n        ],\n        \"requires_python\": \">=3.6.1\",\n        \"provides_extra\": [\n          \"dotenv\",\n          \"email\"\n        ]\n      }\n    },\n    {\n      \"download_info\": {\n        \"url\": \"https://github.com/pypa/packaging\",\n        \"vcs_info\": {\n          \"vcs\": \"git\",\n          \"requested_revision\": \"main\",\n          \"commit_id\": \"4f42225e91a0be634625c09e84dd29ea82b85e27\"\n        }\n      },\n      \"is_direct\": true,\n      \"is_yanked\": false,\n      \"requested\": true,\n      \"metadata\": {\n        \"name\": \"packaging\",\n        \"version\": \"21.4.dev0\",\n        \"requires_dist\": [\n          \"pyparsing (!=3.0.5,>=2.0.2)\"\n        ],\n        \"requires_python\": \">=3.7\"\n      }\n    },\n    {\n      \"download_info\": {\n        \"url\": \"https://files.pythonhosted.org/packages/6c/10/a7d0fa5baea8fe7b50f448ab742f26f52b80bfca85ac2be9d35cdd9a3246/pyparsing-3.0.9-py3-none-any.whl\",\n        \"archive_info\": {\n          \"hashes\": {\n            \"sha256\": \"5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc\"\n          }\n        }\n      },\n      \"is_direct\": false,\n      \"requested\": false,\n      \"metadata\": {\n        \"name\": \"pyparsing\",\n        \"version\": \"3.0.9\",\n        \"requires_dist\": [\n          \"railroad-diagrams ; extra == \\\"diagrams\\\"\",\n          \"jinja2 ; extra == \\\"diagrams\\\"\"\n        ],\n        \"requires_python\": \">=3.6.8\"\n      }\n    },\n    {\n      \"download_info\": {\n        \"url\": \"https://files.pythonhosted.org/packages/75/e1/932e06004039dd670c9d5e1df0cd606bf46e29a28e65d5bb28e894ea29c9/typing_extensions-4.2.0-py3-none-any.whl\",\n        \"archive_info\": {\n          \"hashes\": {\n            \"sha256\": \"6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708\"\n          }\n        }\n      },\n      \"is_direct\": false,\n      \"requested\": false,\n      \"metadata\": {\n        \"name\": \"typing_extensions\",\n        \"version\": \"4.2.0\",\n        \"requires_python\": \">=3.7\"\n      }\n    }\n  ],\n  \"environment\": {\n    \"implementation_name\": \"cpython\",\n    \"implementation_version\": \"3.10.5\",\n    \"os_name\": \"posix\",\n    \"platform_machine\": \"x86_64\",\n    \"platform_release\": \"5.13-generic\",\n    \"platform_system\": \"Linux\",\n    \"platform_version\": \"...\",\n    \"python_full_version\": \"3.10.5\",\n    \"platform_python_implementation\": \"CPython\",\n    \"python_version\": \"3.10\",\n    \"sys_platform\": \"linux\"\n  }\n}\n```\n"
  },
  {
    "path": "docs/html/reference/pip.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip`\n"
  },
  {
    "path": "docs/html/reference/pip_cache.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_cache/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_cache`\n"
  },
  {
    "path": "docs/html/reference/pip_check.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_check/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_check`\n"
  },
  {
    "path": "docs/html/reference/pip_config.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_config/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_config`\n"
  },
  {
    "path": "docs/html/reference/pip_debug.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_debug/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_debug`\n"
  },
  {
    "path": "docs/html/reference/pip_download.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_download/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_download`\n"
  },
  {
    "path": "docs/html/reference/pip_freeze.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_freeze/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_freeze`\n"
  },
  {
    "path": "docs/html/reference/pip_hash.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_hash/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_hash`\n"
  },
  {
    "path": "docs/html/reference/pip_index.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_index/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_index`\n"
  },
  {
    "path": "docs/html/reference/pip_install.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_install/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_install`\n"
  },
  {
    "path": "docs/html/reference/pip_list.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_list/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_list`\n"
  },
  {
    "path": "docs/html/reference/pip_search.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_search/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_search`\n"
  },
  {
    "path": "docs/html/reference/pip_show.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_show/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_show`\n"
  },
  {
    "path": "docs/html/reference/pip_uninstall.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_uninstall/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_uninstall`\n"
  },
  {
    "path": "docs/html/reference/pip_wheel.rst",
    "content": ":orphan:\n\n.. meta::\n\n  :http-equiv=refresh: 3; url=../../cli/pip_wheel/\n\nThis page has moved\n===================\n\nYou should be redirected automatically in 3 seconds. If that didn't\nwork, here's a link: :doc:`../cli/pip_wheel`\n"
  },
  {
    "path": "docs/html/reference/requirement-specifiers.md",
    "content": "(Requirement Specifiers)=\n\n# Requirement Specifiers\n\npip supports installing from a package index using a {term}`requirement specifier <pypug:Requirement Specifier>`. Generally speaking, a requirement specifier is composed of a project name followed by optional {term}`version specifiers <pypug:Version Specifier>`.\n\n{pep}`508` contains a full specification of the format of a requirement.\n\n```{versionadded} 6.0\nSupport for environment markers.\n```\n\n```{versionadded} 19.1\nSupport for the direct URL reference form.\n```\n\n## Overview\n\nA requirement specifier comes in two forms:\n\n- name-based, which is composed of:\n\n  - a package name (eg: `requests`)\n  - optionally, a set of \"extras\" that serve to install optional dependencies (eg: `security`)\n  - optionally, constraints to apply on the version of the package\n  - optionally, environment markers\n\n- URL-based, which is composed of:\n\n  - a package name (eg: `requests`)\n  - optionally, a set of \"extras\" that serve to install optional dependencies (eg: `security`)\n  - a URL for the package\n  - optionally, environment markers\n\n## Examples\n\nA few example name-based requirement specifiers:\n\n```\nSomeProject\nSomeProject == 1.3\nSomeProject >= 1.2, < 2.0\nSomeProject[foo, bar]\nSomeProject ~= 1.4.2\nSomeProject == 5.4 ; python_version < '3.8'\nSomeProject ; sys_platform == 'win32'\nrequests [security] >= 2.8.1, == 2.8.* ; python_version < \"2.7\"\n```\n\n```{note}\nUse quotes around specifiers in the shell when using `>`, `<`, or when using environment markers.\n\nDo _not_ use quotes in requirement files. There is only one exception: pip v7.0 and v7.0.1 (from May 2015) required quotes around specifiers containing environment markers in requirement files.\n```\n\nA few example URL-based requirement specifiers:\n\n```none\npip @ https://github.com/pypa/pip/archive/22.0.2.zip\nrequests [security] @ https://github.com/psf/requests/archive/refs/heads/main.zip ; python_version >= \"3.11\"\n```\n"
  },
  {
    "path": "docs/html/reference/requirements-file-format.md",
    "content": "(requirements-file-format)=\n\n# Requirements File Format\n\nRequirements files serve as a list of items to be installed by pip, when\nusing {ref}`pip install`. Files that use this format are often called\n\"pip requirements.txt files\", since `requirements.txt` is usually what\nthese files are named (although, that is not a requirement).\n\n```{note}\nThe requirements file format is closely tied to a number of internal details of\npip (e.g., pip's command line options). The basic format is relatively stable\nand portable but the full syntax, as described here, is only intended for\nconsumption by pip, and other tools should take that into account before using\nit for their own purposes.\n```\n\n## Example\n\n```\n# This is a comment, to show how #-prefixed lines are ignored.\n# It is possible to specify requirements as plain names.\npytest\npytest-cov\nbeautifulsoup4\n\n# The syntax supported here is the same as that of requirement specifiers.\ndocopt == 0.6.1\nrequests [security] >= 2.8.1, == 2.8.* ; python_version < \"2.7\"\nurllib3 @ https://github.com/urllib3/urllib3/archive/refs/tags/1.26.8.zip\n\n# It is possible to refer to other requirement files or constraints files.\n-r other-requirements.txt\n-c constraints.txt\n\n# It is possible to refer to specific local distribution paths.\n./downloads/numpy-1.9.2-cp34-none-win32.whl\n\n# It is possible to refer to URLs.\nhttp://wxpython.org/Phoenix/snapshot-builds/wxPython_Phoenix-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl\n```\n\n## Structure\n\nEach line of the requirements file indicates something to be installed,\nor arguments to {ref}`pip install`. The following forms are supported:\n\n- `[[--option]...]`\n- `<requirement specifier>`\n- `<archive url/path>`\n- `[-e] <local project path>`\n- `[-e] <vcs project url>`\n\nFor details on requirement specifiers, see {ref}`Requirement Specifiers`. For\nexamples of all these forms, see {ref}`pip install Examples`.\n\n### Encoding\n\nThe default encoding for requirement files is `UTF-8` unless a different\nencoding is specified using a {pep}`263` style comment (e.g. `# -*- coding:\n<encoding name> -*-`).\n\n### Line continuations\n\nA line ending in an unescaped `\\` is treated as a line continuation\nand the newline following it is effectively ignored.\n\n### Comments\n\nA line that begins with `#` is treated as a comment and ignored. Whitespace\nfollowed by a `#` causes the `#` and the remainder of the line to be\ntreated as a comment.\n\nComments are stripped _after_ line continuations are processed.\n\n## Supported options\n\nRequirements files only supports certain pip install options, which are listed\nbelow.\n\n### Global options\n\nThe following options have an effect on the _entire_ `pip install` run, and\nmust be specified on their individual lines.\n\n```{eval-rst}\n.. pip-requirements-file-options-ref-list::\n```\n\n````{admonition} Example\nTo specify {ref}`--pre <install_--pre>`, {ref}`--no-index <install_--no-index>`\nand two {ref}`--find-links <install_--find-links>` locations:\n\n```\n--pre\n--no-index\n--find-links /my/local/archives\n--find-links http://some.archives.com/archives\n```\n````\n\n(per-requirement-options)=\n\n### Per-requirement options\n\n```{versionadded} 7.0\n\n```\n\nThe options which can be applied to individual requirements are:\n\n- {ref}`--config-settings <install_--config-settings>`\n- `--hash` (for {ref}`Hash-checking mode`)\n\n## Referring to other requirements files\n\nIf you wish, you can refer to other requirements files, like this:\n\n```\n-r more_requirements.txt\n```\n\nYou can also refer to {ref}`constraints files <Constraints Files>`, like this:\n\n```\n-c some_constraints.txt\n```\n\n## Using environment variables\n\n```{versionadded} 10.0\n\n```\n\npip supports the use of environment variables inside the\nrequirements file.\n\nYou have to use the POSIX format for variable names including brackets around\nthe uppercase name as shown in this example: `${API_TOKEN}`. pip will attempt\nto find the corresponding environment variable defined on the host system at\nruntime.\n\n```{note}\nThere is no support for other variable expansion syntaxes such as `$VARIABLE`\nand `%VARIABLE%`.\n```\n\nYou can now store sensitive data (tokens, keys, etc.) in environment variables\nand only specify the variable name for your requirements, letting pip lookup\nthe value at runtime. This approach aligns with the commonly used\n[12-factor configuration pattern](https://12factor.net/config).\n"
  },
  {
    "path": "docs/html/topics/authentication.md",
    "content": "# Authentication\n\n## Basic HTTP authentication\n\npip supports basic HTTP-based authentication credentials. This is done by\nproviding the username (and optionally password) in the URL:\n\n```\nhttps://username:password@pypi.company.com/simple\n```\n\nFor indexes that only require single-part authentication tokens, provide the\ntoken as the \"username\" and do not provide a password:\n\n```\nhttps://0123456789abcdef@pypi.company.com/simple\n```\n\n### Percent-encoding special characters\n\n```{versionadded} 10.0\n```\n\nCertain special characters are not valid in the credential part of a URL.\nIf the user or password part of your login credentials contain any of these\n[special characters][reserved-chars], then they must be percent-encoded. As an\nexample, for a user with username `user` and password `he//o` accessing a\nrepository at `pypi.company.com/simple`, the URL with credentials would look\nlike:\n\n```\nhttps://user:he%2F%2Fo@pypi.company.com/simple\n```\n\n[reserved-chars]: https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters\n\n## netrc support\n\npip supports loading credentials from a user's `.netrc` file. If no credentials\nare part of the URL, pip will attempt to get authentication credentials for the\nURL's hostname from the user's `.netrc` file. This behaviour comes from the\nunderlying use of {pypi}`requests`, which in turn delegates it to the\n[Python standard library's `netrc` module][netrc-std-lib].\n\n```{note}\nAs mentioned in the [standard library documentation for netrc][netrc-std-lib],\nonly ASCII characters are allowed in `.netrc` files. Whitespace and\nnon-printable characters are not allowed in passwords.\n```\n\nBelow is an example `.netrc`, for the host `example.com`, with a user named\n`daniel`, using the password `qwerty`:\n\n```\nmachine example.com\nlogin daniel\npassword qwerty\n```\n\nMore information about the `.netrc` file format can be found in the GNU [`ftp`\nman pages][netrc-docs].\n\n[netrc-docs]: https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html\n[netrc-std-lib]: https://docs.python.org/3/library/netrc.html\n\n## Keyring Support\n\npip supports loading credentials stored in your keyring using the\n{pypi}`keyring` library, which can be enabled py passing `--keyring-provider`\nwith a value of `auto`, `disabled`, `import`, or `subprocess`. The default\nvalue `auto` respects `--no-input` and does not query keyring at all if the option\nis used; otherwise it tries the `import`, `subprocess`, and `disabled`\nproviders (in this order) and uses the first one that works.\n\n### Configuring pip's keyring usage\n\nSince the keyring configuration is likely system-wide, a more common way to\nconfigure its usage would be to use a configuration instead:\n\n```{seealso}\n{doc}`./configuration` describes how pip configuration works.\n```\n\n```bash\n$ pip config set --global global.keyring-provider subprocess\n\n# A different user on the same system which has PYTHONPATH configured and and\n# wanting to use keyring installed that way could then run\n$ pip config set --user global.keyring-provider import\n\n# For a specific virtual environment you might want to use disable it again\n# because you will only be using PyPI and the private repo (and mirror)\n# requires 2FA with a keycard and a pincode\n$ pip config set --site global.index https://pypi.org/simple\n$ pip config set --site global.keyring-provider disabled\n\n# configuring it via environment variable is also possible\n$ export PIP_KEYRING_PROVIDER=disabled\n```\n\n### Using keyring's Python module\n\nSetting `keyring-provider` to `import` makes pip communicate with `keyring` via\nits Python interface.\n\n```bash\n# install keyring from PyPI\n$ pip install keyring --index-url https://pypi.org/simple\n$ echo \"your-password\" | keyring set pypi.company.com your-username\n$ pip install your-package --keyring-provider import --index-url https://pypi.company.com/\n```\n\n### Using keyring as a command line application\n\nSetting `keyring-provider` to `subprocess` makes pip look for and use the\n`keyring` command found on `PATH`.\n\nFor this use case, a username *must* be included in the URL, since it is\nrequired by `keyring`'s command line interface. See the example below or the\nbasic HTTP authentication section at the top of this page.\n\n```bash\n# Install keyring from PyPI using pipx, which we assume is installed properly\n# you can also create a venv somewhere and add it to the PATH yourself instead\n$ pipx install keyring --index-url https://pypi.org/simple\n\n# For Azure DevOps, also install its keyring backend.\n$ pipx inject keyring artifacts-keyring --index-url https://pypi.org/simple\n\n# For Google Artifact Registry, also install and initialize its keyring backend.\n$ pipx inject keyring keyrings.google-artifactregistry-auth --index-url https://pypi.org/simple\n$ gcloud auth login\n\n# Note that a username is required in the index URL.\n$ pip install your-package --keyring-provider subprocess --index-url https://username@pypi.example.com/\n```\n\n### Here be dragons\n\nThe `auto` provider is conservative and does not query keyring at all when\n`--no-input` is used because the keyring might require user interaction such as\nprompting the user on the console. Third party tools frequently call Pip for\nyou and do indeed pass `--no-input` as they are well-behaved and don't have\nmuch information to work with. (Keyring does have an api to request a backend\nthat does not require user input.) You have more information about your system,\nhowever!\n\nYou can force keyring usage by requesting a keyring provider other than `auto`\n(or `disabled`). Leaving `import` and `subprocess`. You do this by passing\n`--keyring-provider import` or one of the following methods:\n\n```bash\n# via config file, possibly with --user, --global or --site\n$ pip config set global.keyring-provider subprocess\n# or via environment variable\n$ export PIP_KEYRING_PROVIDER=import\n```\n\n```{warning}\nBe careful when doing this since it could cause tools such as pipx and Pipenv\nto appear to hang. They show their own progress indicator while hiding output\nfrom the subprocess in which they run Pip. You won't know whether the keyring\nbackend is waiting the user input or not in such situations.\n```\n\nNote that `keyring` (the Python package) needs to be installed separately from\npip. This can create a bootstrapping issue if you need the credentials stored in\nthe keyring to download and install keyring.\n\nIt is, thus, expected that users that wish to use pip's keyring support have\nsome mechanism for downloading and installing {pypi}`keyring`.\n"
  },
  {
    "path": "docs/html/topics/caching.md",
    "content": "# Caching\n\n```{versionadded} 6.0\n\n```\n\npip provides an on-by-default caching, designed to reduce the amount of time\nspent on duplicate downloads and builds.\n\n## What is cached\n\n### HTTP responses\n\nThis cache functions like a web browser cache.\n\nWhen making any HTTP request, pip will first check its local cache to determine\nif it has a suitable response stored for that request which has not expired. If\nit does then it returns that response and doesn't re-download the content.\n\nIf it has a response stored but it has expired, then it will attempt to make a\nconditional request to refresh the cache which will either return an empty\nresponse telling pip to simply use the cached item (and refresh the expiration\ntimer) or it will return a whole new response which pip can then store in the\ncache.\n\nWhile this cache attempts to minimize network activity, it does not prevent\nnetwork access altogether. If you want a local install solution that\ncircumvents accessing PyPI, see {ref}`Installing from local packages`.\n\n```{versionchanged} 23.3\nA new cache format is now used, stored in a directory called `http-v2` (see\nbelow for this directory's location). Previously this cache was stored in a\ndirectory called `http` in the main cache directory. If you have completely\nswitched to newer versions of `pip`, you may wish to delete the old directory.\n```\n\n(wheel-caching)=\n\n### Locally built wheels\n\npip attempts to use wheels from its local wheel cache whenever possible.\n\nThis means that if there is a cached wheel for the same version of a specific\npackage name, pip will use that wheel instead of rebuilding the project.\n\nWhen no wheels are found for a source distribution, pip will attempt to build a\nwheel using the package's build system. If the build is successful, this wheel\nis added to the cache and used in subsequent installs for the same package\nversion.\n\nWheels built from source distributions provided to pip as a direct path (such\nas `pip install .`) are not cached across runs, though they may be reused within\nthe same `pip` execution.\n\n```{versionchanged} 20.0\npip now caches wheels when building from an immutable Git reference\n(i.e. a commit hash).\n```\n\n## Where is the cache stored\n\n```{caution}\nThe exact filesystem structure of pip's cache's contents is considered to be\nan implementation detail and may change between any two versions of pip.\n```\n\n### `pip cache dir`\n\n```{versionadded} 20.1\n\n```\n\nYou can use `pip cache dir` to get the cache directory that pip is currently configured to use.\n\n### Default paths\n\n````{tab} Linux\n```\n~/.cache/pip\n```\n\npip will also respect `XDG_CACHE_HOME`.\n````\n\n````{tab} MacOS\n```\n~/Library/Caches/pip\n```\n````\n\n````{tab} Windows\n```\n%LocalAppData%\\pip\\Cache\n```\n````\n\n## Avoiding caching\n\npip tries to use its cache whenever possible, and it is designed do the right\nthing by default.\n\nIn some cases, pip's caching behaviour can be undesirable. As an example, if you\nhave package with optional C extensions, that generates a pure Python wheel\nwhen the C extension can’t be built, pip will use that cached wheel even when\nyou later invoke it from an environment that could have built those optional C\nextensions. This is because pip is seeing a cached wheel that matches the\npackage being built, and pip assumes that the result of building a package from\na package index is deterministic.\n\nThe recommended approach for dealing with these situations is to directly\ninstall from a source distribution instead of letting pip auto-discover the\npackage when it is trying to install. Installing directly from a source\ndistribution will make pip build a wheel, regardless of whether there is a\nmatching cached wheel. This usually means doing something like:\n\n```{pip-cli}\n$ pip download sampleproject==1.0.0 --no-binary :all:\n$ pip install sampleproject-1.0.0.tar.gz\n```\n\nIt is also a good idea to remove the offending cached wheel using the\n{ref}`pip cache` command.\n\n## Cache management\n\nThe {ref}`pip cache` command can be used to manage pip's cache.\n\n### General overview\n\n`pip cache info` provides an overview of the contents of pip's cache, such as the total size and location of various parts of it.\n\n### Removing a single package\n\n`pip cache remove setuptools` removes all wheel files related to setuptools from pip's cache. HTTP cache files are not removed at this time.\n\n### Removing the cache\n\n`pip cache purge` will clear all files from pip's wheel and HTTP caches.\n\n### Listing cached files\n\n`pip cache list` will list all wheel files from pip's cache.\n\n`pip cache list setuptools` will list all setuptools-related wheel files from pip's cache.\n\n## Disabling caching\n\npip's caching behaviour is disabled by passing the `--no-cache-dir` option.\n\nIt is, however, recommended to **NOT** disable pip's caching unless you have caching at a higher level (eg: layered caches in container builds). Doing so can\nsignificantly slow down pip (due to repeated operations and package builds)\nand result in significantly more network usage.\n"
  },
  {
    "path": "docs/html/topics/configuration.md",
    "content": "(configuration)=\n\n# Configuration\n\npip allows a user to change its behaviour via 3 mechanisms:\n\n- command line options\n- environment variables\n- configuration files\n\nThis page explains how the configuration files and environment variables work,\nand how they are related to pip's various command line options.\n\n```{seealso}\n{doc}`../cli/pip_config` command, which helps manage pip's configuration.\n```\n\n(config-file)=\n\n## Configuration Files\n\nConfiguration files can change the default values for command line options.\nThe files are written using standard INI format.\n\npip has 3 \"levels\" of configuration files:\n\n- `global`: system-wide configuration file, shared across users.\n- `user`: per-user configuration file.\n- `site`: per-environment configuration file; i.e. per-virtualenv.\n\nAdditionally, environment variables can be specified which will override any of the above.\n\n### Location\n\npip's configuration files are located in fairly standard locations. This\nlocation is different on different operating systems, and has some additional\ncomplexity for backwards compatibility reasons. Note that if user config files\nexist in both the legacy and current locations, values in the current file\nwill override values in the legacy file.\n\n```{tab} Unix\n\nGlobal\n: In a \"pip\" subdirectory of any of the paths set in the environment variable\n  `XDG_CONFIG_DIRS` (if it exists), for example {file}`/etc/xdg/pip/pip.conf`.\n\n  This will be followed by loading {file}`/etc/pip.conf`.\n\nUser\n: {file}`$HOME/.config/pip/pip.conf`, which respects the `XDG_CONFIG_HOME` environment variable.\n\n  The legacy \"per-user\" configuration file is also loaded, if it exists: {file}`$HOME/.pip/pip.conf`.\n\nSite\n: {file}`$VIRTUAL_ENV/pip.conf`\n```\n\n```{tab} MacOS\n\nGlobal\n: {file}`/Library/Application Support/pip/pip.conf`\n\nUser\n: {file}`$HOME/Library/Application Support/pip/pip.conf`\n  if directory `$HOME/Library/Application Support/pip` exists\n  else {file}`$HOME/.config/pip/pip.conf`\n\n  The legacy \"per-user\" configuration file is also loaded, if it exists: {file}`$HOME/.pip/pip.conf`.\n\nSite\n: {file}`$VIRTUAL_ENV/pip.conf`\n```\n\n```{tab} Windows\n\nGlobal\n: * On Windows 7 and later: {file}`C:\\\\ProgramData\\\\pip\\\\pip.ini`\n    (hidden but writeable)\n  * On Windows Vista: Global configuration is not supported.\n  * On Windows XP:\n    {file}`C:\\\\Documents and Settings\\\\All Users\\\\Application Data\\\\pip\\\\pip.ini`\n\nUser\n: {file}`%APPDATA%\\\\pip\\\\pip.ini`\n\n  The legacy \"per-user\" configuration file is also loaded, if it exists: {file}`%HOME%\\\\pip\\\\pip.ini`\n\nSite\n: {file}`%VIRTUAL_ENV%\\\\pip.ini`\n```\n\n### `PIP_CONFIG_FILE`\n\nAdditionally, the environment variable `PIP_CONFIG_FILE` can be used to specify\na configuration file that's loaded last, and whose values override the values\nset in the aforementioned files. Setting this to {any}`os.devnull`\ndisables the loading of _all_ configuration files. Note that if a file exists\nat the location that this is set to, the user config file will not be loaded.\n\n(config-precedence)=\n\n### Loading order\n\nWhen multiple configuration files are found, pip combines them in the following\norder:\n\n- Global\n- User\n- Site\n- `PIP_CONFIG_FILE`, if given.\n\nEach file read overrides any values read from previous files, so if the\nglobal timeout is specified in both the global file and the per-user file\nthen the latter value will be used.\n\n### Naming\n\nThe names of the settings are derived from the long command line option.\n\nAs an example, if you want to use a different package index (`--index-url`) and\nset the HTTP timeout (`--timeout`) to 60 seconds, your config file would\nlook like this:\n\n```ini\n[global]\ntimeout = 60\nindex-url = https://download.zope.org/ppix\n```\n\n### Per-command section\n\nEach subcommand can be configured optionally in its own section. This overrides\nthe global setting with the same name.\n\nAs an example, if you want to decrease the `timeout` to `10` seconds when\nrunning the {ref}`pip freeze`, and use `60` seconds for all other commands:\n\n```ini\n[global]\ntimeout = 60\n\n[freeze]\ntimeout = 10\n```\n\n### Boolean options\n\nBoolean options like `--ignore-installed` or `--no-dependencies` can be set\nlike this:\n\n```ini\n[install]\nignore-installed = true\nno-dependencies = yes\n```\n\nTo enable the boolean options `--no-compile`, `--no-warn-script-location` and\n`--no-cache-dir`, falsy values have to be used:\n\n```ini\n[global]\nno-cache-dir = false\n\n[install]\nno-compile = no\nno-warn-script-location = false\n```\n\n### Repeatable options\n\nFor options which can be repeated like `--verbose` and `--quiet`, a\nnon-negative integer can be used to represent the level to be specified:\n\n```ini\n[global]\nquiet = 0\nverbose = 2\n```\n\nIt is possible to append values to a section within a configuration file. This\nis applicable to appending options like `--find-links` or `--trusted-host`,\nwhich can be written on multiple lines:\n\n```ini\n[global]\nfind-links =\n    http://download.example.com\n\n[install]\nfind-links =\n    http://mirror1.example.com\n    http://mirror2.example.com\n\ntrusted-host =\n    mirror1.example.com\n    mirror2.example.com\n```\n\nThis enables users to add additional values in the order of entry for such\ncommand line arguments.\n\n## Environment Variables\n\npip's command line options can be set with environment variables using the\nformat `PIP_<UPPER_LONG_NAME>` . Dashes (`-`) have to be replaced with\nunderscores (`_`).\n\n- `PIP_TIMEOUT=60` is the same as `--timeout=60`\n- ```\n  PIP_FIND_LINKS=\"http://mirror1.example.com http://mirror2.example.com\"\n  ```\n\n  is the same as\n\n  ```\n  --find-links=http://mirror1.example.com --find-links=http://mirror2.example.com\n  ```\n\nRepeatable options that do not take a value (such as `--verbose`) can be\nspecified using the number of repetitions:\n\n- `PIP_VERBOSE=3` is the same as `pip install -vvv`\n\n```{note}\nEnvironment variables set to an empty string (like with `export X=` on Unix) will **not** be treated as false.\nUse `no`, `false` or `0` instead.\n```\n\n## Precedence / Override order\n\nCommand line options override environment variables, which override the\nvalues in a configuration file. Within the configuration file, values in\ncommand-specific sections override values in the global section.\n\nExamples:\n\n- `--host=foo` overrides `PIP_HOST=foo`\n- `PIP_HOST=foo` overrides a config file with `[global] host = foo`\n- A command specific section in the config file `[<command>] host = bar`\n  overrides the option with same name in the `[global]` config file section.\n"
  },
  {
    "path": "docs/html/topics/dependency-resolution.md",
    "content": "# Dependency Resolution\n\npip is capable of determining and installing the dependencies of packages. The\nprocess of determining which version of a dependency to install is known as\ndependency resolution. This behaviour can be disabled by passing\n{any}`--no-deps` to {any}`pip install`.\n\n## How it works\n\nWhen a user does a `pip install` (e.g. `pip install tea`), pip needs to work\nout the package's dependencies (e.g. `spoon`, `hot-water`, `tea-leaves` etc.)\nand what the versions of each of those dependencies it should install.\n\nAt the start of a `pip install` run, pip does not have all the dependency\ninformation of the requested packages. It needs to work out the dependencies\nof the requested packages, the dependencies of those dependencies, and so on.\nOver the course of the dependency resolution process, pip will need to download\ndistribution files of the packages which are used to get the dependencies of a\npackage.\n\n## Backtracking\n\n```{versionchanged} 20.3\npip's dependency resolver is now capable of backtracking.\n```\n\nDuring dependency resolution, pip needs to make assumptions about the package\nversions it needs to install and, later, check these assumptions were not\nincorrect. When pip finds that an assumption it made earlier is incorrect, it\nhas to backtrack, which means also discarding some of the work that has already\nbeen done, and going back to choose another path.\n\nThis can look like pip downloading multiple versions of the same package,\nsince pip explicitly presents each download to the user. The backtracking of\nchoices made during this step is not unexpected behaviour or a bug. It is part\nof how dependency resolution for Python packages works.\n\n````{admonition} Example\nThe user requests `pip install tea`. The package `tea` declares a dependency on\n`hot-water`, `spoon`, `cup`, amongst others.\n\npip starts by picking the most recent version of `tea` and gets the list of\ndependencies of that version of `tea`. It will then repeat the process for\nthose packages, picking the most recent version of `spoon` and then `cup`. Now,\npip notices that the version of `cup` it has chosen is not compatible with the\nversion of `spoon` it has chosen. Thus, pip will \"go back\" (backtrack) and try\nto use another version of `cup`. If it is successful, it will continue onto the\nnext package (like `sugar`). Otherwise, it will continue to backtrack on `cup`\nuntil it finds a version of `cup` that is compatible with all the other\npackages.\n\nThis can look like:\n\n```console\n$ pip install tea\nCollecting tea\n  Downloading tea-1.9.8-py2.py3-none-any.whl (346 kB)\n     |████████████████████████████████| 346 kB 10.4 MB/s\nCollecting spoon==2.27.0\n  Downloading spoon-2.27.0-py2.py3-none-any.whl (312 kB)\n     |████████████████████████████████| 312 kB 19.2 MB/s\nCollecting cup>=1.6.0\n  Downloading cup-3.22.0-py2.py3-none-any.whl (397 kB)\n     |████████████████████████████████| 397 kB 28.2 MB/s\nINFO: pip is looking at multiple versions of this package to determine\nwhich version is compatible with other requirements.\nThis could take a while.\n  Downloading cup-3.21.0-py2.py3-none-any.whl (395 kB)\n     |████████████████████████████████| 395 kB 27.0 MB/s\n  Downloading cup-3.20.0-py2.py3-none-any.whl (394 kB)\n     |████████████████████████████████| 394 kB 24.4 MB/s\n  Downloading cup-3.19.1-py2.py3-none-any.whl (394 kB)\n     |████████████████████████████████| 394 kB 21.3 MB/s\n  Downloading cup-3.19.0-py2.py3-none-any.whl (394 kB)\n     |████████████████████████████████| 394 kB 26.2 MB/s\n  Downloading cup-3.18.0-py2.py3-none-any.whl (393 kB)\n     |████████████████████████████████| 393 kB 22.1 MB/s\n  Downloading cup-3.17.0-py2.py3-none-any.whl (382 kB)\n     |████████████████████████████████| 382 kB 23.8 MB/s\n  Downloading cup-3.16.0-py2.py3-none-any.whl (376 kB)\n     |████████████████████████████████| 376 kB 27.5 MB/s\n  Downloading cup-3.15.1-py2.py3-none-any.whl (385 kB)\n     |████████████████████████████████| 385 kB 30.4 MB/s\nINFO: pip is looking at multiple versions of this package to determine\nwhich version is compatible with other requirements.\nThis could take a while.\n  Downloading cup-3.15.0-py2.py3-none-any.whl (378 kB)\n     |████████████████████████████████| 378 kB 21.4 MB/s\n  Downloading cup-3.14.0-py2.py3-none-any.whl (372 kB)\n     |████████████████████████████████| 372 kB 21.1 MB/s\n```\n\nThese multiple `Downloading cup-{version}` lines show that pip is backtracking\nchoices it is making during dependency resolution.\n````\n\nIf pip starts backtracking during dependency resolution, it does not know how\nmany choices it will reconsider, and how much computation would be needed.\n\nFor the user, this means it can take a long time to complete when pip starts\nbacktracking. In the case where a package has a lot of versions, arriving at a\ngood candidate can take a lot of time. The amount of time depends on the\npackage size, the number of versions pip must try, and various other factors.\n\nBacktracking reduces the risk that installing a new package will accidentally\nbreak an existing installed package, and so reduces the risk that your\nenvironment gets messed up. To do this, pip has to do more work, to find out\nwhich version of a package is a good candidate to install.\n\n## Possible ways to reduce backtracking\n\nThere is no one-size-fits-all answer to situations where pip is backtracking\nexcessively during dependency resolution. There are ways to reduce the\ndegree to which pip might backtrack though. Nearly all of these approaches\nrequire some amount of trial and error.\n\n### Allow pip to complete its backtracking\n\nIn most cases, pip will complete the backtracking process successfully.\nThis could take a very long time to complete, so this may not be your\npreferred option.\n\nHowever, it is a possible that pip will not be able to find a set of\ncompatible versions. For this, pip will try every possible combination that\nit needs to and determine that there is no compatible set.\n\nIf you'd prefer not to wait, you can interrupt pip (Ctrl+c) and try the\nstrategies listed below.\n\n### Reduce the number of versions pip is trying to use\n\nIt is usually a good idea to add constraints the package(s) that pip is backtracking on (e.g. in the above example - `cup`).\n\nYou could try something like:\n\n```{pip-cli}\n$ pip install tea \"cup >= 3.13\"\n```\n\nThis will reduce the number of versions of `cup` it tries, and\npossibly reduce the time pip takes to install.\n\nThere is a possibility that the addition constraint is incorrect. When this\nhappens, the reduced search space makes it easier for pip to more quickly\ndetermine what caused the conflict and present that to the user. It could also\nresult in pip backtracking on a different package due to some other conflict.\n\n### Use constraint files or lockfiles\n\nThis option is a progression of the previous section. It requires users to know\nhow to inspect:\n\n- the packages they're trying to install\n- the package release frequency and compatibility policies\n- their release notes and changelogs from past versions\n\nDuring deployment, you can create a lockfile stating the exact package and\nversion number for each dependency of that package. You can create this\nwith [pip-tools](https://github.com/jazzband/pip-tools/).\n\nThis means the \"work\" is done once during development process, and thus\nwill avoid performing dependency resolution during deployment.\n\n(Fixing conflicting dependencies)=\n\n## Dealing with dependency conflicts\n\nThis section uses hypothetical packages (`package_coffee`, `package_tea`, and\n`package_water`) to explain how pip resolves conflicts.\n\nThis section provides practical suggestions to pip users who encounter\na `ResolutionImpossible` error, where pip cannot install their specified\npackages due to conflicting dependencies.\n\n### Understanding your error message\n\nWhen you get a `ResolutionImpossible` error, you might see something\nlike this:\n\n```{pip-cli}\n$ pip install package_coffee==0.44.1 package_tea==4.3.0\n[regular pip output]\nERROR: Cannot install package_coffee==0.44.1 and package_tea==4.3.0 because these package versions have conflicting dependencies.\n\nThe conflict is caused by:\n    package_coffee 0.44.1 depends on package_water<3.0.0,>=2.4.2\n    package_tea 4.3.0 depends on package_water==2.3.1\n```\n\nIn this example, pip cannot install the packages you have requested,\nbecause they each depend on different versions of the same package\n(``package_water``):\n\n- ``package_coffee`` version ``0.44.1`` depends on a version of\n  ``package_water`` that is less than ``3.0.0`` but greater than or equal to\n  ``2.4.2``\n- ``package_tea`` version ``4.3.0`` depends on version ``2.3.1`` of\n  ``package_water``\n\nNote: `package_coffee`, `package_tea`, and `package_water` are hypothetical\npackages used only to illustrate dependency conflicts. They are not real\nprojects you can install.\n\n\nSometimes these messages are straightforward to read, because they use\ncommonly understood comparison operators to specify the required version\n(e.g. `<` or `>`).\n\nHowever, Python packaging also supports some more complex ways for\nspecifying package versions (e.g. `~=` or `*`):\n\n| Operator | Description                                                    | Example                                              |\n| -------- | -------------------------------------------------------------- | ---------------------------------------------------- |\n| `>`      | Any version greater than the specified version.                | `>3.1`: any version greater than `3.1`.              |\n| `<`      | Any version less than the specified version.                   | `<3.1`: any version less than `3.1`.                 |\n| `<=`     | Any version less than or equal to the specified version.       | `<=3.1`: any version less than or equal to `3.1`.    |\n| `>=`     | Any version greater than or equal to the specified version.    | `>=3.1`: any version greater than or equal to `3.1`. |\n| `==`     | Exactly the specified version.                                 | `==3.1`: only version `3.1`.                         |\n| `!=`     | Any version not equal to the specified version.                | `!=3.1`: any version other than `3.1`.               |\n| `~=`     | Any compatible{sup}`1` version.                                | `~=3.1`: any version compatible{sup}`1` with `3.1`.  |\n| `*`      | Can be used at the end of a version number to represent _all_. | `==3.1.*`: any version that starts with `3.1`.       |\n\n{sup}`1` Compatible versions are higher versions that only differ in the final segment.\n`~=3.1.2` is equivalent to `>=3.1.2, ==3.1.*`. `~=3.1` is equivalent to `>=3.1, ==3.*`.\n\nThe detailed specification of supported comparison operators can be\nfound in {pep}`440`.\n\n### Possible solutions\n\nThe solution to your error will depend on your individual use case. Here\nare some things to try:\n\n#### Audit your top level requirements\n\nAs a first step, it is useful to audit your project and remove any\nunnecessary or out of date requirements (e.g. from your `setup.py` or\n`requirements.txt` files). Removing these can significantly reduce the\ncomplexity of your dependency tree, thereby reducing opportunities for\nconflicts to occur.\n\n#### Loosen your top level requirements\n\nSometimes the packages that you have asked pip to install are\nincompatible because you have been too strict when you specified the\npackage version.\n\nIn our first example both `package_coffee` and `package_tea` have been\n_pinned_ to use specific versions\n(`package_coffee==0.44.1 package_tea==4.3.0`).\n\nTo find a version of both `package_coffee` and `package_tea` that depend on\nthe same version of `package_water`, you might consider:\n\n- Loosening the range of packages that you are prepared to install\n  (e.g. `pip install \"package_coffee>0.44\" \"package_tea>4.0.0\"`)\n- Asking pip to install _any_ version of `package_coffee` and `package_tea`\n  by removing the version specifiers altogether (e.g.\n  `pip install package_coffee package_tea`)\n\nIn the second case, pip will automatically find a version of both\n`package_coffee` and `package_tea` that depend on the same version of\n`package_water`, for example:\n\n- `package_coffee 0.44.1`, which depends on `package_water 2.6.1`\n- `package_tea 4.4.3`, which also depends on `package_water 2.6.1`\n\nIf you want to prioritize one package over another, you can add version\nspecifiers to _only_ the more important package:\n\n```{pip-cli}\n$ pip install package_coffee==0.44.1 package_tea\n```\n\nThis will result in:\n\n- `package_coffee 0.44.1`, which depends on `package_water 2.6.1`\n- `package_tea 4.4.3` which _also_ depends on `package_water 2.6.1`\n\nNow that you have resolved the issue, you can repin the compatible\npackage versions as required.\n\n#### Loosen the requirements of your dependencies\n\nAssuming that you cannot resolve the conflict by loosening the version\nof the package you require (as above), you can try to fix the issue on\nyour _dependency_ by:\n\n- Requesting that the package maintainers loosen _their_ dependencies\n- Forking the package and loosening the dependencies yourself\n\n```{warning}\nIf you choose to fork the package yourself, you are _opting out_ of\nany support provided by the package maintainers. Proceed at your own risk!\n```\n\n#### All requirements are appropriate, but a solution does not exist\n\nSometimes it's simply impossible to find a combination of package\nversions that do not conflict. Welcome to [dependency hell].\n\nIn this situation, you could consider:\n\n- Using an alternative package, if that is acceptable for your project.\n  See [Awesome Python] for similar packages.\n- Refactoring your project to reduce the number of dependencies (for\n  example, by breaking up a monolithic code base into smaller pieces).\n\n## Handling Resolution Too Deep Errors\n\nSometimes pip's dependency resolver may exceed its search depth and terminate\nwith a `ResolutionTooDeepError` exception. This typically occurs when the\ndependency graph is extremely complex or when there are too many package\nversions to evaluate.\n\nTo address this error, consider the following strategies:\n\n### Specify Reasonable Lower Bounds\n\nBy setting a higher lower bound for your dependencies, you narrow the search\nspace. This excludes older versions that might trigger excessive backtracking.\nFor example:\n\n```{pip-cli}\n$ pip install \"package_coffee>=0.44.0\" \"package_tea>=4.0.0\"\n```\n\n### Use the `--upgrade` Flag\n\nThe `--upgrade` flag directs pip to ignore already installed versions and\nsearch for the latest versions that meet your requirements. This can help\navoid unnecessary resolution paths:\n\n```{pip-cli}\n$ pip install --upgrade package_coffee package_tea\n```\n\n### Utilize Constraint Files\n\nIf you need to impose additional version restrictions on transitive\ndependencies (dependencies of dependencies), consider using a constraint\nfile. A constraint file specifies version limits for packages that are\nindirectly required. For example:\n\n```\n# constraints.txt\nindirect_dependency>=2.0.0\n```\n\nThen install your packages with:\n\n```{pip-cli}\n$ pip install --constraint constraints.txt package_coffee package_tea\n```\n\n### Use Upper Bounds Sparingly\n\nAlthough upper bounds are generally discouraged because they can complicate\ndependency management, they may be necessary when certain versions are known\nto cause conflicts. Use them cautiously—for example:\n\n```{pip-cli}\n$ pip install \"package_coffee>=0.44.0,<1.0.0\" \"package_tea>=4.0.0\"\n```\n\n### Report ResolutionTooDeep Errors\n\nIf you encounter a `ResolutionTooDeep` error consider reporting it, to help\nthe pip team have real world examples to test against, at the dedicated\n[pip issue](https://github.com/pypa/pip/issues/13281).\n\n## Getting help\n\nIf none of the suggestions above work for you, we recommend that you ask\nfor help on:\n\n- [Python user Discourse](https://discuss.python.org/c/users/7)\n- [Python user forums](https://www.python.org/community/forums/)\n- [Python developers Slack channel](https://pythondev.slack.com/)\n- [Python IRC](https://www.python.org/community/irc/)\n- [Stack Overflow](https://stackoverflow.com/questions/tagged/python)\n\nSee [\"How do I ask a good question?\"] for tips on asking for help.\n\nUnfortunately, **the pip team cannot provide support for individual\ndependency conflict errors**. Please _only_ open a ticket on\n[pip's issue tracker](https://github.com/pypa/pip/issues) if you believe\nthat your problem has exposed a bug in pip.\n\n[\"how do i ask a good question?\"]: https://stackoverflow.com/help/how-to-ask\n[awesome python]: https://python.libhunt.com/\n[dependency hell]: https://en.wikipedia.org/wiki/Dependency_hell\n"
  },
  {
    "path": "docs/html/topics/deps.dot",
    "content": "digraph G {\n  graph [fontname = \"Handlee\"];\n  node [fontname = \"Handlee\"];\n  edge [fontname = \"Handlee\"];\n\n  bgcolor=transparent;\n\n  A [color=blue fontcolor=blue];\n  A -> B [color=red];\n  A -> C [color=red];\n  node [color=lightgrey fontcolor=lightgrey];\n  edge [color=lightgrey];\n  node [color=lightgrey];\n  B -> B1;\n  B -> B2;\n  C -> C1;\n  C -> C2;\n\n}\n"
  },
  {
    "path": "docs/html/topics/https-certificates.md",
    "content": "(SSL Certificate Verification)=\n\n# HTTPS Certificates\n\n```{versionadded} 1.3\n\n```\n\nBy default, pip will perform SSL certificate verification for network\nconnections it makes over HTTPS. These serve to prevent man-in-the-middle\nattacks against package downloads.\n\n## Using a specific certificate store\n\nThe `--cert` option (and the corresponding `PIP_CERT` environment variable)\nallow users to specify a different certificate store/bundle for pip to use. It\nis also possible to use `REQUESTS_CA_BUNDLE` or `CURL_CA_BUNDLE` environment\nvariables.\n\nIf you need a specific certificate bundle, you can download the\n[Mozilla CA bundle provided by the curl project](https://curl.se/docs/caextract.html).\n\n## Using system certificate stores\n\n```{versionadded} 24.2\n\n```\n\n```{note}\nVersions of pip prior to v24.2 did not use system certificates by default.\nTo use system certificates with pip v22.2 or later, you must opt-in using the `--use-feature=truststore` CLI flag.\n```\n\nOn Python 3.10 or later, by default\nsystem certificates are used in addition to certifi to verify HTTPS connections.\nThis functionality is provided through the {pypi}`truststore` package.\n\nIf you encounter a TLS/SSL error when using the `truststore` feature you should\nopen an issue on the [truststore GitHub issue tracker] instead of pip's issue\ntracker. The maintainers of truststore will help diagnose and fix the issue.\n\nTo opt-out of using system certificates you can pass the `--use-deprecated=legacy-certs`\nflag to pip.\n\n```{warning}\nOn Python 3.9 or earlier, only certifi is used to verify HTTPS connections as\n`truststore` requires Python 3.10 or higher to function.\n\nThe system certificate store won't be used in this case, so some situations like proxies\nwith their own certificates may not work. Upgrading to at least Python 3.10 or later is\nthe recommended method to resolve this issue.\n```\n\n[truststore github issue tracker]:\n  https://github.com/sethmlarson/truststore/issues\n"
  },
  {
    "path": "docs/html/topics/index.md",
    "content": "# Topic Guides\n\nThese pages provide detailed information on individual topics.\n\n```{note}\nThis section of the documentation is currently being fleshed out. See\n{issue}`9475` for more details.\n```\n\n```{toctree}\n:maxdepth: 1\n\nauthentication\ncaching\nconfiguration\ndependency-resolution\nmore-dependency-resolution\nhttps-certificates\nlocal-project-installs\nrepeatable-installs\nsecure-installs\nvcs-support\npython-option\nworkflow\n```\n"
  },
  {
    "path": "docs/html/topics/local-project-installs.md",
    "content": "# Local project installs\n\nIt is extremely common to have a project, available in a folder/directory on your computer [^1] that you wish to install.\n\nWith pip, depending on your usecase, there are two ways to do this:\n\n- A regular install\n- An editable install\n\n## Regular installs\n\nYou can install local projects by specifying the project path to pip:\n\n```{pip-cli}\n$ pip install path/to/SomeProject\n```\n\nThis will install the project into the Python that pip is associated with, in a manner similar to how it would actually be installed.\n\nThis is what should be used in CI system and for deployments, since it most closely mirrors how a package would get installed if you build a distribution and installed from it (because that's _exactly_ what it does).\n\n(editable-installs)=\n\n## Editable installs\n\nYou can install local projects in \"editable\" mode:\n\n```{pip-cli}\n$ pip install -e path/to/SomeProject\n```\n\nEditable installs allow you to install your project without copying any files. Instead, the files in the development directory are added to Python's import path. This approach is well suited for development and is also known as a \"development installation\".\n\nWith an editable install, you only need to perform a re-installation if you change the project metadata (eg: version, what scripts need to be generated etc). You will still need to run build commands when you need to perform a compilation for non-Python code in the project (eg: C extensions).\n\n```{caution}\nIt is possible to see behaviour differences between regular installs vs editable installs. These differences depend on the build-backend, and you should check the build-backend documentation for the details. In case you distribute the project as a \"distribution package\", users will see the behaviour of regular installs -- thus, it is important to ensure that regular installs work correctly.\n```\n\n## Build artifacts\n\n```{versionchanged} 21.3\nThe project being installed is no longer copied to a temporary directory before invoking the build system, by default. A `--use-deprecated=out-of-tree-build` option is provided as a temporary fallback to aid user migrations.\n```\n\n```{versionchanged} 22.1\nThe `--use-deprecated=out-of-tree-build` option has been removed.\n```\n\nWhen provided with a project that's in a local directory, pip will invoke the build system \"in place\". This behaviour has several consequences:\n\n- Local project builds will now be significantly faster, for certain kinds of projects and on systems with slow I/O (eg: via network attached storage or overly aggressive antivirus software).\n- Certain build backends (eg: `setuptools`) will litter the project directory with secondary build artifacts (eg: `.egg-info` directories).\n- Certain build backends (eg: `setuptools`) may not be able to perform with parallel builds anymore, since they previously relied on the fact that pip invoked them in a separate directory for each build.\n\n[^1]: Specifically, the current machine's filesystem.\n"
  },
  {
    "path": "docs/html/topics/more-dependency-resolution.md",
    "content": "# More on Dependency Resolution\n\nThis article goes into more detail about pip's dependency resolution algorithm.\nIn certain situations, pip can take a long time to determine what to install,\nand this article is intended to help readers understand what is happening\n\"behind the scenes\" during that process.\n\n```{note}\nThis document is a work in progress. The details included are accurate (at the\ntime of writing), but there is additional information, in particular around\npip's interface with resolvelib, which has not yet been included.\n\nContributions to improve this document are welcome.\n```\n\n## The dependency resolution problem\n\nThe process of finding a set of packages to install, given a set of dependencies\nbetween them, is known to be an [NP-hard](https://en.wikipedia.org/wiki/NP-hardness)\nproblem. What this means in practice is roughly that the process scales\n*extremely* badly as the size of the problem increases. So when you have a lot\nof dependencies, working out what to install will, in the worst case, take a\nvery long time.\n\nThe practical implication of that is that there will always be some situations\nwhere pip cannot determine what to install in a reasonable length of time. We\nmake every effort to ensure that such situations happen rarely, but eliminating\nthem altogether isn't even theoretically possible. We'll discuss what options\nyou have if you hit a problem situation like this a little later.\n\n## Python specific issues\n\nMany algorithms for handling dependency resolution assume that you know the\nfull details of the problem at the start - that is, you know all of the\ndependencies up front. Unfortunately, that is not the case for Python packages.\nWith the current package index structure, dependency metadata is only available\nby downloading the package file, and extracting the data from it. And in the\ncase of source distributions, the situation is even worse as the project must\nbe built after being downloaded in order to determine the dependencies.\n\nWork is ongoing to try to make metadata more readily available at lower cost,\nbut at the time of writing, this has not been completed.\n\nAs downloading projects is a costly operation, pip cannot pre-compute the full\ndependency tree. This means that we are unable to use a number of techniques\nfor solving the dependency resolution problem. In practice, we have to use a\n*backtracking algorithm*.\n\n## Dependency metadata\n\nIt is worth discussing precisely what metadata is needed in order to drive the\npackage resolution process. There are essentially three key pieces of\ninformation:\n\n* The project name\n* The release version\n* The dependencies themselves\n\nThere are other pieces of data (e.g., extras, python version restrictions, wheel\ncompatibility tags) which are used as well, but they do not fundamentally\nalter the process, so we will ignore them here.\n\nThe most important information is the project name and version. Those two pieces\nof information identify an individual \"candidate\" for installation, and must\nuniquely identify such a candidate. Name and version must be available from the\nmoment the candidate object is created. This is not an issue for distribution\nfiles (sdists and wheels) as that data is available from the filename, but for\nunpackaged source trees, pip needs to call the build backend to ask for that\ndata. This is done before resolution proper starts.\n\nThe dependency data is *not* requested in advance (as noted above, doing so\nwould be prohibitively costly, and for a backtracking algorithm it isn't\nneeded). Instead, pip requests dependency data \"on demand\", as the algorithm\nstarts to check that particular candidate.\n\nOne particular implication of the lazy fetching of dependency data is that\noften, pip *does not know* things that might be obvious to a human looking at\nthe dependency tree as a whole. For example, if package A depends on version\n1.0 of package B, it's obvious to a human that there's no point in looking at\nother versions of package B. But if pip starts looking at B before it has\nconsidered A, it doesn't have access to A's dependency data, and so has no way\nof knowing that looking at other versions of B is wasted work. And worse still,\npip cannot even know that there's vital information in A's dependencies.\n\nThis latter point is a common theme with many cases where pip takes a long time\nto complete a resolution - there's information pip doesn't know at the point\nwhere it makes a \"wrong\" choice. Most of the heuristics added to the resolver\nto guide the algorithm are designed to guess correctly in the face of that\nlack of knowledge.\n\n## The resolver and the finder\n\nSo far, we have been talking about the \"resolver\" as a single entity. While that\nis mostly true, the process of getting package data from an index is handled\nby another component of pip, the \"finder\". The finder is responsible for\nfeeding candidates to the resolver, and has a key role to play in selecting\nsuitable candidates.\n\nNote that the resolver is *only* relevant for packages fetched from an index.\nCandidates coming from other sources (local source directories, {ref}`direct\nURL references <pypug:dependency-specifiers>`) do *not* go through the finder,\nand are merged with the candidates provided by the finder as part of the resolver's\n\"provider\" implementation.\n\nAs well as determining what versions exist in the index for a given project,\nthe finder selects the best distribution file to use for that candidate. This\nmay be a wheel or a source distribution, and precisely what is selected is\ncontrolled by wheel compatibility tags, pip's options (whether to prefer binary\nor source) and metadata supplied by the index. In particular, if a file is\nmarked as only being for specific Python versions, the file will be ignored by\nthe finder (and the resolver may never even see that version).\n\nThe finder also provides candidates for a project to the resolver in order of\npreference - the provider implements the rule that later versions are preferred\nover older versions, for example.\n\n## The resolver algorithm\n\nThe resolver itself is based on a separate package, [resolvelib](https://pypi.org/project/resolvelib/).\nThis implements an abstract backtracking resolution algorithm, in a way that is\nindependent of the specifics of Python packages - those specifics are abstracted\naway by pip before calling the resolver.\n\nPip's interface to resolvelib is in the form of a \"provider\", which is the\ninterface between pip's model of packages and the resolution algorithm. The\nprovider deals in \"candidates\" and \"requirements\" and implements the following\noperations:\n\n* `identify` - implements identity for candidates and requirements. It is this\n  operation that implements the rule that candidates are identified by their\n  name and version, for example.\n* `get_preference` - this provides information to the resolver to help it choose\n  which requirement to look at \"next\" when working through the resolution\n  process.\n* `narrow_requirement_selection` - this provides a way to limit the number of\n  identifiers passed to `get_preference`.\n* `find_matches` - given a set of constraints, determine what candidates exist\n  that satisfy them. This is essentially where the finder interacts with the\n  resolver.\n* `is_satisfied_by` - checks if a candidate satisfies a requirement. This is\n  basically the implementation of what a requirement means.\n* `get_dependencies` - get the dependency metadata for a candidate. This is\n  the implementation of the process of getting and reading package metadata.\n\nOf these methods, the only non-trivial ones are the `get_preference` and\n`narrow_requirement_selection` methods. These implement heuristics used\nto guide the resolution, telling it which requirement to try to satisfy next.\nIt's these methods that are responsible for trying to guess which route through\nthe dependency tree will be most productive. As noted above, it's doing this\nwith limited information. See the following diagram:\n\n![](deps.png)\n\nWhen the provider is asked to choose between the red requirements (A->B and\nA->C) it doesn't know anything about the dependencies of B or C (i.e., the\ngrey parts of the graph).\n\nPip's current implementation of the provider implements\n`narrow_requirement_selection` as follows:\n\n* If Requires-Python is present only consider that\n* If there are causes of resolution conflict (backtrack causes) then\n    only consider them until there are no longer any resolution conflicts\n\nPip's current implementation of the provider implements `get_preference`\nfor known requirements with the following preferences in the following order:\n\n* Any requirement that is \"direct\", e.g., points to an explicit URL.\n* Any requirement that is \"pinned\", i.e., contains the operator ``===``\n    or ``==`` without a wildcard.\n* Any requirement that imposes an upper version limit, i.e., contains the\n    operator ``<``, ``<=``, ``~=``, or ``==`` with a wildcard. Because\n    pip prioritizes the latest version, preferring explicit upper bounds\n    can rule out infeasible candidates sooner. This does not imply that\n    upper bounds are good practice; they can make dependency management\n    and resolution harder.\n* Order user-specified requirements as they are specified, placing\n    other requirements afterward.\n* Any \"non-free\" requirement, i.e., one that contains at least one\n    operator, such as ``>=`` or ``!=``.\n* Alphabetical order for consistency (aids debuggability).\n"
  },
  {
    "path": "docs/html/topics/python-option.md",
    "content": "# Managing a different Python interpreter\n\n```{versionadded} 22.3\n```\n\nOccasionally, you may want to use pip to manage a Python installation other than\nthe one pip is installed into. In this case, you can use the `--python` option\nto specify the interpreter you want to manage. This option can take one of two\nvalues:\n\n1. The path to a Python executable.\n2. The path to a virtual environment.\n\nIn both cases, pip will run exactly as if it had been invoked from that Python\nenvironment.\n\nOne example of where this might be useful is to manage a virtual environment\nthat does not have pip installed.\n\n```{pip-cli}\n$ python -m venv .venv --without-pip\n$ pip --python .venv install SomePackage\n[...]\nSuccessfully installed SomePackage\n```\n\nYou could also use `--python .venv/bin/python` (or on Windows,\n`--python .venv\\Scripts\\python.exe`) if you wanted to be explicit, but the\nvirtual environment name is shorter and works exactly the same.\n"
  },
  {
    "path": "docs/html/topics/repeatable-installs.md",
    "content": "(repeatability)=\n# Repeatable Installs\n\npip can be used to achieve various levels of repeatable environments. This page\nwalks through increasingly stricter definitions of what \"repeatable\" means.\n\n## Pinning the package versions\n\nPinning package versions of your dependencies in the requirements file\nprotects you from bugs or incompatibilities in newly released versions:\n\n```\nSomePackage == 1.2.3\nDependencyOfSomePackage == 4.5.6\n```\n\n```{note}\nPinning refers to using the `==` operator to require the package to be a\nspecific version.\n```\n\nA requirements file, containing pinned package versions can be generated using\n{ref}`pip freeze`. This would pin not only the top-level packages, but also all of\ntheir transitive dependencies. Performing the installation using\n{ref}`--no-deps <install_--no-deps>` would provide an extra dose of insurance\nagainst installing anything not explicitly listed.\n\nThis strategy is easy to implement and works across OSes and architectures.\nHowever, it trusts the locations you're fetching the packages from (like PyPI)\nand the certificate authority chain. It also relies on those locations not\nallowing packages to change without a version increase. (PyPI does protect\nagainst this.)\n\n## Hash-checking\n\nBeyond pinning version numbers, you can add hashes against which to verify\ndownloaded packages:\n\n```none\nFooProject == 1.2 --hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n```\n\nThis protects against a compromise of PyPI or the HTTPS certificate chain. It\nalso guards against a package changing without its version number changing (on\nindexes that allow this). This approach is a good fit for automated server\ndeployments.\n\nHash-checking mode is a labour-saving alternative to running a private index\nserver containing approved packages: it removes the need to upload packages,\nmaintain ACLs, and keep an audit trail (which a VCS gives you on the\nrequirements file for free). It can also substitute for a vendored library,\nproviding easier upgrades and less VCS noise. It does not, of course,\nprovide the availability benefits of a private index or a vendored library.\n\n[pip-tools] is a package that builds upon pip, and provides a good workflow for\nmanaging and generating requirements files.\n\n[pip-tools]: https://github.com/jazzband/pip-tools#readme\n\n## Using a wheelhouse (AKA Installation Bundles)\n\n{ref}`pip wheel` can be used to generate and package all of a project's\ndependencies, with all the compilation performed, into a single directory that\ncan be converted into a single archive. This archive then allows installation\nwhen index servers are unavailable and avoids time-consuming recompilation.\n\n````{admonition} Example\nCreating the bundle, on a modern Unix system:\n\n```\n$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)\n$ python -m pip wheel -r requirements.txt --wheel-dir=$tempdir\n$ cwd=`pwd`\n$ (cd \"$tempdir\"; tar -cjvf \"$cwd/bundled.tar.bz2\" *)\n```\n\nInstalling from the bundle, on a modern Unix system:\n\n```\n$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)\n$ (cd $tempdir; tar -xvf /path/to/bundled.tar.bz2)\n$ python -m pip install --force-reinstall --no-index --no-deps $tempdir/*\n```\n````\n\nNote that such a wheelhouse contains compiled packages, which are typically\nOS and architecture-specific, so these archives are not necessarily portable\nacross machines.\n\nHash-checking mode can also be used along with this method (since this uses a\nrequirements file as well), to ensure that future archives are built with\nidentical packages.\n"
  },
  {
    "path": "docs/html/topics/secure-installs.md",
    "content": "# Secure installs\n\nBy default, pip does not perform any checks to protect against remote tampering and involves running arbitrary code from distributions. It is, however, possible to use pip in a manner that changes these behaviours, to provide a more secure installation mechanism.\n\nThis can be achieved by doing the following:\n\n- Enable {ref}`Hash-checking mode`, by passing {any}`--require-hashes`\n- Disallow source distributions, by passing {any}`--only-binary :all: <--only-binary>`\n\n(Hash-checking mode)=\n\n## Hash-checking Mode\n\n```{versionadded} 8.0\n\n```\n\nThis mode uses local hashes, embedded in a requirements.txt file, to protect against remote tampering and network issues. These hashes are specified using a `--hash` [per requirement option](per-requirement-options).\n\nNote that hash-checking is an all-or-nothing proposition. Specifying `--hash` against _any_ requirement will activate this mode globally.\n\nTo add hashes for a package, add them to line as follows:\n\n```\nFooProject == 1.2 \\\n  --hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 \\\n  --hash=sha256:486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\n```\n\n### Additional restrictions\n\n- Hashes are required for _all_ requirements.\n\n  This is because a partially-hashed requirements file is of little use and thus likely an error: a malicious actor could slip bad code into the installation via one of the unhashed requirements.\n\n  Note that hashes embedded in URL-style requirements via the `#md5=...` syntax suffice to satisfy this rule (regardless of hash strength, for legacy reasons), though you should use a stronger hash like sha256 whenever possible.\n\n- Hashes are required for _all_ dependencies.\n\n  If there is a dependency that is not spelled out and hashed in the requirements file, it will result in an error.\n\n- Requirements must be pinned (either to a URL, filesystem path or using `==`).\n\n  This prevents a surprising hash mismatch upon the release of a new version that matches the requirement specifier.\n\n### Forcing Hash-checking mode\n\nIt is possible to force the hash checking mode to be enabled, by passing `--require-hashes` command-line option.\n\nThis can be useful in deploy scripts, to ensure that the author of the requirements file provided hashes. It is also a convenient way to bootstrap your list of hashes, since it shows the hashes of the packages it fetched. It fetches only the preferred archive for each package, so you may still need to add hashes for alternatives archives using {ref}`pip hash`: for instance if there is both a binary and a source distribution.\n\n### Hash algorithms\n\nThe recommended hash algorithm at the moment is sha256, but stronger ones are allowed, including all those supported by `hashlib`. However, weaker ones such as md5, sha1, and sha224 are excluded to avoid giving a false sense of security.\n\n### Multiple hashes per package\n\nIt is possible to use multiple hashes for each package. This is important when a package offers binary distributions for a variety of platforms or when it is important to allow both binary and source distributions.\n\n### Interaction with caching\n\n```{versionchanged} 23.1\nThe {ref}`locally-built wheel cache <wheel-caching>` is used in hash-checking mode too.\n```\n\nWhen installing from the cache of locally built wheels in hash-checking mode, pip verifies\nthe hashes against those of the original source distribution that was used to build the wheel.\nThese original hashes are obtained from a `origin.json` file stored in each cache entry.\n\n### Using hashes from PyPI (or other index servers)\n\nPyPI (and certain other index servers) provides a hash for the distribution, in the fragment portion of each download URL, like `#sha256=123...`, which pip checks as a protection against download corruption.\n\nOther hash algorithms that have guaranteed support from `hashlib` are also supported here: sha1, sha224, sha384, sha256, and sha512. Since this hash originates remotely, it is not a useful guard against tampering and thus does not satisfy the `--require-hashes` demand that every package have a local hash.\n\n## Repeatable installs\n\nHash-checking mode also works with {ref}`pip download` and {ref}`pip wheel`. See {doc}`../topics/repeatable-installs` for a comparison of hash-checking mode with other repeatability strategies.\n\n## Do not use setuptools directly\n\nBe careful not to nullify all your security work by installing your actual project by using setuptools' deprecated interfaces directly: for example, by calling `python setup.py install`, `python setup.py develop`, or `easy_install`.\n\nThese will happily go out and download, unchecked, anything you missed in your requirements file and it’s easy to miss things as your project evolves. To be safe, install your project using pip and {any}`--no-deps`.\n\nInstead of `python setup.py install`, use:\n\n```{pip-cli}\n$ pip install --no-deps .\n```\n\nInstead of `python setup.py develop`, use:\n\n```{pip-cli}\n$ pip install --no-deps -e .\n```\n"
  },
  {
    "path": "docs/html/topics/vcs-support.md",
    "content": "(vcs support)=\n# VCS Support\n\npip supports installing from various version control systems (VCS).\nThis support requires a working executable to be available (for the version\ncontrol system being used). It is used through URL prefixes:\n\n- Git -- `git+`\n- Mercurial -- `hg+`\n- Subversion -- `svn+`\n- Bazaar -- `bzr+`\n\nThe general form of a VCS requirement is `ProjectName @ VCS_URL`, e.g.\n\n```none\nMyProject @ git+https://git.example.com/MyProject\nMyProject[extra] @ git+https:/git.example.com/MyProject\n```\n\nThis is the {ref}`Direct URL <pypug:dependency-specifiers>` requirement syntax.\nIt is also permissible to remove `MyProject @` portion is removed and provide\na bare VCS URL.\n\n```none\ngit+https://git.example.com/MyProject\n```\n\nThis is a pip specific extension. This form can be used as long as pip does\nnot need to know the project name in advance. pip is generally able to infer\nthe project name except in the case of {ref}`editable-vcs-installs`. In\naddition, extras cannot be requested using a bare VCS URL.\n\n## Supported VCS\n\n### Git\n\nThe supported schemes are `git+file`, `git+https`, `git+ssh`, `git+http`,\n`git+git` and `git`. Here are some of the supported forms:\n\n```none\nMyProject @ git+ssh://git@git.example.com/MyProject\nMyProject @ git+file:///home/user/projects/MyProject\nMyProject @ git+https://git.example.com/MyProject\n```\n\n```{warning}\nThe use of `git`, `git+git`, and `git+http` schemes is discouraged.\nThe former two use [the Git Protocol], which lacks authentication, and HTTP is\ninsecure due to lack of TLS based encryption.\n```\n\n[the Git Protocol]: https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols\n\nIt is also possible to specify a \"git ref\" such as branch name, a commit hash or\na tag name:\n\n```none\nMyProject @ git+https://git.example.com/MyProject.git@master\nMyProject @ git+https://git.example.com/MyProject.git@v1.0\nMyProject @ git+https://git.example.com/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709\nMyProject @ git+https://git.example.com/MyProject.git@refs/pull/123/head\n```\n\nWhen passing a commit hash, specifying a full hash is preferable to a partial\nhash because a full hash allows pip to operate more efficiently (e.g. by\nmaking fewer network calls).\n\n### Mercurial\n\nThe supported schemes are `hg+file`, `hg+http`, `hg+https`, `hg+ssh`\nand `hg+static-http`. Here are some of the supported forms:\n\n```\nMyProject @ hg+http://hg.myproject.org/MyProject\nMyProject @ hg+https://hg.myproject.org/MyProject\nMyProject @ hg+ssh://hg.myproject.org/MyProject\nMyProject @ hg+file:///home/user/projects/MyProject\n```\n\nIt is also possible to specify a revision number, a revision hash, a tag name\nor a local branch name:\n\n```none\nMyProject @ hg+http://hg.example.com/MyProject@da39a3ee5e6b\nMyProject @ hg+http://hg.example.com/MyProject@2019\nMyProject @ hg+http://hg.example.com/MyProject@v1.0\nMyProject @ hg+http://hg.example.com/MyProject@special_feature\n```\n\n### Subversion\n\nThe supported schemes are `svn`, `svn+svn`, `svn+http`, `svn+https` and\n`svn+ssh`. Here are some of the supported forms:\n\n```none\nMyProject @ svn+https://svn.example.com/MyProject\nMyProject @ svn+ssh://svn.example.com/MyProject\nMyProject @ svn+ssh://user@svn.example.com/MyProject\n```\n\nYou can also give specific revisions to an SVN URL, like so:\n\n```none\n-e MyProject @ svn+http://svn.example.com/svn/MyProject/trunk@2019\n-e MyProject @ svn+http://svn.example.com/svn/MyProject/trunk@{20080101}\n```\n\nNote that you need to use [Editable VCS installs](#editable-vcs-installs) for\nusing specific revisions from Subversion.\n\n### Bazaar\n\nThe supported schemes are `bzr+http`, `bzr+https`, `bzr+ssh`, `bzr+sftp`,\n`bzr+ftp` and `bzr+lp`. Here are the supported forms:\n\n```none\nMyProject @ bzr+http://bzr.example.com/MyProject/trunk\nMyProject @ bzr+sftp://user@example.com/MyProject/trunk\nMyProject @ bzr+ssh://user@example.com/MyProject/trunk\nMyProject @ bzr+ftp://user@example.com/MyProject/trunk\nMyProject @ bzr+lp:MyProject\n```\n\nTags or revisions can be installed like so:\n\n```none\nMyProject @ bzr+https://bzr.example.com/MyProject/trunk@2019\nMyProject @ bzr+http://bzr.example.com/MyProject/trunk@v1.0\n```\n\n(editable-vcs-installs)=\n\n## Editable VCS installs\n\nVCS projects can be installed in {ref}`editable mode <editable-installs>` (using\nthe {ref}`--editable <install_--editable>` option) or not.\n\nIn editable mode, the project name must be provided upfront using the Direct URL\n(`MyProject @ URL`) form so pip can determine the VCS clone location.\n\n- The default clone location (for editable installs) is:\n\n  - `<venv path>/src/SomeProject` in virtual environments\n  - `<cwd>/src/SomeProject` for global Python installs\n\n  The {ref}`--src <install_--src>` option can be used to modify this location.\n\n- For non-editable installs, the project is built locally in a temp dir and then\n  installed normally.\n\nNote that if a satisfactory version of the package is already installed, the\nVCS source will not overwrite it without an `--upgrade` flag. Further, pip\nlooks at the package version, at the target revision to determine what action to\ntake on the VCS requirement (not the commit itself).\n\n## URL fragments\n\npip looks at the `subdirectory` fragments of VCS URLs for specifying the path to the\nPython package, when it is not in the root of the VCS directory.\n\n```{note}\npip also supports an `egg` fragment to specify the \"project name\". This is a legacy\nfeature and its use is discouraged in favour of the\n{ref}`Direct URL <pypug:dependency-specifiers>` form.\n\nThe `egg` fragment **MUST** be a bare {ref}`project name <pypug:name-normalization>`.\nAnything else is not guaranteed to work.\n```\n\n````{admonition} Example\nIf your repository layout is:\n\n```\npkg_dir\n├── setup.py  # setup.py for package \"pkg\"\n└── some_module.py\nother_dir\n└── some_file\nsome_other_file\n```\n\nThen, to install from this repository, the syntax would be:\n\n```{pip-cli}\n$ pip install \"pkg @ vcs+protocol://repo_url/#subdirectory=pkg_dir\"\n```\n\nor:\n\n```{pip-cli}\n$ pip install -e \"pkg @ vcs+protocol://repo_url/#subdirectory=pkg_dir\"\n```\n````\n"
  },
  {
    "path": "docs/html/topics/workflow.md",
    "content": "# Pip is not a workflow management tool\n\nThe core purpose of pip is to *manage the packages installed in your\nenvironment*. Whilst package management is an important part of most Python\ndevelopment workflows, it is only one part. Tasks like creating and managing\nenvironments, configuring and running development tasks, managing the Python\ninterpreter itself, and managing the overall \"project\", are not part of pip's\nscope. Managing a development workflow as a whole is a complex task and one\nwhere there are many views on the \"correct approach\".\n\nPip has a number of features which make it useful in development workflows - for\nexample, the ability to install the current project via `pip install .`,\neditable installs, and requirements files. However, there is no intention that\npip will manage the workflow as a whole.\n\nAs an example, pip provides the `pip wheel` command, which can be used to build\na wheel for your project. However, there is no corresponding command to build a\nsource distribution. This is because building a wheel is a fundamental step in\ninstalling a package (if that package is only available as source code), whereas\nbuilding a source distribution is never needed when installing. Users who need a\ntool to build their project should use a dedicated tool like `build`, which\nprovides commands to build wheels and source distributions.\n\n\n## The role of `ensurepip`\n\nPip is available in a standard Python installation, via the `ensurepip` stdlib\nmodule. This provides users with an \"out of the box\" installer, which can be\nused to gain access to all of the various tools and libraries available on PyPI.\nIn particular, this enables the installation of a number of workflow tools.\n\nThis \"bootstrapping\" mechanism was proposed (and accepted) in [PEP\n453](https://peps.python.org/pep-0453/).\n\n\n## Further information\n\nThe [Packaging User Guide](https://packaging.python.org) discusses Python\nproject development, and includes tool recommendations for people looking for\nfurther information on how to manage their development workflow.\n"
  },
  {
    "path": "docs/html/user_guide.rst",
    "content": "==========\nUser Guide\n==========\n\n.. Hello there!\n\n   If you're thinking of adding content to this page... please take a moment\n   to consider if this content can live on its own, within a topic guide or a\n   reference page.\n\n   There is active effort being put toward *reducing* the amount of content on\n   this specific page (https://github.com/pypa/pip/issues/9475) and moving it\n   into more focused single-page documents that cover that specific topic.\n\nRunning pip\n===========\n\npip is a command line program. When you install pip, a ``pip`` command is added\nto your system, which can be run from the command prompt as follows:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip <pip arguments>\n\n   ``python -m pip`` executes pip using the Python interpreter you\n   specified as python. So ``/usr/bin/python3.7 -m pip`` means\n   you are executing pip for your interpreter located at ``/usr/bin/python3.7``.\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip <pip arguments>\n\n   ``py -m pip`` executes pip using the latest Python interpreter you\n   have installed. For more details, read the `Python Windows launcher`_ docs.\n\n\nInstalling Packages\n===================\n\npip supports installing from `PyPI`_, version control, local projects, and\ndirectly from distribution files.\n\n\nThe most common scenario is to install from `PyPI`_ using :ref:`Requirement\nSpecifiers`\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install SomePackage            # latest version\n      python -m pip install SomePackage==1.0.4     # specific version\n      python -m pip install 'SomePackage>=1.0.4'     # minimum version\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install SomePackage            # latest version\n      py -m pip install SomePackage==1.0.4     # specific version\n      py -m pip install 'SomePackage>=1.0.4'   # minimum version\n\nFor more information and examples, see the :ref:`pip install` reference.\n\n.. _PyPI: https://pypi.org/\n\n.. _`0-basic-authentication-credentials`:\n.. rubric:: Basic Authentication Credentials\n\nThis is now covered in :doc:`topics/authentication`.\n\n.. _`0-netrc-support`:\n.. rubric:: netrc Support\n\nThis is now covered in :doc:`topics/authentication`.\n\n.. _`0-keyring-support`:\n.. rubric:: Keyring Support\n\nThis is now covered in :doc:`topics/authentication`.\n\nUsing a Proxy Server\n====================\n\nWhen installing packages from `PyPI`_, pip requires internet access, which\nin many corporate environments requires an outbound HTTP proxy server.\n\npip can be configured to connect through a proxy server in various ways:\n\n* using the ``--proxy`` command-line option to specify a proxy in the form\n  ``scheme://[user:passwd@]proxy.server:port``\n* using ``proxy`` in a :ref:`config-file`\n* by setting the standard environment-variables ``http_proxy``, ``https_proxy``\n  and ``no_proxy``.\n* using the environment variable ``PIP_USER_AGENT_USER_DATA`` to include\n  a JSON-encoded string in the user-agent variable used in pip's requests.\n\n\n.. _`Requirements Files`:\n\n\nRequirements Files\n==================\n\n\"Requirements files\" are files containing a list of items to be\ninstalled using :ref:`pip install` like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install -r requirements.txt\n\nDetails on the format of the files are here: :ref:`requirements-file-format`.\n\nLogically, a Requirements file is just a list of :ref:`pip install` arguments\nplaced in a file. Note that you should not rely on the items in the file being\ninstalled by pip in any particular order.\n\nRequirements files can also be served via a URL, e.g.\nhttp://example.com/requirements.txt besides as local files, so that they can\nbe stored and served in a centralized place.\n\nIn practice, there are 4 common uses of Requirements files:\n\n1. Requirements files are used to hold the result from :ref:`pip freeze` for the\n   purpose of achieving :doc:`topics/repeatable-installs`.  In\n   this case, your requirement file contains a pinned version of everything that\n   was installed when ``pip freeze`` was run.\n\n   .. tab:: Unix/macOS\n\n      .. code-block:: shell\n\n         python -m pip freeze > requirements.txt\n         python -m pip install -r requirements.txt\n\n   .. tab:: Windows\n\n      .. code-block:: shell\n\n         py -m pip freeze > requirements.txt\n         py -m pip install -r requirements.txt\n\n2. Requirements files are used to force pip to properly resolve dependencies.\n   pip 20.2 and earlier `doesn't have true dependency resolution\n   <https://github.com/pypa/pip/issues/988>`_, but instead simply uses the first\n   specification it finds for a project. E.g. if ``pkg1`` requires\n   ``pkg3>=1.0`` and ``pkg2`` requires ``pkg3>=1.0,<=2.0``, and if ``pkg1`` is\n   resolved first, pip will only use ``pkg3>=1.0``, and could easily end up\n   installing a version of ``pkg3`` that conflicts with the needs of ``pkg2``.\n   To solve this problem, you can place ``pkg3>=1.0,<=2.0`` (i.e. the correct\n   specification) into your requirements file directly along with the other top\n   level requirements. Like so::\n\n     pkg1\n     pkg2\n     pkg3>=1.0,<=2.0\n\n3. Requirements files are used to force pip to install an alternate version of a\n   sub-dependency.  For example, suppose ``ProjectA`` in your requirements file\n   requires ``ProjectB``, but the latest version (v1.3) has a bug, you can force\n   pip to accept earlier versions like so::\n\n     ProjectA\n     ProjectB<1.3\n\n4. Requirements files are used to override a dependency with a local patch that\n   lives in version control.  For example, suppose a dependency\n   ``SomeDependency`` from PyPI has a bug, and you can't wait for an upstream\n   fix.\n   You could clone/copy the src, make the fix, and place it in VCS with the tag\n   ``sometag``.  You'd reference it in your requirements file with a line like\n   so::\n\n     SomeDependency @ git+https://myvcs.com/some_dependency@sometag\n\n   If ``SomeDependency`` was previously a top-level requirement in your\n   requirements file, then **replace** that line with the new line. If\n   ``SomeDependency`` is a sub-dependency, then **add** the new line.\n\n\nIt's important to be clear that pip determines package dependencies using\nthe project metadata (typically in ``pyproject.toml`` or ``setup.py``),\nnot by discovering ``requirements.txt`` files embedded in projects.\n\nSee also:\n\n* :ref:`requirements-file-format`\n* :ref:`pip freeze`\n* `\"setup.py vs requirements.txt\" (an article by Donald Stufft)\n  <https://caremad.io/2013/07/setup-vs-requirement/>`_\n\n\n.. _`Constraints Files`:\n\n\nConstraints Files\n=================\n\nConstraints files are requirements files that only control which version of a\nrequirement is installed, not whether it is installed or not. Their syntax and\ncontents is a subset of :ref:`Requirements Files`, with several kinds of syntax\nnot allowed: constraints must have a name, they cannot be editable, and they\ncannot specify extras. In terms of semantics, there is one key difference:\nIncluding a package in a constraints file does not trigger installation of the\npackage.\n\nUse a constraints file like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install -c constraints.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install -c constraints.txt\n\nConstraints files are used for exactly the same reason as requirements files\nwhen you don't know exactly what things you want to install. For instance, say\nthat the \"helloworld\" package doesn't work in your environment, so you have a\nlocal patched version. Some things you install depend on \"helloworld\", and some\ndon't.\n\nOne way to ensure that the patched version is used consistently is to\nmanually audit the dependencies of everything you install, and if \"helloworld\"\nis present, write a requirements file to use when installing that thing.\n\nConstraints files offer a better way: write a single constraints file for your\norganisation and use that everywhere. If the thing being installed requires\n\"helloworld\" to be installed, your fixed version specified in your constraints\nfile will be used.\n\nConstraints file support was added in pip 7.1. In :ref:`Resolver\nchanges 2020` we did a fairly comprehensive overhaul, removing several\nundocumented and unsupported quirks from the previous implementation,\nand stripped constraints files down to being purely a way to specify\nglobal (version) limits for packages.\n\nSame as requirements files, constraints files can also be served via a URL,\ne.g. http://example.com/constraints.txt, so that your organization can store and\nserve them in a centralized place.\n\n\n.. _`Build Constraints`:\n\nBuild Constraints\n-----------------\n\n.. versionadded:: 25.3\n\nBuild constraints are a type of constraints file that applies only to isolated\nbuild environments used for building packages from source. Unlike regular\nconstraints, which affect the packages installed in your environment, build\nconstraints only influence the versions of packages available during the\nbuild process.\n\nThis is useful when you need to constrain build dependencies\n(such as ``setuptools``, ``cython``, etc.) without affecting the\nfinal installed environment.\n\nUse build constraints like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --build-constraint build-constraints.txt SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --build-constraint build-constraints.txt SomePackage\n\nExample build constraints file (``build-constraints.txt``):\n\n.. code-block:: text\n\n   # Constrain setuptools version during build\n   setuptools>=45,<80\n   # Pin Cython for packages that use it to build\n   cython==0.29.24\n\nControlling Pre-release Installation\n=====================================\n\n.. versionadded:: 26.0\n\nBy default, pip installs stable versions of packages, unless their specifier includes\na pre-release version (e.g., ``SomePackage>=1.0a1``) or if there are no stable versions\navailable that satisfy the requirement. The ``--all-releases`` and ``--only-final``\noptions provide per-package control over pre-release selection.\n\nUse ``--all-releases`` to allow pre-releases for specific packages:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --all-releases=DependencyPackage SomePackage\n      python -m pip install --all-releases=:all: SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --all-releases=DependencyPackage SomePackage\n      py -m pip install --all-releases=:all: SomePackage\n\nUse ``--only-final`` to explicitly disable pre-releases for specific packages:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --only-final=DependencyPackage SomePackage\n      python -m pip install --only-final=:all: SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --only-final=DependencyPackage SomePackage\n      py -m pip install --only-final=:all: SomePackage\n\nBoth options accept ``:all:`` to apply to all packages, ``:none:`` to clear\nthe setting, or comma-separated package names. Package-specific settings\noverride ``:all:``. These options can also be used in requirements files.\n\n.. note::\n\n   The ``--pre`` flag is equivalent to ``--all-releases :all:`` but cannot\n   be combined with ``--all-releases`` or ``--only-final``.\n\n\n.. _`Filtering by Upload Time`:\n\nFiltering by Upload Time\n=========================\n\n.. versionadded:: 26.0\n\nThe ``--uploaded-prior-to`` option allows you to filter packages by their upload time\nto an index, only considering packages that were uploaded before a specified datetime.\nThis can be useful for creating reproducible builds by ensuring you only install\npackages that were available at a known point in time.\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --uploaded-prior-to=2025-03-16T00:00:00Z SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --uploaded-prior-to=2025-03-16T00:00:00Z SomePackage\n\nThe option accepts ISO 8601 datetime strings in several formats:\n\n* ``2025-03-16`` - Date in local timezone\n* ``2025-03-16T12:30:00`` - Datetime in local timezone\n* ``2025-03-16T12:30:00Z`` - Datetime in UTC\n* ``2025-03-16T12:30:00+05:00`` - Datetime in UTC offset\n\nFor consistency across machines, use either UTC format (with 'Z' suffix) or UTC offset\nformat (with timezone offset like '+05:00'). Local timezone formats may produce different\nresults on different machines.\n\n.. note::\n\n    This option only applies to packages from remote indexes, not local files or VCS\n    requirements. Local package files are allowed regardless of the\n    ``--uploaded-prior-to`` setting, e.g. ``pip install /path/to/package.whl``,\n    packages from ``--find-links`` directories, or VCS requirements like\n    ``git+https://...``.\n\n    This option requires package indexes that provide upload-time metadata\n    (such as PyPI). If the index does not provide upload-time metadata for a\n    package file, pip will fail immediately with an error message indicating\n    that upload-time metadata is required when using ``--uploaded-prior-to``.\n\nYou can combine this option with other filtering mechanisms like constraints files:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install -c constraints.txt --uploaded-prior-to=2025-03-16 SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install -c constraints.txt --uploaded-prior-to=2025-03-16 SomePackage\n\n\n.. _`Dependency Groups`:\n\n\nDependency Groups\n=================\n\n.. versionadded:: 25.1\n\n\"Dependency Groups\" are lists of items to be installed stored in a\n``pyproject.toml`` file.\n\nA dependency group is logically just a list of requirements, similar to the\ncontents of :ref:`Requirements Files`. Unlike requirements files, dependency\ngroups cannot contain non-package arguments for :ref:`pip install`.\n\nGroups can be declared like so:\n\n.. code-block:: toml\n\n    # pyproject.toml\n    [dependency-groups]\n    groupA = [\n        \"pkg1\",\n        \"pkg2\",\n    ]\n\nand installed with :ref:`pip install` like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --group groupA\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --group groupA\n\nFull details on the contents of ``[dependency-groups]`` and more examples are\navailable in :ref:`the specification documentation <pypug:dependency-groups>`.\n\n.. note::\n\n    Dependency Groups are defined by a standard, and therefore do not support\n    ``pip``-specific syntax for requirements, only :ref:`standard dependency\n    specifiers <pypug:dependency-specifiers>`.\n\n``pip`` does not search projects or directories to discover ``pyproject.toml``\nfiles. The ``--group`` option is used to pass the path to the file,\nand if the path is omitted, as in the example above, it defaults to\n``pyproject.toml`` in the current directory. Using explicit paths,\n:ref:`pip install` can use a file from another directory. For example:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --group './project/subproject/pyproject.toml:groupA'\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --group './project/subproject/pyproject.toml:groupA'\n\n\nThis also makes it possible to install groups from multiple different projects\nat once. For example, with a directory structure like so::\n\n    + project/\n      + sub1/\n        - pyproject.toml\n      + sub2/\n        - pyproject.toml\n\nit is possible to install, from the ``project/`` directory, groups from the\nsubprojects thusly:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --group './sub1/pyproject.toml:groupA' --group './sub2/pyproject.toml:groupB'\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --group './sub1/pyproject.toml:groupA' --group './sub2/pyproject.toml:groupB'\n\n\n.. _`Installing from Wheels`:\n\n\nInstalling from Wheels\n======================\n\n\"Wheel\" is a built, archive format that can greatly speed installation compared\nto building and installing from source archives. For more information, see the\n:ref:`specification <pypug:binary-distribution-format>`.\n\npip prefers Wheels where they are available. To disable this, use the\n:ref:`--no-binary <install_--no-binary>` flag for :ref:`pip install`.\n\nIf no satisfactory wheels are found, pip will default to finding source\narchives.\n\n\nTo install directly from a wheel archive:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install SomePackage-1.0-py2.py3-none-any.whl\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install SomePackage-1.0-py2.py3-none-any.whl\n\nTo include optional dependencies provided in the ``provides_extras``\nmetadata in the wheel, you must add quotes around the install target\nname:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install './somepackage-1.0-py2.py3-none-any.whl[my-extras]'\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install './somepackage-1.0-py2.py3-none-any.whl[my-extras]'\n\n.. note::\n\n    In the future, the ``path[extras]`` syntax may become deprecated. It is\n    recommended to use :ref:`standard <pypug:dependency-specifiers>`\n    syntax wherever possible.\n\nFor the cases where wheels are not available, pip offers :ref:`pip wheel` as a\nconvenience, to build wheels for all your requirements and dependencies.\n\nTo build wheels for your requirements and all their dependencies to a local\ndirectory:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install wheel\n      python -m pip wheel --wheel-dir=/local/wheels -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install wheel\n      py -m pip wheel --wheel-dir=/local/wheels -r requirements.txt\n\nAnd *then* to install those requirements just using your local directory of\nwheels (and not from PyPI):\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --no-index --find-links=/local/wheels -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --no-index --find-links=/local/wheels -r requirements.txt\n\n\nUninstalling Packages\n=====================\n\npip is able to uninstall most packages like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip uninstall SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip uninstall SomePackage\n\n\npip also performs an automatic uninstall of an old version of a package\nbefore upgrading to a newer version.\n\nFor more information and examples, see the :ref:`pip uninstall` reference.\n\n\nListing Packages\n================\n\nTo list installed packages:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip list\n      docutils (0.9.1)\n      Jinja2 (2.6)\n      Pygments (1.5)\n      Sphinx (1.1.2)\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip list\n      docutils (0.9.1)\n      Jinja2 (2.6)\n      Pygments (1.5)\n      Sphinx (1.1.2)\n\n\nTo list outdated packages, and show the latest version available:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip list --outdated\n      docutils (Current: 0.9.1 Latest: 0.10)\n      Sphinx (Current: 1.1.2 Latest: 1.1.3)\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip list --outdated\n      docutils (Current: 0.9.1 Latest: 0.10)\n      Sphinx (Current: 1.1.2 Latest: 1.1.3)\n\nTo show details about an installed package:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip show sphinx\n      ---\n      Name: Sphinx\n      Version: 1.1.3\n      Location: /my/env/lib/pythonx.x/site-packages\n      Requires: Pygments, Jinja2, docutils\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip show sphinx\n      ---\n      Name: Sphinx\n      Version: 1.1.3\n      Location: /my/env/lib/pythonx.x/site-packages\n      Requires: Pygments, Jinja2, docutils\n\nFor more information and examples, see the :ref:`pip list` and :ref:`pip show`\nreference pages.\n\n\nSearching for Packages\n======================\n\npip can search `PyPI`_ for packages using the ``pip search``\ncommand:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip search \"query\"\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip search \"query\"\n\nThe query will be used to search the names and summaries of all\npackages.\n\nFor more information and examples, see the :ref:`pip search` reference.\n\n.. _`0-configuration`:\n.. rubric:: Configuration\n\nThis is now covered in :doc:`topics/configuration`.\n\n.. _`0-config-file`:\n.. rubric:: Config file\n\nThis is now covered in :doc:`topics/configuration`.\n\n.. _`0-environment-variables`:\n.. rubric:: Environment Variables\n\nThis is now covered in :doc:`topics/configuration`.\n\n.. _`0-config-precedence`:\n.. rubric:: Config Precedence\n\nThis is now covered in :doc:`topics/configuration`.\n\nCommand Completion\n==================\n\npip comes with support for command line completion in bash, zsh and fish.\n\nTo setup for bash::\n\n    python -m pip completion --bash >> ~/.profile\n\nTo setup for zsh::\n\n    python -m pip completion --zsh >> ~/.zprofile\n\nTo setup for fish::\n\n    python -m pip completion --fish > ~/.config/fish/completions/pip.fish\n\nTo setup for powershell::\n\n   python -m pip completion --powershell | Out-File -Encoding default -Append $PROFILE\n\nAlternatively, you can use the result of the ``completion`` command directly\nwith the eval function of your shell, e.g. by adding the following to your\nstartup file::\n\n    eval \"`pip completion --bash`\"\n\n\n\n.. _`Installing from local packages`:\n\n\nInstalling from local packages\n==============================\n\nIn some cases, you may want to install from local packages only, with no traffic\nto PyPI.\n\nFirst, download the archives that fulfill your requirements:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip download --destination-directory DIR -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip download --destination-directory DIR -r requirements.txt\n\nNote that ``pip download`` will look in your wheel cache first, before\ntrying to download from PyPI.  If you've never installed your requirements\nbefore, you won't have a wheel cache for those items.  In that case, if some of\nyour requirements don't come as wheels from PyPI, and you want wheels, then run\nthis instead:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip wheel --wheel-dir DIR -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip wheel --wheel-dir DIR -r requirements.txt\n\nThen, to install from local only, you'll be using :ref:`--find-links\n<install_--find-links>` and :ref:`--no-index <install_--no-index>` like so:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --no-index --find-links=DIR -r requirements.txt\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --no-index --find-links=DIR -r requirements.txt\n\n\n\"Only if needed\" Recursive Upgrade\n==================================\n\n``pip install --upgrade`` now has a ``--upgrade-strategy`` option which\ncontrols how pip handles upgrading of dependencies. There are 2 upgrade\nstrategies supported:\n\n- ``eager``: upgrades all dependencies regardless of whether they still satisfy\n  the new parent requirements\n- ``only-if-needed``: upgrades a dependency only if it does not satisfy the new\n  parent requirements\n\nThe default strategy is ``only-if-needed``. This was changed in pip 10.0 due to\nthe breaking nature of ``eager`` when upgrading conflicting dependencies.\n\nIt is important to note that ``--upgrade`` affects *direct requirements* (e.g.\nthose specified on the command-line or via a requirements file) while\n``--upgrade-strategy`` affects *indirect requirements* (dependencies of direct\nrequirements).\n\nAs an example, say ``SomePackage`` has a dependency, ``SomeDependency``, and\nboth of them are already installed but are not the latest available versions:\n\n- ``pip install SomePackage``: will not upgrade the existing ``SomePackage`` or\n  ``SomeDependency``.\n- ``pip install --upgrade SomePackage``: will upgrade ``SomePackage``, but not\n  ``SomeDependency`` (unless a minimum requirement is not met).\n- ``pip install --upgrade SomePackage --upgrade-strategy=eager``: upgrades both\n  ``SomePackage`` and ``SomeDependency``.\n\nAs an historic note, an earlier \"fix\" for getting the ``only-if-needed``\nbehaviour was:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      python -m pip install --upgrade --no-deps SomePackage\n      python -m pip install SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      py -m pip install --upgrade --no-deps SomePackage\n      py -m pip install SomePackage\n\n\nA proposal for an ``upgrade-all`` command is being considered as a safer\nalternative to the behaviour of eager upgrading.\n\n\nUser Installs\n=============\n\nWith Python 2.6 came the `\"user scheme\" for installation\n<https://docs.python.org/3/library/sysconfig.html#sysconfig-user-scheme>`_,\nwhich means that all Python distributions support an alternative install\nlocation that is specific to a user.  The default location for each OS is\nexplained in the python documentation for the `site.USER_BASE\n<https://docs.python.org/3/library/site.html#site.USER_BASE>`_ variable.\nThis mode of installation can be turned on by specifying the :ref:`--user\n<install_--user>` option to ``pip install``.\n\nMoreover, the \"user scheme\" can be customized by setting the\n``PYTHONUSERBASE`` environment variable, which updates the value of\n``site.USER_BASE``.\n\nTo install \"SomePackage\" into an environment with ``site.USER_BASE`` customized to\n'/myappenv', do the following:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: shell\n\n      export PYTHONUSERBASE=/myappenv\n      python -m pip install --user SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: shell\n\n      set PYTHONUSERBASE=c:/myappenv\n      py -m pip install --user SomePackage\n\n``pip install --user`` follows four rules:\n\n#. When globally installed packages are on the python path, and they *conflict*\n   with the installation requirements, they are ignored, and *not*\n   uninstalled.\n#. When globally installed packages are on the python path, and they *satisfy*\n   the installation requirements, pip does nothing, and reports that\n   requirement is satisfied (similar to how global packages can satisfy\n   requirements when installing packages in a ``--system-site-packages``\n   virtualenv).\n#. pip will not perform a ``--user`` install in a ``--no-site-packages``\n   virtualenv (i.e. the default kind of virtualenv), due to the user site not\n   being on the python path.  The installation would be pointless.\n#. In a ``--system-site-packages`` virtualenv, pip will not install a package\n   that conflicts with a package in the virtualenv site-packages.  The --user\n   installation would lack sys.path precedence and be pointless.\n\n\nTo make the rules clearer, here are some examples:\n\nFrom within a ``--no-site-packages`` virtualenv (i.e. the default kind):\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install --user SomePackage\n      Can not perform a '--user' install. User site-packages are not visible in this virtualenv.\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install --user SomePackage\n      Can not perform a '--user' install. User site-packages are not visible in this virtualenv.\n\n\nFrom within a ``--system-site-packages`` virtualenv where ``SomePackage==0.3``\nis already installed in the virtualenv:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install --user SomePackage==0.4\n      Will not install to the user site because it will lack sys.path precedence\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install --user SomePackage==0.4\n      Will not install to the user site because it will lack sys.path precedence\n\nFrom within a real python, where ``SomePackage`` is *not* installed globally:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install --user SomePackage\n      [...]\n      Successfully installed SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install --user SomePackage\n      [...]\n      Successfully installed SomePackage\n\nFrom within a real python, where ``SomePackage`` *is* installed globally, but\nis *not* the latest version:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install --user SomePackage\n      [...]\n      Requirement already satisfied (use --upgrade to upgrade)\n      $ python -m pip install --user --upgrade SomePackage\n      [...]\n      Successfully installed SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install --user SomePackage\n      [...]\n      Requirement already satisfied (use --upgrade to upgrade)\n      C:\\> py -m pip install --user --upgrade SomePackage\n      [...]\n      Successfully installed SomePackage\n\nFrom within a real python, where ``SomePackage`` *is* installed globally, and\nis the latest version:\n\n.. tab:: Unix/macOS\n\n   .. code-block:: console\n\n      $ python -m pip install --user SomePackage\n      [...]\n      Requirement already satisfied (use --upgrade to upgrade)\n      $ python -m pip install --user --upgrade SomePackage\n      [...]\n      Requirement already up-to-date: SomePackage\n      # force the install\n      $ python -m pip install --user --ignore-installed SomePackage\n      [...]\n      Successfully installed SomePackage\n\n.. tab:: Windows\n\n   .. code-block:: console\n\n      C:\\> py -m pip install --user SomePackage\n      [...]\n      Requirement already satisfied (use --upgrade to upgrade)\n      C:\\> py -m pip install --user --upgrade SomePackage\n      [...]\n      Requirement already up-to-date: SomePackage\n      # force the install\n      C:\\> py -m pip install --user --ignore-installed SomePackage\n      [...]\n      Successfully installed SomePackage\n\n.. _`0-repeatability`:\n.. _`0-ensuring-repeatability`:\n.. rubric:: Ensuring Repeatability\n\nThis is now covered in :doc:`../topics/repeatable-installs`.\n\n.. _`0-fixing-conflicting-dependencies`:\n.. rubric:: Fixing conflicting dependencies\n\nThis is now covered in :doc:`../topics/dependency-resolution`.\n\n.. _`Using pip from your program`:\n\nUsing pip from your program\n===========================\n\nAs noted previously, pip is a command line program. While it is implemented in\nPython, and so is available from your Python code via ``import pip``, you must\nnot use pip's internal APIs in this way. There are a number of reasons for this:\n\n#. The pip code assumes that it is in sole control of the global state of the\n   program.\n   pip manages things like the logging system configuration, or the values of\n   the standard IO streams, without considering the possibility that user code\n   might be affected.\n\n#. pip's code is *not* thread safe. If you were to run pip in a thread, there\n   is no guarantee that either your code or pip's would work as you expect.\n\n#. pip assumes that once it has finished its work, the process will terminate.\n   It doesn't need to handle the possibility that other code will continue to\n   run after that point, so (for example) calling pip twice in the same process\n   is likely to have issues.\n\nThis does not mean that the pip developers are opposed in principle to the idea\nthat pip could be used as a library - it's just that this isn't how it was\nwritten, and it would be a lot of work to redesign the internals for use as a\nlibrary, handling all of the above issues, and designing a usable, robust and\nstable API that we could guarantee would remain available across multiple\nreleases of pip. And we simply don't currently have the resources to even\nconsider such a task.\n\nWhat this means in practice is that everything inside of pip is considered an\nimplementation detail. Even the fact that the import name is ``pip`` is subject\nto change without notice. While we do try not to break things as much as\npossible, all the internal APIs can change at any time, for any reason. It also\nmeans that we generally *won't* fix issues that are a result of using pip in an\nunsupported way.\n\nIt should also be noted that installing packages into ``sys.path`` in a running\nPython process is something that should only be done with care. The import\nsystem caches certain data, and installing new packages while a program is\nrunning may not always behave as expected. In practice, there is rarely an\nissue, but it is something to be aware of.\n\nHaving said all of the above, it is worth covering the options available if you\ndecide that you do want to run pip from within your program. The most reliable\napproach, and the one that is fully supported, is to run pip in a subprocess.\nThis is easily done using the standard ``subprocess`` module::\n\n  subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])\n\nIf you want to process the output further, use one of the other APIs in the module.\nWe are using `freeze`_ here which outputs installed packages in requirements format.::\n\n  reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])\n\nTo programmatically monitor download progress use the ``--progress-bar=raw`` option.\nThis will print lines to stdout in the format ``Progress CURRENT of TOTAL``, where\n``CURRENT`` and ``TOTAL`` are integers and the unit is bytes.\nIf the real total is unknown then ``TOTAL`` is set to ``0``. Be aware that the\nspecific formatting of pip's outputs are *not* guaranteed to be the same in future versions.\n\nIf you don't want to use pip's command line functionality, but are rather\ntrying to implement code that works with Python packages, their metadata, or\nPyPI, then you should consider other, supported, packages that offer this type\nof ability. Some examples that you could consider include:\n\n* ``packaging`` - Utilities to work with standard package metadata (versions,\n  requirements, etc.)\n\n* ``importlib.metadata`` in the Python stdlib - Functions for querying what\n  packages the user has installed on their system.\n\n* ``distlib`` - Packaging and distribution utilities (including functions for\n  interacting with PyPI).\n\n.. _changes-to-the-pip-dependency-resolver-in-20-2-2020:\n\n.. _`Resolver changes 2020`:\n\nChanges to the pip dependency resolver in 20.3 (2020)\n=====================================================\n\npip 20.3 has a new dependency resolver, on by default for Python 3\nusers. (pip 20.1 and 20.2 included pre-release versions of the new\ndependency resolver, hidden behind optional user flags.) Read below\nfor a migration guide, how to invoke the legacy resolver, and the\ndeprecation timeline. We also made a `two-minute video explanation`_\nyou can watch.\n\nWe will continue to improve the pip dependency resolver in response to\ntesters' feedback. Please give us feedback through the `resolver\ntesting survey`_.\n\n.. _`Migration guide for 2020 resolver changes`:\n\nWatch out for\n-------------\n\nThe big change in this release is to the pip dependency resolver\nwithin pip.\n\nComputers need to know the right order to install pieces of software\n(\"to install ``x``, you need to install ``y`` first\"). So, when Python\nprogrammers share software as packages, they have to precisely describe\nthose installation prerequisites, and pip needs to navigate tricky\nsituations where it's getting conflicting instructions. This new\ndependency resolver will make pip better at handling that tricky\nlogic, and make pip easier for you to use and troubleshoot.\n\nThe most significant changes to the resolver are:\n\n* It will **reduce inconsistency**: it will *no longer install a\n  combination of packages that is mutually inconsistent*. In older\n  versions of pip, it is possible for pip to install a package which\n  does not satisfy the declared requirements of another installed\n  package. For example, in pip 20.0, ``pip install \"six<1.12\"\n  \"virtualenv==20.0.2\"`` does the wrong thing, “successfully” installing\n  ``six==1.11``, even though ``virtualenv==20.0.2`` requires\n  ``six>=1.12.0,<2`` (`defined here\n  <https://github.com/pypa/virtualenv/blob/20.0.2/setup.cfg#L42-L50>`__).\n  The new resolver, instead, outright rejects installing anything if it\n  gets that input.\n\n* It will be **stricter** - if you ask pip to install two packages with\n  incompatible requirements, it will refuse (rather than installing a\n  broken combination, like it did in previous versions).\n\nSo, if you have been using workarounds to force pip to deal with\nincompatible or inconsistent requirements combinations, now's a good\ntime to fix the underlying problem in the packages, because pip will\nbe stricter from here on out.\n\nThis also means that, when you run a ``pip install`` command, pip only\nconsiders the packages you are installing in that command, and **may\nbreak already-installed packages**. It will not guarantee that your\nenvironment will be consistent all the time. If you ``pip install x``\nand then ``pip install y``, it's possible that the version of ``y``\nyou get will be different than it would be if you had run ``pip\ninstall x y`` in a single command. We are considering changing this\nbehavior (per :issue:`7744`) and would like your thoughts on what\npip's behavior should be; please answer `our survey on upgrades that\ncreate conflicts`_.\n\nWe are also changing our support for :ref:`Constraints Files`,\neditable installs, and related functionality. We did a fairly\ncomprehensive overhaul and stripped constraints files down to being\npurely a way to specify global (version) limits for packages, and so\nsome combinations that used to be allowed will now cause\nerrors. Specifically:\n\n* Constraints don't override the existing requirements; they simply\n  constrain what versions are visible as input to the resolver (see\n  :issue:`9020`)\n* Providing an editable requirement (``-e .``) does not cause pip to\n  ignore version specifiers or constraints (see :issue:`8076`), and if\n  you have a conflict between a pinned requirement and a local\n  directory then pip will indicate that it cannot find a version\n  satisfying both (see :issue:`8307`)\n* Hash-checking mode requires that all requirements are specified as a\n  ``==`` match on a version and may not work well in combination with\n  constraints (see :issue:`9020` and :issue:`8792`)\n* If necessary to satisfy constraints, pip will happily reinstall\n  packages, upgrading or downgrading, without needing any additional\n  command-line options (see :issue:`8115` and :doc:`development/architecture/upgrade-options`)\n* Unnamed requirements are not allowed as constraints (see :issue:`6628` and :issue:`8210`)\n* Links are not allowed as constraints (see :issue:`8253`)\n* Constraints cannot have extras (see :issue:`6628`)\n\nPer our :ref:`Python 2 Support` policy, pip 20.3 users who are using\nPython 2 will use the legacy resolver by default. Python 2 users\nshould upgrade to Python 3 as soon as possible, since in pip 21.0 in\nJanuary 2021, pip dropped support for Python 2 altogether.\n\n\nHow to upgrade and migrate\n--------------------------\n\n1. **Install pip 20.3** with ``python -m pip install --upgrade pip``.\n\n2. **Validate your current environment** by running ``pip check``. This\n   will report if you have any inconsistencies in your set of installed\n   packages. Having a clean installation will make it much less likely\n   that you will hit issues with the new resolver (and may\n   address hidden problems in your current environment!). If you run\n   ``pip check`` and run into stuff you can’t figure out, please `ask\n   for help in our issue tracker or chat <https://pip.pypa.io/>`__.\n\n3. **Test the new version of pip**.\n\n   While we have tried to make sure that pip’s test suite covers as\n   many cases as we can, we are very aware that there are people using\n   pip with many different workflows and build processes, and we will\n   not be able to cover all of those without your help.\n\n   -  If you use pip to install your software, try out the new resolver\n      and let us know if it works for you with ``pip install``. Try:\n\n      - installing several packages simultaneously\n      - re-creating an environment using a ``requirements.txt`` file\n      - using ``pip install --force-reinstall`` to check whether\n        it does what you think it should\n      - using constraints files\n      - the \"Setups to test with special attention\" and \"Examples to try\" below\n\n   -  If you have a build pipeline that depends on pip installing your\n      dependencies for you, check that the new resolver does what you\n      need.\n\n   -  Run your project’s CI (test suite, build process, etc.) using the\n      new resolver, and let us know of any issues.\n   -  If you have encountered resolver issues with pip in the past,\n      check whether the new resolver fixes them, and read :ref:`Fixing\n      conflicting dependencies`. Also, let us know if the new resolver\n      has issues with any workarounds you put in to address the\n      current resolver’s limitations. We’ll need to ensure that people\n      can transition off such workarounds smoothly.\n   -  If you develop or support a tool that wraps pip or uses it to\n      deliver part of your functionality, please test your integration\n      with pip 20.3.\n\n4. **Troubleshoot and try these workarounds if necessary.**\n\n   -  If pip is taking longer to install packages, read :doc:`Dependency\n      resolution backtracking <topics/dependency-resolution>` for ways to\n      reduce the time pip spends backtracking due to dependency conflicts.\n   -  If you don't want pip to actually resolve dependencies, use the\n      ``--no-deps`` option. This is useful when you have a set of package\n      versions that work together in reality, even though their metadata says\n      that they conflict. For guidance on a long-term fix, read\n      :ref:`Fixing conflicting dependencies`.\n   -  If you run into resolution errors and need a workaround while you're\n      fixing their root causes, you can choose the old resolver behavior using\n      the flag ``--use-deprecated=legacy-resolver``. This will work until we\n      release pip 21.0 (see\n      :ref:`Deprecation timeline for 2020 resolver changes`).\n\n5. **Please report bugs** through the `resolver testing survey`_.\n\n\nSetups to test with special attention\n-------------------------------------\n\n*    Requirements files with 100+ packages\n\n*    Installation workflows that involve multiple requirements files\n\n*    Requirements files that include hashes (:ref:`hash-checking mode`)\n     or pinned dependencies (perhaps as output from ``pip-compile`` within\n     ``pip-tools``)\n\n*    Using :ref:`Constraints Files`\n\n*    Continuous integration/continuous deployment setups\n\n*    Installing from any kind of version control systems (i.e., Git, Subversion, Mercurial, or CVS), per :doc:`topics/vcs-support`\n\n*    Installing from source code held in local directories\n\nExamples to try\n^^^^^^^^^^^^^^^\n\nInstall:\n\n* `tensorflow`_\n* ``hacking``\n* ``pycodestyle``\n* ``pandas``\n* ``tablib``\n* ``elasticsearch`` and ``requests`` together\n* ``six`` and ``cherrypy`` together\n* ``pip install flake8-import-order==0.17.1 flake8==3.5.0 --use-feature=2020-resolver``\n* ``pip install tornado==5.0 sprockets.http==1.5.0 --use-feature=2020-resolver``\n\nTry:\n\n* ``pip install``\n* ``pip uninstall``\n* ``pip check``\n* ``pip cache``\n\n\nTell us about\n-------------\n\nSpecific things we'd love to get feedback on:\n\n*    Cases where the new resolver produces the wrong result,\n     obviously. We hope there won't be too many of these, but we'd like\n     to trap such bugs before we remove the legacy resolver.\n\n*    Cases where the resolver produced an error when you believe it\n     should have been able to work out what to do.\n\n*    Cases where the resolver gives an error because there's a problem\n     with your requirements, but you need better information to work out\n     what's wrong.\n\n*    If you have workarounds to address issues with the current resolver,\n     does the new resolver let you remove those workarounds? Tell us!\n\nPlease let us know through the `resolver testing survey`_.\n\n.. _`Deprecation timeline for 2020 resolver changes`:\n\nDeprecation timeline\n--------------------\n\nWe plan for the resolver changeover to proceed as follows, using\n:ref:`Feature Flags` and following our :ref:`Release Cadence`:\n\n*    pip 20.1: an alpha version of the new resolver was available,\n     opt-in, using the optional flag\n     ``--unstable-feature=resolver``. pip defaulted to legacy\n     behavior.\n\n*    pip 20.2: a beta of the new resolver was available, opt-in, using\n     the flag ``--use-feature=2020-resolver``. pip defaulted to legacy\n     behavior. Users of pip 20.2 who want pip to default to using the\n     new resolver can run ``pip config set global.use-feature\n     2020-resolver`` (for more on that and the alternate\n     ``PIP_USE_FEATURE`` environment variable option, see `issue\n     8661`_).\n\n*    pip 20.3: pip defaults to the new resolver in Python 3 environments,\n     but a user can opt-out and choose the old resolver behavior,\n     using the flag ``--use-deprecated=legacy-resolver``. In Python 2\n     environments, pip defaults to the old resolver, and the new one is\n     available using the flag ``--use-feature=2020-resolver``.\n\n*    pip 21.0: pip uses new resolver by default, and the old resolver is\n     no longer supported. It will be removed after a currently undecided\n     amount of time, as the removal is dependent on pip's volunteer\n     maintainers' availability. Python 2 support is removed per our\n     :ref:`Python 2 Support` policy.\n\nSince this work will not change user-visible behavior described in the\npip documentation, this change is not covered by the :ref:`Deprecation\nPolicy`.\n\n.. attention::\n\n    The legacy resolver is deprecated and unsupported. New features, such\n    as :doc:`reference/installation-report`, will not work with the\n    legacy resolver and this resolver will be removed in a future\n    release.\n\nContext and followup\n--------------------\n\nAs discussed in `our announcement on the PSF blog`_, the pip team are\nin the process of developing a new \"dependency resolver\" (the part of\npip that works out what to install based on your requirements).\n\nWe're tracking our rollout in :issue:`6536` and you can watch for\nannouncements on the `low-traffic packaging announcements list`_ and\n`the official Python blog`_.\n\n.. _freeze: https://pip.pypa.io/en/latest/reference/pip_freeze/\n.. _resolver testing survey: https://tools.simplysecure.org/survey/index.php?r=survey/index&sid=989272&lang=en\n.. _issue 8661: https://github.com/pypa/pip/issues/8661\n.. _our announcement on the PSF blog: http://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html\n.. _two-minute video explanation: https://www.youtube.com/watch?v=B4GQCBBsuNU\n.. _tensorflow: https://pypi.org/project/tensorflow/\n.. _low-traffic packaging announcements list: https://mail.python.org/mailman3/lists/pypi-announce.python.org/\n.. _our survey on upgrades that create conflicts: https://docs.google.com/forms/d/e/1FAIpQLSeBkbhuIlSofXqCyhi3kGkLmtrpPOEBwr6iJA6SzHdxWKfqdA/viewform\n.. _the official Python blog: https://blog.python.org/\n.. _Python Windows launcher: https://docs.python.org/3/using/windows.html#launcher\n\n.. _`0-using-system-trust-stores-for-verifying-https`:\n.. rubric:: Using system trust stores for verifying HTTPS\n\nThis is now covered in :doc:`topics/https-certificates`.\n"
  },
  {
    "path": "docs/html/ux-research-design/contribute.md",
    "content": "# How to Contribute\n\n## Participate in UX Research\n\nIt is important that we hear from pip users so that we can:\n\n- Understand how pip is currently used by the Python community\n- Understand how pip users _need_ pip to behave\n- Understand how pip users _would like_ pip to behave\n- Understand pip’s strengths and shortcomings\n- Make useful design recommendations for improving pip\n\nIf you are interested in participating in pip user research, please [join pip’s user panel](https://mail.python.org/mailman3/lists/pip-ux-studies.python.org/).\n\n## Test New Features\n\nYou can help the team by testing new features as they are released to the community.\n\n## Report and Work on UX Issues\n\nIf you believe that you have found a user experience bug in pip, or you have ideas for how pip could be made better for all users, please file an issue on the [pip issue tracker](https://github.com/pypa/pip/issues/new).\n\nYou can also help improve pip’s user experience by [working on UX issues](https://github.com/pypa/pip/issues?q=is%3Aissue+label%3AUX+is%3Aopen). Issues that are ideal for new contributors are marked with “[good first issue](https://github.com/pypa/pip/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)”. Explore the\n[UX Guidance](guidance.md) if you have questions.\n"
  },
  {
    "path": "docs/html/ux-research-design/guidance.md",
    "content": "# UX Guidance\n\nThis section of the documentation is intended for contributors who wish to work on improving pip's user experience, including pip's documentation.\n\n## What is User Centered Design?\n\nUser-centered design (UCD) or human-centered design (HCD) is an iterative process in which design decisions are informed by an understanding of users and their needs. There are many terms used to describe this type of work; in this document we will use \"user experience (UX) research and design\".\n\nFor the pip project, UX research and design can be used to:\n\n- Develop a deeper understanding of pip's users, the context in which they use pip and the challenges that they face\n- Inform the design of new or existing pip features, so that pip us more usable and accessible. This may include improving pip's output (including error messages), controls (e.g. commands and flags) and documentation\n- Help pip's development team prioritize feature requests based on user needs\n\nAt a high level, the UX research and design process is comprised of:\n\n1. **[Research](#conducting-research-for-pip)**, where a variety of techniques are used (e.g.[surveys](#surveys) and [interviews](#interviews)) to learn about users and what they want from the tools they use\n2. **[Design](#user-interface-design)**, where solutions are proposed to response to the research conducted. UX research and design is conducted iteratively, with design proposals or prototypes tested with users to validate that they are effective in meeting users' needs. Often, it is necessary to complete several cycles of research, design and validation to find a solution that works:\n\n![Graphic showing an iterative process of Research, Make (Design), Validate, around user goals and needs.](https://user-images.githubusercontent.com/3323703/124515613-c5bae880-ddd7-11eb-99d6-35c0a7522c7a.png)\n\nFor more information on how this process has been applied to the pip project, see [research results](research-results/index).\n\nSee also:\n\n- [Introduction to user centered design from the interaction design foundation](https://www.interaction-design.org/literature/topics/user-centered-design)\n- [User-Centered Design Basics from usability.gov](https://www.usability.gov/what-and-why/user-centered-design.html)\n- [User-centered design articles and videos from Nielson Norman Group](https://www.nngroup.com/topic/user-centered-design/)\n\n## Conducting Research for pip\n\nUser research can be used to answer a few different types of questions:\n\n- _Understanding the context generally_ — e.g. how is pip used by people? What different environments and contexts is pip used in?\n- _Understanding the users more broadly_ — e.g. who uses pip? How much experience do they have typically? How do they learn how to use pip? Are there any common characteristics between pip users? How diverse are the needs of pip's users?\n- _Evaluating a specific need or challenge_ — e.g. how are pip users encountering a given issue? When does it come up? Do pip users regularly encounter this issue? How would a new feature address this issue?\n\nDuring the research process, it is important to engage users for input, and incorporate their feedback into decision making.\n\nInput and feedback from users is as valuable to an open source project as code contributions; end users may not be ready yet to submit a pull request or make fixes into the code directly, but their feedback can help to shape pip's priorities and direction.\n\nThere are many ways to engage users in open source projects, and sometimes input from community members can feel overwhelming! Providing a structure, such as surveys and interviews, can make it easier to collect and understand feedback. Some examples of how to engage users are:\n\n- _Surveys_ — good for targeted feedback about specific issues and broad community context and understanding\n- _Interviews_ — good for in-depth conversations to understand or explore a topic\n- _Testing_ — good to evaluate an issue or validate a design idea\n- _Open issue queues_ (e.g. GitHub issues) & support ticket systems — great data source to understand common challenges\n- _Forums or discussion tools_ — great data source to understand common challenges or engage broader community in open discussion\n- _Conferences and events_ — great opportunity to go lightweight interviews or testing of specific features\n\nWhen running [UX research on pip in 2020](research-results/index), we found that surveys and interviews were particularly useful tools to engage with pip's users. Some general guidelines, as well as pip-specific recommendations are below.\n\n### Surveys\n\nSurveys are great for collecting broad, large scale input, e.g. learning more about pip's user community as a whole, or for getting targeted feedback about a specific issue.\n\nSurveys can also be leveraged to get in-situ feedback with early releases of new tools, e.g. prompting users on the command line if they are using a beta version of a feature or asking people for feedback on a documentation page.\n\nAs an example, in 2020, the pip UX team published several surveys to learn about pip and pip's users. This included:\n\n- Understanding 'who uses pip'\n- Collecting feedback about pip's documentation\n- Collecting feedback about pip's beta release of the 2020 dependency resolver\n- Asking users how specific parts of pip's 2020 dependency resolver should behave\n\nA full list of the surveys published in 2020 and their results [can be found here](research-results/index).\n\n#### Designing Surveys\n\nWhen designing surveys, it is important to first establish what you want to learn. It can be useful to write this down as research-results/index questions. Example pip research-results/index questions [can be found here](https://github.com/pypa/pip/issues/8518).\n\nIf you find that your topic is large, or you have many research-results/index questions, consider publishing several separate surveys, as long surveys risk a low response / high dropoff rate.\n\nBelow is a brief guide to building a survey for pip:\n\n<ol>\n  <li>\n    <strong>Introduce your survey</strong><br>\n    Explain the motivation for the survey, or (for surveys about pip's behaviour) set the scene with a scenario.\n  </li>\n  <li>\n    <strong>Design your questions</strong><br>\n    <ul>\n      <li>\n        Limit the number of questions you ask to avoid a low response rate. A good rule of thumb is: 3-4 questions about the specific topic, 2-3 questions about users level of experience / what they use Python or pip for.<br>\n        When asking about years of experience use the following groupings as options:\n        <ul>\n          <li>< 1 Year</li>\n          <li>1-3 Years</li>\n          <li>4-6 Years</li>\n          <li>7-10 Years</li>\n          <li>11-15 Years</li>\n          <li>16+ Years</li>\n        </ul>\n      </li>\n      <li>\n        Use <a href=\"https://en.wikipedia.org/wiki/Closed-ended_question\">closed questions</a> with a fixed number of possible responses (e.g. yes/no, multiple choice, checkboxes, or <a href=\"https://www.nngroup.com/articles/rating-scales\">likert scale</a>) for measuring behaviour, opinion or preferences\n      </li>\n      <li>\n        Use <a href=\"https://en.wikipedia.org/wiki/Open-ended_question\">open questions</a> to learn about reasoning. If you are using a lot of closed questions in your survey, it is useful to include some open questions to \"fish\" for less expected answers - e.g. asking a user \"why?\" they chose a particular option\n      </li>\n    </ul>\n  </li>\n  <li>\n    <strong>Pilot your survey and modify it based on feedback</strong><br>\n    This could be as simple as sharing it with 1-2 people to see if it makes sense.\n  </li>\n  <li>\n    <strong>Determine where to do outreach</strong><br>\n    Establish who you want to hear from and where you should post the survey. Are there community members or groups that can help you reach more people?<br>\n    <ul>\n      <li>Does the survey need to be translated into other languages to reach a broader set of the community?</li>\n      <li>Are you able to compensate people for their time?</li>\n      <li>Do participants want to be acknowledged as contributors?</li>\n    </ul>\n  </li>\n  <li>\n    <strong>Launch and promote your survey</strong><br>\n    See <a href=\"#survey-and-interview-outreach\">survey and interview outreach</a> for recommendations on how to do outreach for pip based on the UX research-results/index conducted in 2020.\n  </li>\n</ol>\n\n#### Survey Case Study\n\nThe process described above was followed in 2020, when we wanted to establish whether pip [should install packages with conflicting dependencies](https://github.com/pypa/pip/issues/8452).\n\nFirst, we introduced the purpose of the survey, with a scenario:\n\n![survey introduction with scenario with packages that conflict](https://user-images.githubusercontent.com/3323703/124516502-b046be00-ddd9-11eb-830c-62b8a6fb6182.png)\n\nNext, we asked a closed question to establish what the user prefers:\n\n![survey question asking whether pip should allow users to install packages when there are conflicting dependencies](https://user-images.githubusercontent.com/3323703/124516576-e5eba700-ddd9-11eb-8baf-e07773e75742.png)\n\nFollowing this, we qualified the response with an open question:\n\n![survey question asking respondents why pip should allow users to install packages with conflicting dependencies](https://user-images.githubusercontent.com/3323703/124516646-129fbe80-ddda-11eb-9c8a-da127f19fccd.png)\n\nThis was followed by further questions about workarounds, syntax and behaviour preferences.\n\nFinally, we asked survey participants about themselves, including how much Python experience they have, and what they use Python for. This was to find out if different types of Python users answered the questions differently.\n\nThis survey was shared with the pip team and improved several times, before it was published and promoted using a variety of [outreach channels](#survey-and-interview-outreach).\n\nIn total, we received 415 responses, with [clear results](research-results/override-conflicting-dependencies) that helped us to make strong recommendations on how to move forward with this feature.\n\n#### Analysing Survey Results\n\nSurveys are particularly useful for being able to quickly understand trends from a larger population of responses. If your questions are designed well, then you should be able to easily aggregate the data and make statements such as: `X% of respondents said that Option B was the best option.`\n\n#### Contextualizing the Responses\n\nIt's important to remember that the responses to your survey will be biased by the way that you did outreach for your survey, so unless you can be sure that the people who responded to your survey are representative of all of your users, then you need to be sure to contextualize the results to the participants. Within your survey responses it can be helpful to see if there is variation in the responses by different aspects of your users or your user community, e.g.\n\n- By experience level — Are responses consistent across experience level or do they vary? E.g. Do newer or more junior experience users have different responses, needs or challenges?\n- By background/context — Are responses consistent across background or context? E.g. Do users in a corporate context have similar responses to hobbyist/independent users? Do data analysts have similar responses to software engineers?\n\n#### How many responses is enough?\n\nIt depends! This is a hard question to answer in research like this — Traditional statistics would suggest that \"enough\" depends on the total population you need the survey to represent. In UX research, the answer tends to be more around when you see variation in responses level out, and so it's more about signals and trends in the data.\n\nIf you are finding that there aren't patterns in the data, it might mean that your questions weren't clear or provided too many options, or it might mean that you need to reach out to more people.\n\nSee also:\n\n- [28 Tips for Creating Great Qualitative Surveys from Nielson Norman Group](https://www.nngroup.com/articles/qualitative-surveys/)\n- [Open vs. Closed Questions in User Research from Nielsen Norman Group](https://www.nngroup.com/videos/open-vs-closed-questions/)\n- [Survey questions 101: over 70 survey question examples + types of surveys and FAQs - from HotJar](https://www.hotjar.com/blog/survey-questions/)\n\n### Interviews\n\nInterviews are a great way to have more in-depth conversations with users to better understand or explore a topic. Unlike surveys, they are not a great way to understand overall patterns, as it is hard to engage with a large number of people due to the time involved. It can be particularly useful to plan around conferences and events as a way to connect with many users in a more informal setting.\n\n#### Designing Interviews\n\nAs with surveys, it's important to establish what you want to learn before you begin.\n\nOften, interviews are conducted with a script; this helps the interview run smoothly by providing some structure. However, it is also ok to go \"off script\" if the conversation is moving in an interesting or insightful direction.\n\nBelow is a brief guide to running an interview for pip:\n\n<ol>\n  <li>\n    <strong>Write your script</strong><br>\n    This should include an introduction that sets the scene for the participant, explaining what the interview is about, how you (or observers) will take notes, how long it will take, how their feedback will be used (and shared) and any other pointers you want to share.<br>\n    Next, design your questions. Limit the number of questions, so that you have enough time to cover key points and the interview does not run for too long. Like in surveys, a good rule of thumb is 2-3 questions about users' level of experience, and what they use Python/pip for, plus 3-4 questions about the specific topic.<br>\n    There are <a href=\"https://simplysecure.org/resources/qualitative_interviewing.pdf\">four different types of interview questions</a>:\n    <ol>\n      <li>\n        <em>Descriptive</em> — This type of question gives you concrete, specific stories and details. It also helps your interviewee \"arrive\" at the interview, resurfacing their relevant experiences and memories. E.g.<br>\n        <ul>\n          <li>Tell me about a time…</li>\n          <li>Tell me about the first time…</li>\n          <li>Tell me about the last time…</li>\n          <li>Tell me about the worst/best time…</li>\n          <li>Walk me through how you…</li>\n        </ul>\n      </li>\n      <li>\n        <em>Reflective</em> — These questions allow the interviewee to revisit and think more deeply about their experiences. Helping the interviewee reflect is at the heart of your interview. Don't rush – give them lots of space to put their thoughts together.<br>\n        <ul>\n          <li>What do you think about…</li>\n          <li>How do you feel about…</li>\n          <li>Why do you do…</li>\n          <li>Why do you think…</li>\n          <li>What effects did it have when…</li>\n          <li>How has ... changed over time?</li>\n        </ul>\n      </li>\n      <li>\n        <em>Clarifying</em> — This type of question gives interviewees the opportunity to expand on key points. Skillful clarifying questions also let you subtly direct the interviewee's storytelling towards the areas you find most intriguing and relevant.<br>\n        <ul>\n          <li>What do you mean when you say…</li>\n          <li>So, in other words…</li>\n          <li>It sounds like you're saying [...]. Is that right?</li>\n          <li>Can you tell me more about that?</li>\n        </ul>\n      </li>\n      <li>\n        <em>Exploratory</em> — These questions are an invitation to the interview-ee to think creatively about their situation, and are best left for the end of the interview. Careful, though – suggestions from a single person are rarely the answer to your design problem, and you need to be clear to them that you're just collecting ideas at this point.<br/>\n        <ul>\n          <li>How would you change…</li>\n          <li>What would happen if…</li>\n          <li>If you had a magic wand...</li>\n        </ul>\n      </li>\n    </ol>\n  </li>\n  <li>\n    <strong>Pilot interview with 1-2 people & modify based on their feedback</strong>\n  </li>\n  <li>\n    <strong>Determine how to do outreach for interviews</strong><br/>\n    <ul>\n      <li>Who do you want to be sure to hear from? Where do you need to post to contact people for interviews? Are there community members or groups that can help you reach specific people?</li>\n      <li>Do the interviews need to be translated into other languages to reach a broader set of the community or a specific community?</li>\n      <li>How will people sign up for your interview?</li>\n      <li>Are you able to compensate people for their time?</li>\n      <li>Do participants want to be acknowledged as contributors?</li>\n    </ul>\n  </li>\n  <li>\n    <strong>Start outreach!</strong><br/>\n    See <a href=\"#survey-and-interview-outreach\">survey and interview outreach</a> for recommendations on how to do outreach for pip based on the UX research conducted in 2020.\n  </li>\n</ol>\n\nHere is an example user interview script used for speaking to users about pip's documentation:\n\n> **Introduction**\n>\n> - Firstly thank you for giving me your time and for your continued involvement.\n> - The purpose of this interview is to better understand how pip's documentation is perceived and used by Python community members\n> - The interview will take approximately 30 minutes. If you don't understand any of the questions please ask me to repeat or rephrase. If you don't have a good answer, feel free to tell me to skip.\n> - I will be taking notes. These will be shared on GitHub or the pip docs, but we will remove any identifying data to > protect your anonymity\n> - Please be honest - your feedback can help us make pip better. I won't be offended by anything you have to say :)\n> - (optional) Do you mind if I record this session?\n>\n> **Opening questions**\n>\n> - Can you tell me a bit about how you use Python?\n> - How long have you been using pip?\n>\n> **Solving problems**\n>\n> - Can you tell me about a time you had a problem when using pip?\n>   - What happened?\n>   - What did you do?\n>   - Where did you go?\n>   - How did you resolve your problem?\n> - Please go to[ https://pip.pypa.io/en/stable/](https://pip.pypa.io/en/stable/)\n>   - Have you ever used this documentation?\n>   - On a scale of 1-10 how useful was it?\n>   - Why?\n> - Are there any projects that you use that you'd like us to look at when thinking about improving pip's docs?\n>   - What makes that documentation good/useful?\n>\n> **Conclusion**\n>\n> - What one thing could the pip team do to help users troubleshoot pip problems?\n> - Do you have any questions?\n\n#### How many interviews is enough?\n\nThis depends on the complexity of the issue you are discussing, and whether or not you feel that you have gained enough insight from the interviews you have conducted. It also depends on whether you feel you have heard from a wide enough range of people. For example, you may wish to stop interviewing only after you have heard from both expert _and_ novice pip users.\n\nOften, conducting just a few interviews will uncover so many problems that there is enough material to make recommendations to the team.\n\n#### Analyzing Interview Data\n\nFormal interview analysis typically uses a process called \"coding\" where multiple researchers review interview transcripts and label different statements or comments based on a code system or typology that has been developed to align with the research. This is a great practice and a great way to make sure that the researchers' bias is addressed as part of the process, but most teams do not have the staffing or resources to do this practice.\n\nInstead many smaller teams use lightweight processes of capturing interview statements into **themes**, e.g. specific topics or issue areas around needs or challenges. Interviews are also a great source for **quotes**, which can be helpful for providing an example of why something is important or when/how something comes up for users.\n\nInterview analysis is frequently done using sticky notes, where you can write a quote, issue or finding on a sticky note and then move the sticky notes around into clusters that can be labeled or categorized into the themes. Remotely this can be facilitated by any number of tools, e.g. digital sticky board tools like [Miro](https://miro.com/) or [Mural](https://www.mural.co/), or even kanban board tools like [Trello](https://trello.com/), [Wekan](https://wekan.github.io/) or [Cryptpad](https://cryptpad.fr/), or this can be done just with text documents or spreadsheets, using lists and categories. It can be helpful to use a [worksheet for debriefing](https://simplysecure.org/resources/interview_synthesis.pdf) at the end of each interview to capture insights and themes quickly before you forget topics from the specific interview.\n\nSee also:\n\n- [User Interviews: How, When, and Why to Conduct Them from Nielson Norman Group](https://www.nngroup.com/articles/user-interviews/)\n- [Interviewing Users from Nielson Norman Group](https://www.nngroup.com/articles/interviewing-users/)\n\n### Survey and Interview Outreach\n\nThe following is a list of outreach platforms that the pip team used when conducting research in 2020. Some were more successful than others:\n\n#### Recommended: UX Research Panel\n\nAs part of the [2020 UX Work](research-results/index), we published a form that asked people to join a research panel and be regularly contacted about surveys and interview opportunities. This is now a [mailing list that users can sign up for](https://mail.python.org/mailman3/lists/pip-ux-studies.python.org/), and will be used in an ongoing way in addition to broad public outreach.\n\n#### Recommended: Twitter\n\nWe found Twitter to be a very effective platform for engaging with the Python community and drive participation in UX research. We recommend:\n\n1. Asking [ThePSF](https://twitter.com/ThePSF), [PyPA](https://twitter.com/ThePyPA) and [PyPI](https://twitter.com/pypi) to retweet calls for survey and interview participation\n2. Asking specific individuals (who have reach within specific communities, or general followings within the Python community) to retweet.\n3. Explicitly asking for retweets within tweets\n4. Responding to users within Twitter\n\n#### Recommended: Specific Interest Groups\n\nWe engaged with the [PyLadies](https://pyladies.com/) community via their [Slack channel](https://slackin.pyladies.com/) to drive more participation from women using pip, as we found this demographic more difficult to reach via other channels\n\n#### Recommended: Conference Communities\n\nDue to the 2020 Global Pandemic we were unable to engage with users via PyCon (or other regional conferences) as we would have liked. However, we would still recommend this channel as a fast and insightful way to engage with large groups of interested people.\n\n#### Worth Exploring: Adding a prompt/path into pip's 'help' command\n\nWe didn't have a chance to explore this opportunity, but the idea came up during workshops in December 2020 with Pypa Maintainers, and could be a great way to engage users and help point them towards opportunities to contribute.\n\n#### Not recommended: Forums (Discourse, etc)\n\nWe used [discuss.python.org](https://discuss.python.org/) several times, posting to the [packaging forum](https://discuss.python.org/c/packaging/14) to ask packaging maintainers about their views on pip's functionality. Unfortunately, this was not as fruitful as we hoped, with very few responses. We found that engaging with packaging maintainers via Twitter was more effective.\n\nPosting surveys on Reddit was also not as useful as we had expected. If the user posting the survey or call for research participation does not have significant credit on Reddit, then the posting process itself can be challenging. Overall we did not see as much engagement in surveys or interviews come from Reddit relative to other outreach means.\n\n## User Interface Design\n\nMany people associate the term \"user interface\" with websites or applications, however it is important to remember that a CLI is a user interface too, and deserves the same design consideration as graphical user interfaces.\n\nDesigning for pip includes:\n\n- Designing pip's _input_ - establishing the best way to group functionality under commands, and how to name those commands so that they make sense to the user\n- Writing pip's _output_ - establishing how pip responds to commands and what information it provides the user. This includes writing success and error messages.\n- Providing supplemental materials - e.g. documentation that helps users understand pip's operation\n\n### Error Message Format\n\nA good error message should mention:\n\n* what the user has tried to do\n* possible next steps to try and solve the error\n  * possible steps need to go from \"easiest\" to \"most complicated\"\n* why the error has happened - include a way to see more information\n  about the situation\n\nA [sample `ResolutionImpossible` error that follows this guidance\nis available](resolution-impossible-example).\n\n**Further reading**\n\n- <https://uxplanet.org/how-to-write-good-error-messages-858e4551cd4>\n- <https://www.nngroup.com/articles/error-message-guidelines/>\n\n### Design Principles / Usability Heuristics\n\nThere are many interaction design principles that help designers design great experiences. Nielsen Norman's [10 Usability Heuristics for User Interface Design](https://www.nngroup.com/articles/ten-usability-heuristics) is a great place to start. Here are some of the ways these principles apply to pip:\n\n- Visibility of system status: ensure all commands result in clear feedback that is relevant to the user - but do not overload the user with too much information (see \"Aesthetic and minimalist design\")\n- Consistency and standards: when writing interfaces, strive for consistency with the rest of the Python packaging ecosystem, and (where possible) adopt familiar patterns from other CLI tools\n- Aesthetic and minimalist design: remove noise from CLI output to ensure the user can find the most important information\n- Help users recognize, diagnose, and recover from errors: clearly label and explain errors: what happened, why, and what the user can do to try and fix the error. Link to documentation where you need to provide a detailed explanation.\n- Help and documentation: provide help in context and ensure that documentation is task-focussed\n\n#### Additional Resources\n\n- [Command Line Interface Guidelines](https://clig.dev)\n- [10 design principles for delightful CLIs](https://blog.developer.atlassian.com/10-design-principles-for-delightful-clis/)\n\n### Design Tools\n\nTools that are frequently used in the design process are personas and guidelines, but also wireframing, prototyping, and testing, as well as creating flow diagrams or models.\n\n#### Personas\n\n_For a more in-depth overview of personas and using them in open source projects, this [resource from Simply Secure](https://simplysecure.org/blog/personas) may be helpful._\n\nPersonas are abstractions or archetypes of people who might use your tool. It often takes the form of a quick portrait including things like — name, age range, job title, enough to give you a sense of who this person is. You can capture this information into a [persona template](https://simplysecure.org/resources/persona-template-tech.pdf) and share them with your open source community as a resource see [examples from the Gitlab UX Team](https://about.gitlab.com/handbook/marketing/strategic-marketing/roles-personas/).\n\nPersonas are particularly useful to help ground a feature design in priorities for specific needs of specific users. This helps provide useful constraints into the design process, so that you can focus your work, and not try to make every feature a swiss army knife of solutions for every user.\n\nIn 2020, the pip UX team developed the following personas for the pip project:\n\n- Python Software User\n- Python Software Maker\n- Python Package Maintainer\n\nAn in-depth write up on how the pip personas were created, and how they can be applied to future pip UX work can be [found here](research-results/personas).\n\n#### Prototyping\n\nIn any UX project, it is important to prototype and test interfaces with real users. This provides the team with a feedback loop, and ensures that the solution shipped to the end user meets their needs.\n\nPrototyping CLIs can be a challenge. See [Creating rapid CLI prototypes with cli-output](https://www.ei8fdb.org/prototyping-command-line-interfaces-with-cli-output/) for recommendations.\n\n#### Copywriting Style Guides\n\nGiven pip's interface is text, it is particularly important that clear and consistent language is used.\n\nThe following copywriting Style Guides may be useful to the pip team:\n\n- [Warehouse (PyPI) copywriting styleguide and glossary of terms](https://warehouse.readthedocs.io/ui-principles.html#write-clearly-with-consistent-style-and-terminology)\n- Firefox:\n  - [Voice and Tone](https://meet.google.com/linkredirect?authuser=0&dest=https%3A%2F%2Fdesign.firefox.com%2Fphoton%2Fcopy%2Fvoice-and-tone.html)\n  - [Writing for users](https://meet.google.com/linkredirect?authuser=0&dest=https%3A%2F%2Fdesign.firefox.com%2Fphoton%2Fcopy%2Fwriting-for-users.html)\n- [Heroku CLI](https://devcenter.heroku.com/articles/cli-style-guide) (very specific to Heroku's CLI tools)\n- [Redhat Pattern Fly style guide](https://www.patternfly.org/v4/ux-writing/about)\n- [Writing for UIs from Simply Secure](https://simplysecure.org/blog/writing-for-uis)\n\n### General Resources\n\n- Heroku talk on design of their CLI tools ([video](https://www.youtube.com/watch?v=PHiDG-_XoRk) transcript)\n- [Simply Secure: UX Starter Pack](https://simplysecure.org/ux-starter-pack/)\n- [Simply Secure: Feedback Gathering Guide](https://simplysecure.org/blog/feedback-gathering-guide)\n- [Simply Secure: Getting Quick Tool Feedback](https://simplysecure.org/blog/design-spot-tool-feedback)\n- [Internews: UX Feedback Collection Guidebook](https://globaltech.internews.org/our-resources/ux-feedback-collection-guidebook)\n- [Simply Secure: Knowledge Base](http://simplysecure.org/knowledge-base/)\n- [Open Source Design](https://opensourcedesign.net/resources/)\n- [Nielsen Norman Group](https://www.nngroup.com/articles/)\n- [Interaction Design Foundation](https://www.interaction-design.org/literature)\n"
  },
  {
    "path": "docs/html/ux-research-design/index.md",
    "content": "# UX Research & Design\n\n```{toctree}\n:hidden:\n\ncontribute\nguidance\nresearch-results/index\n```\n\nWelcome to pip’s UX research and design documentation. The purpose of this section of the documentation is to:\n\n- [Identify where new contributors can participate in or lead UX research and design activities](contribute)\n- [Share pip UX guidelines](guidance), including an introduction to User Centered Design practices, and how they can be applied to the pip project\n- Share [results of user research](research-results/index) that the pip team has already conducted\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/about-our-users.md",
    "content": "# About pip's Users\n\n## Problem\n\nWe want to understand users' background, their cultural environment, and how they experience the world, so that we can find better ways to serve them.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nTo develop our understanding about pip's users, we published a \"Who uses pip?\" survey that asked users about:\n\n- Their location in the world\n- Their spoken language\n- If they identified as members of an underrepresented group in the Python community\n- Their disabilities and if those disabilities affected their usage of pip\n\n## Results\n\n164 people responded to the survey, with 40% of these coming from English speaking countries. 80% of participants came from Europe or North America.\n\nApprox. 60% did not identify as members of an underrepresented group. The majority of participants who did identify as underrepresented did so for gender reasons.\n\nThe majority of participants (94%) responded that they did not have a disability. Of those that did have a disability, the majority were cognitive disabilities (Attention Deficit Hyperactivity Disorder aka ADHD, Autism, Aspergers, Dyslexia) or a hearing disability.\n\n### Participant Demographics\n\n#### Location\n\nThe majority of participants came from North America and Western Europe. Participation from pip users in Africa, Asia, and the Middle-East was low.\n\n![Map of world showing distribution of participants as per table below](https://i.imgur.com/U2MYiK7.png)\n\nFig. X: Global distribution of pip research participants.\n\n| Country Name             | Number of participants |\n| ------------------------ | ---------------------- |\n| United States of America | 42                     |\n| United Kingdom           | 17                     |\n| France                   | 12                     |\n| Germany                  | 11                     |\n| Canada                   | 10                     |\n| Netherlands              | 8                      |\n| Spain                    | 6                      |\n| Switzerland              | 5                      |\n| Nigeria                  | 4                      |\n| India                    | 4                      |\n| Czech Republic           | 4                      |\n| Argentina                | 4                      |\n| Sweden                   | 3                      |\n| Australia                | 3                      |\n| Ukraine                  | 2                      |\n| Taiwan                   | 2                      |\n| Russia                   | 2                      |\n| Greece                   | 2                      |\n| Colombia                 | 2                      |\n| Chile                    | 2                      |\n| Brazil                   | 2                      |\n| Belgium                  | 2                      |\n| Uganda                   | 1                      |\n| Turkey                   | 1                      |\n| Singapore                | 1                      |\n| Serbia                   | 1                      |\n| Norway                   | 1                      |\n| Luxembourg               | 1                      |\n| Japan                    | 1                      |\n| Italy                    | 1                      |\n| Israel                   | 1                      |\n| Ireland                  | 1                      |\n| Hungary                  | 1                      |\n| Ghana                    | 1                      |\n| Finland                  | 1                      |\n| Bulgaria                 | 1                      |\n| Austria                  | 1                      |\n| Total                    | 164                    |\n\n#### Participant's First Language\n\nEven though the research was carried out mainly in English, 51% of participants spoke languages other than English.\n\n| What spoken language do you feel is your first? | Number of participants |\n| ----------------------------------------------- | ---------------------- |\n| English                                         | 79                     |\n| French                                          | 18                     |\n| Spanish                                         | 12                     |\n| German                                          | 11                     |\n| Russian                                         | 5                      |\n| Czech                                           | 4                      |\n| Italian                                         | 4                      |\n| Portuguese                                      | 3                      |\n| Dutch                                           | 3                      |\n| Ukrainian                                       | 2                      |\n| Swedish                                         | 2                      |\n| Greek                                           | 2                      |\n| Catalan                                         | 2                      |\n| Mandarin                                        | 2                      |\n| Hungarian                                       | 2                      |\n| Bengali                                         | 1                      |\n| Luxembourgish                                   | 1                      |\n| Bulgarian                                       | 1                      |\n| Romanian                                        | 1                      |\n| Chinese                                         | 1                      |\n| Norwegian                                       | 1                      |\n| Serbian                                         | 1                      |\n| Polish                                          | 1                      |\n| Hebrew                                          | 1                      |\n| Indonesian                                      | 1                      |\n| Malayalam                                       | 1                      |\n\nNB: English includes British English and American English. Some participants gave more than one answer, their first answer is included here.\n\n### Participants who identified as underrepresented in the Python community\n\nWe asked research participants if they identified as members of an underrepresented group within the Python community.\n\nThe wording of this question was deliberately broad to discover participants' understanding of the term \"underrepresented\" - we listed gender, age, educational background, spoken language, and what they use Python for as a non-exhaustive list of examples.\n\n![Pie chart showing 17.9% answering - I am not sure, 22.6% answering  -yes, 59.4% answering - No to the question - Do you identify as an underrepresented group in the Python community](https://i.imgur.com/ghwzxg9.png)\n\nOf the 22.6% that responded \"Yes\" the answers were classified as follows :\n\n| Underrepresentation category | Count |\n| ---------------------------- | ----- |\n| Gender                       | 9     |\n| Cultural                     | 3     |\n| Age                          | 3     |\n| Immigration status           | 2     |\n| Neurodiversity               | 3     |\n| Other                        | 6     |\n| No answer                    | 8     |\n\nNB: This question was included after the survey was published. Total participants was 106, as opposed to all other questions which had 164.\n\nThe majority of participants did not identify as part of an underrepresented group. However, due to the small sample size these results cannot be seen as representative of the whole pip user base.\n\n#### Participant comments about identifying (or not) as under-represented\n\nHere is a sample of noteworthy comments from these different groups:\n\n##### Related to Gender\n\n> \"(I am) LGBTQ/IA+\" **- Participant 242608909**\n\n> \"I am a 25 year old female Colombian developer.\" **- Participant 242611698**\n\n> \"Female, 39, no computer science background whatsoever, self taught.\" **- Participant 242614039**\n\n##### Related to Culture\n\n> \"The hispanic community is quite underrepresented in the web in general\" **- Participant 242599212**\n\n> \"I am a 1st generation Dominican-American. My parents are from the Dominican Republic.\" **- Participant 242769361**\n\n##### Related to Age\n\n> \"Older age, I am 50 now.\" **- Participant 242769743**\n\n##### Related to Neurodiversity\n\n> \"I'm a woman. And autistic. But the latter might not be underrepresented ;)\" **- Participant 243428773**\n\n##### Other Noteworthy Comments\n\n> \"Veterans who entered tech post-military\" **- Participant 243524784**\n\n> \"I'm a young white cis male, so by far not a minority in those aspects. But at the same time I'm from a third world country, Argentina, and that sometimes (and I emphasize, only sometimes) makes me feel like a minority. When participating in our local communities (Python Argentina), I feel clearly not-minority, and with the responsibility of helping minorities, trying to build a more welcoming and fair environment for them. But when I participate in the broader global community, at times I feel underrepresented, seeing it mostly guided by english-s[p]eaking people from first world countries. But if I have to choose, I would say I mostly feel not-minority, because I mostly interact with people from our local communities, where I'm not part of a minority.\" **- Participant 242592869**\n\n> \"As a CIS male I conform the majoritarian group in the IT world. I'm hopeful that things are changing everywhere, and will keep changing: inclusion is getting bigger and better, more and more people are starting their careers as devs or similar, disregarding ethnicity and/or sexual orientation and that's great! And we need to keep fighting for that.\" **- Participant 243455292**\n\n### Participant Disabilities\n\nDisabilities - physical, motor, cognitive, hearing, speech - alter how people perceive and interact with the world around them - software included. We asked participants about their disabilities and how it affected their usage of pip.\n\nUnderstanding these disabilities is important particularly when designing pip command structures, and designing pip output.\n\nThe majority of participants (91%) responded that they did not have a disability. Of those that told us that have a disability, the majority were cognitive disabilities (Attention Deficit Hyperactivity Disorder (ADHD), Autism, Aspergers, Dyslexia, or a hearing disability.\n\n#### How many participants identified as having a disability?\n\n| Do you self-identify as someone who has a disability? | Number of responses |\n| ----------------------------------------------------- | ------------------- |\n| No                                                    | 150                 |\n| Yes                                                   | 14                  |\n| Grand Total                                           | 164                 |\n\n#### Vision\n\nParticipants who answered yes to this question were partially sighted. Their vision disability was not corrected by glasses, but did not significantly affect their usage of pip.\n\n#### Hearing\n\nFive participants identified as having a hearing impairment, or hearing loss. While this disability made participants lives more difficult, it did not affect their usage of pip:\n\n> \"Being hard of hearing/impaired makes my life much harder, but so far it never has impacted my usage of pip. Perhaps because I haven‘t used parts of it that would?\" **- Participant 242934019**\n\n> \"Not at all given that everything happens by text in my console.\" **- Participant 243455292**\n\nHowever it did affect the way they consume pip learning materials: if video is being used for learning or support, they should have captions/subtitles/transcriptions available.\n\n> \"any videos released, it is so helpful if there is either a) transcripts, or b) captions.\" **- Participant 243524784**\n\n#### Cognitive Disabilities\n\nNine participants expressed cognitive disabilities including undefined mental health conditions, Attention Deficit Hyperactivity Disorder (ADHD), Autism, Aspergers, Dyslexia.\n\nThese participants did not explain how their cognitive disabilities affect their usage of pip, however there are guidelines and best practices for designing for people with cognitive disabilities.\n\n#### Physical or Mobility Disability\n\nOne participant responded that they had a physical or mobility disability, but did not give detail about it in relation to their usage of pip.\n\n### Participants use of Assistive Technology\n\nThe term \"assistive technology\" (AT) is used to describe products or systems that support and assist individuals with disabilities, restricted mobility or other impairments to perform functions that might otherwise be difficult or impossible. A subset of these are used to make computer technology - hardware and software - more accessible. Common examples of AT used with computer technology are: screen readers, text-to-speech outputs/inputs.\n\nThe majority of participants (94%) said that they have never used assistive technology.\n\n| Do you use assistive technology (AT) when using computers? | Number of responses |\n| ---------------------------------------------------------- | ------------------- |\n| No, I have never used it                                   | 128                 |\n| I only use it when needed                                  | 3                   |\n| I use it everyday                                          | 1                   |\n| I have used it in the past, but not anymore                | 4                   |\n\nOf the eight participants who have used assistive technology, one participant uses assistive technology every day with:\n\n- Text-to-speech output as \"text to speech allow(s) me to listen and learn when my eyes get strained.\"\n- Speech-to-text input as they like using their \"tablet and makes typing easier\"\n- On-screen keyboards\n- Input switches/touch screens\n\nA further seven participants use assistive technology only as needed:\n\n> \"I use custom display filter software to do things like colorize key lines of output automatically (to draw my eye/attention), and provide digit dilimination (I.E. help me tell 1000 and 10000 apart) when using a text console application.\"\n\n> \"The standard Mac user interface design contains enough assistive technology without my needing to use any features which are specifically intended solely as assistive functions.\"\n\n> \"I sometimes use it to make sure that my code will work correctly with AT.\"\n\n#### Operating systems used with assistive technology\n\nParticipants use assistive technology across the three most popular desktop operating systems - Linux (most popular), Windows (2nd most popular), and Mac.\n\n![Pie chart showing breakdown of most popular operating systems for pip users using assistive technology](https://i.imgur.com/CD2ev5P.png)\n\n#### Assistive technology when using pip\n\nWe asked participants how well their assistive technologies worked when they use pip. All participants using assistive technology with pip said it worked well for them.\n\nWe received some feedback about screen readers not coping well with long output, with users experiencing difficulties accessing content at the top of the current terminal window. Therefore, commands or actions (e.g. pip help, pip install, failed builds) that generate a lot of content can be a problem for screenreader users.\n\n## Recommendations\n\n### Supporting languages other than English\n\nAs 51% of participants speak a language other than English, we recommend that the pip team add localization support to the pip documentation and reach out to the community to find pip users who might be willing to contribute translations. Translators that have [contributed translations to PyPI](https://hosted.weblate.org/projects/pypa/warehouse/) may be a good starting point.\n\nIf this is not possible, we recommend linking to useful resources in languages other than English from the pip documentation, as we know from our other research that users use a mixture of the official documentation, search engine searches, Stack Overflow and blogs/websites to find solutions to their problems.\n\n### Supporting pip users with disabilities\n\nPip's operation is generally very good for users with disabilities. Being a command line application there are no distracting images or ancillary content, and the user has a large amount of control on how they experience pip via customisation of interface visual preferences (to use contrasting colours, font size and type) and visual and auditory alerts.\n\nTo better support pip's users with disabilities, the pip team should:\n\n- Ensure any future video or audio support materials are provided with captions\n- Improve pip's output (see below)\n\n### Improving pip output\n\nPip's output is currently too verbose, generating an unhelpful amount of output during its operation. This causes usability issues for all users - especially users with cognitive disabilities.\n\nPip's output should be improved by:\n\n- Retaining only the information that is important to users in their current moment (e.g. at install of a package)\n- Removing unimportant information from the terminal output. The information can still be logged to the log files if needed.\n- Reducing the number of verbosity levels to three. Right now there are seven levels of verbosity, which is overwhelming and in no way useful. We recommend:\n  - Verbosity 0 - shows only what packages are to be installed, notifications identified as important about the operation, any errors and the final outcome\n  - Verbosity 1 - shows more detail about the packages being installed\n  - Verbosity 2 - shows full information which is also logged to logfiles\n\n## Further reading\n\nDesigning for people with disabilities:\n\n- [An Introduction to inclusive design](https://www.nomensa.com/blog/2011/introduction-inclusive-design)\n- [How ADHD and dyslexia teach you to do better UX design](https://themasters.io/blog/posts/how-adhd-dyslexia-teach-better-ux-design)\n- [Improve User Experience by Designing with Cognitive Differences in Mind](https://noti.st/elizabethschafer/fg3BR4)\n- [Designing accessible software - guidelines for different disabilities](https://ukhomeoffice.github.io/accessibility-posters/)\n- [Designing for Children with ADHD: The Search for Guidelines for Non-Experts](https://uxpamagazine.org/designing_children_adhd/) (written for children however applicable generally)\n- [Designing for dyslexia](https://uxplanet.org/designing-for-dyslexia-6d12e8c41cd7)\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/ci-cd.md",
    "content": "# How pip is used in interactive environments (i.e. CI, CD)\n\n## Problem\n\nWe want to know about the contexts in which pip users use pip - interactively (i.e. typing pip commands at the command line terminal) and in an automated environment (i.e. as part of continuous software integration or continuous software development pipelines).\n\nDifferent contexts of use mean that users have different important and common tasks; it means when, where and how they complete these tasks are different.\n\nEach of these contexts bring different needs: interactive usage requires the right feedback/output at the right time, whereas an automated environment requires little or no feedback in the moment but detailed feedback after the task has finished.\n\nWe also wanted to know what users used pip for - as part of their software development toolchain, or purely as a software installer (analogous to Ubuntu Aptitude or Mac Appstore). We also asked about their need for pip to build packages from source.\n\n## Research\n\nWe created a survey and asked users to give answers to the following statements:\n\n- I use pip in an automated environment (e.g. CI/CD pipelines)\n- I have problems with pip in CI/CD pipelines\n- I use pip interactively (e.g. typing pip commands on the commandline)\n- I make software and use pip as part of my software development workflow\n- I use pip only to install and use Python packages\n- I need pip to build software packages from source\n\n## Results\n\nUsing pip interactively makes up the majority of pip usage (91%), the majority (73%) of this usage is basic usage - to only install and use Python packages.\n\nHalf (51%) of all participants used pip in an automated environment, with only 9% having issues with pip in that automated environment. This points to a good use experience for these users.\n\n71% use pip as part of their software toolchain, only 29% needing pip to build from source.\n\nThese results show that the main context of use is interactive - users either writing code, installing software at the command line and we know from other research that interactive usage has its issues e.g. pip output being too verbose.\n\nWhile it is important to provide automated environment users with a good experience, interactive mode users are being underserved.\n\n![Answer to question - I use pip in an automated environment](https://i.imgur.com/pLHqBpN.png)\n\n![Answer to question - I use pip interactively](https://i.imgur.com/8ETVMYS.png)\n\n91% of users said they used pip interactively. This does not preclude them from automated usage.\n\n![Answer to the question - What do you use Python for?](https://i.imgur.com/ySlo2Es.png)\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/improving-pips-documentation.md",
    "content": "# Improving pip's Documentation\n\n## Problem\n\nWe want to establish whether or not the [official pip documentation](https://pip.pypa.io/en/stable/) helps users to solve their pip problems. We also want to identify possible improvements to the content and structure of the docs.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\n### Interviews\n\nWe conducted interviews with pip users specifically discussing documentation. During these interviews we asked about:\n\n- Problems they had experienced while using pip, and how they solved them (with a focus on what information sources they used)\n- How they rate pip's documentation, and what we could do to make the docs more useful\n- What documentation (from other projects or languages) they find valuable, and why\n\n### Surveys\n\nWe collected documentation feedback via two surveys:\n\n- In our survey that profiled pip users, we asked \"What would be your ideal way of getting help with pip?\"\n- We also published a survey specific to pip's docs:\n\n![Screenshot of survey](https://i.imgur.com/dtTnTQJ.png)\n\n### Keyword research\n\nWe used keyword research tools to understand what words (\"keywords\") people use when using search engines to troubleshoot pip problems.\n\n### Other research methods\n\nWe also:\n\n1. Asked for volunteers to participate in a diary study, documenting their experience solving pip problems. Unfortunately this was not completed due to lack of interest from the community.\n2. Asked for user feedback on the pip documentation site:\n   ![screenshot of user feedback mechanism on pip docs](https://i.imgur.com/WJVjl8N.png)\n   Unfortunately, we did not gather any useful feedback via this effort\n3. [Installed analytics on the pip docs](https://github.com/pypa/pip/pull/9146). We are waiting for this to be merged and start providing useful data.\n\n## Results\n\nIn total, we:\n\n- Conducted 5 user interviews about pip's documentation\n- Received 141 responses to the question \"What would be your ideal way of getting help with pip?\"\n- Received 159 responses to the documentation survey\n\nIn general, we found that pip's documentation is underutilized by the community, with many users not knowing that it exists. Instead, most users turn to common tools (Google, Stack Overflow) to solve their pip problems.\n\nIn response to the question \"When you have a problem using pip, what do you do?\" (multiselect):\n\n- 81.9% of respondents Google it\n- 56.9% of respondents search or ask on Stack Overflow\n- 33.8% of respondents use pip help from the command line\n- **25.6% of respondents go to the pip docs**\n- 20.6% of respondents go the the Python Packaging User Guide\n- 8.1% of respondents ask on a forum, community board, or chat channel\n\n![screenshot of survey results](https://i.imgur.com/qlt1b4n.png)\n\nBased on survey results, users find pip's docs:\n\n- Marginally more useful than not useful\n- Marginally more clear than unclear\n- Not opinionated enough\n\nCommon feedback that emerged from both surveys and user interviews includes:\n\n- The documentation performs poorly in search engine results\n- The style and layout is dated (note: this feedback was collected before the [new theme was deployed](https://github.com/pypa/pip/pull/9012))\n- There is not enough guidance/examples on how to resolve common problems, or achieve specific goals\n- The documentation information architecture is difficult to navigate (the monolithic structure of the user guide is a problem) and does not prioritise the most useful content\n- There should be more instructions specific to each user's different situation (e.g. what operating system they are using)\n- The scope of the documentation is unclear\n- The documentation should recognise that pip exists within an ecosystem of other packaging tools\n- [\"There should be one-- and preferably only one --obvious way to do it.\"](https://www.python.org/dev/peps/pep-0020/) - i.e. the documentation should provide stronger recommendations\n\nWhile some users mentioned that video would be helpful, more said that video was too long, or inappropriate for the kind of problems they experience using pip.\n\nSome users mentioned that in person support, forums or chat would be helpful, with many unaware of existing support / community channels.\n\nSeveral users also noted that improving pip's error messages would reduce the need for better documentation.\n\nFrom our keyword research we identified seven _query types_: \"about pip\", \"install pip\", \"uninstall pip\" \"update pip\", \"using pip\", \"errors\", and \"other\".\n\n<details><summary> See keyword research results</summary>\n\n### About pip\n\n- what is pip\n- what is pip in python\n- what is pip python\n- what does pip mean\n- what does pip stand for\n- what does pip stand for python\n- pip meaning\n\n### Install pip\n\n- get pip\n- python install pip\n- install pip\n- installing pip\n- how to install pip python\n- how to install pip\n- how to download pip\n- how to get pip\n- how to check if pip is installed\n- install pip mac\n- how to install pip on mac\n- install pip on mac\n- install pip linux\n- how to install pip linux\n- how to install pip on linux\n- how to install pip in ubuntu\n- how to install pip ubuntu\n- install pip ubuntu\n- ubuntu install pip\n- pip windows\n- install pip windows\n- pip install windows\n- how to install pip windows\n- how to install pip in windows\n- how to install pip on windows\n- how to pip install on windows\n- how to install pip on windows 10\n- how to run pip on windows\n\n### Uninstall pip\n\n- how to uninstall pip\n- uninstall pip\n- pip uninstall\n\n### Update pip\n\n- how to update pip\n- how to upgrade pip\n- pip update\n- pip upgrade\n- upgrade pip\n- how to upgrade pip on windows\n\n### Using pip\n\n- how to use pip\n- how to use pip install\n- how to pip install\n- how to use pip python\n- how to install with pip\n- how to run pip\n- python how to use pip\n- pip install requirements.txt\n- pip requirements.txt\n- pip freeze\n- pip update package\n- pip install specific version\n- pip upgrade package\n- pip uninstall package\n\n### Errors\n\n- no module named pip\n- pip command not found\n- pip is not recognized\n- 'pip' is not recognized as an internal or external command, operable program or batch file.\n- -bash: pip: command not found\n- pip is not recognized as an internal or external command\n- pip install invalid syntax\n\n### Other\n\n- how to add pip to path\n- how to check pip version\n- how does pip work\n- where does pip install packages\n- pip vs pip3\n- where is pip installed\n\n</details>\n<br/>\n\nThe prevalence of \"install pip\" queries strongly suggests that the current installation documentation should be improved and that users are searching for solutions specific to their operating system.\n\nThe \"about pip\" queries also suggest that beginners would benefit from documentation that better explains pip basics - e.g. what pip is and what it does.\n\n## Recommendations\n\nBased on our research, we recommend that the pip team:\n\n- Revise the structure of the documentation:\n  - Break monolithic pages into standalone pages on different subjects, with appropriate meta tags. This will help the docs appear higher in search results for the 81.9% of users who use Google to troubleshoot their pip problems.\n  - Prioritise most used features (see \"[buy a feature](prioritizing-features)\" results for guidance)\n- Add a \"troubleshooting\" section to the documentation that addresses common questions, explains error messages and tells users where they can find more help\n- Provide more context about pip's role in the Python packaging ecosystem by:\n  - Introducing packaging concepts that users need to understand in order to use pip\n  - Explaining pip's role/scope within the packaging ecosystem\n  - Comparing pip to other tools\n- Develop a beginner's guide that walks new pip users through everything they need to know to use pip's most basic functionality. This should include addressing concepts outside of pip's scope (e.g. how to open and use a terminal, how to set up a virtual environment), that may block users from being successful\n- For each page, (where appropriate), add sections for:\n  - \"tips and tricks\" - things to know / gotchas\n  - \"troubleshooting\" - possible error messages and recommended solutions. Where appropriate, this should link to content in the troubleshooting section.\n  - \"see also\" (links to external resources - e.g. useful stack overflow questions, blog articles, etc.)\n- In general, write content that:\n  - Is opinionated. Prioritize solutions that will work in the majority of cases, while pointing to possible edge cases and workarounds in \"tips and tricks\", \"troubleshooting\" and \"see also\" content\n  - Uses keywords to increase search results visibility\n  - Provides instructions for different contexts - e.g. for users on Windows, Linux, MacOSX\n  - Increases interlinking with external sources, including packaging.python.org\n\n### Suggested site map\n\nBased on the above user input, we have developed a proposed [site map](https://i.imgur.com/UP5q09W.png) (link opens larger format image) to help guide the redevelopment of pip's documentation in line with the above recommendations.\n\n![sitemap. for details see summary below](https://i.imgur.com/UP5q09W.png)\n\n<details><summary> See notes for this site map</summary>\n\n#### Node 1.0: Quick reference\n\n_Page purpose:_\n\n- To give pip users a quick overview of how to install pip, and use pip's main functionality\n- To link to other (more detailed) areas of the documentation\n\n_Suggested content:_\n\n- Quick installation guide, including how to use a virtual environment. This is necessary for user who want to install more than one Python project on their machine.\n- Common commands / tasks (based on [buy a feature](prioritizing-features) data)\n\n---\n\n#### Node 2.0: About pip\n\n_Page purpose:_\n\n- To introduce pip to new users\n\n_Suggested content:_\n\n- Introduce pip as a command line program\n- Explain what the command line is and how to use it in different operating systems\n- Explain what pip is/does, and what it stands for\n- Link to packaging concepts (node 2.1)\n- Explain pip's scope (e.g. to install and uninstall packages) and link to other tools (node 2.2)\n\n#### Node 2.1: Packaging concepts\n\n_Page purpose:_\n\n- To introduce packaging concepts for new pip users\n\n_Suggested content:_\n\n- What is a package?\n- What types of packages are there? e.g. file types\n- What is package versioning / what are requirement specifiers? (note: talk about potential dependency conflicts here)\n- Where do I get packages from?\n- How should I control how packages are installed on my system (e.g. virtualenv and environment isolation)\n- How can I reproduce an environment / ensure repeatability? (e.g requirements files)\n- What do I need to know about security? (e.g. hash checking, PyPI name squatting)\n- Link to node 2.2 (\"pip vs other packaging tools\")\n\n#### Node 2.2: pip vs other packaging tools\n\n_Page purpose:_\n\n- To compare pip to other tools with the same scope\n- To highlight that pip exists within a _packaging ecosystem_ and link to other packaging tools\n\n_Suggested content:_\n\n- Compare pip to other installation tools - e.g. poetry, pipenv, conda. What are the features, pros and cons of each? Why do packaging users choose one over the other?\n- Briefly introduce other packaging projects. Link to https://packaging.python.org/key_projects/\n\n---\n\n#### Node 3.0: Installing pip\n\n_Page purpose:_\n\n- To help pip users install pip\n\n_Suggested content:_\n\n- Refactor current page, emphasising pathways for different operating systems\n- Add \"tips and tricks\", \"troubleshooting\" and \"see also\" (link to external resources) sections to provide additional help\n\n---\n\n#### Node 4.0: Tutorials\n\n_Page purpose:_\n\n- To provide a jumping off place into pip's tutorials\n\n_Suggested content:_\n\n- Link to tutorials, including sub pages, where appropriate\n\n#### Node 4.1: Using pip to install your first package\n\n_Page purpose:_\n\n- To help new pip users get started with pip\n\n_Suggested content:_\nStep by step tutorial (possibly broken into several pages) that covers:\n\n- Using the command line\n- Installing pip (or checking pip is installed)\n- Creating/activating a virtual env (use venv for this, but point to alternatives)\n- Installing a package\n- Showing where the package has been installed\n- Deactivating/reactivating virtualenv\n- Uninstalling a package\n\n#### Node 4.2: Advanced tutorial - using pip behind a proxy\n\n_Page purpose:_\n\n- To help advanced pip users achieve specific goals\n\n_Suggested content:_\n\n- Step by step tutorial for using pip behind a proxy\n\nNB: other advanced tutorials should be added as identified by the team and/or requested by the community.\n\n---\n\n#### 5.0: Using pip\n\n_Page purpose:_\n\n- To provide a jumping off point for the user guide and reference guide\n\n_Suggested content:_\n\n- Link to each subject in the user guide\n- Link to reference guide\n\n#### 5.1: User guide\n\n_Page purpose:_\n\n- To provide users with specific detailed instructions on pip's key features\n\n_Suggested content:_\nBreak down current user guide into separate pages, or pages linked by subject. Suggested order:\n\n- Running pip\n- Installing Packages\n- Uninstalling Packages\n- Environment recreation with requirements files\n  - sub heading: \"pinned version numbers\"\n  - sub heading: \"hash checking mode\"\n- Listing Packages\n- Searching for Packages\n- Installing from local packages\n- Installing from Wheels\n- Wheel bundles\n- “Only if needed” Recursive Upgrade\n- Configuration\n- User Installs\n- Command Completion\n- Basic Authentication Credentials\n- Using a Proxy Server (includes link to tutorial)\n- Constraints Files\n- Using pip from your program\n\nWhere possible, each page should include:\n\n- \"tips and tricks\" for workarounds, common _gotchas_ and edge use cases\n- \"troubleshooting\" information, linking to content in node 6.2 (\"Troubleshooting error messages\") where applicable\n- \"see also\", linking to external resources (e.g. stack overflow questions, useful threads on message boards, blogs posts, etc.\n\nNote: the following content should be moved:\n\n- Fixing conflicting dependencies (move to node 6.2 - \"Troubleshooting error messages\")\n- Dependency resolution backtracking (move to node 6.2 - \"Troubleshooting error messages\")\n- Changes to the pip dependency resolver in 20.3 (move to node 7.0 - \"News, changelog and roadmap\")\n\n#### 5.2: Reference guide\n\n_Page purpose:_\n\n- To document pip's CLI\n\n_Suggested content:_\n\n- https://pip.pypa.io/en/stable/reference/\n\n---\n\n#### 6.0: Help\n\n_Page purpose:_\n\n- To provide a jumping off place for users to find answers to their pip questions\n\n_Suggested content:_\n\n- Links to\n  - 6.1 \"FAQs\"\n  - 6.2 \"Troubleshooting error messages\"\n  - 6.3 \"Finding more help\"\n\n#### 6.1: FAQs\n\n_Page purpose:_\n\n- To answer common pip questions / search terms\n\n_Suggested content:_\n\n- What is the difference between pip and pip3?\n- Where does pip install packages?\n- How can I check pip's version?\n- How can I add pip to my path?\n- Where is pip installed?\n- What does pip stand for?\n\nSee [popular questions on Stack Overflow](https://stackoverflow.com/search?q=pip&s=ec4ee117-277a-4c5d-a3f5-c921ca6c5da6) for more examples.\n\n#### 6.2: Troubleshooting error messages\n\n_Page purpose:_\n\n- To help pip users solve their problem when they experience an error using pip\n\n_Suggested content:_\nFor each (common) error message:\n\n- Explain what happened\n- Explain why it happened\n- Explain what the user can do to resolve the problem\n\nNote: the [ResolutionImpossible](https://pip.pypa.io/en/stable/user_guide/#fixing-conflicting-dependencies) and [dependency resolution backtracking](https://pip.pypa.io/en/stable/user_guide/#dependency-resolution-backtracking)\ndocumentation should both be moved here.\n\n#### 6.3: Finding more help\n\n_Page purpose:_\n\n- To point pip users to other resources if they cannot find the information they need within the pip documentation\n\n_Suggested content:_\n\n- See [getting help](https://pip.pypa.io/en/stable/user_guide/#getting-help)\n\n---\n\n#### 7.0: News, changelog and roadmap\n\n_Page purpose:_\n\n- To share information about:\n  - Recent changes to pip\n  - Upcoming changes to pip\n  - Ideas for improving pip, specifically highlighting where funding would be useful\n\n_Suggested content:_\n\n- [Changes to the pip dependency resolver in 20.3 (2020)](https://pip.pypa.io/en/stable/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020)\n- Links to PSF blog posts about pip\n- Link to [fundable packaging improvements](https://github.com/psf/fundable-packaging-improvements/blob/master/FUNDABLES.md)\n\n---\n\n#### 8.0: Contributing\n\n_Page purpose:_\n\n- To encourage new people to contribute to the pip project\n- To demonstrate that the project values different _types_ of contributions, e.g. not just development\n- To recognise past and current contributors\n\n_Suggested content:_\n\n- Introduction to pip as an open source project\n- Contributors code of conduct\n- Recognition of the different types of contributions that are valued\n- Credit list of contributors, including pip maintainers\n\n#### 8.1: Development\n\n_Page purpose:_\n\n- To onboard people who want to contribute code to pip\n\n_Suggested content:_\n\n- https://pip.pypa.io/en/stable/development/\n\n#### 8.2: UX design\n\n_Page purpose:_\n\n- To onboard people who want to contribute UX (research or design) to pip\n- To share UX knowledge and research results with the pip team\n\n_Suggested content:_\n\n- UX guidelines, and how they apply to the pip project\n- Current UX initiatives (e.g. open surveys, interview slots, etc.)\n- Previous research and results, including UX artifacts (e.g. personas)\n\n#### 8.3: Documentation\n\n_Page purpose:_\n\n- To onboard people who want to contribute to pip's docs\n- To share previous research and recommendations related to pip's docs\n\n_Suggested content:_\n\n- This guide\n- Writing styleguide / glossary of terms - see the [Warehouse documentation](https://warehouse.readthedocs.io/ui-principles.html#write-clearly-with-consistent-style-and-terminology) for an example.\n\n</details>\n\n### Future research suggestions\n\nTo continue to improve pip's documentation, we suggest:\n\n- Conducting [card sorting](https://www.nngroup.com/articles/card-sorting-definition/) with pip users to establish the ideal order and grouping of pages\n- Regularly reviewing the documentation analytics, to understand those pages which are most/least visited\n- Regularly reviewing Stack Overflow to identify questions for the FAQ\n- Setting up a mechanism for collecting user feedback while users are on the documentation site\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/index.md",
    "content": "# UX Research Results\n\nOver the course of 2020, the pip team worked on improving pip's user experience, developing a better understanding of pip's UX challenges and opportunities, with a particular focus on pip's new dependency resolver. The [Simply Secure](https://simplysecure.org/) team focused on 4 key areas:\n\n- [Understanding who uses pip](https://github.com/pypa/pip/issues/8518)\n- [Understanding how pip compares to other package managers, and supports other Python packaging tools](https://github.com/pypa/pip/issues/8515)\n- [Understanding how pip's functionality is used could be improved](https://github.com/pypa/pip/issues/8516), and\n- [Understanding how pip's documentation is used, and how it could be improved](https://github.com/pypa/pip/issues/8517)\n\nSome key outcomes from the 2020 work are:\n\n- This documentation & resource section!\n- A pip UX research panel ([Sign up here!](https://mail.python.org/mailman3/lists/pip-ux-studies.python.org/))\n- New and expanded GitHub issues\n- UX improvements in 2020\n  - UX work supporting the dependency resolver\n  - Improved error messaging\n  - Supporting Documentation\n- UX Training for the Pypa + pip maintainers\n\nThis work was made possible through the [pip donor funded roadmap](https://wiki.python.org/psf/Pip2020DonorFundedRoadmap).\n\n## Outreach\n\nWe [recruited participants](https://www.ei8fdb.org/thoughts/2020/03/pip-ux-study-recruitment/) for a user research panel that we could contact when we wanted to run surveys and interviews about pip. In total 472 people signed up to the panel, although some unsubscribed during the research period.\n\nAt the end of the 2020 research, we asked users to opt-in to a [long-term panel](https://mail.python.org/mailman3/lists/pip-ux-studies.python.org/), where they can be contacted for future UX studies. Should the pip team wish to continue to build this panel, we recommend translating the sign-up form into multiple languages and better leveraging local communities and outreach groups (e.g. PyLadies) to increase the diversity of the participants.\n\n## User Interviews\n\nIn total, we **interviewed 48 pip users**, recruited from the user panel, and through social media channels.\n\nDuring the interviews, we asked users about:\n\n- How they use Python\n- How long they have been using pip\n- Whether or not they use a virtual environment\n- If and how they address security issues associated with pip\n- Which pip commands they regularly use\n- How they install packages with pip\n- Their experience using pip list, pip show and pip freeze\n- Their experience using pip wheel\n- Whether or not they use other package managers, and how pip compares to their experience with these other tools\n- What the pip team could do to improve pip\n- Problems they have experienced while using pip, and how they solved these problems\n- Their perception and use of the pip documentation\n- What other technical documentation they value, and how the pip docs could take inspiration from these\n- What other resources the pip team could provide to help pip users solve their problems\n\n## Surveys\n\nWe **published 10 surveys** to gather feedback about pip's users and their preferences:\n\n<div class=\"wy-table-responsive\">\n  <table class=\"colwidths-auto docutils\">\n    <thead>\n      <tr>\n      <th>Title</th>\n      <th>Purpose</th>\n      <th>Results</th>\n      </tr>\n    </thead>\n    <tbody>\n      <tr>\n        <td>\n          Pip research panel survey\n        </td>\n        <td>\n          Recruit pip users to participate in user research, user tests and participate in future surveys. See <a href=\"https://bit.ly/pip-ux-studies\">associated blog post</a> for more information.\n        </td>\n        <td>\n          472 full sign-ups\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Feedback for testing the new pip resolver\n        </td>\n        <td>\n          Understand use cases where the new resolver fails due to dependency conflicts. See <a href=\"https://bit.ly/pip-ux-test-the-new-resolver\">associated blog post</a> for more information.\n        </td>\n        <td>\n          459 responses via the feedback form, approx. 8 issues transferred to issue tracker\n        </td>\n      </tr>\n      <tr>\n        <td>\n          How should pip handle conflicts with already installed packages when updating other packages?\n        </td>\n        <td>\n          Determine if the way that pip handles package upgrades is in-line with user's expectations/needs. See <a href=\"https://www.ei8fdb.org/thoughts/2020/07/how-should-pip-handle-conflicts-when-updating-already-installed-packages/\">related blog post</a> and <a href=\"https://github.com/pypa/pip/issues/7744\">GitHub issue</a> for more information.\n        </td>\n        <td>\n          See <a href=\"pip-upgrade-conflict\">write up, including recommendations</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Learning about our users\n        </td>\n        <td>\n          Learn about pip's users, including:\n          <ul>\n            <li>their usage of Python and pip</li>\n            <li>why and how they started using Python</li>\n            <li>if they are living with any disabilities, and if so what effect (if any) this has on their usage of Python and pip</li>\n            <li>if they use assistive technologies when using Python and pip and how this work for them</li>\n            <li>where they get support when you have issues with pip</li>\n          </ul>\n        </td>\n        <td>\n          See <a href=\"about-our-users\">write up</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Buy a pip feature\n        </td>\n        <td>\n          Establish which features are most important to pip's users\n        </td>\n        <td>\n          See <a href=\"prioritizing-features\">write up</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Should pip install conflicting dependencies?\n        </td>\n        <td>\n          Establish whether pip should provide an override that allows users to install packages with conflicting dependencies\n        </td>\n        <td>\n          See <a href=\"override-conflicting-dependencies\">write up</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          How should pip force reinstall work?\n        </td>\n        <td>\n          Establish whether or not pip force reinstall should continue to behave the way it currently does, if the functionality should be changed, or if the option should be removed\n        </td>\n        <td>\n          See <a href=\"pip-force-reinstall\">write up</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Feedback on pip search\n        </td>\n        <td>\n          To establish whether or not to remove or redesign pip search. See <a href=\"https://github.com/pypa/pip/issues/5216\">this GitHub issue</a> for more information.\n        </td>\n        <td>\n          See <a href=\"pip-search\">write up</a>\n        </td>\n      </tr>\n      <tr>\n        <td>\n          Feedback on pip's docs\n        </td>\n        <td>\n          To gather feedback on pip's docs, supplementing feedback gathered in user interviews\n        </td>\n        <td>\n          See <a href=\"improving-pips-documentation\">write up</a>\n        </td>\n      </tr>\n    </tbody>\n  </table>\n</div>\n\n## All Results\n\n```{toctree}\n:maxdepth: 1\n\nabout-our-users\nmental-models\nusers-and-security\nci-cd\npersonas\nprioritizing-features\noverride-conflicting-dependencies\npip-force-reinstall\npip-search\npip-upgrade-conflict\nimproving-pips-documentation\n```\n\n## Read More\n\n- [Pip team midyear report (blog, July 2020)](https://pyfound.blogspot.com/2020/07/pip-team-midyear-report.html)\n- [Creating rapid CLI prototypes with cli-output (blog, Oct 2020)](https://www.ei8fdb.org/prototyping-command-line-interfaces-with-cli-output/)\n- [Changes are coming to pip (video)](https://www.youtube.com/watch?v=B4GQCBBsuNU)\n- [How should pip handle dependency conflicts when updating already installed packages? (blog, July 2020)](https://www.ei8fdb.org/how-should-pip-handle-conflicts-when-updating-already-installed-packages/)\n- [Test pip's alpha resolver and help us document dependency conflicts (blog, May 2020)](https://www.ei8fdb.org/test-pips-alpha-resolver-and-help-us-document-dependency-conflicts/)\n- [How do you deal with conflicting dependencies caused by pip installs? (blog, April 2020)](https://www.ei8fdb.org/how-do-you-deal-with-conflicting-dependencies-caused-by-pip-installs/)\n- [pip UX studies: response data (blog, March 2020)](https://www.ei8fdb.org/pip-ux-studies-response-data/)\n\nOther PyPA UX work:\n\n- [PyPI User Research (blog, July 2018)](https://whoisnicoleharris.com/2018/07/22/pypi-user-research.html)\n- [Warehouse - The Future of PyPI](https://whoisnicoleharris.com/warehouse/)\n- [Accessibility on Warehouse (PyPI) (blog, May 2018)](https://whoisnicoleharris.com/2018/05/17/warehouse-accessibility.html)\n- [User Testing Warehouse (blog, Mar 2018)](https://whoisnicoleharris.com/2018/03/13/user-testing-warehouse.html)\n- [Designing Warehouse - An Overview (blog, Dec 2015)](https://whoisnicoleharris.com/2015/12/31/designing-warehouse-an-overview.html)\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/mental-models.md",
    "content": "# How Users Understand pip\n\n## Problem\n\nWe want to understand how pip's users understand pip as a tool: what they think it is and what it does.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nIn order to capture participants mental models of pip and how package management works, we asked participants the following questions:\n\n- In your own words, explain what pip is\n- In your own words, explain what happens when pip installs a software package\n- In your own words, explain what a Python package dependency is\n\nWhen we talk about mental models, we talk about \"deep\" or \"shallow\" mental models. When a user has a deep mental models of something, their have a deep understanding with a lot of detail, shallow models are the opposite.\n\nIn order to evaluate those mental models - do they match the reality of pip and package management - we worked with the maintainers to identify 1. pip's behaviours and activities (18 aspects), and 2. the aspects of package dependencies (13), and what a Python package dependency is (10). We then scored participants' answers against those.\n\n## Results\n\nThe analysis focused on participants with between 2 and 10 years of Python experience.\n\nOver 90% of participants did not have a deep understanding of pip - with limited understanding of what pip is, what it does during the install process, and of package management in general.\nHowever, while participants' understanding was low, only 4 participants had factually incorrect understandings of what pip is and does.\n\nParticipants had a slightly deeper understanding of what happens during a pip install process. The most in depth answer included 7 of the 13 identified aspects. The median was 3. Answers focused on resolving dependencies, finding possible package names, downloading assets and installing the package.\n\nParticipants' understanding of software dependencies was again shallow - the most in depth answer included 8 identified aspects. The median was 3. Answers focused on the fact that software dependencies were a result of code reuse, that constraining package versions reduced the possibility of dependency conflicts.\n\nThe full data is available in[ this spreadsheet](https://docs.google.com/spreadsheets/d/1HBiNyehaILxhzZKWcBavkKXDzJr6gIt_Y8Jm8RRgJYg/edit#gid=0).\n\n### Responses to \"In your own words, explain what pip is\"\n\n> \"pip is a standard command-line tool for managing python packages. It has three primary functions: (1) obtaining & caching python packages and/or their dependencies from a repository (typically pypi), (2) building (if needed) and installing python packages--and related dependencies--to a 'site-packages' location in the python path, and (optionally) (3) uninstalling previously-installed packages.\" **- participant 242608909 (Scientist, Professor in the Earth and Atmospheric Sciences Department, using Python for 7 - 10 years)**\n\n> \"Pip is a package management system for python. Kind of like apt in linux, it can be used to install packages in public or private repositories into the current version or environment of Python that invoked the pip command.\" **- participant 240364032 (Professional software developer using Python for 7-10 years)**\n\n> \"pip allows to install/update remove python libraries in your environment. pip manage the library. you will need something else to manage your environment. To use it the easiest is pip install `package-name` I recommend using a requirements.txt and add as you go the library and do pip install -r requirements.txt each time. it avoid to forget a library at the end of the project :)\" **- participant 241178995 (Data scientist working in software engineering)**\n\n> \"python's npm/cargo/opam... dedicated package manager and ecosystem for python libraries and applications\" **- participant 240306262 (self-taught Python creative artist and web developer, using Python for 5-6 years)**\n\n> \"A tool to download & install packages and resolve dependencies. I see it in the same area as yum, zypper or apt-get install in the Linux world.\" **- participant 240306204 (Using Python for scientific research and data analysis for 3 - 4 years)**\n\n> \"Pip is the tool primarily used in the Python community to install packages. (\"Package\" means two different things in Python; it can be a target of the `import` statement that includes modules and other packages, or it can mean a collection of code with a defined interface that can be installed for reuse. I'm referring to the second thing here.) Pip's implementation defines what it means for a package to be installed in a Python environment. Any other tool that wishes to install software into a Python environment (e.g. conda) must match Pip's implementation.\" **- participant 240313922 (Computer security researcher at a university, using Python for 7-10 years)**\n\n### Responses to \"In your own words, explain what happens when pip installs a software package\"\n\n> \"I think pip looks up package \"tea\" in the repository of packages (PyPI by default, but can be changed). If it doesn't find it, it gives an error. If it exists, it downloads some information about the package, like what form it exists in. This can be a wheel, or a package that needs to be built. If it is a wheel, it checks the dependencies and installs them, then it installs the wheel (not sure what this means, probably it extracts it). The wheel is specific to a python distribution and base OS, so it might be available on certain platforms but not others. If it is a package that needs to be built, pip downloads the package source (or clones the repository), and runs setup.py, which installs dependencies and other packages, then the package itself. I forgot to mention that before installing there is some check for checking compatibility of the version required and the versions required by other packages.\" **- participant 240426799 (Scientific researcher - data analysis and computer vision models, using Python for 5-6 years)**\n\n> \"pip searches for a package source (and for me uses the default, so Pypi), then ask the package source for a package with the given name and versions (if specified), then if the package is available download the package in the most appropriate format (depending on my platform), then unzip the package and runs the installer (most probably calls setuptools with the included setup.py file) which will perform the required installation steps. This installation process may contain dependencies (typically specified in setup.py), which will trigger the same process for the dependencies, and so on until all dependencies are installed (if everything is OK).\" **- participant 240670292 (Software developer industrial systems control, using Python for 5-6 years)**\n\n> \"Pip checks PyPI (default package index, assuming that wasn't overridden) for the package matching `tea`. It uses the various specifiers (eg. OS compatibility, Python compatibility, etc) to find the latest version of `tea` compatible with my system. Within that version, it finds the best possible installation match (eg. a `wheel`, if supported on my system and my version of `pip` contains the relevant versioned support [eg. most recently manylinux2010], potentially falling back all the way to a source distribution). After downloading the relevant distribution, it performs the same operations recursively up the dependency chain as specified by the `install_requires` of the `setuptools.setup()` method. After grabbing all relevant packages, it performs the installations as specified in their setup methods -- generally, this involves extracting python files to specific system paths, but various levels of complexity may be added as need be such as compilations, system library bindings, etc. I believe the new resolver changes the above by performing all the lookups simultaneously (eg. by building and solving a dependency graph rather than traversing incrementally) but have not yet read the PEP to learn more. I've answered the above with setuptools in mind -- I believe there was a step added recently to check pyproject.toml first to allow for alternate systems here, but I find the added customization to be a net negative to the ecosystem and have not yet played with it -- the entire Poetry/Pipenv/Pipfile.lock/Flit thing just seems to be adding unnecessary complexity; users who know what they're doing have solved all these issues years ago for their packages and users who find the porcelain makes their lives easier are likely going to run into UX trouble no matter the veneer.\" **- participant 241463652 (Using Python for 5-6 years)**\n\n> \"pip accesses the tea package from pypi (guessing that's where, online at least) and downloads a copy of the files into my local venv\" **- participant 243434435 (Data analysis & machine learning, using Python for 1-2 years)**\n\n> \"Looking up the latest version of of the package from pypi\" **- participant 243897973 (Software testing/writing automated tests using Python 3 - 4 years)**\n\n> \"Download, unpack, sometimes compile a module for my target arch\" **- participant 243428875 (System administration using Python 7 - 10 years)**\n\n## Recommendations\n\nIt's difficult to know what to recommend. Some ideas:\n\n- Question: Is it actually necessary for users to know everything that pip is doing?\n- Better documentation:\n  - Describing the \"blocks of functionality\" that pip carries out and how to deal with them when it breaks\n  - Curating package manager training and help\n  - Improving pip output to expose the different pip functionality blocks\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/override-conflicting-dependencies.md",
    "content": "# Providing an override to install packages with conflicting dependencies\n\n## Problem\n\nCurrently, when a user has dependency conflicts in their project they may be unaware there is a problem, because pip will install conflicting packages without raising an error.\n\nThe new pip resolver is more strict and will no longer allow users to install packages that have conflicting dependencies.\n\nAs a result, some users may feel that newer versions of pip are \"broken\" when pip refuses to install conflicting packages.\n\nFor this reason, the pip team wanted to know if they should provide an override that allows users to install conflicting packages.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nWe published a survey with the following introduction:\n\n<blockquote>\nImagine you have packages tea and coffee:\n\ntea 1.0.0 depends on water <1.12.<br>\ncoffee 1.0.0 depends on water>=1.12<br>\n\nInstalling tea 1.0.0 and coffee 1.0.0 will cause a conflict because they each rely on different versions of water - this is known as a \"dependency conflict\".\n\nThe pip team has recently changed the way that pip resolves dependency conflicts. The new implementation is stricter than before: pip will no longer install packages where there is a dependency conflict - instead it will show an error.\n\nThe purpose of this survey is to gather feedback on providing a way to override this behaviour.\n\nAll questions are optional - please provide as much information as you can.\n\n</blockquote>\n\nWe then asked users:\n\n- If pip should provide an override that allows users to install packages when there are dependency conflicts\n- Why they answered yes or no\n- For users that answered yes, we asked:\n  - When they would use the override\n  - How often they would use the override\n  - How easy it would be to find a workaround, if pip did not provide an override\n  - What syntax they prefer\n\n## Results\n\nIn total, we received 415 responses to the survey.\n\nAn overwhelming majority (>70%) of respondents indicated that they want some kind of override that allows them to install packages when there are dependency conflicts. Despite desiring this feature, most respondents said if it exists they would use it \"not often\" — this indicates that it is an advanced feature that is not critical to day-to-day usage. Nevertheless, because it would be difficult or very difficult to find a workaround (>60%), we suggest that pip should offer a override feature (see recommendations, below).\n\nOver half of the respondents said that `pip install tea coffee --ignore-conflicts` was the most ideal syntax for this command when installing multiple packages at once with a conflicting dependency. When using the `pip install --ignore-conflicts` command, a majority (>48%) of respondents said they would prefer pip to install to the most recent version of the conflicted dependency.\n\nMost respondents suggested that installing the latest version by default is safer, because it could include security fixes or features that would be difficult to replicate on their own. They also trust that dependencies will be largely backwards-compatible. However, they said it was very important that it is necessary to have a way to override this default behavior, in case they need to use an older version of the conflicted package.\n\n## Recommendations\n\nBased on this research we recommend that the pip team:\n\n- Implement an `--ignore-conflicts` option, that allows users to install packages with conflicting dependencies\n- Ensure that `--ignore-conflicts` installs the most recent version of the conflicting package. For example, for conflicting package `water<1.1.2` and `water≥1.1.2`, pip should prefer to install `water≥1.1.2`.\n- Allow users to override this default behavior by specifying the version of the conflicting packages. For example, `pip install tea coffee water==1.1.1 --ignore-conflicts`\n- Warn users that they used the `--ignore-conflicts` flag and that this may cause unexpected behavior in their program\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/personas.md",
    "content": "# pip Personas\n\n## Problem\n\nWe want to develop personas for pip's user to facilitate faster user-centered decision making for the pip development team.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nFrom early interviews with pip users, and from desk research into the different communities that use Python, it was our expectation that there were large communities who were not professional software developers. For example the SciPy library is widely used in the science and engineering communities for mathematical analysis, signal and image processing.\n\nBased on this, we expected a lot of these users would have different expectations, challenges and needs from pip.\n\nOur hypothesis was that:\n\n1. Python users fall into 3 main user types - a software user, a software maker and a software/package maintainer\n2. That the majority (over 60%) would define themselves as Python software users\n3. That the minority would define themselves as Python software maintainers\n\n### Usertype definitions\n\nDuring the research we've met different user types in the Python community. The 3 types of Python users, we proposed were:\n\n#### The Python Software User\n\n\"I use Python software mainly as a tool to help me do what I want to do. This might be running scientific experiments, making music or analysing data with Python software I install with pip. I don't write Python software for others.\"\n\n#### The Python Software Maker\n\n\"I use the Python software language and Python software packages to make software for others, mostly for other people. An example might be - building web applications for my customers. To make this web application I might use the Django framework, and a number of Python packages and libraries.\"\n\n#### The Python Package Maintainer\n\n\"I spend a lot of my time creating Python software packages and libraries for other people to use in the software they make. I might make Python packages and libraries and then publish them on pypi.org or other software repositories.\"\n\n## Results\n\nDuring our research we found that these user types did fit with participants' sense of their usage of Python. Participants did not identify significantly different Python user types when asked.\n\nEach of these user types is a spectrum. Some Python users after time, and with experience/training, a need to use code more than once, started to make their own Python software.\n\nIdentifying as one of these user types does not preclude users from also being another user type. Python users were more likely to Python software makers, but rarely Python software maintainers.\n\nMost (86%) participants identified as being a Python software user. This ranged a) from using Python applications - SciPy, Scikit-Learn - as a tool, with no knowledge, or interest to do more, to b) more advanced usage of Python involving modifying others code/scripts, possibly using libraries to create code specifically for their needs.\n\n75% identified as a Python software maker - as with Python software user, this ranged from writing basic scripts, code, to being a professional software developer.\n\n40% identified as a Python software maintainer - the activities of a maintainer were seen as only available to someone who had many years of Python experience, was heavily involved in a particular package or application, or did it as part of their job.\n\n### I am a Python software user\n\nAs expected, almost all participants identified as a Python software user (86%). This was the most fundamental user type - both trained software developers and those who came to Python as a result of their job were users.\n\nNon-software developer users identified Python as a language to get stuff done -\n\n> \"Almost everyone falls into the user (category) - that’s the target. It's not an obscure language that's meant for specific domains - it's a broad general purpose language designed to get stuff done. It's used by many who don't know other languages, they just need a language to get what they're doing finished.\" **- Participant 240312164**\n\nHowever, \"using Python software\" meant different things depending on who you ask - participants identified as a Python software user on a spectrum.\n\n<table>\n  <thead>\n    <tr>\n     <th>I am a Python software user</th>\n     <th>Number of responses</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>I agree</td>\n      <td>50</td>\n    </tr>\n    <tr>\n      <td>I disagree</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <td>I have no opinion</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <td>I strongly agree</td>\n      <td>70</td>\n    </tr>\n    <tr>\n      <td>I strongly disagree</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <td><strong>Grand Total</strong></td>\n      <td><strong>140</strong></td>\n    </tr>\n  </tbody>\n</table>\n\n![Pie chart with responses to question - I am a Python software user](https://i.imgur.com/ir3tP3B.png)\n\n#### Low end of the spectrum\n\nPython software applications were identified by some as a tool they use to do their \"actual\" work - the scientist, the data analyst, the engineer, the journalist.\n\nHere, they were \"using\" Python applications like SciPy, PsychPi, NumPy, to run scientific experiments, to gather data, to analyse data, with the objective of creating knowledge to make decisions, to identify what to do next.\n\nThese were users who 1) who were new to Python software, 2) came across these Python applications in their profession, and used them as tools.\n\nThey describe NumPy, or SciPy as a Python software application in itself, analogous to being a Windows user, or a Mac user.\n\nThese users are not \"classically trained programmers\" as one participant identified themselves. As a result, they may not have the training, or knowledge about programming concepts like software dependencies. When they are expected to deal with complex or confusing error messages or instructions they have problems, often stopping them.\n\n#### High-end of the spectrum\n\nPython users who \"move up the spectrum\" to more advanced Python usage had been using Python for longer periods - many years.\n\nAgain they may not have been classically trained developers, but through exposure - from work colleagues and their own usage - they started to experiment. This experimentation was in the form of modifying others scripts, taking classes, reading books so they could use code for other purposes.\n\nThis was _making_ software - this software could be used by them as part of their day-job, but it could also be used by many others.\n\nWe asked participants to explain the progression on this user spectrum - what is the difference between a user and a maker?\n\nParticipants spoke about \"are you working on something reusable or are you using the tools to achieve a one time task?\"\n\n> \"I didn't have classic software development training, more statistical analysis experience. I was clueless to the idea that it was a repository that anyone could upload packages to and become a maintainer.\" **- Participant \\_240396891 (Data scientist at an applied research lab using Python do to network traffic analysis/parsing or Machine Learning)**\n\n> \"Firstly I use my own software written in Python, I use Python libraries from pip. I use Django, Flask, libraries like requests.\" **- Participant 240302171**\n\n> \"I am not a classically trained programmer, so it's a great way for me to learn and keep current in techniques. Not being a classically trained programmer, in some cases it detracts, I have a reasonable knowledge of the way to use hashes, but if I wanted to change Python's hash I'd have to read books. I can find information out there.\" **- Participant 240312164 (Nuclear physicist using Python for computer simulations, designing experimental methods)**\n\n### I am a Python software maker\n\nBeing a \"Python software maker\" was a natural progression for some Python users, particularly those who had software development training - either on the job, personal learning or formal education. This training was important to understand fundamental programming concepts.\n\nAs discussed earlier, some participants identified as \"advanced\" Python users, using Python software to modify or create other software. These users were likely to progress onto being software makers.\n\n55% of participants who identified as a software maker had between 5-20+ years of experience with Python. Only 18% of software makers had less than 2 years of experience.\n\n![Pie chart with responses to question - I am a Python software maker](https://i.imgur.com/aqg1kaL.png)\n\nWe did not ask these participants about the \"quality\" of the software they created, but apart from the professional software developers, the opinion of these users was they were not software developers.\n\n<table>\n  <thead>\n    <tr>\n     <th>I am a Python software user</th>\n     <th>Number of responses</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>I agree</td>\n      <td>50</td>\n    </tr>\n    <tr>\n      <td>I disagree</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <td>I have no opinion</td>\n      <td>14</td>\n    </tr>\n    <tr>\n      <td>I strongly agree</td>\n      <td>56</td>\n    </tr>\n    <tr>\n      <td>I strongly disagree</td>\n      <td>10</td>\n    </tr>\n    <tr>\n     <td><strong>Grand Total</strong></td>\n     <td><strong>140</strong></td>\n    </tr>\n  </tbody>\n</table>\n\nMaking software was as defined earlier as \"are you working on something reusable or are you using the tools to achieve a one time task?\"\n\n> \"I'm using Python software and libraries to make this product I'm working on, it's foundation is based on Python, with React, D3 and all built on Python. The cloud assets are Python and testing is Python.\" **- Participant 240315927 (a professional IT developer building a Python based data analysis application)**\n\n> \"I make software in Python. My day job is making software in python. Mainly Django web design. I work for a retail company, where I write calculating orders, creating data in other inventory management systems. Data analysis.\" **- Participant 240393825**\n\n> \"I have written software, sometimes for business and personal reasons. At one point I worked on a django website project, that was being used by 1000s of people. I don't think any of my live projects are based.\n\n> \"Most of it is for sysadmin, automation. I [like] to use python instead of shell scripting. I manage a server with wordpress sites. I wrote a script to update these sites, mailman list and sql DB management, and for different utilities.\" **- Participant 240313542**\n\n> \"I use Python for creating things - like outputs for data scientist, software engineer. I make software to look at patterns, and analyse stuff. I think I'm a maker because someone else is using - they are colleagues. Usually its non-technical colleagues. I produce outputs - make data understandable. They use the results, or a package it behind a flask app. Or analyse graphs.\" **- Participant 240426799**\n\n### I am a Python software maintainer\n\nThe Python software/package maintainer user type was seen as requiring a significant amount of time and experience - domain experience as the software could be very specific (e.g. SciKit Learn, SciPy, etc), technical/coding experience, and experience in the community. You need to have spent time in doing the other jobs, before you could become a maintainer.\n\nFor large projects it was seen as necessary to have core code contributors, and maintainers. Maintainers did not always write code - they could be more involved with technical architecture, technical design, than writing code.\n\nAn aspect of the software maintainer role that wasn’t mentioned a lot was the community management aspect.\n\n![Pie chart with responses to question - I am a Python software maintainer](https://i.imgur.com/gXPc946.png)\n\n<table>\n  <thead>\n    <tr>\n      <th>I am a Python package maintainer</th>\n      <th>Number of responses</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>I agree</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <td>I disagree</td>\n      <td>24</td>\n    </tr>\n    <tr>\n      <td>I have no opinion</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>I strongly agree</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <td>I strongly disagree</td>\n      <td>38</td>\n    </tr>\n    <tr>\n     <td><strong>Grand Total</strong></td>\n     <td><strong>140</strong></td>\n    </tr>\n  </tbody>\n</table>\n\n> \"You can become a maintainer once you get past a certain level of experience.\" **- Participant 240278297**\n\n> \"To be a package maintainer, you'd have to spend a lot of time fixing issues, e.g. your package is on Github and you'd be looking at issues, reviewing PRs, writing documentation. A package maintainer is someone heavily involved in the project. They deal with more support calls, they do more thinking about issues to get your package into multiple environments. That's the good thing about the Python community - I was trying to use a Python package but there was an issue with the documentation. I said, there's a better way of doing this example. They answered and said \"great, do you want to do it? Doing package maintaining, it doesn't interest me, I don't have time for it really - if I have a specific issue I will focus on it. It'd be nice (to do more).\" **- Participant 240278297 (professional Python software developer)**\n\n> \"I am a core developer of scikit-learn, I spend time writing code. These days strictly speaking - writing code is the least thing I do - mostly I do reviews of other people's code. There is a lot of API design work, it can translate into writing code. I may be the one writing the code or not. I am involved with the CI every now and then. [...] I have been the release manager for the last 2 releases. There are different types of maintainer - writing code maintainers, but you do need core devs writing code. But being a maintainer and building a community -that is about communication and PRs, and mentoring people.\" **- Participant 240306385 (core maintainer of SciKit-Learn)**\n\n## Recommendations\n\n### Provide documentation recommending \"best/recommended ways\"\n\nThe majority of participants were using Python as a tool, as a participant said: \"it's a broad general purpose language designed to get stuff done.\"\n\nThe majority of participants - scientists, product/electronic engineers, data analysts, nuclear physicists - used Python for their work - they may write Python software, for themselves, possibly for colleagues. A smaller number are maintainers of widely used Python packages.\n\nAs a result they are not classically trained software developers and so may not have \"the right\" understanding of important software programming concepts.\n\nUsers of all types, and experience struggled with knowing the \"right\" way to do something. They often spoke about the \"recommended way\" to do something - to start a new project, to make a package:\n\n> \"As a new comer, it's not easy to figure out what should be in the right way to structure a _setup.py_ or _pyproject.toml_. There is a good guide, but it's not easy to figure out what to use. I wish there was a guide like 'Make an application (or library) in 30 minutes'.\"\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/pip-force-reinstall.md",
    "content": "# pip --force-reinstall\n\n## Problem\n\nCurrently, when `pip install [package-name] --force-reinstall` is executed, instead of reinstalling the package at the version previously installed, pip installs the package at the newest version available.\n\ni.e. `pip install [package name] --force-reinstall` acts as `pip [package name] --upgrade`\n\nWe want to find out if users understand (or desire) this implicit behaviour.\n\nMore information can be found on [this GitHub issue](https://github.com/pypa/pip/issues/8238).\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nTo help us understand what users want from the `--force-reinstall` option, we launched a survey with the following scenario:\n\n<blockquote>\nYou have the requests package and its dependencies installed:\n\nrequests==2.22.0<br>\nasgiref==3.2.10<br>\ncertifi==2020.6.20<br>\nchardet==3.0.4<br>\nDjango==3.1<br>\nidna==2.8<br>\npytz==2020.1<br>\nsqlparse==0.3.1<br>\nurllib3==1.25.10<br>\n\nYou run 'pip install requests --force-reinstall'. What should happen?\n\n</blockquote>\n\nRespondents could choose from one of the following options:\n\n- pip reinstalls the same version of requests. pip does not reinstall request's dependencies.\n- pip reinstalls requests and its dependencies, updating all these packages to the latest compatible versions\n- pip reinstalls requests and its dependencies, keeping every package on the same version\n- pip reinstalls requests, updating it to the latest version. pip updates request's dependencies where necessary to support the newer version.\n- I don't know what pip should do\n- I don't understand the question\n- Other (allows respondent to provide their own answer)\n\nWe also asked how useful `pip --force-reinstall` is, and how often it is used.\n\n## Results\n\nIn total we received 190 responses to our survey, with 186 people telling us what pip should do when the `--force-reinstall` option is executed.\n\n![pie chart with survey results](https://i.imgur.com/yoN02o9.png)\n\n- **31.7%** (59/186) of respondents said that pip should reinstall requests and its dependencies, keeping every package on the same version\n- **28%** (52/186) of respondents said that pip should reinstall requests, updating it to the latest version, with pip updating request's dependencies where necessary to support the newer version.\n- **15.6%** (29/186) of respondents said that pip should reinstall requests and its dependencies, updating all these packages to the latest compatible versions\n- **14%** (26/186) of respondents said that pip should reinstall the same version of requests, and not reinstall request's dependencies\n\nIf we group responses into \"upgrade\" or \"do not upgrade\" (ignoring responses that could not be grouped), we find:\n\n- 46.32% (88/186) of respondents thought that pip should install the same version of requests - i.e. that `--force-reinstall` should _not_ implicitly upgrade\n- 43.16% (82/186) of respondents thought that pip should upgrade requests to the latest version - i.e that `--force-reinstall` _should_ implicitly upgrade\n\nMost respondents use `--force-reinstall` \"almost never\" (65.6%):\n\n![screenshot of survey question of how often users use --force-reinstall](https://i.imgur.com/fjLQUPV.png)\n![bar chart of how often users use --force-reinstall](https://i.imgur.com/Xe1XDkI.png)\n\nAmongst respondents who said they use `--force-reinstall` often or very often:\n\n- 54.54% (6/11) of respondents thought that pip should install the same version of requests - i.e. that `--force-reinstall` should _not_ implicitly upgrade\n- 45.45% (5/11) of respondents thought that pip should upgrade requests to the latest version - i.e that `--force-reinstall` _should_ implicitly upgrade\n\nRespondents find `--force-reinstall` less useful than useful:\n\n![screenshot of survey question of how useful users find --force-reinstall](https://i.imgur.com/6cv4lFn.png)\n![bar chart of how useful users find --force-reinstall](https://i.imgur.com/gMUBDBo.png)\n\nAmongst respondents who said they find `--force-reinstall` useful or very useful:\n\n- 38.46% (20/52) of respondents thought that pip should install the same version of requests - i.e. that `--force-reinstall` should _not_ implicitly upgrade\n- 50% (26/52) of respondents thought that pip should upgrade requests to the latest version - i.e that `--force-reinstall` _should_ implicitly upgrade\n\n## Recommendations\n\nGiven that this option is not regularly used and not strongly rated as useful, we recommend that the development team consider removing `--force-reinstall` _should they wish to reduce maintenance overhead_.\n\nIn this case, we recommend showing the following message when a user tries to use `--force-reinstall`:\n\n> Error: the pip install --force-reinstall option no longer exists. Use pip uninstall then pip install to replace up-to-date packages, or pip install --upgrade to update your packages to the latest available versions.\n\nShould the pip development team wish to keep `--force-reinstall`, we recommend maintaining the current (implicit upgrade) behaviour, as pip's users have not expressed a clear preference for a different behaviour.\n\nIn this case, we recommend upgrading the [help text](https://pip.pypa.io/en/stable/reference/pip_install/#cmdoption-force-reinstall) to be more explicit:\n\nOld help text:\n\n> Reinstall all packages even if they are already up-to-date.\n\nNew help text:\n\n> Reinstall package(s), and their dependencies, even if they are already up-to-date. Where package(s) are not up-to-date, upgrade these to the latest version (unless version specifiers are used).\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/pip-search.md",
    "content": "# pip search\n\n## Problem\n\nBy default, `pip search` searches packages on PyPI.org from the command line. However, the team are [considering removing it](https://github.com/pypa/pip/issues/5216), because they think it's not that useful and using too many resources on PyPI ([PyPI XMLRPC search has been disabled](https://status.python.org/incidents/grk0k7sz6zkp) because of abuse/overuse).\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nPrior to PyPI XMLRPC search being disabled, we:\n\n- Gathered feedback on pip search via the \"buy a feature\" survey\n- Published a survey specifically about pip search, asking users about:\n  - Their current use of pip search\n  - How useful they find pip search results\n  - How clear they find pip search results\n  - Where users expect pip to search (e.g. PyPI vs private index)\n  - What data pip should search _other_ than project name\n  - What changes or additions they would make to pip search\n\n## Results\n\nIn total, we received 1070 responses to the buy a feature survey, with 541 (50.4%) respondents selecting \"Search pypi.org for packages\" in their top 10 features.\n\nHowever, search ranked lower than the following features:\n\n1. Run pip without requiring any user input (e.g. in CI) _718_\n2. Show information about all installed packages _707_\n3. Show information about a single installed package _596_\n\nWe received 302 responses to the pip search survey, with 62 of the 302 (20.5%) respondents either not knowing that the command existed, never using it, or using it \"rarely\".\n\nWe found that the remaining ~80% of respondents who do use pip search use it to:\n\n- Find/search for the right/new/alternate packages to install:\n  - Checking package name (verify correct spelling)\n  - Assessing functionality (check a package's description)\n  - Verifying availability (check if such package exists)\n- Search for the latest version of a package (verify version)\n- Find package libraries and new modules\n\nIn general, pip search is regarded as:\n\n- more useful than not useful\n- more clear than not clear\n\nWhen asked if pip should search on items _other_ than the package name, respondents most commonly asked to search the package description:\n\n![wordcloud of common search terms](https://i.imgur.com/lxS2TG6.png)\n\nSome users also mentioned that they would like the search to be configurable, e.g. by passing flags/options.\n\nWhen asked how they would improve pip search, users said they would improve:\n\n**1. Search methods:**\n\n- fuzzy search and insensitive case should be acceptable\n- users should have the option to filter/sort by description, name, tag\n\n**2. Search results:**\n\n- relevancy: the results should show both the exact match and closest match\n- order/category: the result should display items in a certain order, e.g highest number of downloads (popularity), development status (last updated/latest version), etc.\n- there should be a limited number of search results\n\n**3. User interface:**\n\n- link package to pypi page\n- use color coding / system for better clarity\n- distinguish exact match search results from others: by highlighting, or using a different color\n- indicate version compatibility\n\n## Recommendations\n\n### Deprecation strategy\n\nGiven that the [PyPI](https://pypi.org/pypi) search API is currently disabled (as of 1st Jan, 2021) for technical and sustainability reasons, we recommend that the pip team display a clear error message to users who use the command:\n\n```\nThe PyPI search API has been disabled due to unmanageable load.\nTo search PyPI, open your browser to search for packages at https://pypi.org\nAlternatively, you can search a different index using the --index command.\n```\n\nIn the longer term, **we recommend that the PyPI team investigate alternative methods of serving search results (e.g. via caching)** that would enable pip search to work again. This recommendation is supported by our research which suggests that many pip users find this functionality useful.\n\nIf this is not possible, the pip team should create clear instructions that tells users what to use instead. Some suggestions (based on common user flows) are listed below:\n\n#### Finding a new package based on tags and keywords\n\nThis is the most common feature that you would expect from `pip search` and likely the hardest to replace after deprecation.\n\nAs mentioned above, the pip CLI should - as soon as possible - hide the full-trace error message present when a user types `pip search`. Instead, pip should show a message that encourages users to use the search index on the website itself (in their browser) by providing a link directly to [https://pypi.org](https://pypi.org). Also, pip should provide a short hint on how to use an alternative index.\n\n```\n$ pip search pytest\n\nThe PyPI search API has been disabled due to unmanageable load.\n\nPlease open your browser to search for packages at https://pypi.org\n\nAlternatively, you can use a different index using the --index command.\n\n   pip search pytest --index <URL>\n```\n\nIn addition, the pip team could implement an alternative to the PyPI search API that works without a hard dependency on a centralized service. Similar to other distribution systems like `apt` and `yum`, the metadata of all package names could be downloaded on the user's machine with an opt-in workflow:\n\n```\n$ pip search pytest\nUsing pip search on the command line requires you to download the index first.\nAlternatively, you can open your browser to search for packages at https://pypi.org\n\nDownload the index to /System/Library/Frameworks/Python.framework/\nVersions/2.7/Resources/Python.app/Contents/MacOS/search.db? (y/n) y\n......... done!\n\n<results>\n\n$ pip search pytest\n<results>\n```\n\nThis is a more complex route that will require more engineering time, but can aim to provide command line users with a similar functionality to the old `pip search` command. It can also check the age of the local index and show a warning if it is getting old.\n\n#### Verifying the latest version of a package\n\nUsers also use the `pip search` command to find or verify a particular package's version.\n\nAs a replacement, the pip team could do either of the following:\n\n1. Extend the `pip show` feature to include known latest versions of the package;\n2. Create a `pip outdated` command which scans the current dependency tree and outputs the packages that are outdated (compared to the latest versions on the configured index).\n\n### UX improvements\n\nShould it be possible to continue to support pip search, we strongly recommend the following UX improvements:\n\n- Adding support for [fuzzy search](https://en.wikipedia.org/wiki/Approximate_string_matching), or suggesting alternative/related search terms\n- Adding support for case insensitive search\n- Searching based on a package's description\n- Linking search results to a package's PyPI page (where appropriate)\n\nOther user feedback (as detailed above) should also be considered by the team on a case-by-case basis.\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/pip-upgrade-conflict.md",
    "content": "# pip Upgrade Conflict\n\n## Problem\n\nCurrently, pip does _not_ take into account packages that are already installed when a user asks pip to upgrade a package. This can cause dependency conflicts for pip's users.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nWe published a [survey](https://bit.ly/2ZqJijr) asking users how they would solve the following scenario:\n\n<blockquote>\nImagine you have package tea and coffee with the following dependencies:\n\ntea 1.0.0 - depends on water<1.12<br>\ntea 2.0.0 - depends on water>=1.12<br>\ncoffee 1.0.0 - depends on water<1.12<br>\ncoffee 2.0.0 - depends on water>=1.12<br>\n\nYou have the following packages installed:\n\ntea 1.0.0<br>\ncoffee 1.0.0<br>\nwater 1.11.0<br>\n\nYou ask pip to upgrade tea. What should pip do?\n\nIf pip upgrades tea to 2.0.0, water needs to be upgraded as well, creating a conflict with coffee...\n\n</blockquote>\n\nWe gave users four choices:\n\n1. Upgrade tea and water. Show a warning explaining that coffee now has unsatisfied requirements.\n2. Upgrade coffee automatically to 2.0.0\n3. Install nothing. Tell the user that everything is up-to-date (since the version of tea they have installed is the latest version without conflicts).\n4. Install nothing. Show an error explaining that the upgrade would cause incompatibilities.\n\nWe allowed users to post their own solution, and asked why they came to their decision.\n\n## Results\n\nIn total, we received 693 responses, 407 of which included an explanation of why a particular solution was best.\n\n![](https://i.imgur.com/UdBWkaQ.png)\n\n- 497 responses (71.7%) preferred option 4: that pip should install nothing and raise an error message\n- 102 responses (14.7%) preferred option 2: that pip should upgrade package_coffee\n- 79 responses (11.4%) preferred option 1: that pip should upgrade tea and water\n- 15 responses (2.2%) preferred option 3: that pip should install nothing and tell the user that everything is up to date\n\nFrom the 407 responses that answered \"why\" a particular solution was best, the following key themes emerged:\n\n- \"explicit is better than implicit\" - pip should not create \"side effects\" that the user does not understand, has not anticipated, and has not consented to\n- pip should do everything in its power to avoid introducing conflicts (pip should not \"break\" the development environment)\n- Telling the user that everything is up to date (option 3) is misleading / dishonest\n- pip could be more flexible by:\n  - allowing the user to choose how they want to resolve the situation\n  - allowing the user to override the default behaviour (using flags)\n\n## Recommendations\n\nBased on the results of this research, the pip UX team has made the following recommendations to the development team:\n\n- While the current behaviour exists, [warn the user when conflicts are introduced](https://github.com/pypa/pip/issues/7744#issuecomment-717573440)\n- [Change the current behaviour](https://github.com/pypa/pip/issues/9094), so that pip takes into account packages that are already installed when upgrading other packages. Show the user a warning when pip anticipates a dependency conflict (as per option 4)\n- Explore [the possibility of adding additional flags to the upgrade command](https://github.com/pypa/pip/issues/9095), to give users more control\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/prioritizing-features.md",
    "content": "# Prioritizing pip Features\n\n## Problem\n\nThe pip development team is small, and has limited time and energy to work on issues reported via the [issue tracker](https://github.com/pypa/pip/issues). There is also a significant backlog of issues (782 as of November, 2020) for the team to respond to.\nFor the team to prioritize their work based on what will have the most impact, we need to develop a better understanding of what users want from pip.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nTo help answer this question, we developed a \"buy a feature\" survey, with the following scenario:\n\n<blockquote>\nHelp us to understand what's important to you by participating in our \"buy a feature\" game:\n\nYou have an allocated budget of $200 to spend on redesigning pip.\n\nWith your $200 budget, \"buy\" the functionality you'd most like to keep.\n\nYou don't have to spend the whole $200, but you should also not overspend your budget!\n\n</blockquote>\n\nWe asked users to spend their first $100 on features related to `pip install`, and to spend their remaining $100 on other pip features. We also gave users an additional $10 to suggest a new feature:\n\n![survey question where users are asked to buy features for pip install](https://i.imgur.com/2QShgYo.png)\n\n![survey question where users are asked to buy features other than pip install](https://i.imgur.com/sY8gdXD.png)\n\n![survey question where users are asked to spend an additional ten dollars](https://i.imgur.com/hvgjdEG.png)\n\n## Results\n\nWe received 1076 responses, 1070 of which were valid. The most popular features included the core competencies of pip:\n\n- Recreating an environment from a list of installed dependencies;\n- Install, uninstall, and upgrade packages from a virtual control system, file, or local directory;\n- Warn about broken or conflicting dependencies.\n\n### pip install\n\nThe top ten features related to pip install were:\n\n![pip install results](https://i.imgur.com/1rNIOB7.png)\n\n1. Install and uninstall packages\n2. Upgrade packages to the latest version\n3. Warn about broken dependencies\n4. Install a package from a version control system (e.g. Git, Mercurial, etc.)\n5. Install packages as specified in a file\n6. Install a package from a local directory\n7. Verify downloaded packages against hashes\n8. Install packages from an alternative package index, or indexes (default is PyPI only)\n9. Install a package from wheels (no need for compiling code)\n10. Control where you want your installed package to live on your computer\n\n### Other pip functionality\n\nThe top ten features related to other pip functionality were:\n\n![other pip functionality results](https://i.imgur.com/xrp9XWw.png)\n\n1. Generate a list of installed packages that can be used to recreate the environment\n2. Check that your installed packages do not have dependency conflicts\n3. Run pip without requiring any user input (e.g. in CI)\n4. Show information about all installed packages\n5. Show information about a single installed package\n6. Search pypi.org for packages\n7. Show information about pip (version information, help information, etc.)\n8. Download packages, build wheels and keep them in a directory for offline use\n9. Manage pip's default configuration (e.g. by using configuration files)\n10. Customise pip's output (e.g. reduce or increase verbosity, suppress colors, send output to a log)\n\nResults varied by the amount of Python experience the user had.\n\n<details>\n<summary>See how likely users are to select a feature based on their experience level</summary>\n\n#### Verify downloaded packages against hashes\n\n![screenshot of verify downloaded packages against hashes](https://i.imgur.com/oVHOGBQ.png)\n\n#### Warn about broken dependencies\n\n![Screenshot of Warn about broken dependencies](https://i.imgur.com/uNv2tnG.png)\n\n#### Upgrade packages to the latest version\n\n![Screenshot of Upgrade packages to the latest version](https://i.imgur.com/pQgCLBO.png)\n\n#### Install packages from an alternative package index, or indexes\n\n![Screenshot of Install packages from an alternative package index, or indexes](https://i.imgur.com/E1LnTBt.png)\n\n#### Install packages as specified in a file\n\n![Screenshot of Install packages as specified in a file](https://i.imgur.com/87uh4xp.png)\n\n#### Install and uninstall packages\n\n![Screenshot of Install and uninstall packages](https://i.imgur.com/GRsazBy.png)\n\n#### Install packages from a version control system\n\n![Screenshot of Install packages from a version control system](https://i.imgur.com/iW7d0Sq.png)\n\n#### Install a package from wheels\n\n![Screenshot of Install a package from wheels](https://i.imgur.com/9DMBfNL.png)\n\n#### Install a package from a local directory\n\n![Screenshot of Install a package from a local directory](https://i.imgur.com/Jp95rak.png)\n\n#### Control where you want your installed package to live on your computer\n\n![Screenshot of Control where you want your installed package to live on your computer](https://i.imgur.com/32fpww2.png)\n\n</details>\n\n## Recommendations\n\n### Environment recreation\n\nEnvironment recreation is already included in pip as part of the `requirements.txt` feature; however, with it's popularity and demand, we recommend that **pip should improve it's support of this feature.**\n\n- Improve environment recreation user output and help guides directly in the pip CLI;\n- Improve pip documentation & user guide to prominently feature environment recreation as a core feature of pip;\n- Improve environment recreation process itself by considering virtual environments as a core competency \"built-in\" to pip.\n\n**Recreating an environment from a list of installed dependencies was the most valued feature request overall** as well as in each user group, _except for those with less than 6 months of experience and those with 16-19 years of experience (for which it was the second most valued)._\n\nWhen asked to enter a feature request with freetext, users placed the words 'built-in,' 'virtual,' 'automatic,' and 'isolation' alongside the word 'environment,' which suggest that users expect pip to recreate environments with a high level of intelligence and usability.\n\n**Selected direct quotes**\n\n> Make pip warn you when you are not in virtualenv\n\n> Automatic virtual env creation with a command line argument\n\n> Eliminate virtual environments. Just use ./python_modules/ like everyone else\n\n> I would love to see pip manage the python version and virtual env similar to the minicona\n\n> Would spend all my $200 on this: Integrate pipenv or venv into pip so installing an application doesn't install it's dependencies in the system package store. And allow pinning dependency versions for application packages (like how pip-compile does it)\n\n### Dependency management\n\nWe recommend that the pip team improve warning and error messages related to dependencies (e.g., conflicts) with practical hints for resolution. This can be rolled out in multiple timescales, including:\n\n- Give hints to the user on how to resolve this issue directly alongside the error message;\n- Prominently include virtual environment creation in the documentation, upon `pip install` conflict errors, and if possible as a built-in feature of pip;\n- Upgrading the dependency resolver (in progress).\n\nIt is clear that dependency management, including warning about conflicting packages and upgrades, is important for pip users. By helping users better manage their dependencies through virtual environments, pip can reduce the overall warnings and conflict messages that users encounter.\n"
  },
  {
    "path": "docs/html/ux-research-design/research-results/users-and-security.md",
    "content": "# How pip users think about security\n\n## Problem\n\nWe wanted to understand how pip users think about security when installing packages with pip.\n\n[Skip to recommendations](#recommendations)\n\n## Research\n\nWe asked participants about their behaviours and practices in terms of the security and integrity of the Python packages they install with pip, and of the software they create.\n\nWe asked participants to tell us how often they:\n\n1. Carry out a code audit of the Python software they install with pip\n2. Think about the security and integrity of the (Python) software they install (with pip)\n3. Think about the security and integrity of the (Python) code they create\n\n## Results\n\nWhile the security and integrity of the software users install (51%) and make (71%) is important to research participants, less than 7% do code audits of the packages or code they install with pip.\n\nThis is due to lack of time to audit large packages, lack of expertise, reliance on widely adopted Python packages, the expectation that pip automatically checks hashes, and reliance of the wider Python community to act as canary in the coalmine.\n\nThis behaviour was common across all user types, and baselines of software development experience.\n\nThese results - particularly the lack of expertise in auditing packages fits in with the overall findings that the majority of pip users are not \"classically trained\" (i.e. having formally learned software development) software developers and so lack the expertise and/or formal training in software development practices.\n\nThere is a gulf between what the maintainers expect users to think, and worry about, and what the users actually worry and think about. Right now, pip leaves users to \"fend for themselves\" in terms of providing them with assurance of the software they install. This isn't meant as a criticism, but an observation.\n\n### Responses to question: before I install any Python software with pip, I carry out a code audit\n\nThe vast majority of participants, 82%, do not (rarely or never) do a code audit of the software packages they install using pip, the reasons are explained below.\n\n| Before I install any Python software with pip, I carry out a code audit: | Number of responses |\n| ------------------------------------------------------------------------ | ------------------- |\n| Always                                                                   | 3                   |\n| Frequently                                                               | 9                   |\n| Rarely                                                                   | 66                  |\n| Never                                                                    | 68                  |\n| I'm not sure what this means                                             | 5                   |\n| No opinion                                                               | 13                  |\n| **Total number of participants**                                         | **164**             |\n\n### Responses to question: I think about the security and integrity of the software I install\n\n![screenshot of responses to question about security](https://i.imgur.com/wy4lGwJ.png)\n\nThe vast majority of participants did think about the security and integrity of the software they installed - and unlike responses about code audits, in some cases participants made attempts to verify the security and integrity of the software they installed.\n\nMost attempts were made by those who had experience in software development, however in some cases, people gave up.\n\nThose who were not classically trained software developers did not know where to start.\n\nBoth of these groups identified their \"sphere of influence\" and did their best to cover this.\n\n### User thoughts about security\n\nSelected quotes from research participants\n\n#### Responsibility as author\n\nParticipants who spent a lot of their time writing Python code - either for community or as part of their job - expressed a responsibility to their users for the code they wrote - people who wrote code which was made public expressed a stronger responsibility.\n\nThey thought about where the software would be used, who would use it, and possible attack surfaces.\n\n> \"On the basic point, I have to think about attack surfaces. If I am writing the thing (software), I have to give a crap. I have to answer the emails! In the code I push to[ pypi.org](http://pypi.org/) I think about it doubley. What could people do with this code? Whether I do a good job, that's different! I am aware of it when publishing it or making it [publicly] available. Whether I do a good job, that's different! I am aware of it when publishing it or making it [publicly] available. I rely on community resources - Python security related, I follow security people blogs, Twitter. I use Hypothesis for fuzz-testing. I also rely on having security policies in place and a reporting mechanism. I steer clear of crypto, I rely on other peoples. There's a certain amount of knowledge in the Python community, I am actively involved in it. If something happens, I will hear about it. I use Twitter, if something happens, in the morning it can take me awhile to figure out what's happened. I have a lot of trust in the ecosystem to be self healing. As long as you don't stray too far-off the reservation (into using odd or uncommon or new packages), it's a better sense of security.\" **- Participant (data scientist turned Python developer)**\n\n> Yes, because I'm liable for that. If the problem is my code, and I deliver something and they get attacked. I'm screwed. **- Participant (professional Python developer and trainer)**\n\n#### Reliance on software packages\n\nParticipants also explained they rely on code security scanning and checking software packages.\n\n> \"I use linters (Bandit), I scan the code I have created and when there is an issue I raise a red flag.\"\n\n> \"I use Hypothesis for fuzz-testing.\"\n\n#### Reliance on good software development practices\n\nA small number of participants explained they have good software practices in place, which help with writing secure software.\n\n> \"We have a book about ethics of code - we have mandatory certification.\"\n\n> \"I also rely on having security policies in place and a reporting mechanism. I steer clear of crypto, I rely on other peoples.\"\n\nOf the users who have used pip's hash checking functionality:\n\n- One finds the error messages \"too annoying and loud\", and has difficulty matching the file name to the hash\n- Another finds the process of explicitly pinning hashes to be too tiresome (especially for dependencies)\n\nOne user mentioned that he likes [NPM audit](https://docs.npmjs.com/cli/v6/commands/npm-audit) and would like to see something similar in the Python ecosystem.\n\n#### Lack of time\n\nThe lack of time to carry out the audit of the package code, and that of the dependencies, was cited as a very common reason. In most cases participants used Python code as a means to achieving their goal.\n\n#### Lack of expertise to carry out the audit\n\nThe lack of expertise or knowledge of auditing software was mainly due to participants expertise not being software development. However, in the case participants were \"classically\" software developers, lack of expertise was also a commonly given reason for not carrying out audits.\n\n#### Use of only widely used, well-established packages\n\nUse of well-established, high-quality packages was a common reason amongst all types of participants - professional Python software developers and those who used Python as a tool.\n\n\"Well-established, high-quality packages\" were defined by users as packages that:\n\n- have been in existence for many years\n- are popular, or commonly used by those in their community or industry\n- have responsive maintainers\n- maintained by people the participant has heard of\n- have many hundreds or thousands of users\n- are in active development (many open issues, many forks, Github stars)\n- are developed in the open, and transparently\n- their history is known, or can be found out publicly\n\n#### Reliance on the Python community to find issues\n\nThere was a reliance on the community to find issues and make them know publicly - \"Many eyes shallow bugs\".\n\n> \"I rarely do code audits. Most of the time I rely on the opinions of the community. I look at how many maintainers there are. Maybe it's not good practice but I don't have time to go through the code.\" **- Participant 240315091**\n\n#### Use of only internal packages\n\n> \"I only install internal packages, so I don't need to worry about this.\"\n\nThis theme was not that common, mainly in large software development environments or where security was of high importance.\n\n#### Expectation that pip audits packages\n\nSome users expect/assume that pip (and PyPI) should \"protect\" them from malicious actors - e.g. by automatically checking hashes, or detecting malicious packages.\n\n> \"If I was downloading a package on my own I check the hash, if it's installed by pip, then no. I expect pip to do it. If it doesn't do it, it does surprise me. Every package manager checks the hash against what it downloads. The hashes are already known on pypi.\" **- Participant 240312164 (Nuclear physicist)**\n\n#### Other notable comments\n\n> \"Never. I should but I never do [audit code]. I don't stray, I am risk adverse. I install packages that are good already. I consider my risk surface small. I don't have time or resources to audit them. I have sufficient faith in the ecosystem to be self-auditing. If something turned up in a well known package, the community is well known for making a stink. And anyway a code audit wouldn't pick it up.\" **- Participant 240326752 (professional Python developer)**\n\n> \"On the private level (work) the code is developed internally. I don't audit the code on pypi - due to lack of time auditing the dependencies, and I trust it. I know they had a security breach a few years ago, but it doesn't happen that often. I know they don't audit anything but I still don't audit the code.\"\n\n> \"I wouldn't know how to [audit code], also I'm writing this stuff for myself. It'll work or not. Sometimes I end up installing 2 or 3 packages and find out that I need to install something else. I move on if it doesn't work. The last resort is I will write the code myself.\"\n\n> \"I'm quite trusting - Python is open source, I'm assuming that if a package is on[ pypi.org](http://pypi.org/) - it must be alright. I install the package first, then I look at it. I find a package by figuring out - we need to do a certain task, we search for it on the Internet, look at the documentation, we install it and then see if it is what we want\" **- Participant 240278297**\n\n> \"If I want to install a package, it's for a reason. I want to calculate the azimuth and elevation of the moon with PyEphem. Do a code audit? Pffff. Most of the stuff I do is banal. It needs to meet a dependency, so I install it. I'm not going to do a code audit. I don't care. Never, but this is one of the things - is the package on pypi the exact source I see on Github? You could end up with files that are distributed differently. Probably (I don't do it) because I am too scared to look. There is this thing that pip verifies (the packages) hash - so that is a feature to guard against this. What is the hash of? No idea. It's located in the local python install.\" **- Participant 240426799 (systems administrator)**\n\n> \"No [I don't audit code]. [laughs] Coz, I'm not going to read thousands of lines of code before I install a package. Oh my God. [..] I wouldn't be able to find it. I'm trading off - honestly how popular the package is, number of stars on GH. pypi doesn't have any UI way to tell me how many downloads it has. If it did I would use that.\" **- Participant 240386315 (IT administrator)**\n\n> \"Well, I don't have the background to do a code audit of something like Numerical Python. Most packages I use are huge. Most people aren't doing code of those packages, except the maintainer. I am relying on whatever is built into pip to do package security. I also assume if there is an exploit someone will find it and let the world now. I'm really lazy.\" **- Participant 240312164 (Nuclear physicist)**\n\n> \"I would like some security advisor, [like in npm](https://docs.npmjs.com/auditing-package-dependencies-for-security-vulnerabilities) - it works very well, when you install a package \"there are security vulns. with this package - 1 low, 5 medium, 8 high. I haven't come across security issues with Python packages.\" **- CZI convening research participant**\n\n## Recommendations\n\n### Provide package security guidance or auditing mechanism\n\nA small number of participants (3-4) over the research period mentioned the[ NPM audit command](https://docs.npmjs.com/auditing-package-dependencies-for-security-vulnerabilities) as an example of a good way to assess package security. It may provide a model for how to approach this user need.\n\n### Automatically check package hashes\n\npip should **by default** check packages hashes during install, providing a way for users to turn this behaviour off.\n\nIn the case of no hash being available, pip should warn users and provide recommendations for users - from simplest to most advanced.\n\n### Mechanism to report suspicious packages\n\nUsers should have a mechanism to report suspicious, or malicious, packages/behaviour. Where this mechanism should exist is open to discussion. The minimum should be a mechanism for users to flag packages on pypi.org.\n\n### Improve the output of pips activities easier to understand\n\nRight now pip's output is overwhelming and while it contains a lot of information, little of it is perceivable to the user - meaning is lost in \"the wall of text\".\n\nPip's output must be redesigned to provide users with the right information - including security warnings - at the right time.\n"
  },
  {
    "path": "docs/html/ux-research-design/resolution-impossible-example.md",
    "content": "---\norphan:\n---\n\n# Example error: ResolutionImpossible\n\n## What if there are user-provided pinned packages?\n\nWhere a user wants to install packages (with 1 or more pinned version)\nwith default verbose level\n\n```\n$ pip install peach=1.0 apple=2.0\n\nDue to conflicting dependencies pip cannot install Peach1.0 and Apple2.0:\n\n* Peach 1.0 depends on Banana 3.0\n* Apple2.0 depends on Banana2.0\n\nThere are a number of possible solutions. You can try:\n1. removing package versions from your requirements, and letting pip try to resolve the problem for you\n2. Trying  a version of Peach that depends on Banana2.0. Try `pip-search peach —dep banana2.0`\n3. replacing Apple or Peach with a different package altogether\n4. patching Apple2.0 to use Banana3.0\n5. force installing (Be aware!)\n\nFor instructions on how to do these steps visit: https://pypa.io/SomeLink\nTo debug this further you can run `pip-tree` to see all of your dependencies.\n```\n\n**with verbose level -vv**\n\nIf a user ran the same pip command with more verbosity, what would they see?\n\n**with verbose level -vvv**\n\nIf a user ran the same pip command with more verbosity, what would they see?\n\n## What if there are no user-provided version restrictions?\n\nNB: We are assuming this resolver behaviour gets implemented, based on [GH issues 8249](https://github.com/pypa/pip/issues/8249).\n\n**with default verbose level**\n\n```\n$ pip install apple peach\n\nDue to conflicting dependencies pip cannot install apple or peach. Both depend on banana, but pip can't find a version of either where they depend on the same banana version.\n\nThere are a number of possible solutions. You can try:\n1. replacing apple or peach with a different package altogether\n2. patching apple or peach to use the same version of banana\n3. force installing (Be aware!)\n\nTo debug this further you can run pip-tree to see all of your dependencies.\n```\n\n**with verbose level -vv**\n\nIf a user ran the same pip command with more verbosity, what would they see?\n\n**with verbose level -vvv**\n\nIf a user ran the same pip command with more verbosity, what would they see?\n\n**What should be in the \"documentation\" page?**\n\n* ways to swap a package for another\n* how to patch a package to support a version (various ways)\n\n## Recommendations\n\n* Write official documentation / guide \"How to resolve dependency conflicts\" explaining:\n  * Why conflicts can exist\n  * How you can avoid them (pinning)\n  * How you can resolve them\n    * Use alternative package\n    * Use older version\n    * Patch package\n* Introduce new commands to pip, inspired by poetry:\n  * Tree: Show full tree of dependencies\n  * Show `<package>` Show details of a package, including it's dependencies\n  * latest - shows latest vs installed versions\n  * outdated - shows only outdated versions\n* Expose commands / help link in output??\n  * when particular issue happens provide ways to move on (ala pipenv), e.g.\n    * run this command to see X\n    * is it your internet connection?\n    * is it the pypi website?\n* Aspirational commands\n  * `pip search PackageName —dep PackageNameVersion`\n    * a command that will search for a version of a package that has a dependency on another packageversion\n"
  },
  {
    "path": "docs/man/commands/cache.rst",
    "content": ":orphan:\n\n=========\npip-cache\n=========\n\nDescription\n***********\n\n.. pip-command-description:: cache\n\nUsage\n*****\n\n.. pip-command-usage:: cache\n\nOptions\n*******\n\n.. pip-command-options:: cache\n"
  },
  {
    "path": "docs/man/commands/check.rst",
    "content": ":orphan:\n\n=========\npip-check\n=========\n\nDescription\n***********\n\n.. pip-command-description:: check\n\nUsage\n*****\n\n.. pip-command-usage:: check\n\nOptions\n*******\n\n.. pip-command-options:: check\n"
  },
  {
    "path": "docs/man/commands/config.rst",
    "content": ":orphan:\n\n==========\npip-config\n==========\n\nDescription\n***********\n\n.. pip-command-description:: config\n\nUsage\n*****\n\n.. pip-command-usage:: config\n\nOptions\n*******\n\n.. pip-command-options:: config\n"
  },
  {
    "path": "docs/man/commands/debug.rst",
    "content": ":orphan:\n\n==========\npip-debug\n==========\n\nDescription\n***********\n\n.. pip-command-description:: debug\n\nUsage\n*****\n\n.. pip-command-usage:: debug\n\n\n.. warning::\n    This command is only meant for debugging.\n    Its options and outputs are provisional and may change without notice.\n\n\nOptions\n*******\n\n.. pip-command-options:: debug\n"
  },
  {
    "path": "docs/man/commands/download.rst",
    "content": ":orphan:\n\n============\npip-download\n============\n\nDescription\n***********\n\n.. pip-command-description:: download\n\nUsage\n*****\n\n.. pip-command-usage:: download\n\nOptions\n*******\n\n.. pip-command-options:: download\n"
  },
  {
    "path": "docs/man/commands/freeze.rst",
    "content": ":orphan:\n\n==========\npip-freeze\n==========\n\nDescription\n***********\n\n.. pip-command-description:: freeze\n\nUsage\n*****\n\n.. pip-command-usage:: freeze\n\nOptions\n*******\n\n.. pip-command-options:: freeze\n"
  },
  {
    "path": "docs/man/commands/hash.rst",
    "content": ":orphan:\n\n========\npip-hash\n========\n\nDescription\n***********\n\n.. pip-command-description:: hash\n\nUsage\n*****\n\n.. pip-command-usage:: hash\n\nOptions\n*******\n\n.. pip-command-options:: hash\n"
  },
  {
    "path": "docs/man/commands/help.rst",
    "content": ":orphan:\n\n========\npip-help\n========\n\nDescription\n***********\n\n.. pip-command-description:: help\n\nUsage\n*****\n\n.. pip-command-usage:: help\n\nOptions\n*******\n\n.. pip-command-options:: help\n"
  },
  {
    "path": "docs/man/commands/index.rst",
    "content": ":orphan:\n\n===========\npip-index\n===========\n\nDescription\n***********\n\n.. pip-command-description:: index\n\nUsage\n*****\n\n.. pip-command-usage:: index\n\nOptions\n*******\n\n.. pip-command-options:: index\n"
  },
  {
    "path": "docs/man/commands/install.rst",
    "content": ":orphan:\n\n===========\npip-install\n===========\n\nDescription\n***********\n\n.. pip-command-description:: install\n\nUsage\n*****\n\n.. pip-command-usage:: install\n\nOptions\n*******\n\n.. pip-command-options:: install\n"
  },
  {
    "path": "docs/man/commands/list.rst",
    "content": ":orphan:\n\n========\npip-list\n========\n\nDescription\n***********\n\n.. pip-command-description:: list\n\nUsage\n*****\n\n.. pip-command-usage:: list\n\nOptions\n*******\n\n.. pip-command-options:: list\n"
  },
  {
    "path": "docs/man/commands/lock.rst",
    "content": ":orphan:\n\n========\npip-lock\n========\n\nDescription\n***********\n\n.. pip-command-description:: lock\n\nUsage\n*****\n\n.. pip-command-usage:: lock\n\nOptions\n*******\n\n.. pip-command-options:: lock\n"
  },
  {
    "path": "docs/man/commands/search.rst",
    "content": ":orphan:\n\n==========\npip-search\n==========\n\nDescription\n***********\n\n.. pip-command-description:: search\n\nUsage\n*****\n\n.. pip-command-usage:: search\n\nOptions\n*******\n\n.. pip-command-options:: search\n"
  },
  {
    "path": "docs/man/commands/show.rst",
    "content": ":orphan:\n\n========\npip-show\n========\n\nDescription\n***********\n\n.. pip-command-description:: show\n\nUsage\n*****\n\n.. pip-command-usage:: show\n\nOptions\n*******\n\n.. pip-command-options:: show\n"
  },
  {
    "path": "docs/man/commands/uninstall.rst",
    "content": ":orphan:\n\n=============\npip-uninstall\n=============\n\nDescription\n***********\n\n.. pip-command-description:: uninstall\n\nUsage\n*****\n\n.. pip-command-usage:: uninstall\n\nOptions\n*******\n\n.. pip-command-options:: uninstall\n"
  },
  {
    "path": "docs/man/commands/wheel.rst",
    "content": ":orphan:\n\n=========\npip-wheel\n=========\n\nDescription\n***********\n\n.. pip-command-description:: wheel\n\nUsage\n*****\n\n.. pip-command-usage:: wheel\n\nOptions\n*******\n\n.. pip-command-options:: wheel\n"
  },
  {
    "path": "docs/man/index.rst",
    "content": ":orphan:\n\n========\nMan Page\n========\n\nSYNOPSIS\n********\n\npip <command> [options]\n\nDESCRIPTION\n***********\n\npip is the PyPA recommended package manager for Python packages\n\nOPTIONS\n*******\n\n.. pip-general-options::\n\nCOMMANDS\n********\n\npip-install(1)\n    Install packages.\n\npip-download(1)\n    Download packages.\n\npip-uninstall(1)\n    Uninstall packages.\n\npip-freeze(1)\n    Output installed packages in requirements format.\n\npip-lock(1)\n    Generate a lock file for requirements and their dependencies.\n\npip-list(1)\n    List installed packages.\n\npip-show(1)\n    Show information about installed packages.\n\npip-check(1)\n    Verify installed packages have compatible dependencies.\n\npip-search(1)\n    Search PyPI for packages.\n\npip-wheel(1)\n    Build wheels from your requirements.\n\npip-hash(1)\n    Compute hashes of package archives.\n\npip-help(1)\n    Show help for pip commands.\n"
  },
  {
    "path": "docs/pip_sphinxext.py",
    "content": "\"\"\"pip sphinx extensions\"\"\"\n\nfrom __future__ import annotations\n\nimport optparse\nimport pathlib\nimport re\nimport sys\nfrom collections.abc import Iterable, Iterator\nfrom textwrap import dedent\n\nfrom docutils import nodes, statemachine\nfrom docutils.parsers import rst\nfrom docutils.statemachine import StringList, ViewList\nfrom sphinx.application import Sphinx\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.commands import commands_dict, create_command\nfrom pip._internal.configuration import _normalize_name\nfrom pip._internal.req.req_file import SUPPORTED_OPTIONS\n\n\ndef convert_cli_option_to_envvar(opt_name: str) -> str:\n    undashed_opt_name = _normalize_name(opt_name)\n    normalized_opt_name = undashed_opt_name.upper().replace(\"-\", \"_\")\n    return f\"PIP_{normalized_opt_name}\"\n\n\ndef convert_cli_opt_names_to_envvars(original_cli_opt_names: list[str]) -> list[str]:\n    return [\n        convert_cli_option_to_envvar(opt_name) for opt_name in original_cli_opt_names\n    ]\n\n\nclass PipNewsInclude(rst.Directive):\n    required_arguments = 1\n\n    def _is_version_section_title_underline(self, prev: str | None, curr: str) -> bool:\n        \"\"\"Find a ==== line that marks the version section title.\"\"\"\n        if prev is None:\n            return False\n        if re.match(r\"^=+$\", curr) is None:\n            return False\n        if len(curr) < len(prev):\n            return False\n        return True\n\n    def _iter_lines_with_refs(self, lines: Iterable[str]) -> Iterator[str]:\n        \"\"\"Transform the input lines to add a ref before each section title.\n\n        This is done by looking one line ahead and locate a title's underline,\n        and add a ref before the title text.\n\n        Dots in the version is converted into dash, and a ``v`` is prefixed.\n        This makes Sphinx use them as HTML ``id`` verbatim without generating\n        auto numbering (which would make the the anchors unstable).\n        \"\"\"\n        prev = None\n        for line in lines:\n            # Transform the previous line to include an explicit ref.\n            if self._is_version_section_title_underline(prev, line):\n                assert prev is not None\n                vref = prev.split(None, 1)[0].replace(\".\", \"-\")\n                yield f\".. _`v{vref}`:\"\n                yield \"\"  # Empty line between ref and the title.\n            if prev is not None:\n                yield prev\n            prev = line\n        if prev is not None:\n            yield prev\n\n    def run(self) -> list[nodes.Node]:\n        source = self.state_machine.input_lines.source(\n            self.lineno - self.state_machine.input_offset - 1,\n        )\n        path = (\n            pathlib.Path(source).resolve().parent.joinpath(self.arguments[0]).resolve()\n        )\n        include_lines = statemachine.string2lines(\n            path.read_text(encoding=\"utf-8\"),\n            self.state.document.settings.tab_width,\n            convert_whitespace=True,\n        )\n        include_lines = list(self._iter_lines_with_refs(include_lines))\n        self.state_machine.insert_input(include_lines, str(path))\n        return []\n\n\nclass PipCommandUsage(rst.Directive):\n    required_arguments = 1\n    optional_arguments = 3\n\n    def run(self) -> list[nodes.Node]:\n        cmd = create_command(self.arguments[0])\n        cmd_prefix = \"python -m pip\"\n        if len(self.arguments) > 1:\n            cmd_prefix = \" \".join(self.arguments[1:])\n            cmd_prefix = cmd_prefix.strip('\"')\n            cmd_prefix = cmd_prefix.strip(\"'\")\n        usage = dedent(cmd.usage.replace(\"%prog\", f\"{cmd_prefix} {cmd.name}\")).strip()\n        node = nodes.literal_block(usage, usage)\n        return [node]\n\n\nclass PipCommandDescription(rst.Directive):\n    required_arguments = 1\n\n    def run(self) -> list[nodes.Node]:\n        node = nodes.paragraph()\n        node.document = self.state.document\n        desc = ViewList()\n        cmd = create_command(self.arguments[0])\n        assert cmd.__doc__ is not None\n        description = dedent(cmd.__doc__)\n        for line in description.split(\"\\n\"):\n            desc.append(line, \"\")\n        self.state.nested_parse(desc, 0, node)\n        return [node]\n\n\nclass PipOptions(rst.Directive):\n    def _format_option(\n        self, option: optparse.Option, cmd_name: str | None = None\n    ) -> list[str]:\n        bookmark_line = (\n            f\".. _`{cmd_name}_{option._long_opts[0]}`:\"\n            if cmd_name\n            else f\".. _`{option._long_opts[0]}`:\"\n        )\n        line = \".. option:: \"\n        if option._short_opts:\n            line += option._short_opts[0]\n        if option._short_opts and option._long_opts:\n            line += \", \" + option._long_opts[0]\n        elif option._long_opts:\n            line += option._long_opts[0]\n        if option.takes_value():\n            metavar = option.metavar or option.dest\n            assert metavar is not None\n            line += f\" <{metavar.lower()}>\"\n        # fix defaults\n        assert option.help is not None\n        opt_help = option.help.replace(\"%default\", str(option.default))\n        # fix paths with sys.prefix\n        opt_help = opt_help.replace(sys.prefix, \"<sys.prefix>\")\n        env_var_names = convert_cli_opt_names_to_envvars(option._long_opts)\n        env_var_names_src = \", \".join(f\"``{env_var}``\" for env_var in env_var_names)\n        return [\n            bookmark_line,\n            \"\",\n            line,\n            \"\",\n            f\"    {opt_help}\",\n            \"\",\n            f\"    (environment variable: {env_var_names_src})\",\n            \"\",\n        ]\n\n    def _format_options(\n        self, options: Iterable[optparse.Option], cmd_name: str | None = None\n    ) -> None:\n        for option in options:\n            if option.help == optparse.SUPPRESS_HELP:\n                continue\n            for line in self._format_option(option, cmd_name):\n                self.view_list.append(line, \"\")\n\n    def run(self) -> list[nodes.Node]:\n        node = nodes.paragraph()\n        node.document = self.state.document\n        self.view_list = ViewList()\n        self.process_options()\n        self.state.nested_parse(self.view_list, 0, node)\n        return [node]\n\n\nclass PipGeneralOptions(PipOptions):\n    def process_options(self) -> None:\n        self._format_options([o() for o in cmdoptions.general_group[\"options\"]])\n\n\nclass PipIndexOptions(PipOptions):\n    required_arguments = 1\n\n    def process_options(self) -> None:\n        cmd_name = self.arguments[0]\n        self._format_options(\n            [o() for o in cmdoptions.index_group[\"options\"]],\n            cmd_name=cmd_name,\n        )\n\n\nclass PipPackageSelectionOptions(PipOptions):\n    required_arguments = 1\n\n    def process_options(self) -> None:\n        cmd_name = self.arguments[0]\n        self._format_options(\n            [o() for o in cmdoptions.package_selection_group[\"options\"]],\n            cmd_name=cmd_name,\n        )\n\n\nclass PipCommandOptions(PipOptions):\n    required_arguments = 1\n\n    def process_options(self) -> None:\n        cmd = create_command(self.arguments[0])\n        self._format_options(\n            cmd.parser.option_groups[0].option_list,\n            cmd_name=cmd.name,\n        )\n\n\nclass PipReqFileOptionsReference(PipOptions):\n    def determine_opt_prefix(self, opt_name: str) -> str:\n        for command in commands_dict:\n            cmd = create_command(command)\n            if cmd.cmd_opts.has_option(opt_name):\n                return command\n\n        raise KeyError(f\"Could not identify prefix of opt {opt_name}\")\n\n    def process_options(self) -> None:\n        for option in SUPPORTED_OPTIONS:\n            if getattr(option, \"deprecated\", False):\n                continue\n\n            opt = option()\n            opt_name = opt._long_opts[0]\n            if opt._short_opts:\n                short_opt_name = f\"{opt._short_opts[0]}, \"\n            else:\n                short_opt_name = \"\"\n\n            if option in cmdoptions.general_group[\"options\"]:\n                prefix = \"\"\n            else:\n                prefix = f\"{self.determine_opt_prefix(opt_name)}_\"\n\n            self.view_list.append(\n                f\"*  :ref:`{short_opt_name}{opt_name}<{prefix}{opt_name}>`\",\n                \"\\n\",\n            )\n\n\nclass PipCLIDirective(rst.Directive):\n    \"\"\"\n    - Only works when used in a MyST document.\n    - Requires sphinx-inline-tabs' tab directive.\n    \"\"\"\n\n    has_content = True\n    optional_arguments = 1\n\n    def run(self) -> list[nodes.Node]:\n        node = nodes.paragraph()\n        node.document = self.state.document\n\n        os_variants = {\n            \"Linux\": {\n                \"highlighter\": \"console\",\n                \"executable\": \"python\",\n                \"prompt\": \"$\",\n            },\n            \"MacOS\": {\n                \"highlighter\": \"console\",\n                \"executable\": \"python\",\n                \"prompt\": \"$\",\n            },\n            \"Windows\": {\n                \"highlighter\": \"doscon\",\n                \"executable\": \"py\",\n                \"prompt\": \"C:>\",\n            },\n        }\n\n        if self.arguments:\n            assert self.arguments == [\"in-a-venv\"]\n            in_virtual_environment = True\n        else:\n            in_virtual_environment = False\n\n        lines = []\n        # Create a tab for each OS\n        for os, variant in os_variants.items():\n            # Unpack the values\n            prompt = variant[\"prompt\"]\n            highlighter = variant[\"highlighter\"]\n            if in_virtual_environment:\n                executable = \"python\"\n                pip_spelling = \"pip\"\n            else:\n                executable = variant[\"executable\"]\n                pip_spelling = f\"{executable} -m pip\"\n\n            # Substitute the various \"prompts\" into the correct variants\n            substitution_pipeline = [\n                (\n                    r\"(^|(?<=\\n))\\$ python\",\n                    f\"{prompt} {executable}\",\n                ),\n                (\n                    r\"(^|(?<=\\n))\\$ pip\",\n                    f\"{prompt} {pip_spelling}\",\n                ),\n            ]\n            content = self.block_text\n            for pattern, substitution in substitution_pipeline:\n                content = re.sub(pattern, substitution, content)\n\n            # Write the tab\n            lines.append(f\"````{{tab}} {os}\")\n            lines.append(f\"```{highlighter}\")\n            lines.append(f\"{content}\")\n            lines.append(\"```\")\n            lines.append(\"````\")\n\n        string_list = StringList(lines)\n        self.state.nested_parse(string_list, 0, node)\n        return [node]\n\n\ndef setup(app: Sphinx) -> dict[str, bool | str]:\n    app.add_directive(\"pip-command-usage\", PipCommandUsage)\n    app.add_directive(\"pip-command-description\", PipCommandDescription)\n    app.add_directive(\"pip-command-options\", PipCommandOptions)\n    app.add_directive(\"pip-general-options\", PipGeneralOptions)\n    app.add_directive(\"pip-index-options\", PipIndexOptions)\n    app.add_directive(\"pip-package-selection-options\", PipPackageSelectionOptions)\n    app.add_directive(\n        \"pip-requirements-file-options-ref-list\", PipReqFileOptionsReference\n    )\n    app.add_directive(\"pip-news-include\", PipNewsInclude)\n    app.add_directive(\"pip-cli\", PipCLIDirective)\n    return {\n        \"parallel_read_safe\": True,\n        \"parallel_write_safe\": True,\n    }\n"
  },
  {
    "path": "news/.gitignore",
    "content": "!.gitignore\n"
  },
  {
    "path": "news/13226.bugfix.rst",
    "content": "Fix misleading error message when a constraint file cannot be opened.\n"
  },
  {
    "path": "news/13826.process.rst",
    "content": "Add an explicit AI policy.\n"
  },
  {
    "path": "news/13845.trivial.rst",
    "content": "Add Python 3.15 to CI and fix ``importlib.metadata`` compatibility.\n"
  },
  {
    "path": "noxfile.py",
    "content": "\"\"\"Automation using nox.\"\"\"\n\nimport argparse\nimport glob\nimport os\nimport shutil\nimport sys\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\nimport nox\n\n# fmt: off\nsys.path.append(\".\")\nfrom tools import release  # isort:skip\nsys.path.pop()\n# fmt: on\n\nnox.options.reuse_existing_virtualenvs = True\nnox.options.sessions = [\"lint\"]\nnox.needs_version = \">=2024.03.02\"  # for session.run_install()\n\nLOCATIONS = {\n    \"common-wheels\": \"tests/data/common_wheels\",\n    \"protected-pip\": \"tools/protected_pip.py\",\n}\n\nAUTHORS_FILE = \"AUTHORS.txt\"\nVERSION_FILE = \"src/pip/__init__.py\"\n\n\ndef run_with_protected_pip(session: nox.Session, *arguments: str) -> None:\n    \"\"\"Do a session.run(\"pip\", *arguments), using a \"protected\" pip.\n\n    This invokes a wrapper script, that forwards calls to original virtualenv\n    (stable) version, and not the code being tested. This ensures pip being\n    used is not the code being tested.\n    \"\"\"\n    env = {\"VIRTUAL_ENV\": session.virtualenv.location}\n\n    command = (\"python\", LOCATIONS[\"protected-pip\"]) + arguments\n    # By using run_install(), these installation steps can be skipped when -R\n    # or --no-install is passed.\n    session.run_install(*command, env=env, silent=True)\n\n\ndef should_update_common_wheels(session: nox.Session) -> bool:\n    \"\"\"Determine if the common wheels cache needs to be updated.\n\n    The cache is invalidated if:\n    1. It doesn't exist yet\n    2. pyproject.toml was modified after the cache was created\n    3. The cached wheels cannot satisfy the current Python version's requirements\n    \"\"\"\n    # If the cache hasn't been created, create it.\n    if not os.path.exists(LOCATIONS[\"common-wheels\"]):\n        return True\n\n    # If the pyproject.toml was updated after cache, we'll repopulate it.\n    cache_last_populated_at = os.path.getmtime(LOCATIONS[\"common-wheels\"])\n    pyproject_updated_at = os.path.getmtime(\"pyproject.toml\")\n    need_to_repopulate = pyproject_updated_at > cache_last_populated_at\n\n    if not need_to_repopulate:\n        # Check all common wheels are available for the current Python version,\n        # by using --ignore-installed and --dry-run against the common-wheels\n        # directory.\n        result = session.run(\n            \"python\",\n            LOCATIONS[\"protected-pip\"],\n            \"install\",\n            \"--dry-run\",\n            \"--ignore-installed\",\n            \"--no-index\",\n            \"--find-links\",\n            LOCATIONS[\"common-wheels\"],\n            \"--group\",\n            \"test-common-wheels\",\n            env={\"VIRTUAL_ENV\": session.virtualenv.location},\n            silent=True,\n            success_codes=[0, 1],  # Accept both success and failure and check result\n        )\n\n        # Result is the stdout of the pip install command.\n        if result is None or \"Would install\" not in result:\n            session.log(\n                \"Regenerating common wheels as cached wheels \"\n                \"cannot satisfy test-common-wheels\"\n            )\n            need_to_repopulate = True\n\n    # Clear the stale cache.\n    if need_to_repopulate:\n        shutil.rmtree(LOCATIONS[\"common-wheels\"], ignore_errors=True)\n\n    return need_to_repopulate\n\n\ndef get_common_wheels(session: nox.Session) -> None:\n    \"\"\"Build the common wheels needed by tests.\"\"\"\n    if should_update_common_wheels(session):\n        # fmt: off\n        run_with_protected_pip(\n            session,\n            \"wheel\",\n            \"-w\", LOCATIONS[\"common-wheels\"],\n            \"--group\", \"test-common-wheels\",\n        )\n        # fmt: on\n    else:\n        msg = f\"Reusing existing common-wheels at {LOCATIONS['common-wheels']}.\"\n        session.log(msg)\n\n\n# -----------------------------------------------------------------------------\n# Development Commands\n# -----------------------------------------------------------------------------\n@nox.session(name=\"common-wheels\")\ndef common_wheels(session: nox.Session) -> None:\n    \"\"\"Build the common wheels needed by tests.\"\"\"\n    get_common_wheels(session)\n\n\n@nox.session(python=[\"3.9\", \"3.10\", \"3.11\", \"3.12\", \"3.13\", \"3.14\", \"3.15\", \"pypy3\"])\ndef test(session: nox.Session) -> None:\n    # Get the common wheels.\n    get_common_wheels(session)\n\n    # Build source distribution\n    # HACK: we want to skip building and installing pip when nox's --no-install\n    # flag is given (to save time when running tests back to back with different\n    # arguments), but unfortunately nox does not expose this configuration state\n    # yet. https://github.com/wntrblm/nox/issues/710\n    no_install = \"-R\" in sys.argv or \"--no-install\" in sys.argv\n    sdist_dir = os.path.join(session.virtualenv.location, \"sdist\")\n    if not no_install and os.path.exists(sdist_dir):\n        shutil.rmtree(sdist_dir, ignore_errors=True)\n\n    run_with_protected_pip(session, \"install\", \"build\")\n    # build uses the pip present in the outer environment (aka the nox environment)\n    # as an optimization. This will crash if the last test run installed a broken\n    # pip, so uninstall pip to force build to provision a known good version of pip.\n    run_with_protected_pip(session, \"uninstall\", \"pip\", \"-y\")\n    # fmt: off\n    session.run_install(\n        \"python\", \"-I\", \"-m\", \"build\", \"--sdist\", \"--outdir\", sdist_dir,\n        silent=True,\n    )\n    # fmt: on\n\n    generated_files = os.listdir(sdist_dir)\n    assert len(generated_files) == 1\n    generated_sdist = os.path.join(sdist_dir, generated_files[0])\n\n    # Install source distribution\n    run_with_protected_pip(session, \"install\", generated_sdist)\n\n    # Install test dependencies\n    run_with_protected_pip(session, \"install\", \"--group\", \"test\")\n\n    # Parallelize tests as much as possible, by default.\n    arguments = session.posargs or [\"-n\", \"auto\"]\n\n    # Run the tests\n    #   LC_CTYPE is set to get UTF-8 output inside of the subprocesses that our\n    #   tests use.\n    session.run(\n        \"pytest\",\n        *arguments,\n        env={\n            \"LC_CTYPE\": \"en_US.UTF-8\",\n        },\n    )\n\n\n@nox.session\ndef docs(session: nox.Session) -> None:\n    session.install(\"-e\", \".\")\n    session.install(\"--group\", \"docs\")\n\n    def get_sphinx_build_command(kind: str) -> list[str]:\n        # Having the conf.py in the docs/html is weird but needed because we\n        # can not use a different configuration directory vs source directory\n        # on RTD currently. So, we'll pass \"-c docs/html\" here.\n        # See https://github.com/rtfd/readthedocs.org/issues/1543.\n        # fmt: off\n        return [\n            \"sphinx-build\",\n            \"--keep-going\",\n            \"--tag\", kind,\n            \"-W\",\n            \"-c\", \"docs/html\",  # see note above\n            \"-d\", \"docs/build/doctrees/\" + kind,\n            \"-b\", kind,\n            \"--jobs\", \"auto\",\n            \"docs/\" + kind,\n            \"docs/build/\" + kind,\n        ]\n        # fmt: on\n\n    shutil.rmtree(\"docs/build\", ignore_errors=True)\n    session.run(*get_sphinx_build_command(\"html\"))\n    session.run(*get_sphinx_build_command(\"man\"))\n\n\n@nox.session(name=\"docs-live\")\ndef docs_live(session: nox.Session) -> None:\n    session.install(\"-e\", \".\")\n    session.install(\"--group\", \"docs\", \"sphinx-autobuild\")\n\n    session.run(\n        \"sphinx-autobuild\",\n        \"-d=docs/build/doctrees/livehtml\",\n        \"-b=dirhtml\",\n        \"docs/html\",\n        \"docs/build/livehtml\",\n        \"--jobs=auto\",\n        *session.posargs,\n    )\n\n\n@nox.session\ndef lint(session: nox.Session) -> None:\n    session.install(\"pre-commit\")\n\n    if session.posargs:\n        args = session.posargs + [\"--all-files\"]\n    else:\n        args = [\"--all-files\", \"--show-diff-on-failure\"]\n\n    session.run(\"pre-commit\", \"run\", *args)\n\n\n# NOTE: This session will COMMIT upgrades to vendored libraries.\n# You should therefore not run it directly against `main`. If you\n# do (assuming you started with a clean main), you can run:\n#\n# git checkout -b vendoring-updates\n# git checkout main\n# git reset --hard origin/main\n@nox.session\ndef vendoring(session: nox.Session) -> None:\n    # Ensure that the session Python is running 3.10+\n    # so that truststore can be installed correctly.\n    session.run(\n        \"python\", \"-c\", \"import sys; sys.exit(1 if sys.version_info < (3, 10) else 0)\"\n    )\n\n    parser = argparse.ArgumentParser(prog=\"nox -s vendoring\")\n    parser.add_argument(\"--upgrade-all\", action=\"store_true\")\n    parser.add_argument(\"--upgrade\", action=\"append\", default=[])\n    parser.add_argument(\"--skip\", action=\"append\", default=[])\n    args = parser.parse_args(session.posargs)\n\n    session.install(\"vendoring~=1.2.0\")\n\n    if not (args.upgrade or args.upgrade_all):\n        session.run(\"vendoring\", \"sync\", \"-v\")\n        return\n\n    def pinned_requirements(path: Path) -> Iterator[tuple[str, str]]:\n        for line in path.read_text().splitlines(keepends=False):\n            one, sep, two = line.partition(\"==\")\n            if not sep:\n                continue\n            name = one.strip()\n            version = two.split(\"#\", 1)[0].strip()\n            if name and version:\n                yield name, version\n\n    vendor_txt = Path(\"src/pip/_vendor/vendor.txt\")\n    for name, old_version in pinned_requirements(vendor_txt):\n        if name in args.skip:\n            continue\n        if args.upgrade and name not in args.upgrade:\n            continue\n\n        # update requirements.txt\n        session.run(\"vendoring\", \"update\", \".\", name)\n\n        # get the updated version\n        new_version = old_version\n        for inner_name, inner_version in pinned_requirements(vendor_txt):\n            if inner_name == name:\n                # this is a dedicated assignment, to make lint happy\n                new_version = inner_version\n                break\n        else:\n            session.error(f\"Could not find {name} in {vendor_txt}\")\n\n        # check if the version changed.\n        if new_version == old_version:\n            continue  # no change, nothing more to do here.\n\n        # synchronize the contents\n        session.run(\"vendoring\", \"sync\", \".\")\n\n        # Determine the correct message\n        message = f\"Upgrade {name} to {new_version}\"\n\n        # Write our news fragment\n        news_file = Path(\"news\") / (name + \".vendor.rst\")\n        news_file.write_text(message + \"\\n\")  # \"\\n\" appeases end-of-line-fixer\n\n        # Commit the changes\n        release.commit_file(session, \".\", message=message)\n\n\n@nox.session\ndef coverage(session: nox.Session) -> None:\n    # Install source distribution\n    run_with_protected_pip(session, \"install\", \".\")\n\n    # Install test dependencies\n    run_with_protected_pip(session, \"install\", \"--group\", \"tests\")\n\n    if not os.path.exists(\".coverage-output\"):\n        os.mkdir(\".coverage-output\")\n    session.run(\n        \"pytest\",\n        \"--cov=pip\",\n        \"--cov-config=./setup.cfg\",\n        *session.posargs,\n        env={\n            \"COVERAGE_OUTPUT_DIR\": \"./.coverage-output\",\n            \"COVERAGE_PROCESS_START\": os.fsdecode(Path(\"setup.cfg\").resolve()),\n        },\n    )\n\n\n# -----------------------------------------------------------------------------\n# Release Commands\n# -----------------------------------------------------------------------------\n@nox.session(name=\"prepare-release\")\ndef prepare_release(session: nox.Session) -> None:\n    version = release.get_version_from_arguments(session)\n    if not version:\n        session.error(\"Usage: nox -s prepare-release -- <version>\")\n\n    session.log(\"# Ensure nothing is staged\")\n    if release.modified_files_in_git(\"--staged\"):\n        session.error(\"There are files staged in git\")\n\n    session.log(f\"# Updating {AUTHORS_FILE}\")\n    release.generate_authors(AUTHORS_FILE)\n    if release.modified_files_in_git():\n        release.commit_file(session, AUTHORS_FILE, message=f\"Update {AUTHORS_FILE}\")\n    else:\n        session.log(f\"# No changes to {AUTHORS_FILE}\")\n\n    session.log(\"# Generating NEWS\")\n    release.generate_news(session, version)\n    if sys.stdin.isatty():\n        input(\n            \"Please review the NEWS file, make necessary edits, and stage them.\\n\"\n            \"Press Enter to continue...\"\n        )\n\n    session.log(f\"# Bumping for release {version}\")\n    release.update_version_file(version, VERSION_FILE)\n    release.commit_file(session, VERSION_FILE, message=\"Bump for release\")\n\n    session.log(\"# Tagging release\")\n    release.create_git_tag(session, version, message=f\"Release {version}\")\n\n    session.log(\"# Bumping for development\")\n    next_dev_version = release.get_next_development_version(version)\n    release.update_version_file(next_dev_version, VERSION_FILE)\n    release.commit_file(session, VERSION_FILE, message=\"Bump for development\")\n\n\n@nox.session(name=\"build-release\")\ndef build_release(session: nox.Session) -> None:\n    version = release.get_version_from_arguments(session)\n    if not version:\n        session.error(\"Usage: nox -s build-release -- YY.N[.P]\")\n\n    session.log(\"# Ensure no files in dist/\")\n    if release.have_files_in_folder(\"dist\"):\n        session.error(\n            \"There are files in dist/. Remove them and try again. \"\n            \"You can use `git clean -fxdi -- dist` command to do this\"\n        )\n\n    session.log(\"# Install dependencies\")\n    session.install(\"twine\")\n\n    with release.isolated_temporary_checkout(session, version) as build_dir:\n        session.log(\n            \"# Start the build in an isolated, \"\n            f\"temporary Git checkout at {build_dir!s}\",\n        )\n        with release.workdir(session, build_dir):\n            tmp_dists = build_dists(session)\n\n        tmp_dist_paths = (build_dir / p for p in tmp_dists)\n        session.log(f\"# Copying dists from {build_dir}\")\n        os.makedirs(\"dist\", exist_ok=True)\n        for dist, final in zip(tmp_dist_paths, tmp_dists):\n            session.log(f\"# Copying {dist} to {final}\")\n            shutil.copy(dist, final)\n\n\ndef build_dists(session: nox.Session) -> list[str]:\n    \"\"\"Return dists with valid metadata.\"\"\"\n    session.log(\n        \"# Check if there's any Git-untracked files before building the wheel\",\n    )\n\n    has_forbidden_git_untracked_files = any(\n        # Don't report the environment this session is running in\n        not untracked_file.startswith(\".nox/build-release/\")\n        for untracked_file in release.get_git_untracked_files()\n    )\n    if has_forbidden_git_untracked_files:\n        session.error(\n            \"There are untracked files in the working directory. \"\n            \"Remove them and try again\",\n        )\n\n    session.log(\"# Build distributions\")\n    session.run(\"python\", \"build-project/build-project.py\", silent=True)\n    produced_dists = glob.glob(\"dist/*\")\n\n    session.log(f\"# Verify distributions: {', '.join(produced_dists)}\")\n    session.run(\"twine\", \"check\", \"--strict\", *produced_dists, silent=True)\n\n    return produced_dists\n\n\n@nox.session(name=\"upload-release\")\ndef upload_release(session: nox.Session) -> None:\n    version = release.get_version_from_arguments(session)\n    if not version:\n        session.error(\"Usage: nox -s upload-release -- YY.N[.P]\")\n\n    session.log(\"# Install dependencies\")\n    session.install(\"twine\")\n\n    distribution_files = glob.glob(\"dist/*\")\n    session.log(f\"# Distribution files: {distribution_files}\")\n\n    # Sanity check: Make sure there's 2 distribution files.\n    count = len(distribution_files)\n    if count != 2:\n        session.error(\n            f\"Expected 2 distribution files for upload, got {count}. \"\n            f\"Remove dist/ and run 'nox -s build-release -- {version}'\"\n        )\n    # Sanity check: Make sure the files are correctly named.\n    distfile_names = (os.path.basename(fn) for fn in distribution_files)\n    expected_distribution_files = [\n        f\"pip-{version}-py3-none-any.whl\",\n        f\"pip-{version}.tar.gz\",\n    ]\n    if sorted(distfile_names) != sorted(expected_distribution_files):\n        session.error(f\"Distribution files do not seem to be for {version} release.\")\n\n    session.log(\"# Upload distributions\")\n    session.run(\"twine\", \"upload\", *distribution_files)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\ndynamic = [\"version\"]\nname = \"pip\"\ndescription = \"The PyPA recommended tool for installing Python packages.\"\nreadme = \"README.rst\"\nlicense = \"MIT\"\nlicense-files = [\n  \"AUTHORS.txt\",\n  \"LICENSE.txt\",\n  \"src/pip/_vendor/**/*COPYING*\",\n  \"src/pip/_vendor/**/*LICENSE*\",\n]\nclassifiers = [\n  \"Development Status :: 5 - Production/Stable\",\n  \"Intended Audience :: Developers\",\n  \"Topic :: Software Development :: Build Tools\",\n  \"Programming Language :: Python\",\n  \"Programming Language :: Python :: 3\",\n  \"Programming Language :: Python :: 3 :: Only\",\n  \"Programming Language :: Python :: 3.9\",\n  \"Programming Language :: Python :: 3.10\",\n  \"Programming Language :: Python :: 3.11\",\n  \"Programming Language :: Python :: 3.12\",\n  \"Programming Language :: Python :: 3.13\",\n  \"Programming Language :: Python :: 3.14\",\n  \"Programming Language :: Python :: Implementation :: CPython\",\n  \"Programming Language :: Python :: Implementation :: PyPy\",\n]\nauthors = [\n  {name = \"The pip developers\", email = \"distutils-sig@python.org\"},\n]\n\n# NOTE: requires-python is duplicated in __pip-runner__.py.\n# When changing this value, please change the other copy as well.\nrequires-python = \">=3.9\"\n\n[project.scripts]\npip = \"pip._internal.cli.main:main\"\npip3 = \"pip._internal.cli.main:main\"\n\n[project.urls]\nHomepage = \"https://pip.pypa.io/\"\nDocumentation = \"https://pip.pypa.io\"\nSource = \"https://github.com/pypa/pip\"\nChangelog = \"https://pip.pypa.io/en/stable/news/\"\n\n[build-system]\nrequires = [\"flit-core >=3.11,<4\"]\nbuild-backend = \"flit_core.buildapi\"\n\n[dependency-groups]\ntest = [\n    \"cryptography\",\n    \"flit-core >= 3.11, < 4\",\n    \"freezegun\",\n    \"installer\",\n    # pytest-subket requires 7.0+\n    \"pytest >= 7.0\",\n    \"pytest-cov\",\n    \"pytest-rerunfailures\",\n    \"pytest-xdist\",\n    \"pytest-subket\",\n    \"scripttest\",\n    \"setuptools\",\n    # macOS (darwin) arm64 always uses virtualenv >= 20.0\n    # for other platforms, it depends on python version\n    \"virtualenv < 20.0 ; python_version < '3.10' and (sys_platform != 'darwin' or platform_machine != 'arm64')\",\n    \"virtualenv >= 20.0 ; python_version >= '3.10' or (sys_platform == 'darwin' and platform_machine == 'arm64')\",\n    \"werkzeug\",\n    \"tomli-w\",\n    \"proxy.py\",\n]\n\ntest-common-wheels = [\n    \"flit-core >= 3.11, < 4\",\n    # We pin setuptools<80 because our test suite currently\n    # depends on setup.py develop to generate egg-link files.\n    \"setuptools >= 70.1.0, <80\",\n    # As required by pytest-cov.\n    \"coverage >= 4.4\",\n    \"pytest-subket >= 0.8.1\",\n    \"keyring\",\n]\n\ndocs = [\n    \"sphinx ~= 7.0\",\n    # currently incompatible with sphinxcontrib-towncrier\n    # https://github.com/sphinx-contrib/sphinxcontrib-towncrier/issues/92\n    \"towncrier < 24\",\n    \"furo\",\n    \"myst_parser\",\n    \"sphinx-copybutton\",\n    \"sphinx-inline-tabs\",\n    \"sphinxcontrib-towncrier >= 0.2.0a0\",\n    \"sphinx-issues\",\n]\n\n[tool.flit.sdist]\ninclude = [\n    \"NEWS.rst\",\n    \"SECURITY.md\",\n    \"AI_POLICY.md\",\n    \"build-project/.python-version\",\n    \"build-project/build-project.py\",\n    \"build-project/build-requirements.in\",\n    \"build-project/build-requirements.txt\",\n    \"docs/**/*.css\",\n    \"docs/**/*.dot\",\n    \"docs/**/*.md\",\n    \"docs/**/*.png\",\n    \"docs/**/*.py\",\n    \"docs/**/*.rst\",\n]\nexclude = [\n    \".devcontainer/devcontainer.json\",\n    \"src/pip/_vendor/**/*.pyi\",\n]\n\n######################################################################################\n# towncrier\n#\n\n[tool.towncrier]\n# For finding the __version__\npackage = \"pip\"\npackage_dir = \"src\"\n# For writing into the correct file\nfilename = \"NEWS.rst\"\n# For finding the news fragments\ndirectory = \"news/\"\n\n# For rendering properly for this project\nissue_format = \"`#{issue} <https://github.com/pypa/pip/issues/{issue}>`_\"\ntemplate = \"tools/news/template.rst\"\n\n# Grouping of entries, within our changelog\ntype = [\n  { name = \"Deprecations and Removals\", directory = \"removal\", showcontent = true },\n  { name = \"Features\",                  directory = \"feature\", showcontent = true },\n  { name = \"Bug Fixes\",                 directory = \"bugfix\",  showcontent = true },\n  { name = \"Vendored Libraries\",        directory = \"vendor\",  showcontent = true },\n  { name = \"Improved Documentation\",    directory = \"doc\",     showcontent = true },\n  { name = \"Process\",                   directory = \"process\", showcontent = true },\n  { name = \"Trivial Changes\",           directory = \"trivial\", showcontent = false },\n]\n\n######################################################################################\n# vendoring\n#\n\n[tool.vendoring]\ndestination = \"src/pip/_vendor/\"\nrequirements = \"src/pip/_vendor/vendor.txt\"\nnamespace = \"pip._vendor\"\n\nprotected-files = [\"__init__.py\", \"README.rst\", \"vendor.txt\"]\npatches-dir = \"tools/vendoring/patches\"\n\n[tool.vendoring.transformations]\nsubstitute = [\n  # pkg_resource's vendored packages are directly vendored in pip.\n  { match='pkg_resources\\.extern', replace=\"pip._vendor\" },\n  { match='from \\.extern', replace=\"from pip._vendor\" },\n  { match='''\\('pygments\\.lexers\\.''', replace=\"('pip._vendor.pygments.lexers.\" },\n]\ndrop = [\n  # contains unnecessary scripts\n  \"bin/\",\n  # interpreter and OS specific msgpack libs\n  \"msgpack/*.so\",\n  # optional accelerator extension libraries\n  \"*mypyc*.so\",\n  \"tomli/*.so\",\n  # unneeded parts of setuptools\n  \"easy_install.py\",\n  \"setuptools\",\n  \"pkg_resources/_vendor/\",\n  \"_distutils_hack\",\n  \"distutils-precedence.pth\",\n  \"pkg_resources/extern/\",\n  # trim vendored pygments styles, lexers, formatters, and CLI\n  \"pygments/styles/[!_]*.py\",\n  '^pygments/lexers/(?!python|__init__|_mapping).*\\.py$',\n  '^pygments/formatters/(?!__init__|_mapping).*\\.py$',\n  '^pygments/cmdline\\.py$',\n  # trim rich's markdown support\n  \"rich/markdown.py\",\n  # trim parts of distlib that aren't related to scripts\n  '^distlib/(?!__init__|compat|resources|scripts|util).*\\.py$',\n]\n\n[tool.vendoring.typing-stubs]\ndistro = []\n\n[tool.vendoring.license.directories]\nsetuptools = \"pkg_resources\"\n\n[tool.vendoring.license.fallback-urls]\ndistlib = \"https://bitbucket.org/pypa/distlib/raw/master/LICENSE.txt\"\n\n######################################################################################\n# ruff\n#\n\n[tool.ruff]\n# Pinned to delay pyupgrade changes (https://github.com/pypa/pip/issues/13236)\ntarget-version = \"py39\"  # Pin Ruff to Python 3.9\nsrc = [\"src\"]\nline-length = 88\nextend-exclude = [\n    \"_vendor\",\n    \"./build\",\n    \".scratch\",\n    \"data\",\n]\n\n[tool.ruff.lint]\nignore = [\n    \"B020\",\n    \"B904\", # Ruff enables opinionated warnings by default\n    \"B905\", # Ruff enables opinionated warnings by default\n    \"C420\", # unnecessary-dict-comprehension-for-iterable (worsens readability)\n]\nselect = [\n    \"ASYNC\",\n    \"B\",\n    \"C4\",\n    \"C90\",\n    \"E\",\n    \"F\",\n    \"FA\",\n    \"G\",\n    \"I\",\n    \"ISC\",\n    \"PIE810\",\n    \"PLE\",\n    \"PLR0\",\n    \"RUF100\",\n    \"UP\",\n    \"W\",\n]\n\n[tool.ruff.lint.isort]\nsection-order = [\n  \"future\",\n  \"standard-library\",\n  \"third-party\",\n  \"vendored\",\n  \"first-party\",\n  \"tests\",\n  \"local-folder\",\n]\n\n[tool.ruff.lint.isort.sections]\n\"vendored\" = [\"pip._vendor\"]\n\"tests\" = [\"tests\"]\n\n[tool.ruff.lint.mccabe]\nmax-complexity = 33  # default is 10\n\n[tool.ruff.lint.per-file-ignores]\n\"noxfile.py\" = [\"G\"]\n\"src/pip/_internal/*\" = [\"PERF203\"]\n\"tests/*\" = [\"B011\"]\n\"tests/unit/test_finder.py\" = [\"C414\"]\n\"src/pip/__pip-runner__.py\" = [\"UP\"] # Must be compatible with Python 2.7\n\n[tool.ruff.lint.pylint]\nmax-args = 15  # default is 5\nmax-branches = 28  # default is 12\nmax-returns = 15  # default is 6\nmax-statements = 134  # default is 50\n\n[tool.ruff.per-file-target-version]\n# `__pip-runner__.py` should be Python 2.7 compatible but the\n# earliest version of Python ruff will check is 3.7\n\"src/pip/__pip-runner__.py\" = \"py37\"\n\n######################################################################################\n# mypy\n#\n\n[tool.mypy]\nmypy_path = \"$MYPY_CONFIG_FILE_DIR/src\"\nstrict = true\nno_implicit_reexport = false\ndisallow_subclassing_any = false\ndisallow_untyped_calls = false\nwarn_return_any = false\nignore_missing_imports = true\n\n[[tool.mypy.overrides]]\nmodule = \"pip._internal.utils._jaraco_text\"\nignore_errors = true\n\n[[tool.mypy.overrides]]\nmodule = \"pip._vendor.*\"\nignore_errors = true\n\n# These vendored libraries use runtime magic to populate things and don't sit\n# well with static typing out of the box. Eventually we should provide correct\n# typing information for their public interface and remove these configs.\n\n[[tool.mypy.overrides]]\nmodule = \"pip._vendor.pkg_resources\"\nfollow_imports = \"skip\"\n\n[[tool.mypy.overrides]]\nmodule = \"pip._vendor.requests.*\"\nfollow_imports = \"skip\"\n\n######################################################################################\n# pytest\n#\n\n[tool.pytest.ini_options]\naddopts = [\n    \"-r=aR\",\n    \"--color=yes\",\n    \"--ignore=src/pip/_vendor\",\n    \"--ignore=tests/tests_cache\",\n    \"--disable-socket\",\n    \"--allow-unix-socket\",\n    \"--allow-hosts=localhost\",\n]\nxfail_strict = true\nmarkers = [\n    \"network: tests that need network\",\n    \"incompatible_with_sysconfig\",\n    \"incompatible_with_venv\",\n    \"no_auto_tempdir_manager\",\n    \"unit: unit tests\",\n    \"integration: integration tests\",\n    \"bzr: VCS: Bazaar\",\n    \"svn: VCS: Subversion\",\n    \"mercurial: VCS: Mercurial\",\n    \"git: VCS: git\",\n    \"search: tests for 'pip search'\",\n]\n\n######################################################################################\n# coverage\n#\n\n[tool.coverage.run]\nbranch = true\n# Do not gather coverage for vendored libraries.\nomit = \"*/_vendor/*\"\n# Centralized absolute file prefix for coverage files.\ndata_file = \"${COVERAGE_OUTPUT_DIR}/.coverage\"\n# By default, each covered process will try to truncate and then write to\n# `data_file`, but with `parallel`, they will write to separate files suffixed\n# with hostname, pid, and a timestamp.\nparallel = true\n# If not set, then at the termination of each worker (when using pytest-xdist),\n# the following is traced: \"Coverage.py warning: Module pip was previously\n# imported, but not measured (module-not-measured)\"\ndisable_warnings = \"module-not-measured\"\n\n[tool.coverage.paths]\n# We intentionally use \"source0\" here because pytest-cov unconditionally sets\n# \"source\" after loading the config.\nsource0 = [\n    # The primary source code path which other paths will be combined into.\n    \"src/pip/\",\n    # Unit test source directory e.g.\n    # `.tox/coverage-py3/lib/pythonX.Y/site-packages/pip/...`\n    \"*/site-packages/pip/\",\n    # Functional test virtual environment directories, which look like\n    # `tmpdir/pip0/pip/src/pip/...`\n    \"*/pip/src/pip/\",\n]\n\n[tool.coverage.report]\nexclude_also = [\n    # This excludes typing-specific code, which will be validated by mypy anyway.\n    \"if TYPE_CHECKING\",\n]\n\n[tool.check-sdist]\ngit-only = [\n  \"tests/**\",\n  \"tools/**\",\n  \"news/.gitignore\",\n  \".devcontainer/**\",\n  \".gitattributes\",\n  \".gitignore\",\n  \".git-blame-ignore-revs\",\n  \".mailmap\",\n  \".readthedocs-custom-redirects.yml\"\n]\n"
  },
  {
    "path": "src/pip/__init__.py",
    "content": "from __future__ import annotations\n\n__version__ = \"26.1.dev0\"\n\n\ndef main(args: list[str] | None = None) -> int:\n    \"\"\"This is an internal API only meant for use by pip's own console scripts.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "src/pip/__main__.py",
    "content": "import os\nimport sys\n\n# Remove '' and current working directory from the first entry\n# of sys.path, if present to avoid using current directory\n# in pip commands check, freeze, install, list and show,\n# when invoked as python -m pip <command>\nif sys.path[0] in (\"\", os.getcwd()):\n    sys.path.pop(0)\n\n# If we are running from a wheel, add the wheel to sys.path\n# This allows the usage python pip-*.whl/pip install pip-*.whl\nif __package__ == \"\":\n    # __file__ is pip-*.whl/pip/__main__.py\n    # first dirname call strips of '/__main__.py', second strips off '/pip'\n    # Resulting path is the name of the wheel itself\n    # Add that to sys.path so we can import pip\n    path = os.path.dirname(os.path.dirname(__file__))\n    sys.path.insert(0, path)\n\nif __name__ == \"__main__\":\n    from pip._internal.cli.main import main as _main\n\n    sys.exit(_main())\n"
  },
  {
    "path": "src/pip/__pip-runner__.py",
    "content": "\"\"\"Execute exactly this copy of pip, within a different environment.\n\nThis file is named as it is, to ensure that this module can't be imported via\nan import statement.\n\"\"\"\n\n# /!\\ This version compatibility check section must be Python 2 compatible. /!\\\n\nimport sys\n\n# Copied from pyproject.toml\nPYTHON_REQUIRES = (3, 9)\n\n\ndef version_str(version):  # type: ignore\n    return \".\".join(str(v) for v in version)\n\n\nif sys.version_info[:2] < PYTHON_REQUIRES:\n    raise SystemExit(\n        \"This version of pip does not support python {} (requires >={}).\".format(\n            version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES)\n        )\n    )\n\n# From here on, we can use Python 3 features, but the syntax must remain\n# Python 2 compatible.\n\nimport runpy  # noqa: E402\nfrom importlib.machinery import PathFinder  # noqa: E402\nfrom os.path import dirname  # noqa: E402\n\nPIP_SOURCES_ROOT = dirname(dirname(__file__))\n\n\nclass PipImportRedirectingFinder:\n    @classmethod\n    def find_spec(self, fullname, path=None, target=None):  # type: ignore\n        if fullname != \"pip\":\n            return None\n\n        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)\n        assert spec, (PIP_SOURCES_ROOT, fullname)\n        return spec\n\n\nsys.meta_path.insert(0, PipImportRedirectingFinder())\n\nassert __name__ == \"__main__\", \"Cannot run __pip-runner__.py as a non-main module\"\nrunpy.run_module(\"pip\", run_name=\"__main__\", alter_sys=True)\n"
  },
  {
    "path": "src/pip/_internal/__init__.py",
    "content": "from __future__ import annotations\n\nfrom pip._internal.utils import _log\n\n# init_logging() must be called before any call to logging.getLogger()\n# which happens at import of most modules.\n_log.init_logging()\n\n\ndef main(args: list[str] | None = None) -> int:\n    \"\"\"This is preserved for old console scripts that may still be referencing\n    it.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "src/pip/_internal/build_env.py",
    "content": "\"\"\"Build Environment used for isolation during sdist building\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport pathlib\nimport site\nimport sys\nimport textwrap\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Sequence\nfrom contextlib import AbstractContextManager as ContextManager\nfrom contextlib import nullcontext\nfrom io import StringIO\nfrom types import TracebackType\nfrom typing import TYPE_CHECKING, Protocol, TypedDict\n\nfrom pip._vendor.packaging.version import Version\n\nfrom pip import __file__ as pip_location\nfrom pip._internal.cli.spinners import open_rich_spinner, open_spinner\nfrom pip._internal.exceptions import (\n    BuildDependencyInstallError,\n    DiagnosticPipError,\n    InstallWheelBuildError,\n    PipError,\n)\nfrom pip._internal.locations import get_platlib, get_purelib, get_scheme\nfrom pip._internal.metadata import get_default_environment, get_environment\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.logging import VERBOSE, capture_logging\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.subprocess import call_subprocess\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\n\nif TYPE_CHECKING:\n    from pip._internal.cache import WheelCache\n    from pip._internal.index.package_finder import PackageFinder\n    from pip._internal.operations.build.build_tracker import BuildTracker\n    from pip._internal.req.req_install import InstallRequirement\n    from pip._internal.resolution.base import BaseResolver\n\n    class ExtraEnviron(TypedDict, total=False):\n        extra_environ: dict[str, str]\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _dedup(a: str, b: str) -> tuple[str] | tuple[str, str]:\n    return (a, b) if a != b else (a,)\n\n\nclass _Prefix:\n    def __init__(self, path: str) -> None:\n        self.path = path\n        self.setup = False\n        scheme = get_scheme(\"\", prefix=path)\n        self.bin_dir = scheme.scripts\n        self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)\n\n\ndef get_runnable_pip() -> str:\n    \"\"\"Get a file to pass to a Python executable, to run the currently-running pip.\n\n    This is used to run a pip subprocess, for installing requirements into the build\n    environment.\n    \"\"\"\n    source = pathlib.Path(pip_location).resolve().parent\n\n    if not source.is_dir():\n        # This would happen if someone is using pip from inside a zip file. In that\n        # case, we can use that directly.\n        return str(source)\n\n    return os.fsdecode(source / \"__pip-runner__.py\")\n\n\ndef _get_system_sitepackages() -> set[str]:\n    \"\"\"Get system site packages\n\n    Usually from site.getsitepackages,\n    but fallback on `get_purelib()/get_platlib()` if unavailable\n    (e.g. in a virtualenv created by virtualenv<20)\n\n    Returns normalized set of strings.\n    \"\"\"\n    if hasattr(site, \"getsitepackages\"):\n        system_sites = site.getsitepackages()\n    else:\n        # virtualenv < 20 overwrites site.py without getsitepackages\n        # fallback on get_purelib/get_platlib.\n        # this is known to miss things, but shouldn't in the cases\n        # where getsitepackages() has been removed (inside a virtualenv)\n        system_sites = [get_purelib(), get_platlib()]\n    return {os.path.normcase(path) for path in system_sites}\n\n\nclass BuildEnvironmentInstaller(Protocol):\n    \"\"\"\n    Interface for installing build dependencies into an isolated build\n    environment.\n    \"\"\"\n\n    def install(\n        self,\n        requirements: Iterable[str],\n        prefix: _Prefix,\n        *,\n        kind: str,\n        for_req: InstallRequirement | None,\n    ) -> None: ...\n\n\nclass SubprocessBuildEnvironmentInstaller:\n    \"\"\"\n    Install build dependencies by calling pip in a subprocess.\n    \"\"\"\n\n    def __init__(\n        self,\n        finder: PackageFinder,\n        build_constraints: list[str] | None = None,\n        build_constraint_feature_enabled: bool = False,\n    ) -> None:\n        self.finder = finder\n        self._build_constraints = build_constraints or []\n        self._build_constraint_feature_enabled = build_constraint_feature_enabled\n\n    def _deprecation_constraint_check(self) -> None:\n        \"\"\"\n        Check for deprecation warning: PIP_CONSTRAINT affecting build environments.\n\n        This warns when build-constraint feature is NOT enabled and PIP_CONSTRAINT\n        is not empty.\n        \"\"\"\n        if self._build_constraint_feature_enabled or self._build_constraints:\n            return\n\n        pip_constraint = os.environ.get(\"PIP_CONSTRAINT\")\n        if not pip_constraint or not pip_constraint.strip():\n            return\n\n        deprecated(\n            reason=(\n                \"Setting PIP_CONSTRAINT will not affect \"\n                \"build constraints in the future,\"\n            ),\n            replacement=(\n                \"to specify build constraints using --build-constraint or \"\n                \"PIP_BUILD_CONSTRAINT. To disable this warning without \"\n                \"any build constraints set --use-feature=build-constraint or \"\n                'PIP_USE_FEATURE=\"build-constraint\"'\n            ),\n            gone_in=\"26.2\",\n            issue=None,\n        )\n\n    def install(\n        self,\n        requirements: Iterable[str],\n        prefix: _Prefix,\n        *,\n        kind: str,\n        for_req: InstallRequirement | None,\n    ) -> None:\n        self._deprecation_constraint_check()\n\n        finder = self.finder\n        args: list[str] = [\n            sys.executable,\n            get_runnable_pip(),\n            \"install\",\n            \"--ignore-installed\",\n            \"--no-user\",\n            \"--prefix\",\n            prefix.path,\n            \"--no-warn-script-location\",\n            \"--disable-pip-version-check\",\n            # As the build environment is ephemeral, it's wasteful to\n            # pre-compile everything, especially as not every Python\n            # module will be used/compiled in most cases.\n            \"--no-compile\",\n            # The prefix specified two lines above, thus\n            # target from config file or env var should be ignored\n            \"--target\",\n            \"\",\n        ]\n        if logger.getEffectiveLevel() <= logging.DEBUG:\n            args.append(\"-vv\")\n        elif logger.getEffectiveLevel() <= VERBOSE:\n            args.append(\"-v\")\n        for format_control in (\"no_binary\", \"only_binary\"):\n            formats = getattr(finder.format_control, format_control)\n            args.extend(\n                (\n                    \"--\" + format_control.replace(\"_\", \"-\"),\n                    \",\".join(sorted(formats or {\":none:\"})),\n                )\n            )\n\n        if finder.release_control is not None:\n            # Use ordered args to preserve the user's original command-line order\n            # This is important because later flags can override earlier ones\n            for attr_name, value in finder.release_control.get_ordered_args():\n                args.extend((\"--\" + attr_name.replace(\"_\", \"-\"), value))\n\n        index_urls = finder.index_urls\n        if index_urls:\n            args.extend([\"-i\", index_urls[0]])\n            for extra_index in index_urls[1:]:\n                args.extend([\"--extra-index-url\", extra_index])\n        else:\n            args.append(\"--no-index\")\n        for link in finder.find_links:\n            args.extend([\"--find-links\", link])\n\n        if finder.proxy:\n            args.extend([\"--proxy\", finder.proxy])\n        for host in finder.trusted_hosts:\n            args.extend([\"--trusted-host\", host])\n        if finder.custom_cert:\n            args.extend([\"--cert\", finder.custom_cert])\n        if finder.client_cert:\n            args.extend([\"--client-cert\", finder.client_cert])\n        if finder.prefer_binary:\n            args.append(\"--prefer-binary\")\n\n        # Handle build constraints\n        if self._build_constraint_feature_enabled:\n            args.extend([\"--use-feature\", \"build-constraint\"])\n\n        if self._build_constraints:\n            # Build constraints must be passed as both constraints\n            # and build constraints, so that nested builds receive\n            # build constraints\n            for constraint_file in self._build_constraints:\n                args.extend([\"--constraint\", constraint_file])\n                args.extend([\"--build-constraint\", constraint_file])\n\n        extra_environ: ExtraEnviron = {}\n        if self._build_constraint_feature_enabled and not self._build_constraints:\n            # If there are no build constraints but the build constraints\n            # feature is enabled then we must ignore regular constraints\n            # in the isolated build environment\n            extra_environ = {\"extra_environ\": {\"_PIP_IN_BUILD_IGNORE_CONSTRAINTS\": \"1\"}}\n\n        if finder.uploaded_prior_to:\n            args.extend([\"--uploaded-prior-to\", finder.uploaded_prior_to.isoformat()])\n        args.append(\"--\")\n        args.extend(requirements)\n\n        identify_requirement = (\n            f\" for {for_req.name}\" if for_req and for_req.name else \"\"\n        )\n        with open_spinner(f\"Installing {kind}\") as spinner:\n            call_subprocess(\n                args,\n                command_desc=f\"installing {kind}{identify_requirement}\",\n                spinner=spinner,\n                **extra_environ,\n            )\n\n\nclass InprocessBuildEnvironmentInstaller:\n    \"\"\"\n    Build dependency installer that runs in the same pip process.\n\n    This contains a stripped down version of the install command with\n    only the logic necessary for installing build dependencies. The\n    finder, session, build tracker, and wheel cache are reused, but new\n    instances of everything else are created as needed.\n\n    Options are inherited from the parent install command unless\n    they don't make sense for build dependencies (in which case, they\n    are hard-coded, see comments below).\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        finder: PackageFinder,\n        build_tracker: BuildTracker,\n        wheel_cache: WheelCache,\n        build_constraints: Sequence[InstallRequirement] = (),\n        verbosity: int = 0,\n    ) -> None:\n        from pip._internal.operations.prepare import RequirementPreparer\n\n        self._finder = finder\n        self._build_constraints = build_constraints\n        self._wheel_cache = wheel_cache\n        self._level = 0\n\n        build_dir = TempDirectory(kind=\"build-env-install\", globally_managed=True)\n        self._preparer = RequirementPreparer(\n            build_isolation_installer=self,\n            # Inherited options or state.\n            finder=finder,\n            session=finder._link_collector.session,\n            build_dir=build_dir.path,\n            build_tracker=build_tracker,\n            verbosity=verbosity,\n            # This is irrelevant as it only applies to editable requirements.\n            src_dir=\"\",\n            # Hard-coded options (that should NOT be inherited).\n            download_dir=None,\n            build_isolation=True,\n            check_build_deps=False,\n            progress_bar=\"off\",\n            # TODO: hash-checking should be extended to build deps, but that is\n            # deferred for later as it'd be a breaking change.\n            require_hashes=False,\n            use_user_site=False,\n            lazy_wheel=False,\n            legacy_resolver=False,\n        )\n\n    def install(\n        self,\n        requirements: Iterable[str],\n        prefix: _Prefix,\n        *,\n        kind: str,\n        for_req: InstallRequirement | None,\n    ) -> None:\n        \"\"\"Install entrypoint. Manages output capturing and error handling.\"\"\"\n        capture_logs = not logger.isEnabledFor(VERBOSE) and self._level == 0\n        if capture_logs:\n            # Hide the logs from the installation of build dependencies.\n            # They will be shown only if an error occurs.\n            capture_ctx: ContextManager[StringIO] = capture_logging()\n            spinner: ContextManager[None] = open_rich_spinner(f\"Installing {kind}\")\n        else:\n            # Otherwise, pass-through all logs (with a header).\n            capture_ctx, spinner = nullcontext(StringIO()), nullcontext()\n            logger.info(\"Installing %s ...\", kind)\n\n        try:\n            self._level += 1\n            with spinner, capture_ctx as stream:\n                self._install_impl(requirements, prefix)\n\n        except DiagnosticPipError as exc:\n            # Format similar to a nested subprocess error, where the\n            # causing error is shown first, followed by the build error.\n            logger.info(textwrap.dedent(stream.getvalue()))\n            logger.error(\"%s\", exc, extra={\"rich\": True})\n            logger.info(\"\")\n            raise BuildDependencyInstallError(\n                for_req, requirements, cause=exc, log_lines=None\n            )\n\n        except Exception as exc:\n            logs: list[str] | None = textwrap.dedent(stream.getvalue()).splitlines()\n            if not capture_logs:\n                # If logs aren't being captured, then display the error inline\n                # with the rest of the logs.\n                logs = None\n                if isinstance(exc, PipError):\n                    logger.error(\"%s\", exc)\n                else:\n                    logger.exception(\"pip crashed unexpectedly\")\n            raise BuildDependencyInstallError(\n                for_req, requirements, cause=exc, log_lines=logs\n            )\n\n        finally:\n            self._level -= 1\n\n    def _install_impl(self, requirements: Iterable[str], prefix: _Prefix) -> None:\n        \"\"\"Core build dependency install logic.\"\"\"\n        from pip._internal.commands.install import installed_packages_summary\n        from pip._internal.req import install_given_reqs\n        from pip._internal.req.constructors import install_req_from_line\n        from pip._internal.wheel_builder import build\n\n        ireqs = [install_req_from_line(req, user_supplied=True) for req in requirements]\n        ireqs.extend(self._build_constraints)\n\n        resolver = self._make_resolver()\n        resolved_set = resolver.resolve(ireqs, check_supported_wheels=True)\n        self._preparer.prepare_linked_requirements_more(\n            resolved_set.requirements.values()\n        )\n\n        reqs_to_build = [\n            r for r in resolved_set.requirements_to_install if not r.is_wheel\n        ]\n        _, build_failures = build(reqs_to_build, self._wheel_cache, verify=True)\n        if build_failures:\n            raise InstallWheelBuildError(build_failures)\n\n        installed = install_given_reqs(\n            resolver.get_installation_order(resolved_set),\n            prefix=prefix.path,\n            # Hard-coded options (that should NOT be inherited).\n            root=None,\n            home=None,\n            warn_script_location=False,\n            use_user_site=False,\n            # As the build environment is ephemeral, it's wasteful to\n            # pre-compile everything since not all modules will be used.\n            pycompile=False,\n            progress_bar=\"off\",\n        )\n\n        env = get_environment(list(prefix.lib_dirs))\n        if summary := installed_packages_summary(installed, env):\n            logger.info(summary)\n\n    def _make_resolver(self) -> BaseResolver:\n        \"\"\"Create a new resolver for one time use.\"\"\"\n        # Legacy installer never used the legacy resolver so create a\n        # resolvelib resolver directly. Yuck.\n        from pip._internal.req.constructors import install_req_from_req_string\n        from pip._internal.resolution.resolvelib.resolver import Resolver\n\n        return Resolver(\n            make_install_req=install_req_from_req_string,\n            # Inherited state.\n            preparer=self._preparer,\n            finder=self._finder,\n            wheel_cache=self._wheel_cache,\n            # Hard-coded options (that should NOT be inherited).\n            ignore_requires_python=False,\n            use_user_site=False,\n            ignore_dependencies=False,\n            ignore_installed=True,\n            force_reinstall=False,\n            upgrade_strategy=\"to-satisfy-only\",\n            py_version_info=None,\n        )\n\n\nclass BuildEnvironment:\n    \"\"\"Creates and manages an isolated environment to install build deps\"\"\"\n\n    def __init__(self, installer: BuildEnvironmentInstaller) -> None:\n        self.installer = installer\n        temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)\n\n        self._prefixes = OrderedDict(\n            (name, _Prefix(os.path.join(temp_dir.path, name)))\n            for name in (\"normal\", \"overlay\")\n        )\n\n        self._bin_dirs: list[str] = []\n        self._lib_dirs: list[str] = []\n        for prefix in reversed(list(self._prefixes.values())):\n            self._bin_dirs.append(prefix.bin_dir)\n            self._lib_dirs.extend(prefix.lib_dirs)\n\n        # Customize site to:\n        # - ensure .pth files are honored\n        # - prevent access to system site packages\n        system_sites = _get_system_sitepackages()\n\n        self._site_dir = os.path.join(temp_dir.path, \"site\")\n        if not os.path.exists(self._site_dir):\n            os.mkdir(self._site_dir)\n        with open(\n            os.path.join(self._site_dir, \"sitecustomize.py\"), \"w\", encoding=\"utf-8\"\n        ) as fp:\n            fp.write(\n                textwrap.dedent(\n                    \"\"\"\n                import os, site, sys\n\n                # First, drop system-sites related paths.\n                original_sys_path = sys.path[:]\n                known_paths = set()\n                for path in {system_sites!r}:\n                    site.addsitedir(path, known_paths=known_paths)\n                system_paths = set(\n                    os.path.normcase(path)\n                    for path in sys.path[len(original_sys_path):]\n                )\n                original_sys_path = [\n                    path for path in original_sys_path\n                    if os.path.normcase(path) not in system_paths\n                ]\n                sys.path = original_sys_path\n\n                # Second, add lib directories.\n                # ensuring .pth file are processed.\n                for path in {lib_dirs!r}:\n                    assert not path in sys.path\n                    site.addsitedir(path)\n                \"\"\"\n                ).format(system_sites=system_sites, lib_dirs=self._lib_dirs)\n            )\n\n    def __enter__(self) -> None:\n        self._save_env = {\n            name: os.environ.get(name, None)\n            for name in (\"PATH\", \"PYTHONNOUSERSITE\", \"PYTHONPATH\")\n        }\n\n        path = self._bin_dirs[:]\n        old_path = self._save_env[\"PATH\"]\n        if old_path:\n            path.extend(old_path.split(os.pathsep))\n\n        pythonpath = [self._site_dir]\n\n        os.environ.update(\n            {\n                \"PATH\": os.pathsep.join(path),\n                \"PYTHONNOUSERSITE\": \"1\",\n                \"PYTHONPATH\": os.pathsep.join(pythonpath),\n            }\n        )\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        for varname, old_value in self._save_env.items():\n            if old_value is None:\n                os.environ.pop(varname, None)\n            else:\n                os.environ[varname] = old_value\n\n    def check_requirements(\n        self, reqs: Iterable[str]\n    ) -> tuple[set[tuple[str, str]], set[str]]:\n        \"\"\"Return 2 sets:\n        - conflicting requirements: set of (installed, wanted) reqs tuples\n        - missing requirements: set of reqs\n        \"\"\"\n        missing = set()\n        conflicting = set()\n        if reqs:\n            env = (\n                get_environment(self._lib_dirs)\n                if hasattr(self, \"_lib_dirs\")\n                else get_default_environment()\n            )\n            for req_str in reqs:\n                req = get_requirement(req_str)\n                # We're explicitly evaluating with an empty extra value, since build\n                # environments are not provided any mechanism to select specific extras.\n                if req.marker is not None and not req.marker.evaluate({\"extra\": \"\"}):\n                    continue\n                dist = env.get_distribution(req.name)\n                if not dist:\n                    missing.add(req_str)\n                    continue\n                if isinstance(dist.version, Version):\n                    installed_req_str = f\"{req.name}=={dist.version}\"\n                else:\n                    installed_req_str = f\"{req.name}==={dist.version}\"\n                if not req.specifier.contains(dist.version, prereleases=True):\n                    conflicting.add((installed_req_str, req_str))\n                # FIXME: Consider direct URL?\n        return conflicting, missing\n\n    def install_requirements(\n        self,\n        requirements: Iterable[str],\n        prefix_as_string: str,\n        *,\n        kind: str,\n        for_req: InstallRequirement | None = None,\n    ) -> None:\n        prefix = self._prefixes[prefix_as_string]\n        assert not prefix.setup\n        prefix.setup = True\n        if not requirements:\n            return\n        self.installer.install(requirements, prefix, kind=kind, for_req=for_req)\n\n\nclass NoOpBuildEnvironment(BuildEnvironment):\n    \"\"\"A no-op drop-in replacement for BuildEnvironment\"\"\"\n\n    def __init__(self) -> None:\n        pass\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        pass\n\n    def cleanup(self) -> None:\n        pass\n\n    def install_requirements(\n        self,\n        requirements: Iterable[str],\n        prefix_as_string: str,\n        *,\n        kind: str,\n        for_req: InstallRequirement | None = None,\n    ) -> None:\n        raise NotImplementedError()\n"
  },
  {
    "path": "src/pip/_internal/cache.py",
    "content": "\"\"\"Cache Management\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Any\n\nfrom pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import InvalidWheelFilename\nfrom pip._internal.models.direct_url import DirectUrl\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\nfrom pip._internal.utils.urls import path_to_url\n\nlogger = logging.getLogger(__name__)\n\nORIGIN_JSON_NAME = \"origin.json\"\n\n\ndef _hash_dict(d: dict[str, str]) -> str:\n    \"\"\"Return a stable sha224 of a dictionary.\"\"\"\n    s = json.dumps(d, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=True)\n    return hashlib.sha224(s.encode(\"ascii\")).hexdigest()\n\n\nclass Cache:\n    \"\"\"An abstract class - provides cache directories for data from links\n\n    :param cache_dir: The root of the cache.\n    \"\"\"\n\n    def __init__(self, cache_dir: str) -> None:\n        super().__init__()\n        assert not cache_dir or os.path.isabs(cache_dir)\n        self.cache_dir = cache_dir or None\n\n    def _get_cache_path_parts(self, link: Link) -> list[str]:\n        \"\"\"Get parts of part that must be os.path.joined with cache_dir\"\"\"\n\n        # We want to generate an url to use as our cache key, we don't want to\n        # just reuse the URL because it might have other items in the fragment\n        # and we don't care about those.\n        key_parts = {\"url\": link.url_without_fragment}\n        if link.hash_name is not None and link.hash is not None:\n            key_parts[link.hash_name] = link.hash\n        if link.subdirectory_fragment:\n            key_parts[\"subdirectory\"] = link.subdirectory_fragment\n\n        # Include interpreter name, major and minor version in cache key\n        # to cope with ill-behaved sdists that build a different wheel\n        # depending on the python version their setup.py is being run on,\n        # and don't encode the difference in compatibility tags.\n        # https://github.com/pypa/pip/issues/7296\n        key_parts[\"interpreter_name\"] = interpreter_name()\n        key_parts[\"interpreter_version\"] = interpreter_version()\n\n        # Encode our key url with sha224, we'll use this because it has similar\n        # security properties to sha256, but with a shorter total output (and\n        # thus less secure). However the differences don't make a lot of\n        # difference for our use case here.\n        hashed = _hash_dict(key_parts)\n\n        # We want to nest the directories some to prevent having a ton of top\n        # level directories where we might run out of sub directories on some\n        # FS.\n        parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]\n\n        return parts\n\n    def _get_candidates(self, link: Link, canonical_package_name: str) -> list[Any]:\n        can_not_cache = not self.cache_dir or not canonical_package_name or not link\n        if can_not_cache:\n            return []\n\n        path = self.get_path_for_link(link)\n        if os.path.isdir(path):\n            return [(candidate, path) for candidate in os.listdir(path)]\n        return []\n\n    def get_path_for_link(self, link: Link) -> str:\n        \"\"\"Return a directory to store cached items in for link.\"\"\"\n        raise NotImplementedError()\n\n    def get(\n        self,\n        link: Link,\n        package_name: str | None,\n        supported_tags: list[Tag],\n    ) -> Link:\n        \"\"\"Returns a link to a cached item if it exists, otherwise returns the\n        passed link.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass SimpleWheelCache(Cache):\n    \"\"\"A cache of wheels for future installs.\"\"\"\n\n    def __init__(self, cache_dir: str) -> None:\n        super().__init__(cache_dir)\n\n    def get_path_for_link(self, link: Link) -> str:\n        \"\"\"Return a directory to store cached wheels for link\n\n        Because there are M wheels for any one sdist, we provide a directory\n        to cache them in, and then consult that directory when looking up\n        cache hits.\n\n        We only insert things into the cache if they have plausible version\n        numbers, so that we don't contaminate the cache with things that were\n        not unique. E.g. ./package might have dozens of installs done for it\n        and build a version of 0.0...and if we built and cached a wheel, we'd\n        end up using the same wheel even if the source has been edited.\n\n        :param link: The link of the sdist for which this will cache wheels.\n        \"\"\"\n        parts = self._get_cache_path_parts(link)\n        assert self.cache_dir\n        # Store wheels within the root cache_dir\n        return os.path.join(self.cache_dir, \"wheels\", *parts)\n\n    def get(\n        self,\n        link: Link,\n        package_name: str | None,\n        supported_tags: list[Tag],\n    ) -> Link:\n        candidates = []\n\n        if not package_name:\n            return link\n\n        canonical_package_name = canonicalize_name(package_name)\n        for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):\n            try:\n                wheel = Wheel(wheel_name)\n            except InvalidWheelFilename:\n                continue\n            if wheel.name != canonical_package_name:\n                logger.debug(\n                    \"Ignoring cached wheel %s for %s as it \"\n                    \"does not match the expected distribution name %s.\",\n                    wheel_name,\n                    link,\n                    package_name,\n                )\n                continue\n            if not wheel.supported(supported_tags):\n                # Built for a different python/arch/etc\n                continue\n            candidates.append(\n                (\n                    wheel.support_index_min(supported_tags),\n                    wheel_name,\n                    wheel_dir,\n                )\n            )\n\n        if not candidates:\n            return link\n\n        _, wheel_name, wheel_dir = min(candidates)\n        return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))\n\n\nclass EphemWheelCache(SimpleWheelCache):\n    \"\"\"A SimpleWheelCache that creates it's own temporary cache directory\"\"\"\n\n    def __init__(self) -> None:\n        self._temp_dir = TempDirectory(\n            kind=tempdir_kinds.EPHEM_WHEEL_CACHE,\n            globally_managed=True,\n        )\n\n        super().__init__(self._temp_dir.path)\n\n\nclass CacheEntry:\n    def __init__(\n        self,\n        link: Link,\n        persistent: bool,\n    ):\n        self.link = link\n        self.persistent = persistent\n        self.origin: DirectUrl | None = None\n        origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME\n        if origin_direct_url_path.exists():\n            try:\n                self.origin = DirectUrl.from_json(\n                    origin_direct_url_path.read_text(encoding=\"utf-8\")\n                )\n            except Exception as e:\n                logger.warning(\n                    \"Ignoring invalid cache entry origin file %s for %s (%s)\",\n                    origin_direct_url_path,\n                    link.filename,\n                    e,\n                )\n\n\nclass WheelCache(Cache):\n    \"\"\"Wraps EphemWheelCache and SimpleWheelCache into a single Cache\n\n    This Cache allows for gracefully degradation, using the ephem wheel cache\n    when a certain link is not found in the simple wheel cache first.\n    \"\"\"\n\n    def __init__(self, cache_dir: str) -> None:\n        super().__init__(cache_dir)\n        self._wheel_cache = SimpleWheelCache(cache_dir)\n        self._ephem_cache = EphemWheelCache()\n\n    def get_path_for_link(self, link: Link) -> str:\n        return self._wheel_cache.get_path_for_link(link)\n\n    def get_ephem_path_for_link(self, link: Link) -> str:\n        return self._ephem_cache.get_path_for_link(link)\n\n    def get(\n        self,\n        link: Link,\n        package_name: str | None,\n        supported_tags: list[Tag],\n    ) -> Link:\n        cache_entry = self.get_cache_entry(link, package_name, supported_tags)\n        if cache_entry is None:\n            return link\n        return cache_entry.link\n\n    def get_cache_entry(\n        self,\n        link: Link,\n        package_name: str | None,\n        supported_tags: list[Tag],\n    ) -> CacheEntry | None:\n        \"\"\"Returns a CacheEntry with a link to a cached item if it exists or\n        None. The cache entry indicates if the item was found in the persistent\n        or ephemeral cache.\n        \"\"\"\n        retval = self._wheel_cache.get(\n            link=link,\n            package_name=package_name,\n            supported_tags=supported_tags,\n        )\n        if retval is not link:\n            return CacheEntry(retval, persistent=True)\n\n        retval = self._ephem_cache.get(\n            link=link,\n            package_name=package_name,\n            supported_tags=supported_tags,\n        )\n        if retval is not link:\n            return CacheEntry(retval, persistent=False)\n\n        return None\n\n    @staticmethod\n    def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None:\n        origin_path = Path(cache_dir) / ORIGIN_JSON_NAME\n        if origin_path.exists():\n            try:\n                origin = DirectUrl.from_json(origin_path.read_text(encoding=\"utf-8\"))\n            except Exception as e:\n                logger.warning(\n                    \"Could not read origin file %s in cache entry (%s). \"\n                    \"Will attempt to overwrite it.\",\n                    origin_path,\n                    e,\n                )\n            else:\n                # TODO: use DirectUrl.equivalent when\n                # https://github.com/pypa/pip/pull/10564 is merged.\n                if origin.url != download_info.url:\n                    logger.warning(\n                        \"Origin URL %s in cache entry %s does not match download URL \"\n                        \"%s. This is likely a pip bug or a cache corruption issue. \"\n                        \"Will overwrite it with the new value.\",\n                        origin.url,\n                        cache_dir,\n                        download_info.url,\n                    )\n        origin_path.write_text(download_info.to_json(), encoding=\"utf-8\")\n"
  },
  {
    "path": "src/pip/_internal/cli/__init__.py",
    "content": "\"\"\"Subpackage containing all of pip's command line interface related code\"\"\"\n\n# This file intentionally does not import submodules\n"
  },
  {
    "path": "src/pip/_internal/cli/autocompletion.py",
    "content": "\"\"\"Logic that powers autocompletion installed by ``pip completion``.\"\"\"\n\nfrom __future__ import annotations\n\nimport optparse\nimport os\nimport sys\nfrom collections.abc import Iterable\nfrom itertools import chain\nfrom typing import Any\n\nfrom pip._internal.cli.main_parser import create_main_parser\nfrom pip._internal.commands import commands_dict, create_command\nfrom pip._internal.metadata import get_default_environment\n\n\ndef autocomplete() -> None:\n    \"\"\"Entry Point for completion of main and subcommand options.\"\"\"\n    # Don't complete if user hasn't sourced bash_completion file.\n    if \"PIP_AUTO_COMPLETE\" not in os.environ:\n        return\n    # Don't complete if autocompletion environment variables\n    # are not present\n    if not os.environ.get(\"COMP_WORDS\") or not os.environ.get(\"COMP_CWORD\"):\n        return\n    cwords = os.environ[\"COMP_WORDS\"].split()[1:]\n    cword = int(os.environ[\"COMP_CWORD\"])\n    try:\n        current = cwords[cword - 1]\n    except IndexError:\n        current = \"\"\n\n    parser = create_main_parser()\n    subcommands = list(commands_dict)\n    options = []\n\n    # subcommand\n    subcommand_name: str | None = None\n    for word in cwords:\n        if word in subcommands:\n            subcommand_name = word\n            break\n    # subcommand options\n    if subcommand_name is not None:\n        # special case: 'help' subcommand has no options\n        if subcommand_name == \"help\":\n            sys.exit(1)\n        # special case: list locally installed dists for show and uninstall\n        should_list_installed = not current.startswith(\"-\") and subcommand_name in [\n            \"show\",\n            \"uninstall\",\n        ]\n        if should_list_installed:\n            env = get_default_environment()\n            lc = current.lower()\n            installed = [\n                dist.canonical_name\n                for dist in env.iter_installed_distributions(local_only=True)\n                if dist.canonical_name.startswith(lc)\n                and dist.canonical_name not in cwords[1:]\n            ]\n            # if there are no dists installed, fall back to option completion\n            if installed:\n                for dist in installed:\n                    print(dist)\n                sys.exit(1)\n\n        should_list_installables = (\n            not current.startswith(\"-\") and subcommand_name == \"install\"\n        )\n        if should_list_installables:\n            for path in auto_complete_paths(current, \"path\"):\n                print(path)\n            sys.exit(1)\n\n        subcommand = create_command(subcommand_name)\n\n        for opt in subcommand.parser.option_list_all:\n            if opt.help != optparse.SUPPRESS_HELP:\n                options += [\n                    (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts\n                ]\n\n        # filter out previously specified options from available options\n        prev_opts = [x.split(\"=\")[0] for x in cwords[1 : cword - 1]]\n        options = [(x, v) for (x, v) in options if x not in prev_opts]\n        # filter options by current input\n        options = [(k, v) for k, v in options if k.startswith(current)]\n        # get completion type given cwords and available subcommand options\n        completion_type = get_path_completion_type(\n            cwords,\n            cword,\n            subcommand.parser.option_list_all,\n        )\n        # get completion files and directories if ``completion_type`` is\n        # ``<file>``, ``<dir>`` or ``<path>``\n        if completion_type:\n            paths = auto_complete_paths(current, completion_type)\n            options = [(path, 0) for path in paths]\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1] and option[0][:2] == \"--\":\n                opt_label += \"=\"\n            print(opt_label)\n\n        # Complete sub-commands (unless one is already given).\n        if not any(name in cwords for name in subcommand.handler_map()):\n            for handler_name in subcommand.handler_map():\n                if handler_name.startswith(current):\n                    print(handler_name)\n    else:\n        # show main parser options only when necessary\n\n        opts = [i.option_list for i in parser.option_groups]\n        opts.append(parser.option_list)\n        flattened_opts = chain.from_iterable(opts)\n        if current.startswith(\"-\"):\n            for opt in flattened_opts:\n                if opt.help != optparse.SUPPRESS_HELP:\n                    subcommands += opt._long_opts + opt._short_opts\n        else:\n            # get completion type given cwords and all available options\n            completion_type = get_path_completion_type(cwords, cword, flattened_opts)\n            if completion_type:\n                subcommands = list(auto_complete_paths(current, completion_type))\n\n        print(\" \".join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef get_path_completion_type(\n    cwords: list[str], cword: int, opts: Iterable[Any]\n) -> str | None:\n    \"\"\"Get the type of path completion (``file``, ``dir``, ``path`` or None)\n\n    :param cwords: same as the environmental variable ``COMP_WORDS``\n    :param cword: same as the environmental variable ``COMP_CWORD``\n    :param opts: The available options to check\n    :return: path completion type (``file``, ``dir``, ``path`` or None)\n    \"\"\"\n    if cword < 2 or not cwords[cword - 2].startswith(\"-\"):\n        return None\n    for opt in opts:\n        if opt.help == optparse.SUPPRESS_HELP:\n            continue\n        for o in str(opt).split(\"/\"):\n            if cwords[cword - 2].split(\"=\")[0] == o:\n                if not opt.metavar or any(\n                    x in (\"path\", \"file\", \"dir\") for x in opt.metavar.split(\"/\")\n                ):\n                    return opt.metavar\n    return None\n\n\ndef auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:\n    \"\"\"If ``completion_type`` is ``file`` or ``path``, list all regular files\n    and directories starting with ``current``; otherwise only list directories\n    starting with ``current``.\n\n    :param current: The word to be completed\n    :param completion_type: path completion type(``file``, ``path`` or ``dir``)\n    :return: A generator of regular files and/or directories\n    \"\"\"\n    directory, filename = os.path.split(current)\n    current_path = os.path.abspath(directory)\n    # Don't complete paths if they can't be accessed\n    if not os.access(current_path, os.R_OK):\n        return\n    filename = os.path.normcase(filename)\n    # list all files that start with ``filename``\n    file_list = (\n        x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)\n    )\n    for f in file_list:\n        opt = os.path.join(current_path, f)\n        comp_file = os.path.normcase(os.path.join(directory, f))\n        # complete regular files when there is not ``<dir>`` after option\n        # complete directories when there is ``<file>``, ``<path>`` or\n        # ``<dir>``after option\n        if completion_type != \"dir\" and os.path.isfile(opt):\n            yield comp_file\n        elif os.path.isdir(opt):\n            yield os.path.join(comp_file, \"\")\n"
  },
  {
    "path": "src/pip/_internal/cli/base_command.py",
    "content": "\"\"\"Base Command class, and related routines\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport logging.config\nimport optparse\nimport os\nimport sys\nimport traceback\nfrom optparse import Values\nfrom typing import Callable\n\nfrom pip._vendor.rich import reconfigure\nfrom pip._vendor.rich import traceback as rich_traceback\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.command_context import CommandContextMixIn\nfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip._internal.cli.status_codes import (\n    ERROR,\n    PREVIOUS_BUILD_DIR_ERROR,\n    UNKNOWN_ERROR,\n    VIRTUALENV_NOT_FOUND,\n)\nfrom pip._internal.exceptions import (\n    BadCommand,\n    CommandError,\n    DiagnosticPipError,\n    InstallationError,\n    NetworkConnectionError,\n    PreviousBuildDirError,\n)\nfrom pip._internal.utils.filesystem import check_path_owner\nfrom pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging\nfrom pip._internal.utils.misc import get_prog, normalize_path\nfrom pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry\nfrom pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n__all__ = [\"Command\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(CommandContextMixIn):\n    usage: str = \"\"\n    ignore_require_venv: bool = False\n\n    def __init__(self, name: str, summary: str, isolated: bool = False) -> None:\n        super().__init__()\n\n        self.name = name\n        self.summary = summary\n        self.parser = ConfigOptionParser(\n            usage=self.usage,\n            prog=f\"{get_prog()} {name}\",\n            formatter=UpdatingDefaultsHelpFormatter(),\n            add_help_option=False,\n            name=name,\n            description=self.__doc__,\n            isolated=isolated,\n        )\n\n        self.tempdir_registry: TempDirRegistry | None = None\n\n        # Commands should add options to this option group\n        optgroup_name = f\"{self.name.capitalize()} Options\"\n        self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)\n\n        # Add the general options\n        gen_opts = cmdoptions.make_option_group(\n            cmdoptions.general_group,\n            self.parser,\n        )\n        self.parser.add_option_group(gen_opts)\n\n        self.add_options()\n\n    def add_options(self) -> None:\n        pass\n\n    def handle_pip_version_check(self, options: Values) -> None:\n        \"\"\"\n        This is a no-op so that commands by default do not do the pip version\n        check.\n        \"\"\"\n        # Make sure we do the pip version check if the index_group options\n        # are present.\n        assert not hasattr(options, \"no_index\")\n\n    def run(self, options: Values, args: list[str]) -> int:\n        raise NotImplementedError\n\n    def _run_wrapper(self, level_number: int, options: Values, args: list[str]) -> int:\n        def _inner_run() -> int:\n            try:\n                return self.run(options, args)\n            finally:\n                self.handle_pip_version_check(options)\n\n        if options.debug_mode:\n            rich_traceback.install(show_locals=True)\n            return _inner_run()\n\n        try:\n            status = _inner_run()\n            assert isinstance(status, int)\n            return status\n        except DiagnosticPipError as exc:\n            logger.error(\"%s\", exc, extra={\"rich\": True})\n            logger.debug(\"Exception information:\", exc_info=True)\n\n            return ERROR\n        except PreviousBuildDirError as exc:\n            logger.critical(str(exc))\n            logger.debug(\"Exception information:\", exc_info=True)\n\n            return PREVIOUS_BUILD_DIR_ERROR\n        except (\n            InstallationError,\n            BadCommand,\n            NetworkConnectionError,\n        ) as exc:\n            logger.critical(str(exc))\n            logger.debug(\"Exception information:\", exc_info=True)\n\n            return ERROR\n        except CommandError as exc:\n            logger.critical(\"%s\", exc)\n            logger.debug(\"Exception information:\", exc_info=True)\n\n            return ERROR\n        except BrokenStdoutLoggingError:\n            # Bypass our logger and write any remaining messages to\n            # stderr because stdout no longer works.\n            print(\"ERROR: Pipe to stdout was broken\", file=sys.stderr)\n            if level_number <= logging.DEBUG:\n                traceback.print_exc(file=sys.stderr)\n\n            return ERROR\n        except KeyboardInterrupt:\n            logger.critical(\"Operation cancelled by user\")\n            logger.debug(\"Exception information:\", exc_info=True)\n\n            return ERROR\n        except BaseException:\n            logger.critical(\"Exception:\", exc_info=True)\n\n            return UNKNOWN_ERROR\n\n    def parse_args(self, args: list[str]) -> tuple[Values, list[str]]:\n        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args: list[str]) -> int:\n        try:\n            with self.main_context():\n                return self._main(args)\n        finally:\n            logging.shutdown()\n\n    def _main(self, args: list[str]) -> int:\n        # We must initialize this before the tempdir manager, otherwise the\n        # configuration would not be accessible by the time we clean up the\n        # tempdir manager.\n        self.tempdir_registry = self.enter_context(tempdir_registry())\n        # Intentionally set as early as possible so globally-managed temporary\n        # directories are available to the rest of the code.\n        self.enter_context(global_tempdir_manager())\n\n        options, args = self.parse_args(args)\n\n        # Set verbosity so that it can be used elsewhere.\n        self.verbosity = options.verbose - options.quiet\n        if options.debug_mode:\n            self.verbosity = 2\n\n        if hasattr(options, \"progress_bar\") and options.progress_bar == \"auto\":\n            options.progress_bar = \"on\" if self.verbosity >= 0 else \"off\"\n\n        reconfigure(no_color=options.no_color)\n        level_number = setup_logging(\n            verbosity=self.verbosity,\n            no_color=options.no_color,\n            user_log_file=options.log,\n        )\n\n        always_enabled_features = set(options.features_enabled) & set(\n            cmdoptions.ALWAYS_ENABLED_FEATURES\n        )\n        if always_enabled_features:\n            logger.warning(\n                \"The following features are always enabled: %s. \",\n                \", \".join(sorted(always_enabled_features)),\n            )\n\n        # Make sure that the --python argument isn't specified after the\n        # subcommand. We can tell, because if --python was specified,\n        # we should only reach this point if we're running in the created\n        # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment\n        # variable set.\n        if options.python and \"_PIP_RUNNING_IN_SUBPROCESS\" not in os.environ:\n            logger.critical(\n                \"The --python option must be placed before the pip subcommand name\"\n            )\n            sys.exit(ERROR)\n\n        # TODO: Try to get these passing down from the command?\n        #       without resorting to os.environ to hold these.\n        #       This also affects isolated builds and it should.\n\n        if options.no_input:\n            os.environ[\"PIP_NO_INPUT\"] = \"1\"\n\n        if options.exists_action:\n            os.environ[\"PIP_EXISTS_ACTION\"] = \" \".join(options.exists_action)\n\n        if options.require_venv and not self.ignore_require_venv:\n            # If a venv is required check if it can really be found\n            if not running_under_virtualenv():\n                logger.critical(\"Could not find an activated virtualenv (required).\")\n                sys.exit(VIRTUALENV_NOT_FOUND)\n\n        if options.cache_dir:\n            options.cache_dir = normalize_path(options.cache_dir)\n            if not check_path_owner(options.cache_dir):\n                logger.warning(\n                    \"The directory '%s' or its parent directory is not owned \"\n                    \"or is not writable by the current user. The cache \"\n                    \"has been disabled. Check the permissions and owner of \"\n                    \"that directory. If executing pip with sudo, you should \"\n                    \"use sudo's -H flag.\",\n                    options.cache_dir,\n                )\n                options.cache_dir = None\n\n        if (\n            \"inprocess-build-deps\" in options.features_enabled\n            and os.environ.get(\"PIP_CONSTRAINT\", \"\")\n            and \"build-constraint\" not in options.features_enabled\n        ):\n            logger.warning(\n                \"In-process build dependencies are enabled, \"\n                \"PIP_CONSTRAINT will have no effect for build dependencies\"\n            )\n            options.features_enabled.append(\"build-constraint\")\n\n        return self._run_wrapper(level_number, options, args)\n\n    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:\n        \"\"\"\n        map of names to handler actions for commands with sub-actions\n        \"\"\"\n        return {}\n"
  },
  {
    "path": "src/pip/_internal/cli/cmdoptions.py",
    "content": "\"\"\"\nshared options and groups\n\nThe principle here is to define options once, but *not* instantiate them\nglobally. One reason being that options with action='append' can carry state\nbetween parses. pip parses general options twice internally, and shouldn't\npass on state. To be consistent, all options will follow this design.\n\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport pathlib\nimport textwrap\nfrom functools import partial\nfrom optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values\nfrom textwrap import dedent\nfrom typing import Any, Callable\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli.parser import ConfigOptionParser\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.locations import USER_CACHE_DIR, get_src_prefix\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.utils.datetime import parse_iso_datetime\nfrom pip._internal.utils.hashes import STRONG_HASHES\nfrom pip._internal.utils.misc import strtobool\n\nlogger = logging.getLogger(__name__)\n\n\ndef raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:\n    \"\"\"\n    Raise an option parsing error using parser.error().\n\n    Args:\n      parser: an OptionParser instance.\n      option: an Option instance.\n      msg: the error text.\n    \"\"\"\n    msg = f\"{option} error: {msg}\"\n    msg = textwrap.fill(\" \".join(msg.split()))\n    parser.error(msg)\n\n\ndef make_option_group(group: dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:\n    \"\"\"\n    Return an OptionGroup object\n    group  -- assumed to be dict with 'name' and 'options' keys\n    parser -- an optparse Parser\n    \"\"\"\n    option_group = OptionGroup(parser, group[\"name\"])\n    for option in group[\"options\"]:\n        option_group.add_option(option())\n    return option_group\n\n\ndef check_dist_restriction(options: Values, check_target: bool = False) -> None:\n    \"\"\"Function for determining if custom platform options are allowed.\n\n    :param options: The OptionParser options.\n    :param check_target: Whether or not to check if --target is being used.\n    \"\"\"\n    dist_restriction_set = any(\n        [\n            options.python_version,\n            options.platforms,\n            options.abis,\n            options.implementation,\n        ]\n    )\n\n    binary_only = FormatControl(set(), {\":all:\"})\n    sdist_dependencies_allowed = (\n        options.format_control != binary_only and not options.ignore_dependencies\n    )\n\n    # Installations or downloads using dist restrictions must not combine\n    # source distributions and dist-specific wheels, as they are not\n    # guaranteed to be locally compatible.\n    if dist_restriction_set and sdist_dependencies_allowed:\n        raise CommandError(\n            \"When restricting platform and interpreter constraints using \"\n            \"--python-version, --platform, --abi, or --implementation, \"\n            \"either --no-deps must be set, or --only-binary=:all: must be \"\n            \"set and --no-binary must not be set (or must be set to \"\n            \":none:).\"\n        )\n\n    if check_target:\n        if not options.dry_run and dist_restriction_set and not options.target_dir:\n            raise CommandError(\n                \"Can not use any platform or abi specific options unless \"\n                \"installing via '--target' or using '--dry-run'\"\n            )\n\n\ndef check_build_constraints(options: Values) -> None:\n    \"\"\"Function for validating build constraints options.\n\n    :param options: The OptionParser options.\n    \"\"\"\n    if hasattr(options, \"build_constraints\") and options.build_constraints:\n        if not options.build_isolation:\n            raise CommandError(\n                \"--build-constraint cannot be used with --no-build-isolation.\"\n            )\n\n        # Import here to avoid circular imports\n        from pip._internal.network.session import PipSession\n        from pip._internal.req.req_file import get_file_content\n\n        # Eagerly check build constraints file contents\n        # is valid so that we don't fail in when trying\n        # to check constraints in isolated build process\n        with PipSession() as session:\n            for constraint_file in options.build_constraints:\n                get_file_content(constraint_file, session)\n\n\ndef _path_option_check(option: Option, opt: str, value: str) -> str:\n    return os.path.expanduser(value)\n\n\ndef _package_name_option_check(option: Option, opt: str, value: str) -> str:\n    return canonicalize_name(value)\n\n\nclass PipOption(Option):\n    TYPES = Option.TYPES + (\"path\", \"package_name\")\n    TYPE_CHECKER = Option.TYPE_CHECKER.copy()\n    TYPE_CHECKER[\"package_name\"] = _package_name_option_check\n    TYPE_CHECKER[\"path\"] = _path_option_check\n\n\n###########\n# options #\n###########\n\nhelp_: Callable[..., Option] = partial(\n    Option,\n    \"-h\",\n    \"--help\",\n    dest=\"help\",\n    action=\"help\",\n    help=\"Show help.\",\n)\n\ndebug_mode: Callable[..., Option] = partial(\n    Option,\n    \"--debug\",\n    dest=\"debug_mode\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Let unhandled exceptions propagate outside the main subroutine, \"\n        \"instead of logging them to stderr.\"\n    ),\n)\n\nisolated_mode: Callable[..., Option] = partial(\n    Option,\n    \"--isolated\",\n    dest=\"isolated_mode\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Run pip in an isolated mode, ignoring environment variables and user \"\n        \"configuration.\"\n    ),\n)\n\nrequire_virtualenv: Callable[..., Option] = partial(\n    Option,\n    \"--require-virtualenv\",\n    \"--require-venv\",\n    dest=\"require_venv\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Allow pip to only run in a virtual environment; exit with an error otherwise.\"\n    ),\n)\n\noverride_externally_managed: Callable[..., Option] = partial(\n    Option,\n    \"--break-system-packages\",\n    dest=\"override_externally_managed\",\n    action=\"store_true\",\n    help=\"Allow pip to modify an EXTERNALLY-MANAGED Python installation\",\n)\n\npython: Callable[..., Option] = partial(\n    Option,\n    \"--python\",\n    dest=\"python\",\n    help=\"Run pip with the specified Python interpreter.\",\n)\n\nverbose: Callable[..., Option] = partial(\n    Option,\n    \"-v\",\n    \"--verbose\",\n    dest=\"verbose\",\n    action=\"count\",\n    default=0,\n    help=\"Give more output. Option is additive, and can be used up to 3 times.\",\n)\n\nno_color: Callable[..., Option] = partial(\n    Option,\n    \"--no-color\",\n    dest=\"no_color\",\n    action=\"store_true\",\n    default=False,\n    help=\"Suppress colored output.\",\n)\n\nversion: Callable[..., Option] = partial(\n    Option,\n    \"-V\",\n    \"--version\",\n    dest=\"version\",\n    action=\"store_true\",\n    help=\"Show version and exit.\",\n)\n\nquiet: Callable[..., Option] = partial(\n    Option,\n    \"-q\",\n    \"--quiet\",\n    dest=\"quiet\",\n    action=\"count\",\n    default=0,\n    help=(\n        \"Give less output. Option is additive, and can be used up to 3\"\n        \" times (corresponding to WARNING, ERROR, and CRITICAL logging\"\n        \" levels).\"\n    ),\n)\n\nprogress_bar: Callable[..., Option] = partial(\n    Option,\n    \"--progress-bar\",\n    dest=\"progress_bar\",\n    type=\"choice\",\n    choices=[\"auto\", \"on\", \"off\", \"raw\"],\n    default=\"auto\",\n    help=(\n        \"Specify whether the progress bar should be used. In 'auto'\"\n        \" mode, --quiet will suppress all progress bars.\"\n        \" [auto, on, off, raw] (default: auto)\"\n    ),\n)\n\nlog: Callable[..., Option] = partial(\n    PipOption,\n    \"--log\",\n    \"--log-file\",\n    \"--local-log\",\n    dest=\"log\",\n    metavar=\"path\",\n    type=\"path\",\n    help=\"Path to a verbose appending log.\",\n)\n\nno_input: Callable[..., Option] = partial(\n    Option,\n    # Don't ask for input\n    \"--no-input\",\n    dest=\"no_input\",\n    action=\"store_true\",\n    default=False,\n    help=\"Disable prompting for input.\",\n)\n\nkeyring_provider: Callable[..., Option] = partial(\n    Option,\n    \"--keyring-provider\",\n    dest=\"keyring_provider\",\n    choices=[\"auto\", \"disabled\", \"import\", \"subprocess\"],\n    default=\"auto\",\n    help=(\n        \"Enable the credential lookup via the keyring library if user input is allowed.\"\n        \" Specify which mechanism to use [auto, disabled, import, subprocess].\"\n        \" (default: %default)\"\n    ),\n)\n\nproxy: Callable[..., Option] = partial(\n    Option,\n    \"--proxy\",\n    dest=\"proxy\",\n    type=\"str\",\n    default=\"\",\n    help=\"Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.\",\n)\n\nretries: Callable[..., Option] = partial(\n    Option,\n    \"--retries\",\n    dest=\"retries\",\n    type=\"int\",\n    default=5,\n    help=\"Maximum attempts to establish a new HTTP connection. (default: %default)\",\n)\n\nresume_retries: Callable[..., Option] = partial(\n    Option,\n    \"--resume-retries\",\n    dest=\"resume_retries\",\n    type=\"int\",\n    default=5,\n    help=\"Maximum attempts to resume or restart an incomplete download. \"\n    \"(default: %default)\",\n)\n\ntimeout: Callable[..., Option] = partial(\n    Option,\n    \"--timeout\",\n    \"--default-timeout\",\n    metavar=\"sec\",\n    dest=\"timeout\",\n    type=\"float\",\n    default=15,\n    help=\"Set the socket timeout (default %default seconds).\",\n)\n\n\ndef exists_action() -> Option:\n    return Option(\n        # Option when path already exist\n        \"--exists-action\",\n        dest=\"exists_action\",\n        type=\"choice\",\n        choices=[\"s\", \"i\", \"w\", \"b\", \"a\"],\n        default=[],\n        action=\"append\",\n        metavar=\"action\",\n        help=\"Default action when a path already exists: \"\n        \"(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.\",\n    )\n\n\ncert: Callable[..., Option] = partial(\n    PipOption,\n    \"--cert\",\n    dest=\"cert\",\n    type=\"path\",\n    metavar=\"path\",\n    help=(\n        \"Path to PEM-encoded CA certificate bundle. \"\n        \"If provided, overrides the default. \"\n        \"See 'SSL Certificate Verification' in pip documentation \"\n        \"for more information.\"\n    ),\n)\n\nclient_cert: Callable[..., Option] = partial(\n    PipOption,\n    \"--client-cert\",\n    dest=\"client_cert\",\n    type=\"path\",\n    default=None,\n    metavar=\"path\",\n    help=\"Path to SSL client certificate, a single file containing the \"\n    \"private key and the certificate in PEM format.\",\n)\n\nindex_url: Callable[..., Option] = partial(\n    Option,\n    \"-i\",\n    \"--index-url\",\n    \"--pypi-url\",\n    dest=\"index_url\",\n    metavar=\"URL\",\n    default=PyPI.simple_url,\n    help=\"Base URL of the Python Package Index (default %default). \"\n    \"This should point to a repository compliant with PEP 503 \"\n    \"(the simple repository API) or a local directory laid out \"\n    \"in the same format.\",\n)\n\n\ndef extra_index_url() -> Option:\n    return Option(\n        \"--extra-index-url\",\n        dest=\"extra_index_urls\",\n        metavar=\"URL\",\n        action=\"append\",\n        default=[],\n        help=\"Extra URLs of package indexes to use in addition to \"\n        \"--index-url. Should follow the same rules as \"\n        \"--index-url.\",\n    )\n\n\nno_index: Callable[..., Option] = partial(\n    Option,\n    \"--no-index\",\n    dest=\"no_index\",\n    action=\"store_true\",\n    default=False,\n    help=\"Ignore package index (only looking at --find-links URLs instead).\",\n)\n\n\ndef find_links() -> Option:\n    return Option(\n        \"-f\",\n        \"--find-links\",\n        dest=\"find_links\",\n        action=\"append\",\n        default=[],\n        metavar=\"url\",\n        help=\"If a URL or path to an html file, then parse for links to \"\n        \"archives such as sdist (.tar.gz) or wheel (.whl) files. \"\n        \"If a local path or file:// URL that's a directory, \"\n        \"then look for archives in the directory listing. \"\n        \"Links to VCS project URLs are not supported.\",\n    )\n\n\ndef _handle_uploaded_prior_to(\n    option: Option, opt: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    This is an optparse.Option callback for the --uploaded-prior-to option.\n\n    Parses an ISO 8601 datetime string. If no timezone is specified in the string,\n    local timezone is used.\n\n    Note: This option only works with indexes that provide upload-time metadata\n    as specified in the simple repository API:\n    https://packaging.python.org/en/latest/specifications/simple-repository-api/\n    \"\"\"\n    if value is None:\n        return None\n\n    try:\n        uploaded_prior_to = parse_iso_datetime(value)\n        # Use local timezone if no offset is given in the ISO string.\n        if uploaded_prior_to.tzinfo is None:\n            uploaded_prior_to = uploaded_prior_to.astimezone()\n        parser.values.uploaded_prior_to = uploaded_prior_to\n    except ValueError as exc:\n        msg = (\n            f\"invalid value: {value!r}: {exc}. \"\n            f\"Expected an ISO 8601 datetime string, \"\n            f\"e.g '2023-01-01' or '2023-01-01T00:00:00Z'\"\n        )\n        raise_option_error(parser, option=option, msg=msg)\n\n\ndef uploaded_prior_to() -> Option:\n    return Option(\n        \"--uploaded-prior-to\",\n        dest=\"uploaded_prior_to\",\n        metavar=\"datetime\",\n        action=\"callback\",\n        callback=_handle_uploaded_prior_to,\n        type=\"str\",\n        help=(\n            \"Only consider packages uploaded prior to the given date time. \"\n            \"Accepts ISO 8601 strings (e.g., '2023-01-01T00:00:00Z'). \"\n            \"Uses local timezone if none specified. Only effective when \"\n            \"installing from indexes that provide upload-time metadata.\"\n        ),\n    )\n\n\ndef trusted_host() -> Option:\n    return Option(\n        \"--trusted-host\",\n        dest=\"trusted_hosts\",\n        action=\"append\",\n        metavar=\"HOSTNAME\",\n        default=[],\n        help=\"Mark this host or host:port pair as trusted, even though it \"\n        \"does not have valid or any HTTPS.\",\n    )\n\n\ndef constraints() -> Option:\n    return Option(\n        \"-c\",\n        \"--constraint\",\n        dest=\"constraints\",\n        action=\"append\",\n        default=[],\n        metavar=\"file\",\n        help=\"Constrain versions using the given constraints file. \"\n        \"This option can be used multiple times.\",\n    )\n\n\ndef build_constraints() -> Option:\n    return Option(\n        \"--build-constraint\",\n        dest=\"build_constraints\",\n        action=\"append\",\n        type=\"str\",\n        default=[],\n        metavar=\"file\",\n        help=(\n            \"Constrain build dependencies using the given constraints file. \"\n            \"This option can be used multiple times.\"\n        ),\n    )\n\n\ndef requirements() -> Option:\n    return Option(\n        \"-r\",\n        \"--requirement\",\n        dest=\"requirements\",\n        action=\"append\",\n        default=[],\n        metavar=\"file\",\n        help=\"Install from the given requirements file. \"\n        \"This option can be used multiple times.\",\n    )\n\n\ndef requirements_from_scripts() -> Option:\n    return Option(\n        \"--requirements-from-script\",\n        action=\"append\",\n        default=[],\n        dest=\"requirements_from_scripts\",\n        metavar=\"file\",\n        help=\"Install dependencies of the given script file\"\n        \"as defined by PEP 723 inline metadata. \",\n    )\n\n\ndef editable() -> Option:\n    return Option(\n        \"-e\",\n        \"--editable\",\n        dest=\"editables\",\n        action=\"append\",\n        default=[],\n        metavar=\"path/url\",\n        help=(\n            \"Install a project in editable mode (i.e. setuptools \"\n            '\"develop mode\") from a local project path or a VCS url.'\n        ),\n    )\n\n\ndef _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:\n    value = os.path.abspath(value)\n    setattr(parser.values, option.dest, value)\n\n\nsrc: Callable[..., Option] = partial(\n    PipOption,\n    \"--src\",\n    \"--source\",\n    \"--source-dir\",\n    \"--source-directory\",\n    dest=\"src_dir\",\n    type=\"path\",\n    metavar=\"dir\",\n    default=get_src_prefix(),\n    action=\"callback\",\n    callback=_handle_src,\n    help=\"Directory to check out editable projects into. \"\n    'The default in a virtualenv is \"<venv path>/src\". '\n    'The default for global installs is \"<current dir>/src\".',\n)\n\n\ndef _get_format_control(values: Values, option: Option) -> Any:\n    \"\"\"Get a format_control object.\"\"\"\n    return getattr(values, option.dest)\n\n\ndef _handle_no_binary(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_format_control(parser.values, option)\n    FormatControl.handle_mutual_excludes(\n        value,\n        existing.no_binary,\n        existing.only_binary,\n    )\n\n\ndef _handle_only_binary(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_format_control(parser.values, option)\n    FormatControl.handle_mutual_excludes(\n        value,\n        existing.only_binary,\n        existing.no_binary,\n    )\n\n\ndef no_binary() -> Option:\n    format_control = FormatControl(set(), set())\n    return Option(\n        \"--no-binary\",\n        dest=\"format_control\",\n        action=\"callback\",\n        callback=_handle_no_binary,\n        type=\"str\",\n        default=format_control,\n        help=\"Do not use binary packages. Can be supplied multiple times, and \"\n        'each time adds to the existing value. Accepts either \":all:\" to '\n        'disable all binary packages, \":none:\" to empty the set (notice '\n        \"the colons), or one or more package names with commas between \"\n        \"them (no colons). Note that some packages are tricky to compile \"\n        \"and may fail to install when this option is used on them.\",\n    )\n\n\ndef only_binary() -> Option:\n    format_control = FormatControl(set(), set())\n    return Option(\n        \"--only-binary\",\n        dest=\"format_control\",\n        action=\"callback\",\n        callback=_handle_only_binary,\n        type=\"str\",\n        default=format_control,\n        help=\"Do not use source packages. Can be supplied multiple times, and \"\n        'each time adds to the existing value. Accepts either \":all:\" to '\n        'disable all source packages, \":none:\" to empty the set, or one '\n        \"or more package names with commas between them. Packages \"\n        \"without binary distributions will fail to install when this \"\n        \"option is used on them.\",\n    )\n\n\ndef _get_release_control(values: Values, option: Option) -> Any:\n    \"\"\"Get a release_control object.\"\"\"\n    return getattr(values, option.dest)\n\n\ndef _handle_all_releases(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_release_control(parser.values, option)\n    existing.handle_mutual_excludes(\n        value,\n        existing.all_releases,\n        existing.only_final,\n        \"all_releases\",\n    )\n\n\ndef _handle_only_final(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_release_control(parser.values, option)\n    existing.handle_mutual_excludes(\n        value,\n        existing.only_final,\n        existing.all_releases,\n        \"only_final\",\n    )\n\n\ndef all_releases() -> Option:\n    release_control = ReleaseControl(set(), set())\n    return Option(\n        \"--all-releases\",\n        dest=\"release_control\",\n        action=\"callback\",\n        callback=_handle_all_releases,\n        type=\"str\",\n        default=release_control,\n        help=\"Allow all release types (including pre-releases) for a package. \"\n        \"Can be supplied multiple times, and each time adds to the existing \"\n        'value. Accepts either \":all:\" to allow pre-releases for all '\n        'packages, \":none:\" to empty the set (notice the colons), or one or '\n        \"more package names with commas between them (no colons). Cannot be \"\n        \"used with --pre.\",\n    )\n\n\ndef only_final() -> Option:\n    release_control = ReleaseControl(set(), set())\n    return Option(\n        \"--only-final\",\n        dest=\"release_control\",\n        action=\"callback\",\n        callback=_handle_only_final,\n        type=\"str\",\n        default=release_control,\n        help=\"Only allow final releases (no pre-releases) for a package. Can be \"\n        \"supplied multiple times, and each time adds to the existing value. \"\n        'Accepts either \":all:\" to disable pre-releases for all packages, '\n        '\":none:\" to empty the set, or one or more package names with commas '\n        \"between them. Cannot be used with --pre.\",\n    )\n\n\ndef check_release_control_exclusive(options: Values) -> None:\n    \"\"\"\n    Raise an error if --pre is used with --all-releases or --only-final,\n    and transform --pre into --all-releases :all: if used alone.\n    \"\"\"\n    if not hasattr(options, \"pre\") or not options.pre:\n        return\n\n    release_control = options.release_control\n    if release_control.all_releases or release_control.only_final:\n        raise CommandError(\"--pre cannot be used with --all-releases or --only-final.\")\n\n    # Transform --pre into --all-releases :all:\n    release_control.all_releases.add(\":all:\")\n\n\nplatforms: Callable[..., Option] = partial(\n    Option,\n    \"--platform\",\n    dest=\"platforms\",\n    metavar=\"platform\",\n    action=\"append\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with <platform>. Defaults to the \"\n        \"platform of the running system. Use this option multiple times to \"\n        \"specify multiple platforms supported by the target interpreter.\"\n    ),\n)\n\n\n# This was made a separate function for unit-testing purposes.\ndef _convert_python_version(value: str) -> tuple[tuple[int, ...], str | None]:\n    \"\"\"\n    Convert a version string like \"3\", \"37\", or \"3.7.3\" into a tuple of ints.\n\n    :return: A 2-tuple (version_info, error_msg), where `error_msg` is\n        non-None if and only if there was a parsing error.\n    \"\"\"\n    if not value:\n        # The empty string is the same as not providing a value.\n        return (None, None)\n\n    parts = value.split(\".\")\n    if len(parts) > 3:\n        return ((), \"at most three version parts are allowed\")\n\n    if len(parts) == 1:\n        # Then we are in the case of \"3\" or \"37\".\n        value = parts[0]\n        if len(value) > 1:\n            parts = [value[0], value[1:]]\n\n    try:\n        version_info = tuple(int(part) for part in parts)\n    except ValueError:\n        return ((), \"each version part must be an integer\")\n\n    return (version_info, None)\n\n\ndef _handle_python_version(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Handle a provided --python-version value.\n    \"\"\"\n    version_info, error_msg = _convert_python_version(value)\n    if error_msg is not None:\n        msg = f\"invalid --python-version value: {value!r}: {error_msg}\"\n        raise_option_error(parser, option=option, msg=msg)\n\n    parser.values.python_version = version_info\n\n\npython_version: Callable[..., Option] = partial(\n    Option,\n    \"--python-version\",\n    dest=\"python_version\",\n    metavar=\"python_version\",\n    action=\"callback\",\n    callback=_handle_python_version,\n    type=\"str\",\n    default=None,\n    help=dedent(\n        \"\"\"\\\n    The Python interpreter version to use for wheel and \"Requires-Python\"\n    compatibility checks. Defaults to a version derived from the running\n    interpreter. The version can be specified using up to three dot-separated\n    integers (e.g. \"3\" for 3.0.0, \"3.7\" for 3.7.0, or \"3.7.3\"). A major-minor\n    version can also be given as a string without dots (e.g. \"37\" for 3.7.0).\n    \"\"\"\n    ),\n)\n\n\nimplementation: Callable[..., Option] = partial(\n    Option,\n    \"--implementation\",\n    dest=\"implementation\",\n    metavar=\"implementation\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with Python \"\n        \"implementation <implementation>, e.g. 'pp', 'jy', 'cp', \"\n        \" or 'ip'. If not specified, then the current \"\n        \"interpreter implementation is used.  Use 'py' to force \"\n        \"implementation-agnostic wheels.\"\n    ),\n)\n\n\nabis: Callable[..., Option] = partial(\n    Option,\n    \"--abi\",\n    dest=\"abis\",\n    metavar=\"abi\",\n    action=\"append\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. \"\n        \"If not specified, then the current interpreter abi tag is used. \"\n        \"Use this option multiple times to specify multiple abis supported \"\n        \"by the target interpreter. Generally you will need to specify \"\n        \"--implementation, --platform, and --python-version when using this \"\n        \"option.\"\n    ),\n)\n\n\ndef add_target_python_options(cmd_opts: OptionGroup) -> None:\n    cmd_opts.add_option(platforms())\n    cmd_opts.add_option(python_version())\n    cmd_opts.add_option(implementation())\n    cmd_opts.add_option(abis())\n\n\ndef make_target_python(options: Values) -> TargetPython:\n    target_python = TargetPython(\n        platforms=options.platforms,\n        py_version_info=options.python_version,\n        abis=options.abis,\n        implementation=options.implementation,\n    )\n\n    return target_python\n\n\ndef prefer_binary() -> Option:\n    return Option(\n        \"--prefer-binary\",\n        dest=\"prefer_binary\",\n        action=\"store_true\",\n        default=False,\n        help=(\n            \"Prefer binary packages over source packages, even if the \"\n            \"source packages are newer.\"\n        ),\n    )\n\n\ncache_dir: Callable[..., Option] = partial(\n    PipOption,\n    \"--cache-dir\",\n    dest=\"cache_dir\",\n    default=USER_CACHE_DIR,\n    metavar=\"dir\",\n    type=\"path\",\n    help=\"Store the cache data in <dir>.\",\n)\n\n\ndef _handle_no_cache_dir(\n    option: Option, opt: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Process a value provided for the --no-cache-dir option.\n\n    This is an optparse.Option callback for the --no-cache-dir option.\n    \"\"\"\n    # The value argument will be None if --no-cache-dir is passed via the\n    # command-line, since the option doesn't accept arguments.  However,\n    # the value can be non-None if the option is triggered e.g. by an\n    # environment variable, like PIP_NO_CACHE_DIR=true.\n    if value is not None:\n        # Then parse the string value to get argument error-checking.\n        try:\n            strtobool(value)\n        except ValueError as exc:\n            raise_option_error(parser, option=option, msg=str(exc))\n\n    # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()\n    # converted to 0 (like \"false\" or \"no\") caused cache_dir to be disabled\n    # rather than enabled (logic would say the latter).  Thus, we disable\n    # the cache directory not just on values that parse to True, but (for\n    # backwards compatibility reasons) also on values that parse to False.\n    # In other words, always set it to False if the option is provided in\n    # some (valid) form.\n    parser.values.cache_dir = False\n\n\nno_cache: Callable[..., Option] = partial(\n    Option,\n    \"--no-cache-dir\",\n    dest=\"cache_dir\",\n    action=\"callback\",\n    callback=_handle_no_cache_dir,\n    help=\"Disable the cache.\",\n)\n\nno_deps: Callable[..., Option] = partial(\n    Option,\n    \"--no-deps\",\n    \"--no-dependencies\",\n    dest=\"ignore_dependencies\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't install package dependencies.\",\n)\n\n\ndef _handle_dependency_group(\n    option: Option, opt: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Process a value provided for the --group option.\n\n    Splits on the rightmost \":\", and validates that the path (if present) ends\n    in `pyproject.toml`. Defaults the path to `pyproject.toml` when one is not given.\n\n    `:` cannot appear in dependency group names, so this is a safe and simple parse.\n\n    This is an optparse.Option callback for the dependency_groups option.\n    \"\"\"\n    path, sep, groupname = value.rpartition(\":\")\n    if not sep:\n        path = \"pyproject.toml\"\n    else:\n        # check for 'pyproject.toml' filenames using pathlib\n        if pathlib.PurePath(path).name != \"pyproject.toml\":\n            msg = \"group paths use 'pyproject.toml' filenames\"\n            raise_option_error(parser, option=option, msg=msg)\n\n    parser.values.dependency_groups.append((path, groupname))\n\n\ndependency_groups: Callable[..., Option] = partial(\n    Option,\n    \"--group\",\n    dest=\"dependency_groups\",\n    default=[],\n    type=str,\n    action=\"callback\",\n    callback=_handle_dependency_group,\n    metavar=\"[path:]group\",\n    help='Install a named dependency-group from a \"pyproject.toml\" file. '\n    'If a path is given, the name of the file must be \"pyproject.toml\". '\n    'Defaults to using \"pyproject.toml\" in the current directory.',\n)\n\nignore_requires_python: Callable[..., Option] = partial(\n    Option,\n    \"--ignore-requires-python\",\n    dest=\"ignore_requires_python\",\n    action=\"store_true\",\n    help=\"Ignore the Requires-Python information.\",\n)\n\n\nno_build_isolation: Callable[..., Option] = partial(\n    Option,\n    \"--no-build-isolation\",\n    dest=\"build_isolation\",\n    action=\"store_false\",\n    default=True,\n    help=\"Disable isolation when building a modern source distribution. \"\n    \"Build dependencies specified by PEP 518 must be already installed \"\n    \"if this option is used.\",\n)\n\ncheck_build_deps: Callable[..., Option] = partial(\n    Option,\n    \"--check-build-dependencies\",\n    dest=\"check_build_deps\",\n    action=\"store_true\",\n    default=False,\n    help=\"Check the build dependencies.\",\n)\n\n\nuse_pep517: Any = partial(\n    Option,\n    \"--use-pep517\",\n    dest=\"use_pep517\",\n    action=\"store_true\",\n    default=True,\n    help=SUPPRESS_HELP,\n)\n\n\ndef _handle_config_settings(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    key, sep, val = value.partition(\"=\")\n    if sep != \"=\":\n        parser.error(f\"Arguments to {opt_str} must be of the form KEY=VAL\")\n    dest = getattr(parser.values, option.dest)\n    if dest is None:\n        dest = {}\n        setattr(parser.values, option.dest, dest)\n    if key in dest:\n        if isinstance(dest[key], list):\n            dest[key].append(val)\n        else:\n            dest[key] = [dest[key], val]\n    else:\n        dest[key] = val\n\n\nconfig_settings: Callable[..., Option] = partial(\n    Option,\n    \"-C\",\n    \"--config-settings\",\n    dest=\"config_settings\",\n    type=str,\n    action=\"callback\",\n    callback=_handle_config_settings,\n    metavar=\"settings\",\n    help=\"Configuration settings to be passed to the build backend. \"\n    \"Settings take the form KEY=VALUE. Use multiple --config-settings options \"\n    \"to pass multiple keys to the backend.\",\n)\n\nno_clean: Callable[..., Option] = partial(\n    Option,\n    \"--no-clean\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't clean up build directories.\",\n)\n\npre: Callable[..., Option] = partial(\n    Option,\n    \"--pre\",\n    action=\"store_true\",\n    default=False,\n    help=\"Include pre-release and development versions. By default, \"\n    \"pip only finds stable versions.\",\n)\n\njson: Callable[..., Option] = partial(\n    Option,\n    \"--json\",\n    action=\"store_true\",\n    default=False,\n    help=\"Output data in a machine-readable JSON format.\",\n)\n\ndisable_pip_version_check: Callable[..., Option] = partial(\n    Option,\n    \"--disable-pip-version-check\",\n    dest=\"disable_pip_version_check\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't periodically check PyPI to determine whether a new version \"\n    \"of pip is available for download. Implied with --no-index.\",\n)\n\nroot_user_action: Callable[..., Option] = partial(\n    Option,\n    \"--root-user-action\",\n    dest=\"root_user_action\",\n    default=\"warn\",\n    choices=[\"warn\", \"ignore\"],\n    help=\"Action if pip is run as a root user [warn, ignore] (default: warn)\",\n)\n\n\ndef _handle_merge_hash(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"Given a value spelled \"algo:digest\", append the digest to a list\n    pointed to in a dict by the algo name.\"\"\"\n    if not parser.values.hashes:\n        parser.values.hashes = {}\n    try:\n        algo, digest = value.split(\":\", 1)\n    except ValueError:\n        parser.error(\n            f\"Arguments to {opt_str} must be a hash name \"\n            \"followed by a value, like --hash=sha256:\"\n            \"abcde...\"\n        )\n    if algo not in STRONG_HASHES:\n        parser.error(\n            \"Allowed hash algorithms for {} are {}.\".format(\n                opt_str, \", \".join(STRONG_HASHES)\n            )\n        )\n    parser.values.hashes.setdefault(algo, []).append(digest)\n\n\nhash: Callable[..., Option] = partial(\n    Option,\n    \"--hash\",\n    # Hash values eventually end up in InstallRequirement.hashes due to\n    # __dict__ copying in process_line().\n    dest=\"hashes\",\n    action=\"callback\",\n    callback=_handle_merge_hash,\n    type=\"string\",\n    help=\"Verify that the package's archive matches this \"\n    \"hash before installing. Example: --hash=sha256:abcdef...\",\n)\n\n\nrequire_hashes: Callable[..., Option] = partial(\n    Option,\n    \"--require-hashes\",\n    dest=\"require_hashes\",\n    action=\"store_true\",\n    default=False,\n    help=\"Require a hash to check each requirement against, for \"\n    \"repeatable installs. This option is implied when any package in a \"\n    \"requirements file has a --hash option.\",\n)\n\n\nlist_path: Callable[..., Option] = partial(\n    PipOption,\n    \"--path\",\n    dest=\"path\",\n    type=\"path\",\n    action=\"append\",\n    help=\"Restrict to the specified installation path for listing \"\n    \"packages (can be used multiple times).\",\n)\n\n\ndef check_list_path_option(options: Values) -> None:\n    if options.path and (options.user or options.local):\n        raise CommandError(\"Cannot combine '--path' with '--user' or '--local'\")\n\n\nlist_exclude: Callable[..., Option] = partial(\n    PipOption,\n    \"--exclude\",\n    dest=\"excludes\",\n    action=\"append\",\n    metavar=\"package\",\n    type=\"package_name\",\n    help=\"Exclude specified package from the output\",\n)\n\n\nno_python_version_warning: Callable[..., Option] = partial(\n    Option,\n    \"--no-python-version-warning\",\n    dest=\"no_python_version_warning\",\n    action=\"store_true\",\n    default=False,\n    help=SUPPRESS_HELP,  # No-op, a hold-over from the Python 2->3 transition.\n)\n\n\n# Features that are now always on. A warning is printed if they are used.\nALWAYS_ENABLED_FEATURES = [\n    \"truststore\",  # always on since 24.2\n    \"no-binary-enable-wheel-cache\",  # always on since 23.1\n]\n\nuse_new_feature: Callable[..., Option] = partial(\n    Option,\n    \"--use-feature\",\n    dest=\"features_enabled\",\n    metavar=\"feature\",\n    action=\"append\",\n    default=[],\n    choices=[\n        \"fast-deps\",\n        \"build-constraint\",\n        \"inprocess-build-deps\",\n    ]\n    + ALWAYS_ENABLED_FEATURES,\n    help=\"Enable new functionality, that may be backward incompatible.\",\n)\n\nuse_deprecated_feature: Callable[..., Option] = partial(\n    Option,\n    \"--use-deprecated\",\n    dest=\"deprecated_features_enabled\",\n    metavar=\"feature\",\n    action=\"append\",\n    default=[],\n    choices=[\n        \"legacy-resolver\",\n        \"legacy-certs\",\n    ],\n    help=(\"Enable deprecated functionality, that will be removed in the future.\"),\n)\n\n##########\n# groups #\n##########\n\ngeneral_group: dict[str, Any] = {\n    \"name\": \"General Options\",\n    \"options\": [\n        help_,\n        debug_mode,\n        isolated_mode,\n        require_virtualenv,\n        python,\n        verbose,\n        version,\n        quiet,\n        log,\n        no_input,\n        keyring_provider,\n        proxy,\n        retries,\n        timeout,\n        exists_action,\n        trusted_host,\n        cert,\n        client_cert,\n        cache_dir,\n        no_cache,\n        disable_pip_version_check,\n        no_color,\n        no_python_version_warning,\n        use_new_feature,\n        use_deprecated_feature,\n        resume_retries,\n    ],\n}\n\nindex_group: dict[str, Any] = {\n    \"name\": \"Package Index Options\",\n    \"options\": [\n        index_url,\n        extra_index_url,\n        no_index,\n        find_links,\n        uploaded_prior_to,\n    ],\n}\n\npackage_selection_group: dict[str, Any] = {\n    \"name\": \"Package Selection Options\",\n    \"options\": [\n        pre,\n        all_releases,\n        only_final,\n        no_binary,\n        only_binary,\n        prefer_binary,\n    ],\n}\n"
  },
  {
    "path": "src/pip/_internal/cli/command_context.py",
    "content": "from collections.abc import Generator\nfrom contextlib import AbstractContextManager, ExitStack, contextmanager\nfrom typing import TypeVar\n\n_T = TypeVar(\"_T\", covariant=True)\n\n\nclass CommandContextMixIn:\n    def __init__(self) -> None:\n        super().__init__()\n        self._in_main_context = False\n        self._main_context = ExitStack()\n\n    @contextmanager\n    def main_context(self) -> Generator[None, None, None]:\n        assert not self._in_main_context\n\n        self._in_main_context = True\n        try:\n            with self._main_context:\n                yield\n        finally:\n            self._in_main_context = False\n\n    def enter_context(self, context_provider: AbstractContextManager[_T]) -> _T:\n        assert self._in_main_context\n\n        return self._main_context.enter_context(context_provider)\n"
  },
  {
    "path": "src/pip/_internal/cli/index_command.py",
    "content": "\"\"\"\nContains command classes which may interact with an index / the network.\n\nUnlike its sister module, req_command, this module still uses lazy imports\nso commands which don't always hit the network (e.g. list w/o --outdated or\n--uptodate) don't need waste time importing PipSession and friends.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport sys\nfrom functools import lru_cache\nfrom optparse import Values\nfrom typing import TYPE_CHECKING\n\nfrom pip._vendor import certifi\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.command_context import CommandContextMixIn\n\nif TYPE_CHECKING:\n    from ssl import SSLContext\n\n    from pip._vendor.packaging.utils import NormalizedName\n\n    from pip._internal.network.session import PipSession\n\nlogger = logging.getLogger(__name__)\n\n\n@lru_cache\ndef _create_truststore_ssl_context() -> SSLContext | None:\n    if sys.version_info < (3, 10):\n        logger.debug(\"Disabling truststore because Python version isn't 3.10+\")\n        return None\n\n    try:\n        import ssl\n    except ImportError:\n        logger.warning(\"Disabling truststore since ssl support is missing\")\n        return None\n\n    try:\n        from pip._vendor import truststore\n    except ImportError:\n        logger.warning(\"Disabling truststore because platform isn't supported\")\n        return None\n\n    ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n    ctx.load_verify_locations(certifi.where())\n    return ctx\n\n\nclass SessionCommandMixin(CommandContextMixIn):\n    \"\"\"\n    A class mixin for command classes needing _build_session().\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        self._session: PipSession | None = None\n\n    @classmethod\n    def _get_index_urls(cls, options: Values) -> list[str] | None:\n        \"\"\"Return a list of index urls from user-provided options.\"\"\"\n        index_urls = []\n        if not getattr(options, \"no_index\", False):\n            url = getattr(options, \"index_url\", None)\n            if url:\n                index_urls.append(url)\n        urls = getattr(options, \"extra_index_urls\", None)\n        if urls:\n            index_urls.extend(urls)\n        # Return None rather than an empty list\n        return index_urls or None\n\n    def get_default_session(self, options: Values) -> PipSession:\n        \"\"\"Get a default-managed session.\"\"\"\n        if self._session is None:\n            self._session = self.enter_context(self._build_session(options))\n            # there's no type annotation on requests.Session, so it's\n            # automatically ContextManager[Any] and self._session becomes Any,\n            # then https://github.com/python/mypy/issues/7696 kicks in\n            assert self._session is not None\n        return self._session\n\n    def _build_session(\n        self,\n        options: Values,\n        retries: int | None = None,\n        timeout: int | None = None,\n    ) -> PipSession:\n        from pip._internal.network.session import PipSession\n\n        cache_dir = options.cache_dir\n        assert not cache_dir or os.path.isabs(cache_dir)\n\n        if \"legacy-certs\" not in options.deprecated_features_enabled:\n            ssl_context = _create_truststore_ssl_context()\n        else:\n            ssl_context = None\n\n        session = PipSession(\n            cache=os.path.join(cache_dir, \"http-v2\") if cache_dir else None,\n            retries=retries if retries is not None else options.retries,\n            resume_retries=options.resume_retries,\n            trusted_hosts=options.trusted_hosts,\n            index_urls=self._get_index_urls(options),\n            ssl_context=ssl_context,\n        )\n\n        # Handle custom ca-bundles from the user\n        if options.cert:\n            session.verify = options.cert\n\n        # Handle SSL client certificate\n        if options.client_cert:\n            session.cert = options.client_cert\n\n        # Handle timeouts\n        if options.timeout or timeout:\n            session.timeout = timeout if timeout is not None else options.timeout\n\n        # Handle configured proxies\n        if options.proxy:\n            session.proxies = {\n                \"http\": options.proxy,\n                \"https\": options.proxy,\n            }\n            session.trust_env = False\n            session.pip_proxy = options.proxy\n\n        # Determine if we can prompt the user for authentication or not\n        session.auth.prompting = not options.no_input\n        session.auth.keyring_provider = options.keyring_provider\n\n        return session\n\n\ndef _pip_self_version_check(session: PipSession, options: Values) -> None:\n    from pip._internal.self_outdated_check import pip_self_version_check as check\n\n    check(session, options)\n\n\nclass IndexGroupCommand(Command, SessionCommandMixin):\n    \"\"\"\n    Abstract base class for commands with the index_group options.\n\n    This also corresponds to the commands that permit the pip version check.\n    \"\"\"\n\n    def should_exclude_prerelease(\n        self, options: Values, package_name: NormalizedName\n    ) -> bool:\n        \"\"\"\n        Determine if pre-releases should be excluded for a package.\n        \"\"\"\n        # Check per-package release control settings\n        if options.release_control:\n            allow_prereleases = options.release_control.allows_prereleases(package_name)\n            if allow_prereleases is True:\n                return False  # Include pre-releases\n            elif allow_prereleases is False:\n                return True  # Exclude pre-releases\n\n        # No specific setting: exclude prereleases by default\n        return True\n\n    def handle_pip_version_check(self, options: Values) -> None:\n        \"\"\"\n        Do the pip version check if not disabled.\n\n        This overrides the default behavior of not doing the check.\n        \"\"\"\n        # Make sure the index_group options are present.\n        assert hasattr(options, \"no_index\")\n\n        if options.disable_pip_version_check or options.no_index:\n            return\n\n        try:\n            # Otherwise, check if we're using the latest version of pip available.\n            session = self._build_session(\n                options,\n                retries=0,\n                timeout=min(5, options.timeout),\n            )\n            with session:\n                _pip_self_version_check(session, options)\n        except Exception:\n            logger.warning(\"There was an error checking the latest version of pip.\")\n            logger.debug(\"See below for error\", exc_info=True)\n"
  },
  {
    "path": "src/pip/_internal/cli/main.py",
    "content": "\"\"\"Primary application entrypoint.\"\"\"\n\nfrom __future__ import annotations\n\nimport locale\nimport logging\nimport os\nimport sys\nimport warnings\n\nlogger = logging.getLogger(__name__)\n\n\n# Do not import and use main() directly! Using it directly is actively\n# discouraged by pip's maintainers. The name, location and behavior of\n# this function is subject to change, so calling it directly is not\n# portable across different pip versions.\n\n# In addition, running pip in-process is unsupported and unsafe. This is\n# elaborated in detail at\n# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.\n# That document also provides suggestions that should work for nearly\n# all users that are considering importing and using main() directly.\n\n# However, we know that certain users will still want to invoke pip\n# in-process. If you understand and accept the implications of using pip\n# in an unsupported manner, the best approach is to use runpy to avoid\n# depending on the exact location of this entry point.\n\n# The following example shows how to use runpy to invoke pip in that\n# case:\n#\n#     sys.argv = [\"pip\", your, args, here]\n#     runpy.run_module(\"pip\", run_name=\"__main__\")\n#\n# Note that this will exit the process after running, unlike a direct\n# call to main. As it is not safe to do any processing after calling\n# main, this should not be an issue in practice.\n\n\ndef main(args: list[str] | None = None) -> int:\n    # NOTE: Lazy imports to speed up import of this module,\n    # which is imported from the pip console script. This doesn't\n    # speed up normal pip execution, but might be important in the future\n    # if we use ``multiprocessing`` module,\n    # which imports __main__ for each spawned subprocess.\n    from pip._internal.cli.autocompletion import autocomplete\n    from pip._internal.cli.main_parser import parse_command\n    from pip._internal.commands import create_command\n    from pip._internal.exceptions import PipError\n    from pip._internal.utils import deprecation\n\n    if args is None:\n        args = sys.argv[1:]\n\n    # Suppress the pkg_resources deprecation warning\n    # Note - we use a module of .*pkg_resources to cover\n    # the normal case (pip._vendor.pkg_resources) and the\n    # devendored case (a bare pkg_resources)\n    warnings.filterwarnings(\n        action=\"ignore\", category=DeprecationWarning, module=\".*pkg_resources\"\n    )\n\n    # Configure our deprecation warnings to be sent through loggers\n    deprecation.install_warning_logger()\n\n    autocomplete()\n\n    try:\n        cmd_name, cmd_args = parse_command(args)\n    except PipError as exc:\n        sys.stderr.write(f\"ERROR: {exc}\")\n        sys.stderr.write(os.linesep)\n        sys.exit(1)\n\n    # Needed for locale.getpreferredencoding(False) to work\n    # in pip._internal.utils.encoding.auto_decode\n    try:\n        locale.setlocale(locale.LC_ALL, \"\")\n    except locale.Error as e:\n        # setlocale can apparently crash if locale are uninitialized\n        logger.debug(\"Ignoring error %s when setting locale\", e)\n    command = create_command(cmd_name, isolated=(\"--isolated\" in cmd_args))\n\n    return command.main(cmd_args)\n"
  },
  {
    "path": "src/pip/_internal/cli/main_parser.py",
    "content": "\"\"\"A single place for constructing and exposing the main parser\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\n\nfrom pip._vendor.rich.markup import escape\n\nfrom pip._internal.build_env import get_runnable_pip\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip._internal.commands import commands_dict, get_similar_commands\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.utils.misc import get_pip_version, get_prog\n\n__all__ = [\"create_main_parser\", \"parse_command\"]\n\n\ndef create_main_parser() -> ConfigOptionParser:\n    \"\"\"Creates and returns the main parser for pip's CLI\"\"\"\n\n    parser = ConfigOptionParser(\n        usage=\"\\n%prog <command> [options]\",\n        add_help_option=False,\n        formatter=UpdatingDefaultsHelpFormatter(),\n        name=\"global\",\n        prog=get_prog(),\n    )\n    parser.disable_interspersed_args()\n\n    parser.version = get_pip_version()\n\n    # add the general options\n    gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)\n    parser.add_option_group(gen_opts)\n\n    # so the help formatter knows\n    parser.main = True  # type: ignore\n\n    # create command listing for description\n    description = [\"\"] + [\n        f\"[optparse.longargs]{name:27}[/] {escape(command_info.summary)}\"\n        for name, command_info in commands_dict.items()\n    ]\n    parser.description = \"\\n\".join(description)\n\n    return parser\n\n\ndef identify_python_interpreter(python: str) -> str | None:\n    # If the named file exists, use it.\n    # If it's a directory, assume it's a virtual environment and\n    # look for the environment's Python executable.\n    if os.path.exists(python):\n        if os.path.isdir(python):\n            # bin/python for Unix, Scripts/python.exe for Windows\n            # Try both in case of odd cases like cygwin.\n            for exe in (\"bin/python\", \"Scripts/python.exe\"):\n                py = os.path.join(python, exe)\n                if os.path.exists(py):\n                    return py\n        else:\n            return python\n\n    # Could not find the interpreter specified\n    return None\n\n\ndef parse_command(args: list[str]) -> tuple[str, list[str]]:\n    parser = create_main_parser()\n\n    # Note: parser calls disable_interspersed_args(), so the result of this\n    # call is to split the initial args into the general options before the\n    # subcommand and everything else.\n    # For example:\n    #  args: ['--timeout=5', 'install', '--user', 'INITools']\n    #  general_options: ['--timeout==5']\n    #  args_else: ['install', '--user', 'INITools']\n    general_options, args_else = parser.parse_args(args)\n\n    # --python\n    if general_options.python and \"_PIP_RUNNING_IN_SUBPROCESS\" not in os.environ:\n        # Re-invoke pip using the specified Python interpreter\n        interpreter = identify_python_interpreter(general_options.python)\n        if interpreter is None:\n            raise CommandError(\n                f\"Could not locate Python interpreter {general_options.python}\"\n            )\n\n        pip_cmd = [\n            interpreter,\n            get_runnable_pip(),\n        ]\n        pip_cmd.extend(args)\n\n        # Set a flag so the child doesn't re-invoke itself, causing\n        # an infinite loop.\n        os.environ[\"_PIP_RUNNING_IN_SUBPROCESS\"] = \"1\"\n        returncode = 0\n        try:\n            proc = subprocess.run(pip_cmd)\n            returncode = proc.returncode\n        except (subprocess.SubprocessError, OSError) as exc:\n            raise CommandError(f\"Failed to run pip under {interpreter}: {exc}\")\n        sys.exit(returncode)\n\n    # --version\n    if general_options.version:\n        sys.stdout.write(parser.version)\n        sys.stdout.write(os.linesep)\n        sys.exit()\n\n    # pip || pip help -> print_help()\n    if not args_else or (args_else[0] == \"help\" and len(args_else) == 1):\n        parser.print_help()\n        sys.exit()\n\n    # the subcommand name\n    cmd_name = args_else[0]\n\n    if cmd_name not in commands_dict:\n        guess = get_similar_commands(cmd_name)\n\n        msg = [f'unknown command \"{cmd_name}\"']\n        if guess:\n            msg.append(f'maybe you meant \"{guess}\"')\n\n        raise CommandError(\" - \".join(msg))\n\n    # all the args without the subcommand\n    cmd_args = args[:]\n    cmd_args.remove(cmd_name)\n\n    return cmd_name, cmd_args\n"
  },
  {
    "path": "src/pip/_internal/cli/parser.py",
    "content": "\"\"\"Base option parser setup\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport optparse\nimport os\nimport re\nimport shutil\nimport sys\nimport textwrap\nfrom collections.abc import Generator\nfrom contextlib import suppress\nfrom typing import Any, NoReturn\n\nfrom pip._vendor.rich.markup import escape\nfrom pip._vendor.rich.theme import Theme\n\nfrom pip._internal.cli.status_codes import UNKNOWN_ERROR\nfrom pip._internal.configuration import Configuration, ConfigurationError\nfrom pip._internal.utils.logging import PipConsole\nfrom pip._internal.utils.misc import redact_auth_from_url, strtobool\n\nlogger = logging.getLogger(__name__)\n\n\nclass PrettyHelpFormatter(optparse.IndentedHelpFormatter):\n    \"\"\"A prettier/less verbose help formatter for optparse.\"\"\"\n\n    styles = {\n        \"optparse.shortargs\": \"green\",\n        \"optparse.longargs\": \"cyan\",\n        \"optparse.groups\": \"bold blue\",\n        \"optparse.metavar\": \"yellow\",\n    }\n    highlights = {\n        r\"\\s(-{1}[\\w]+[\\w-]*)\": \"shortargs\",  # highlight -letter as short args\n        r\"\\s(-{2}[\\w]+[\\w-]*)\": \"longargs\",  # highlight --words as long args\n    }\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        # help position must be aligned with __init__.parseopts.description\n        kwargs[\"max_help_position\"] = 30\n        kwargs[\"indent_increment\"] = 1\n        kwargs[\"width\"] = shutil.get_terminal_size()[0] - 2\n        super().__init__(*args, **kwargs)\n\n    def format_option_strings(self, option: optparse.Option) -> str:\n        \"\"\"Return a comma-separated list of option strings and metavars.\"\"\"\n        opts = []\n\n        if option._short_opts:\n            opts.append(f\"[optparse.shortargs]{option._short_opts[0]}[/]\")\n        if option._long_opts:\n            opts.append(f\"[optparse.longargs]{option._long_opts[0]}[/]\")\n        if len(opts) > 1:\n            opts.insert(1, \", \")\n\n        if option.takes_value():\n            assert option.dest is not None\n            metavar = option.metavar or option.dest.lower()\n            opts.append(f\" [optparse.metavar]<{escape(metavar.lower())}>[/]\")\n\n        return \"\".join(opts)\n\n    def format_option(self, option: optparse.Option) -> str:\n        \"\"\"Overridden method with Rich support.\"\"\"\n        # fmt: off\n        result = []\n        opts = self.option_strings[option]\n        opt_width = self.help_position - self.current_indent - 2\n        # Remove the rich style tags before calculating width during\n        # text wrap calculations. Also store the length removed to adjust\n        # the padding in the else branch.\n        stripped = re.sub(r\"(\\[[a-z.]+\\])|(\\[\\/\\])\", \"\", opts)\n        style_tag_length = len(opts) - len(stripped)\n        if len(stripped) > opt_width:\n            opts = \"%*s%s\\n\" % (self.current_indent, \"\", opts)  # noqa: UP031\n            indent_first = self.help_position\n        else:                       # start help on same line as opts\n            opts = \"%*s%-*s  \" % (self.current_indent, \"\",      # noqa: UP031\n                                  opt_width + style_tag_length, opts)\n            indent_first = 0\n        result.append(opts)\n        if option.help:\n            help_text = self.expand_default(option)\n            help_lines = textwrap.wrap(help_text, self.help_width)\n            result.append(\"%*s%s\\n\" % (indent_first, \"\", help_lines[0]))  # noqa: UP031\n            result.extend([\"%*s%s\\n\" % (self.help_position, \"\", line)     # noqa: UP031\n                           for line in help_lines[1:]])\n        elif opts[-1] != \"\\n\":\n            result.append(\"\\n\")\n        return \"\".join(result)\n        # fmt: on\n\n    def format_heading(self, heading: str) -> str:\n        if heading == \"Options\":\n            return \"\"\n        return \"[optparse.groups]\" + escape(heading) + \":[/]\\n\"\n\n    def format_usage(self, usage: str) -> str:\n        \"\"\"\n        Ensure there is only one newline between usage and the first heading\n        if there is no description.\n        \"\"\"\n        contents = self.indent_lines(textwrap.dedent(usage), \"  \")\n        msg = f\"\\n[optparse.groups]Usage:[/] {escape(contents)}\\n\"\n        return msg\n\n    def format_description(self, description: str | None) -> str:\n        # leave full control over description to us\n        if description:\n            if hasattr(self.parser, \"main\"):\n                label = \"[optparse.groups]Commands:[/]\"\n            else:\n                label = \"[optparse.groups]Description:[/]\"\n\n            # some doc strings have initial newlines, some don't\n            description = description.lstrip(\"\\n\")\n            # some doc strings have final newlines and spaces, some don't\n            description = description.rstrip()\n            # dedent, then reindent\n            description = self.indent_lines(textwrap.dedent(description), \"  \")\n            description = f\"{label}\\n{description}\\n\"\n            return description\n        else:\n            return \"\"\n\n    def format_epilog(self, epilog: str | None) -> str:\n        # leave full control over epilog to us\n        if epilog:\n            return escape(epilog)\n        else:\n            return \"\"\n\n    def expand_default(self, option: optparse.Option) -> str:\n        \"\"\"Overridden HelpFormatter.expand_default() which colorizes flags.\"\"\"\n        help = escape(super().expand_default(option))\n        for regex, style in self.highlights.items():\n            help = re.sub(regex, rf\"[optparse.{style}] \\1[/]\", help)\n        return help\n\n    def indent_lines(self, text: str, indent: str) -> str:\n        new_lines = [indent + line for line in text.split(\"\\n\")]\n        return \"\\n\".join(new_lines)\n\n\nclass UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):\n    \"\"\"Custom help formatter for use in ConfigOptionParser.\n\n    This is updates the defaults before expanding them, allowing\n    them to show up correctly in the help listing.\n\n    Also redact auth from url type options\n    \"\"\"\n\n    def expand_default(self, option: optparse.Option) -> str:\n        default_values = None\n        if self.parser is not None:\n            assert isinstance(self.parser, ConfigOptionParser)\n            self.parser._update_defaults(self.parser.defaults)\n            assert option.dest is not None\n            default_values = self.parser.defaults.get(option.dest)\n        help_text = super().expand_default(option)\n\n        if default_values and option.metavar == \"URL\":\n            if isinstance(default_values, str):\n                default_values = [default_values]\n\n            # If its not a list, we should abort and just return the help text\n            if not isinstance(default_values, list):\n                default_values = []\n\n            for val in default_values:\n                help_text = help_text.replace(val, redact_auth_from_url(val))\n\n        return help_text\n\n\nclass CustomOptionParser(optparse.OptionParser):\n    def insert_option_group(\n        self, idx: int, *args: Any, **kwargs: Any\n    ) -> optparse.OptionGroup:\n        \"\"\"Insert an OptionGroup at a given position.\"\"\"\n        group = self.add_option_group(*args, **kwargs)\n\n        self.option_groups.pop()\n        self.option_groups.insert(idx, group)\n\n        return group\n\n    @property\n    def option_list_all(self) -> list[optparse.Option]:\n        \"\"\"Get a list of all options, including those in option groups.\"\"\"\n        res = self.option_list[:]\n        for i in self.option_groups:\n            res.extend(i.option_list)\n\n        return res\n\n\nclass ConfigOptionParser(CustomOptionParser):\n    \"\"\"Custom option parser which updates its defaults by checking the\n    configuration files and environmental variables\"\"\"\n\n    def __init__(\n        self,\n        *args: Any,\n        name: str,\n        isolated: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        self.name = name\n        self.config = Configuration(isolated)\n\n        assert self.name\n        super().__init__(*args, **kwargs)\n\n    def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:\n        try:\n            return option.check_value(key, val)\n        except optparse.OptionValueError as exc:\n            print(f\"An error occurred during configuration: {exc}\")\n            sys.exit(3)\n\n    def _get_ordered_configuration_items(\n        self,\n    ) -> Generator[tuple[str, Any], None, None]:\n        # Configuration gives keys in an unordered manner. Order them.\n        override_order = [\"global\", self.name, \":env:\"]\n\n        # Pool the options into different groups\n        # Use a dict because we need to implement the fallthrough logic after PR 12201\n        # was merged which removed the fallthrough logic for options\n        section_items_dict: dict[str, dict[str, Any]] = {\n            name: {} for name in override_order\n        }\n\n        for _, value in self.config.items():\n            for section_key, val in value.items():\n\n                section, key = section_key.split(\".\", 1)\n                if section in override_order:\n                    section_items_dict[section][key] = val\n\n        # Now that we a dict of items per section, convert to list of tuples\n        # Make sure we completely remove empty values again\n        section_items = {\n            name: [(k, v) for k, v in section_items_dict[name].items() if v]\n            for name in override_order\n        }\n\n        # Yield each group in their override order\n        for section in override_order:\n            yield from section_items[section]\n\n    def _update_defaults(self, defaults: dict[str, Any]) -> dict[str, Any]:\n        \"\"\"Updates the given defaults with values from the config files and\n        the environ. Does a little special handling for certain types of\n        options (lists).\"\"\"\n\n        # Accumulate complex default state.\n        self.values = optparse.Values(self.defaults)\n        late_eval = set()\n        # Then set the options with those values\n        for key, val in self._get_ordered_configuration_items():\n            # '--' because configuration supports only long names\n            option = self.get_option(\"--\" + key)\n\n            # Ignore options not present in this parser. E.g. non-globals put\n            # in [global] by users that want them to apply to all applicable\n            # commands.\n            if option is None:\n                continue\n\n            assert option.dest is not None\n\n            if option.action in (\"store_true\", \"store_false\"):\n                try:\n                    val = strtobool(val)\n                except ValueError:\n                    self.error(\n                        f\"{val} is not a valid value for {key} option, \"\n                        \"please specify a boolean value like yes/no, \"\n                        \"true/false or 1/0 instead.\"\n                    )\n            elif option.action == \"count\":\n                with suppress(ValueError):\n                    val = strtobool(val)\n                with suppress(ValueError):\n                    val = int(val)\n                if not isinstance(val, int) or val < 0:\n                    self.error(\n                        f\"{val} is not a valid value for {key} option, \"\n                        \"please instead specify either a non-negative integer \"\n                        \"or a boolean value like yes/no or false/true \"\n                        \"which is equivalent to 1/0.\"\n                    )\n            elif option.action == \"append\":\n                val = val.split()\n                val = [self.check_default(option, key, v) for v in val]\n            elif option.action == \"callback\":\n                assert option.callback is not None\n                late_eval.add(option.dest)\n                opt_str = option.get_opt_string()\n                val = option.convert_value(opt_str, val)\n                # From take_action\n                args = option.callback_args or ()\n                kwargs = option.callback_kwargs or {}\n                option.callback(option, opt_str, val, self, *args, **kwargs)\n            else:\n                val = self.check_default(option, key, val)\n\n            defaults[option.dest] = val\n\n        for key in late_eval:\n            defaults[key] = getattr(self.values, key)\n        self.values = None\n        return defaults\n\n    def get_default_values(self) -> optparse.Values:\n        \"\"\"Overriding to make updating the defaults after instantiation of\n        the option parser possible, _update_defaults() does the dirty work.\"\"\"\n        if not self.process_default_values:\n            # Old, pre-Optik 1.5 behaviour.\n            return optparse.Values(self.defaults)\n\n        # Load the configuration, or error out in case of an error\n        try:\n            self.config.load()\n        except ConfigurationError as err:\n            self.exit(UNKNOWN_ERROR, str(err))\n\n        defaults = self._update_defaults(self.defaults.copy())  # ours\n        for option in self._get_all_options():\n            assert option.dest is not None\n            default = defaults.get(option.dest)\n            if isinstance(default, str):\n                opt_str = option.get_opt_string()\n                defaults[option.dest] = option.check_value(opt_str, default)\n        return optparse.Values(defaults)\n\n    def error(self, msg: str) -> NoReturn:\n        self.print_usage(sys.stderr)\n        self.exit(UNKNOWN_ERROR, f\"{msg}\\n\")\n\n    def print_help(self, file: Any = None) -> None:\n        # This is unfortunate but necessary since arguments may have not been\n        # parsed yet at this point, so detect --no-color manually.\n        no_color = (\n            \"--no-color\" in sys.argv\n            or bool(strtobool(os.environ.get(\"PIP_NO_COLOR\", \"no\") or \"no\"))\n            or \"NO_COLOR\" in os.environ\n        )\n        console = PipConsole(\n            theme=Theme(PrettyHelpFormatter.styles), no_color=no_color, file=file\n        )\n        console.print(self.format_help().rstrip(), highlight=False)\n"
  },
  {
    "path": "src/pip/_internal/cli/progress_bars.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport sys\nfrom collections.abc import Generator, Iterable, Iterator\nfrom typing import TYPE_CHECKING, Callable, Literal, TypeVar\n\nfrom pip._vendor.rich.progress import (\n    BarColumn,\n    DownloadColumn,\n    FileSizeColumn,\n    MofNCompleteColumn,\n    Progress,\n    ProgressColumn,\n    SpinnerColumn,\n    TextColumn,\n    TimeElapsedColumn,\n    TimeRemainingColumn,\n    TransferSpeedColumn,\n)\n\nfrom pip._internal.cli.spinners import RateLimiter\nfrom pip._internal.utils.logging import get_console, get_indentation\n\nif TYPE_CHECKING:\n    from pip._internal.req.req_install import InstallRequirement\n\nT = TypeVar(\"T\")\nProgressRenderer = Callable[[Iterable[T]], Iterator[T]]\nBarType = Literal[\"on\", \"off\", \"raw\"]\n\n\ndef _rich_download_progress_bar(\n    iterable: Iterable[bytes],\n    *,\n    bar_type: BarType,\n    size: int | None,\n    initial_progress: int | None = None,\n) -> Generator[bytes, None, None]:\n    assert bar_type == \"on\", \"This should only be used in the default mode.\"\n\n    if not size:\n        total = float(\"inf\")\n        columns: tuple[ProgressColumn, ...] = (\n            TextColumn(\"[progress.description]{task.description}\"),\n            SpinnerColumn(\"line\", speed=1.5),\n            FileSizeColumn(),\n            TransferSpeedColumn(),\n            TimeElapsedColumn(),\n        )\n    else:\n        total = size\n        columns = (\n            TextColumn(\"[progress.description]{task.description}\"),\n            BarColumn(),\n            DownloadColumn(),\n            TransferSpeedColumn(),\n            TextColumn(\"{task.fields[time_description]}\"),\n            TimeRemainingColumn(elapsed_when_finished=True),\n        )\n\n    progress = Progress(*columns, refresh_per_second=5)\n    task_id = progress.add_task(\n        \" \" * (get_indentation() + 2), total=total, time_description=\"eta\"\n    )\n    if initial_progress is not None:\n        progress.update(task_id, advance=initial_progress)\n    with progress:\n        for chunk in iterable:\n            yield chunk\n            progress.update(task_id, advance=len(chunk))\n        progress.update(task_id, time_description=\"\")\n\n\ndef _rich_install_progress_bar(\n    iterable: Iterable[InstallRequirement], *, total: int\n) -> Iterator[InstallRequirement]:\n    columns = (\n        TextColumn(\"{task.fields[indent]}\"),\n        BarColumn(),\n        MofNCompleteColumn(),\n        TextColumn(\"{task.description}\"),\n    )\n    console = get_console()\n\n    bar = Progress(*columns, refresh_per_second=6, console=console, transient=True)\n    # Hiding the progress bar at initialization forces a refresh cycle to occur\n    # until the bar appears, avoiding very short flashes.\n    task = bar.add_task(\"\", total=total, indent=\" \" * get_indentation(), visible=False)\n    with bar:\n        for req in iterable:\n            bar.update(task, description=rf\"\\[{req.name}]\", visible=True)\n            yield req\n            bar.advance(task)\n\n\ndef _raw_progress_bar(\n    iterable: Iterable[bytes],\n    *,\n    size: int | None,\n    initial_progress: int | None = None,\n) -> Generator[bytes, None, None]:\n    def write_progress(current: int, total: int) -> None:\n        sys.stdout.write(f\"Progress {current} of {total}\\n\")\n        sys.stdout.flush()\n\n    current = initial_progress or 0\n    total = size or 0\n    rate_limiter = RateLimiter(0.25)\n\n    write_progress(current, total)\n    for chunk in iterable:\n        current += len(chunk)\n        if rate_limiter.ready() or current == total:\n            write_progress(current, total)\n            rate_limiter.reset()\n        yield chunk\n\n\ndef get_download_progress_renderer(\n    *, bar_type: BarType, size: int | None = None, initial_progress: int | None = None\n) -> ProgressRenderer[bytes]:\n    \"\"\"Get an object that can be used to render the download progress.\n\n    Returns a callable, that takes an iterable to \"wrap\".\n    \"\"\"\n    if bar_type == \"on\":\n        return functools.partial(\n            _rich_download_progress_bar,\n            bar_type=bar_type,\n            size=size,\n            initial_progress=initial_progress,\n        )\n    elif bar_type == \"raw\":\n        return functools.partial(\n            _raw_progress_bar,\n            size=size,\n            initial_progress=initial_progress,\n        )\n    else:\n        return iter  # no-op, when passed an iterator\n\n\ndef get_install_progress_renderer(\n    *, bar_type: BarType, total: int\n) -> ProgressRenderer[InstallRequirement]:\n    \"\"\"Get an object that can be used to render the install progress.\n    Returns a callable, that takes an iterable to \"wrap\".\n    \"\"\"\n    if bar_type == \"on\":\n        return functools.partial(_rich_install_progress_bar, total=total)\n    else:\n        return iter\n"
  },
  {
    "path": "src/pip/_internal/cli/req_command.py",
    "content": "\"\"\"Contains the RequirementCommand base class.\n\nThis class is in a separate module so the commands that do not always\nneed PackageFinder capability don't unnecessarily import the\nPackageFinder machinery and all its vendored dependencies, etc.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nfrom functools import partial\nfrom optparse import Values\nfrom typing import Any, Callable, TypeVar\n\nfrom pip._internal.build_env import (\n    BuildEnvironmentInstaller,\n    InprocessBuildEnvironmentInstaller,\n    SubprocessBuildEnvironmentInstaller,\n)\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.index_command import IndexGroupCommand\nfrom pip._internal.cli.index_command import SessionCommandMixin as SessionCommandMixin\nfrom pip._internal.exceptions import (\n    CommandError,\n    PreviousBuildDirError,\n    UnsupportedPythonVersion,\n)\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import BuildTracker\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n    install_req_from_req_string,\n)\nfrom pip._internal.req.pep723 import PEP723Exception, pep723_metadata\nfrom pip._internal.req.req_dependency_group import parse_dependency_groups\nfrom pip._internal.req.req_file import parse_requirements\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.resolution.base import BaseResolver\nfrom pip._internal.utils.packaging import check_requires_python\nfrom pip._internal.utils.temp_dir import (\n    TempDirectory,\n    TempDirectoryTypeRegistry,\n    tempdir_kinds,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef should_ignore_regular_constraints(options: Values) -> bool:\n    \"\"\"\n    Check if regular constraints should be ignored because\n    we are in a isolated build process and build constraints\n    feature is enabled but no build constraints were passed.\n    \"\"\"\n\n    return os.environ.get(\"_PIP_IN_BUILD_IGNORE_CONSTRAINTS\") == \"1\"\n\n\nKEEPABLE_TEMPDIR_TYPES = [\n    tempdir_kinds.BUILD_ENV,\n    tempdir_kinds.EPHEM_WHEEL_CACHE,\n    tempdir_kinds.REQ_BUILD,\n]\n\n\n_CommandT = TypeVar(\"_CommandT\", bound=\"RequirementCommand\")\n\n\ndef with_cleanup(\n    func: Callable[[_CommandT, Values, list[str]], int],\n) -> Callable[[_CommandT, Values, list[str]], int]:\n    \"\"\"Decorator for common logic related to managing temporary\n    directories.\n    \"\"\"\n\n    def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:\n        for t in KEEPABLE_TEMPDIR_TYPES:\n            registry.set_delete(t, False)\n\n    def wrapper(self: _CommandT, options: Values, args: list[str]) -> int:\n        assert self.tempdir_registry is not None\n        if options.no_clean:\n            configure_tempdir_registry(self.tempdir_registry)\n\n        try:\n            return func(self, options, args)\n        except PreviousBuildDirError:\n            # This kind of conflict can occur when the user passes an explicit\n            # build directory with a pre-existing folder. In that case we do\n            # not want to accidentally remove it.\n            configure_tempdir_registry(self.tempdir_registry)\n            raise\n\n    return wrapper\n\n\ndef parse_constraint_files(\n    constraint_files: list[str],\n    finder: PackageFinder,\n    options: Values,\n    session: PipSession,\n) -> list[InstallRequirement]:\n    requirements = []\n    for filename in constraint_files:\n        for parsed_req in parse_requirements(\n            filename,\n            constraint=True,\n            finder=finder,\n            options=options,\n            session=session,\n        ):\n            req_to_add = install_req_from_parsed_requirement(\n                parsed_req,\n                isolated=options.isolated_mode,\n                user_supplied=False,\n            )\n            requirements.append(req_to_add)\n\n    return requirements\n\n\nclass RequirementCommand(IndexGroupCommand):\n    def __init__(self, *args: Any, **kw: Any) -> None:\n        super().__init__(*args, **kw)\n\n        self.cmd_opts.add_option(cmdoptions.dependency_groups())\n        self.cmd_opts.add_option(cmdoptions.no_clean())\n\n    @staticmethod\n    def determine_resolver_variant(options: Values) -> str:\n        \"\"\"Determines which resolver should be used, based on the given options.\"\"\"\n        if \"legacy-resolver\" in options.deprecated_features_enabled:\n            return \"legacy\"\n\n        return \"resolvelib\"\n\n    @classmethod\n    def make_requirement_preparer(\n        cls,\n        temp_build_dir: TempDirectory,\n        options: Values,\n        build_tracker: BuildTracker,\n        session: PipSession,\n        finder: PackageFinder,\n        use_user_site: bool,\n        download_dir: str | None = None,\n        verbosity: int = 0,\n    ) -> RequirementPreparer:\n        \"\"\"\n        Create a RequirementPreparer instance for the given parameters.\n        \"\"\"\n        temp_build_dir_path = temp_build_dir.path\n        assert temp_build_dir_path is not None\n        legacy_resolver = False\n\n        resolver_variant = cls.determine_resolver_variant(options)\n        if resolver_variant == \"resolvelib\":\n            lazy_wheel = \"fast-deps\" in options.features_enabled\n            if lazy_wheel:\n                logger.warning(\n                    \"pip is using lazily downloaded wheels using HTTP \"\n                    \"range requests to obtain dependency information. \"\n                    \"This experimental feature is enabled through \"\n                    \"--use-feature=fast-deps and it is not ready for \"\n                    \"production.\"\n                )\n        else:\n            legacy_resolver = True\n            lazy_wheel = False\n            if \"fast-deps\" in options.features_enabled:\n                logger.warning(\n                    \"fast-deps has no effect when used with the legacy resolver.\"\n                )\n\n        # Handle build constraints\n        build_constraints = getattr(options, \"build_constraints\", [])\n        build_constraint_feature_enabled = (\n            \"build-constraint\" in options.features_enabled\n        )\n\n        env_installer: BuildEnvironmentInstaller\n        if \"inprocess-build-deps\" in options.features_enabled:\n            build_constraint_reqs = parse_constraint_files(\n                build_constraints, finder, options, session\n            )\n            env_installer = InprocessBuildEnvironmentInstaller(\n                finder=finder,\n                build_tracker=build_tracker,\n                build_constraints=build_constraint_reqs,\n                verbosity=verbosity,\n                wheel_cache=WheelCache(options.cache_dir),\n            )\n        else:\n            env_installer = SubprocessBuildEnvironmentInstaller(\n                finder,\n                build_constraints=build_constraints,\n                build_constraint_feature_enabled=build_constraint_feature_enabled,\n            )\n\n        return RequirementPreparer(\n            build_dir=temp_build_dir_path,\n            src_dir=options.src_dir,\n            download_dir=download_dir,\n            build_isolation=options.build_isolation,\n            build_isolation_installer=env_installer,\n            check_build_deps=options.check_build_deps,\n            build_tracker=build_tracker,\n            session=session,\n            progress_bar=options.progress_bar,\n            finder=finder,\n            require_hashes=options.require_hashes,\n            use_user_site=use_user_site,\n            lazy_wheel=lazy_wheel,\n            verbosity=verbosity,\n            legacy_resolver=legacy_resolver,\n        )\n\n    @classmethod\n    def make_resolver(\n        cls,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        options: Values,\n        wheel_cache: WheelCache | None = None,\n        use_user_site: bool = False,\n        ignore_installed: bool = True,\n        ignore_requires_python: bool = False,\n        force_reinstall: bool = False,\n        upgrade_strategy: str = \"to-satisfy-only\",\n        py_version_info: tuple[int, ...] | None = None,\n    ) -> BaseResolver:\n        \"\"\"\n        Create a Resolver instance for the given parameters.\n        \"\"\"\n        make_install_req = partial(\n            install_req_from_req_string,\n            isolated=options.isolated_mode,\n        )\n        resolver_variant = cls.determine_resolver_variant(options)\n        # The long import name and duplicated invocation is needed to convince\n        # Mypy into correctly typechecking. Otherwise it would complain the\n        # \"Resolver\" class being redefined.\n        if resolver_variant == \"resolvelib\":\n            import pip._internal.resolution.resolvelib.resolver\n\n            return pip._internal.resolution.resolvelib.resolver.Resolver(\n                preparer=preparer,\n                finder=finder,\n                wheel_cache=wheel_cache,\n                make_install_req=make_install_req,\n                use_user_site=use_user_site,\n                ignore_dependencies=options.ignore_dependencies,\n                ignore_installed=ignore_installed,\n                ignore_requires_python=ignore_requires_python,\n                force_reinstall=force_reinstall,\n                upgrade_strategy=upgrade_strategy,\n                py_version_info=py_version_info,\n            )\n        import pip._internal.resolution.legacy.resolver\n\n        return pip._internal.resolution.legacy.resolver.Resolver(\n            preparer=preparer,\n            finder=finder,\n            wheel_cache=wheel_cache,\n            make_install_req=make_install_req,\n            use_user_site=use_user_site,\n            ignore_dependencies=options.ignore_dependencies,\n            ignore_installed=ignore_installed,\n            ignore_requires_python=ignore_requires_python,\n            force_reinstall=force_reinstall,\n            upgrade_strategy=upgrade_strategy,\n            py_version_info=py_version_info,\n        )\n\n    def get_requirements(\n        self,\n        args: list[str],\n        options: Values,\n        finder: PackageFinder,\n        session: PipSession,\n    ) -> list[InstallRequirement]:\n        \"\"\"\n        Parse command-line arguments into the corresponding requirements.\n        \"\"\"\n        requirements: list[InstallRequirement] = []\n\n        if not should_ignore_regular_constraints(options):\n            constraints = parse_constraint_files(\n                options.constraints, finder, options, session\n            )\n            requirements.extend(constraints)\n\n        for req in args:\n            if not req.strip():\n                continue\n            req_to_add = install_req_from_line(\n                req,\n                comes_from=None,\n                isolated=options.isolated_mode,\n                user_supplied=True,\n                config_settings=getattr(options, \"config_settings\", None),\n            )\n            requirements.append(req_to_add)\n\n        if options.dependency_groups:\n            for req in parse_dependency_groups(options.dependency_groups):\n                req_to_add = install_req_from_req_string(\n                    req,\n                    isolated=options.isolated_mode,\n                    user_supplied=True,\n                )\n                requirements.append(req_to_add)\n\n        for req in options.editables:\n            req_to_add = install_req_from_editable(\n                req,\n                user_supplied=True,\n                isolated=options.isolated_mode,\n                config_settings=getattr(options, \"config_settings\", None),\n            )\n            requirements.append(req_to_add)\n\n        # NOTE: options.require_hashes may be set if --require-hashes is True\n        for filename in options.requirements:\n            for parsed_req in parse_requirements(\n                filename, finder=finder, options=options, session=session\n            ):\n                req_to_add = install_req_from_parsed_requirement(\n                    parsed_req,\n                    isolated=options.isolated_mode,\n                    user_supplied=True,\n                    config_settings=(\n                        parsed_req.options.get(\"config_settings\")\n                        if parsed_req.options\n                        else None\n                    ),\n                )\n                requirements.append(req_to_add)\n\n        if options.requirements_from_scripts:\n            if len(options.requirements_from_scripts) > 1:\n                raise CommandError(\"--requirements-from-script can only be given once\")\n\n            script = options.requirements_from_scripts[0]\n            try:\n                script_metadata = pep723_metadata(script)\n            except PEP723Exception as exc:\n                raise CommandError(exc.msg)\n\n            script_requires_python = script_metadata.get(\"requires-python\", \"\")\n\n            if script_requires_python and not options.ignore_requires_python:\n                target_python = make_target_python(options)\n\n                if not check_requires_python(\n                    requires_python=script_requires_python,\n                    version_info=target_python.py_version_info,\n                ):\n                    raise UnsupportedPythonVersion(\n                        f\"Script {script!r} requires a different Python: \"\n                        f\"{target_python.py_version} not in {script_requires_python!r}\"\n                    )\n\n            for req in script_metadata.get(\"dependencies\", []):\n                req_to_add = install_req_from_req_string(\n                    req,\n                    isolated=options.isolated_mode,\n                    user_supplied=True,\n                )\n                requirements.append(req_to_add)\n\n        # If any requirement has hash options, enable hash checking.\n        if any(req.has_hash_options for req in requirements):\n            options.require_hashes = True\n\n        if not (\n            args\n            or options.editables\n            or options.requirements\n            or options.dependency_groups\n            or options.requirements_from_scripts\n        ):\n            opts = {\"name\": self.name}\n            if options.find_links:\n                raise CommandError(\n                    \"You must give at least one requirement to {name} \"\n                    '(maybe you meant \"pip {name} {links}\"?)'.format(\n                        **dict(opts, links=\" \".join(options.find_links))\n                    )\n                )\n            else:\n                raise CommandError(\n                    \"You must give at least one requirement to {name} \"\n                    '(see \"pip help {name}\")'.format(**opts)\n                )\n\n        return requirements\n\n    @staticmethod\n    def trace_basic_info(finder: PackageFinder) -> None:\n        \"\"\"\n        Trace basic information about the provided objects.\n        \"\"\"\n        # Display where finder is looking for packages\n        search_scope = finder.search_scope\n        locations = search_scope.get_formatted_locations()\n        if locations:\n            logger.info(locations)\n\n    def _build_package_finder(\n        self,\n        options: Values,\n        session: PipSession,\n        target_python: TargetPython | None = None,\n        ignore_requires_python: bool | None = None,\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to this requirement command.\n\n        :param ignore_requires_python: Whether to ignore incompatible\n            \"Requires-Python\" values in links. Defaults to False.\n        \"\"\"\n        link_collector = LinkCollector.create(session, options=options)\n        selection_prefs = SelectionPreferences(\n            allow_yanked=True,\n            format_control=options.format_control,\n            release_control=options.release_control,\n            prefer_binary=options.prefer_binary,\n            ignore_requires_python=ignore_requires_python,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n            target_python=target_python,\n            uploaded_prior_to=options.uploaded_prior_to,\n        )\n"
  },
  {
    "path": "src/pip/_internal/cli/spinners.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport itertools\nimport logging\nimport sys\nimport time\nfrom collections.abc import Generator\nfrom typing import IO, Final\n\nfrom pip._vendor.rich.console import (\n    Console,\n    ConsoleOptions,\n    RenderableType,\n    RenderResult,\n)\nfrom pip._vendor.rich.live import Live\nfrom pip._vendor.rich.measure import Measurement\nfrom pip._vendor.rich.text import Text\n\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.logging import get_console, get_indentation\n\nlogger = logging.getLogger(__name__)\n\nSPINNER_CHARS: Final = r\"-\\|/\"\nSPINS_PER_SECOND: Final = 8\n\n\nclass SpinnerInterface:\n    def spin(self) -> None:\n        raise NotImplementedError()\n\n    def finish(self, final_status: str) -> None:\n        raise NotImplementedError()\n\n\nclass InteractiveSpinner(SpinnerInterface):\n    def __init__(\n        self,\n        message: str,\n        file: IO[str] | None = None,\n        spin_chars: str = SPINNER_CHARS,\n        # Empirically, 8 updates/second looks nice\n        min_update_interval_seconds: float = 1 / SPINS_PER_SECOND,\n    ):\n        self._message = message\n        if file is None:\n            file = sys.stdout\n        self._file = file\n        self._rate_limiter = RateLimiter(min_update_interval_seconds)\n        self._finished = False\n\n        self._spin_cycle = itertools.cycle(spin_chars)\n\n        self._file.write(\" \" * get_indentation() + self._message + \" ... \")\n        self._width = 0\n\n    def _write(self, status: str) -> None:\n        assert not self._finished\n        # Erase what we wrote before by backspacing to the beginning, writing\n        # spaces to overwrite the old text, and then backspacing again\n        backup = \"\\b\" * self._width\n        self._file.write(backup + \" \" * self._width + backup)\n        # Now we have a blank slate to add our status\n        self._file.write(status)\n        self._width = len(status)\n        self._file.flush()\n        self._rate_limiter.reset()\n\n    def spin(self) -> None:\n        if self._finished:\n            return\n        if not self._rate_limiter.ready():\n            return\n        self._write(next(self._spin_cycle))\n\n    def finish(self, final_status: str) -> None:\n        if self._finished:\n            return\n        self._write(final_status)\n        self._file.write(\"\\n\")\n        self._file.flush()\n        self._finished = True\n\n\n# Used for dumb terminals, non-interactive installs (no tty), etc.\n# We still print updates occasionally (once every 60 seconds by default) to\n# act as a keep-alive for systems like Travis-CI that take lack-of-output as\n# an indication that a task has frozen.\nclass NonInteractiveSpinner(SpinnerInterface):\n    def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:\n        self._message = message\n        self._finished = False\n        self._rate_limiter = RateLimiter(min_update_interval_seconds)\n        self._update(\"started\")\n\n    def _update(self, status: str) -> None:\n        assert not self._finished\n        self._rate_limiter.reset()\n        logger.info(\"%s: %s\", self._message, status)\n\n    def spin(self) -> None:\n        if self._finished:\n            return\n        if not self._rate_limiter.ready():\n            return\n        self._update(\"still running...\")\n\n    def finish(self, final_status: str) -> None:\n        if self._finished:\n            return\n        self._update(f\"finished with status '{final_status}'\")\n        self._finished = True\n\n\nclass RateLimiter:\n    def __init__(self, min_update_interval_seconds: float) -> None:\n        self._min_update_interval_seconds = min_update_interval_seconds\n        self._last_update: float = 0\n\n    def ready(self) -> bool:\n        now = time.time()\n        delta = now - self._last_update\n        return delta >= self._min_update_interval_seconds\n\n    def reset(self) -> None:\n        self._last_update = time.time()\n\n\n@contextlib.contextmanager\ndef open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:\n    # Interactive spinner goes directly to sys.stdout rather than being routed\n    # through the logging system, but it acts like it has level INFO,\n    # i.e. it's only displayed if we're at level INFO or better.\n    # Non-interactive spinner goes through the logging system, so it is always\n    # in sync with logging configuration.\n    if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:\n        spinner: SpinnerInterface = InteractiveSpinner(message)\n    else:\n        spinner = NonInteractiveSpinner(message)\n    try:\n        with hidden_cursor(sys.stdout):\n            yield spinner\n    except KeyboardInterrupt:\n        spinner.finish(\"canceled\")\n        raise\n    except Exception:\n        spinner.finish(\"error\")\n        raise\n    else:\n        spinner.finish(\"done\")\n\n\nclass _PipRichSpinner:\n    \"\"\"\n    Custom rich spinner that matches the style of the legacy spinners.\n\n    (*) Updates will be handled in a background thread by a rich live panel\n        which will call render() automatically at the appropriate time.\n    \"\"\"\n\n    def __init__(self, label: str) -> None:\n        self.label = label\n        self._spin_cycle = itertools.cycle(SPINNER_CHARS)\n        self._spinner_text = \"\"\n        self._finished = False\n        self._indent = get_indentation() * \" \"\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        yield self.render()\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        text = self.render()\n        return Measurement.get(console, options, text)\n\n    def render(self) -> RenderableType:\n        if not self._finished:\n            self._spinner_text = next(self._spin_cycle)\n\n        return Text.assemble(self._indent, self.label, \" ... \", self._spinner_text)\n\n    def finish(self, status: str) -> None:\n        \"\"\"Stop spinning and set a final status message.\"\"\"\n        self._spinner_text = status\n        self._finished = True\n\n\n@contextlib.contextmanager\ndef open_rich_spinner(label: str, console: Console | None = None) -> Generator[None]:\n    if not logger.isEnabledFor(logging.INFO):\n        # Don't show spinner if --quiet is given.\n        yield\n        return\n\n    console = console or get_console()\n    spinner = _PipRichSpinner(label)\n    with Live(spinner, refresh_per_second=SPINS_PER_SECOND, console=console):\n        try:\n            yield\n        except KeyboardInterrupt:\n            spinner.finish(\"canceled\")\n            raise\n        except Exception:\n            spinner.finish(\"error\")\n            raise\n        else:\n            spinner.finish(\"done\")\n\n\nHIDE_CURSOR = \"\\x1b[?25l\"\nSHOW_CURSOR = \"\\x1b[?25h\"\n\n\n@contextlib.contextmanager\ndef hidden_cursor(file: IO[str]) -> Generator[None, None, None]:\n    # The Windows terminal does not support the hide/show cursor ANSI codes,\n    # even via colorama. So don't even try.\n    if WINDOWS:\n        yield\n    # We don't want to clutter the output with control characters if we're\n    # writing to a file, or if the user is running with --quiet.\n    # See https://github.com/pypa/pip/issues/3418\n    elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:\n        yield\n    else:\n        file.write(HIDE_CURSOR)\n        try:\n            yield\n        finally:\n            file.write(SHOW_CURSOR)\n"
  },
  {
    "path": "src/pip/_internal/cli/status_codes.py",
    "content": "SUCCESS = 0\nERROR = 1\nUNKNOWN_ERROR = 2\nVIRTUALENV_NOT_FOUND = 3\nPREVIOUS_BUILD_DIR_ERROR = 4\nNO_MATCHES_FOUND = 23\n"
  },
  {
    "path": "src/pip/_internal/commands/__init__.py",
    "content": "\"\"\"\nPackage containing all pip commands\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nfrom collections import namedtuple\nfrom typing import Any\n\nfrom pip._internal.cli.base_command import Command\n\nCommandInfo = namedtuple(\"CommandInfo\", \"module_path, class_name, summary\")\n\n# This dictionary does a bunch of heavy lifting for help output:\n# - Enables avoiding additional (costly) imports for presenting `--help`.\n# - The ordering matters for help display.\n#\n# Even though the module path starts with the same \"pip._internal.commands\"\n# prefix, the full path makes testing easier (specifically when modifying\n# `commands_dict` in test setup / teardown).\ncommands_dict: dict[str, CommandInfo] = {\n    \"install\": CommandInfo(\n        \"pip._internal.commands.install\",\n        \"InstallCommand\",\n        \"Install packages.\",\n    ),\n    \"lock\": CommandInfo(\n        \"pip._internal.commands.lock\",\n        \"LockCommand\",\n        \"Generate a lock file.\",\n    ),\n    \"download\": CommandInfo(\n        \"pip._internal.commands.download\",\n        \"DownloadCommand\",\n        \"Download packages.\",\n    ),\n    \"uninstall\": CommandInfo(\n        \"pip._internal.commands.uninstall\",\n        \"UninstallCommand\",\n        \"Uninstall packages.\",\n    ),\n    \"freeze\": CommandInfo(\n        \"pip._internal.commands.freeze\",\n        \"FreezeCommand\",\n        \"Output installed packages in requirements format.\",\n    ),\n    \"inspect\": CommandInfo(\n        \"pip._internal.commands.inspect\",\n        \"InspectCommand\",\n        \"Inspect the python environment.\",\n    ),\n    \"list\": CommandInfo(\n        \"pip._internal.commands.list\",\n        \"ListCommand\",\n        \"List installed packages.\",\n    ),\n    \"show\": CommandInfo(\n        \"pip._internal.commands.show\",\n        \"ShowCommand\",\n        \"Show information about installed packages.\",\n    ),\n    \"check\": CommandInfo(\n        \"pip._internal.commands.check\",\n        \"CheckCommand\",\n        \"Verify installed packages have compatible dependencies.\",\n    ),\n    \"config\": CommandInfo(\n        \"pip._internal.commands.configuration\",\n        \"ConfigurationCommand\",\n        \"Manage local and global configuration.\",\n    ),\n    \"search\": CommandInfo(\n        \"pip._internal.commands.search\",\n        \"SearchCommand\",\n        \"Search PyPI for packages.\",\n    ),\n    \"cache\": CommandInfo(\n        \"pip._internal.commands.cache\",\n        \"CacheCommand\",\n        \"Inspect and manage pip's wheel cache.\",\n    ),\n    \"index\": CommandInfo(\n        \"pip._internal.commands.index\",\n        \"IndexCommand\",\n        \"Inspect information available from package indexes.\",\n    ),\n    \"wheel\": CommandInfo(\n        \"pip._internal.commands.wheel\",\n        \"WheelCommand\",\n        \"Build wheels from your requirements.\",\n    ),\n    \"hash\": CommandInfo(\n        \"pip._internal.commands.hash\",\n        \"HashCommand\",\n        \"Compute hashes of package archives.\",\n    ),\n    \"completion\": CommandInfo(\n        \"pip._internal.commands.completion\",\n        \"CompletionCommand\",\n        \"A helper command used for command completion.\",\n    ),\n    \"debug\": CommandInfo(\n        \"pip._internal.commands.debug\",\n        \"DebugCommand\",\n        \"Show information useful for debugging.\",\n    ),\n    \"help\": CommandInfo(\n        \"pip._internal.commands.help\",\n        \"HelpCommand\",\n        \"Show help for commands.\",\n    ),\n}\n\n\ndef create_command(name: str, **kwargs: Any) -> Command:\n    \"\"\"\n    Create an instance of the Command class with the given name.\n    \"\"\"\n    module_path, class_name, summary = commands_dict[name]\n    module = importlib.import_module(module_path)\n    command_class = getattr(module, class_name)\n    command = command_class(name=name, summary=summary, **kwargs)\n\n    return command\n\n\ndef get_similar_commands(name: str) -> str | None:\n    \"\"\"Command name auto-correct.\"\"\"\n    from difflib import get_close_matches\n\n    name = name.lower()\n\n    close_commands = get_close_matches(name, commands_dict.keys())\n\n    if close_commands:\n        return close_commands[0]\n    else:\n        return None\n"
  },
  {
    "path": "src/pip/_internal/commands/cache.py",
    "content": "import os\nimport textwrap\nfrom optparse import Values\nfrom typing import Callable\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.exceptions import CommandError, PipError\nfrom pip._internal.utils import filesystem\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import format_size\n\nlogger = getLogger(__name__)\n\n\nclass CacheCommand(Command):\n    \"\"\"\n    Inspect and manage pip's wheel cache.\n\n    Subcommands:\n\n    - dir: Show the cache directory.\n    - info: Show information about the cache.\n    - list: List filenames of packages stored in the cache.\n    - remove: Remove one or more package from the cache.\n    - purge: Remove all items from the cache.\n\n    ``<pattern>`` can be a glob expression or a package name.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n        %prog dir\n        %prog info\n        %prog list [<pattern>] [--format=[human, abspath]]\n        %prog remove <pattern>\n        %prog purge\n    \"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--format\",\n            action=\"store\",\n            dest=\"list_format\",\n            default=\"human\",\n            choices=(\"human\", \"abspath\"),\n            help=\"Select the output format among: human (default) or abspath\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:\n        return {\n            \"dir\": self.get_cache_dir,\n            \"info\": self.get_cache_info,\n            \"list\": self.list_cache_items,\n            \"remove\": self.remove_cache_items,\n            \"purge\": self.purge_cache,\n        }\n\n    def run(self, options: Values, args: list[str]) -> int:\n        handler_map = self.handler_map()\n\n        if not options.cache_dir:\n            logger.error(\"pip cache commands can not function since cache is disabled.\")\n            return ERROR\n\n        # Determine action\n        if not args or args[0] not in handler_map:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handler_map)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handler_map[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def get_cache_dir(self, options: Values, args: list[str]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        logger.info(options.cache_dir)\n\n    def get_cache_info(self, options: Values, args: list[str]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        num_http_files = len(self._find_http_files(options))\n        num_packages = len(self._find_wheels(options, \"*\"))\n\n        http_cache_location = self._cache_dir(options, \"http-v2\")\n        old_http_cache_location = self._cache_dir(options, \"http\")\n        wheels_cache_location = self._cache_dir(options, \"wheels\")\n        http_cache_size = filesystem.format_size(\n            filesystem.directory_size(http_cache_location)\n            + filesystem.directory_size(old_http_cache_location)\n        )\n        wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)\n\n        message = (\n            textwrap.dedent(\n                \"\"\"\n                    Package index page cache location (pip v23.3+): {http_cache_location}\n                    Package index page cache location (older pips): {old_http_cache_location}\n                    Package index page cache size: {http_cache_size}\n                    Number of HTTP files: {num_http_files}\n                    Locally built wheels location: {wheels_cache_location}\n                    Locally built wheels size: {wheels_cache_size}\n                    Number of locally built wheels: {package_count}\n                \"\"\"  # noqa: E501\n            )\n            .format(\n                http_cache_location=http_cache_location,\n                old_http_cache_location=old_http_cache_location,\n                http_cache_size=http_cache_size,\n                num_http_files=num_http_files,\n                wheels_cache_location=wheels_cache_location,\n                package_count=num_packages,\n                wheels_cache_size=wheels_cache_size,\n            )\n            .strip()\n        )\n\n        logger.info(message)\n\n    def list_cache_items(self, options: Values, args: list[str]) -> None:\n        if len(args) > 1:\n            raise CommandError(\"Too many arguments\")\n\n        if args:\n            pattern = args[0]\n        else:\n            pattern = \"*\"\n\n        files = self._find_wheels(options, pattern)\n        if options.list_format == \"human\":\n            self.format_for_human(files)\n        else:\n            self.format_for_abspath(files)\n\n    def format_for_human(self, files: list[str]) -> None:\n        if not files:\n            logger.info(\"No locally built wheels cached.\")\n            return\n\n        results = []\n        for filename in files:\n            wheel = os.path.basename(filename)\n            size = filesystem.format_file_size(filename)\n            results.append(f\" - {wheel} ({size})\")\n        logger.info(\"Cache contents:\\n\")\n        logger.info(\"\\n\".join(sorted(results)))\n\n    def format_for_abspath(self, files: list[str]) -> None:\n        if files:\n            logger.info(\"\\n\".join(sorted(files)))\n\n    def remove_cache_items(self, options: Values, args: list[str]) -> None:\n        if len(args) > 1:\n            raise CommandError(\"Too many arguments\")\n\n        if not args:\n            raise CommandError(\"Please provide a pattern\")\n\n        files = self._find_wheels(options, args[0])\n\n        no_matching_msg = \"No matching packages\"\n        if args[0] == \"*\":\n            # Only fetch http files if no specific pattern given\n            files += self._find_http_files(options)\n        else:\n            # Add the pattern to the log message\n            no_matching_msg += f' for pattern \"{args[0]}\"'\n\n        if not files:\n            logger.warning(no_matching_msg)\n\n        bytes_removed = 0\n        for filename in files:\n            bytes_removed += os.stat(filename).st_size\n            os.unlink(filename)\n            logger.verbose(\"Removed %s\", filename)\n\n        http_dirs = filesystem.subdirs_without_files(self._cache_dir(options, \"http\"))\n        wheel_dirs = filesystem.subdirs_without_wheels(\n            self._cache_dir(options, \"wheels\")\n        )\n        dirs = [*http_dirs, *wheel_dirs]\n\n        for subdir in dirs:\n            try:\n                for file in subdir.iterdir():\n                    file.unlink(missing_ok=True)\n                subdir.rmdir()\n            except FileNotFoundError:\n                # If the directory is already gone, that's fine.\n                pass\n            logger.verbose(\"Removed %s\", subdir)\n\n        # selfcheck.json is no longer used by pip.\n        selfcheck_json = self._cache_dir(options, \"selfcheck.json\")\n        if os.path.isfile(selfcheck_json):\n            os.remove(selfcheck_json)\n            logger.verbose(\"Removed legacy selfcheck.json file\")\n\n        logger.info(\"Files removed: %s (%s)\", len(files), format_size(bytes_removed))\n        logger.info(\"Directories removed: %s\", len(dirs))\n\n    def purge_cache(self, options: Values, args: list[str]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        return self.remove_cache_items(options, [\"*\"])\n\n    def _cache_dir(self, options: Values, subdir: str) -> str:\n        return os.path.join(options.cache_dir, subdir)\n\n    def _find_http_files(self, options: Values) -> list[str]:\n        old_http_dir = self._cache_dir(options, \"http\")\n        new_http_dir = self._cache_dir(options, \"http-v2\")\n        return filesystem.find_files(old_http_dir, \"*\") + filesystem.find_files(\n            new_http_dir, \"*\"\n        )\n\n    def _find_wheels(self, options: Values, pattern: str) -> list[str]:\n        wheel_dir = self._cache_dir(options, \"wheels\")\n\n        # The wheel filename format, as specified in PEP 427, is:\n        #     {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl\n        #\n        # Additionally, non-alphanumeric values in the distribution are\n        # normalized to underscores (_), meaning hyphens can never occur\n        # before `-{version}`.\n        #\n        # Given that information:\n        # - If the pattern we're given contains a hyphen (-), the user is\n        #   providing at least the version. Thus, we can just append `*.whl`\n        #   to match the rest of it.\n        # - If the pattern we're given doesn't contain a hyphen (-), the\n        #   user is only providing the name. Thus, we append `-*.whl` to\n        #   match the hyphen before the version, followed by anything else.\n        #\n        # PEP 427: https://www.python.org/dev/peps/pep-0427/\n        pattern = pattern + (\"*.whl\" if \"-\" in pattern else \"-*.whl\")\n\n        return filesystem.find_files(wheel_dir, pattern)\n"
  },
  {
    "path": "src/pip/_internal/commands/check.py",
    "content": "import logging\nfrom optparse import Values\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.operations.check import (\n    check_package_set,\n    check_unsupported,\n    create_package_set_from_installed,\n)\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass CheckCommand(Command):\n    \"\"\"Verify installed packages have compatible dependencies.\"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def run(self, options: Values, args: list[str]) -> int:\n        package_set, parsing_probs = create_package_set_from_installed()\n        missing, conflicting = check_package_set(package_set)\n        unsupported = list(\n            check_unsupported(\n                get_default_environment().iter_installed_distributions(),\n                get_supported(),\n            )\n        )\n\n        for project_name in missing:\n            version = package_set[project_name].version\n            for dependency in missing[project_name]:\n                write_output(\n                    \"%s %s requires %s, which is not installed.\",\n                    project_name,\n                    version,\n                    dependency[0],\n                )\n\n        for project_name in conflicting:\n            version = package_set[project_name].version\n            for dep_name, dep_version, req in conflicting[project_name]:\n                write_output(\n                    \"%s %s has requirement %s, but you have %s %s.\",\n                    project_name,\n                    version,\n                    req,\n                    dep_name,\n                    dep_version,\n                )\n        for package in unsupported:\n            write_output(\n                \"%s %s is not supported on this platform\",\n                package.raw_name,\n                package.version,\n            )\n        if missing or conflicting or parsing_probs or unsupported:\n            return ERROR\n        else:\n            write_output(\"No broken requirements found.\")\n            return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/completion.py",
    "content": "import sys\nimport textwrap\nfrom optparse import Values\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.utils.misc import get_prog\n\nBASE_COMPLETION = \"\"\"\n# pip {shell} completion start{script}# pip {shell} completion end\n\"\"\"\n\nCOMPLETION_SCRIPTS = {\n    \"bash\": \"\"\"\n        _pip_completion()\n        {{\n            local IFS=$' \\\\t\\\\n'\n            COMPREPLY=( $( COMP_WORDS=\"${{COMP_WORDS[*]}}\" \\\\\n                           COMP_CWORD=$COMP_CWORD \\\\\n                           PIP_AUTO_COMPLETE=1 \"$1\" 2>/dev/null ) )\n        }}\n        complete -o default -F _pip_completion {prog}\n    \"\"\",\n    \"zsh\": \"\"\"\n        #compdef -P pip[0-9.]#\n        __pip() {{\n          compadd $( COMP_WORDS=\"$words[*]\" \\\\\n                     COMP_CWORD=$((CURRENT-1)) \\\\\n                     PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )\n        }}\n        if [[ $zsh_eval_context[-1] == loadautofunc ]]; then\n          # autoload from fpath, call function directly\n          __pip \"$@\"\n        else\n          # eval/source/. command, register function for later\n          compdef __pip -P 'pip[0-9.]#'\n        fi\n    \"\"\",\n    \"fish\": \"\"\"\n        function __fish_complete_pip\n            set -lx COMP_WORDS \\\\\n                (commandline --current-process --tokenize --cut-at-cursor) \\\\\n                (commandline --current-token --cut-at-cursor)\n            set -lx COMP_CWORD (math (count $COMP_WORDS) - 1)\n            set -lx PIP_AUTO_COMPLETE 1\n            set -l completions\n            if string match -q '2.*' $version\n                set completions (eval $COMP_WORDS[1])\n            else\n                set completions ($COMP_WORDS[1])\n            end\n            string split \\\\  -- $completions\n        end\n        complete -fa \"(__fish_complete_pip)\" -c {prog}\n    \"\"\",\n    \"powershell\": \"\"\"\n        if ((Test-Path Function:\\\\TabExpansion) -and -not `\n            (Test-Path Function:\\\\_pip_completeBackup)) {{\n            Rename-Item Function:\\\\TabExpansion _pip_completeBackup\n        }}\n        function TabExpansion($line, $lastWord) {{\n            $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()\n            if ($lastBlock.StartsWith(\"{prog} \")) {{\n                $Env:COMP_WORDS=$lastBlock\n                $Env:COMP_CWORD=$lastBlock.Split().Length - 1\n                $Env:PIP_AUTO_COMPLETE=1\n                (& {prog}).Split()\n                Remove-Item Env:COMP_WORDS\n                Remove-Item Env:COMP_CWORD\n                Remove-Item Env:PIP_AUTO_COMPLETE\n            }}\n            elseif (Test-Path Function:\\\\_pip_completeBackup) {{\n                # Fall back on existing tab expansion\n                _pip_completeBackup $line $lastWord\n            }}\n        }}\n    \"\"\",\n}\n\n\nclass CompletionCommand(Command):\n    \"\"\"A helper command to be used for command completion.\"\"\"\n\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--bash\",\n            \"-b\",\n            action=\"store_const\",\n            const=\"bash\",\n            dest=\"shell\",\n            help=\"Emit completion code for bash\",\n        )\n        self.cmd_opts.add_option(\n            \"--zsh\",\n            \"-z\",\n            action=\"store_const\",\n            const=\"zsh\",\n            dest=\"shell\",\n            help=\"Emit completion code for zsh\",\n        )\n        self.cmd_opts.add_option(\n            \"--fish\",\n            \"-f\",\n            action=\"store_const\",\n            const=\"fish\",\n            dest=\"shell\",\n            help=\"Emit completion code for fish\",\n        )\n        self.cmd_opts.add_option(\n            \"--powershell\",\n            \"-p\",\n            action=\"store_const\",\n            const=\"powershell\",\n            dest=\"shell\",\n            help=\"Emit completion code for powershell\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        \"\"\"Prints the completion code of the given shell\"\"\"\n        shells = COMPLETION_SCRIPTS.keys()\n        shell_options = [\"--\" + shell for shell in sorted(shells)]\n        if options.shell in shells:\n            script = textwrap.dedent(\n                COMPLETION_SCRIPTS.get(options.shell, \"\").format(prog=get_prog())\n            )\n            print(BASE_COMPLETION.format(script=script, shell=options.shell))\n            return SUCCESS\n        else:\n            sys.stderr.write(\n                \"ERROR: You must pass {}\\n\".format(\" or \".join(shell_options))\n            )\n            return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/configuration.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport subprocess\nfrom optparse import Values\nfrom typing import Any, Callable\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.configuration import (\n    Configuration,\n    Kind,\n    get_configuration_files,\n    kinds,\n)\nfrom pip._internal.exceptions import PipError\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import get_prog, write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass ConfigurationCommand(Command):\n    \"\"\"\n    Manage local and global configuration.\n\n    Subcommands:\n\n    - list: List the active configuration (or from the file specified)\n    - edit: Edit the configuration file in an editor\n    - get: Get the value associated with command.option\n    - set: Set the command.option=value\n    - unset: Unset the value associated with command.option\n    - debug: List the configuration files and values defined under them\n\n    Configuration keys should be dot separated command and option name,\n    with the special prefix \"global\" affecting any command. For example,\n    \"pip config set global.index-url https://example.org/\" would configure\n    the index url for all commands, but \"pip config set download.timeout 10\"\n    would configure a 10 second timeout only for \"pip download\" commands.\n\n    If none of --user, --global and --site are passed, a virtual\n    environment configuration file is used if one is active and the file\n    exists. Otherwise, all modifications happen to the user file by\n    default.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n        %prog [<file-option>] list\n        %prog [<file-option>] [--editor <editor-path>] edit\n\n        %prog [<file-option>] get command.option\n        %prog [<file-option>] set command.option value\n        %prog [<file-option>] unset command.option\n        %prog [<file-option>] debug\n    \"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--editor\",\n            dest=\"editor\",\n            action=\"store\",\n            default=None,\n            help=(\n                \"Editor to use to edit the file. Uses VISUAL or EDITOR \"\n                \"environment variables if not provided.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--global\",\n            dest=\"global_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the system-wide configuration file only\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the user configuration file only\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--site\",\n            dest=\"site_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the current environment configuration file only\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:\n        return {\n            \"list\": self.list_values,\n            \"edit\": self.open_in_editor,\n            \"get\": self.get_name,\n            \"set\": self.set_name_value,\n            \"unset\": self.unset_name,\n            \"debug\": self.list_config_values,\n        }\n\n    def run(self, options: Values, args: list[str]) -> int:\n        handler_map = self.handler_map()\n\n        # Determine action\n        if not args or args[0] not in handler_map:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handler_map)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Determine which configuration files are to be loaded\n        #    Depends on whether the command is modifying.\n        try:\n            load_only = self._determine_file(\n                options, need_value=(action in [\"get\", \"set\", \"unset\", \"edit\"])\n            )\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        # Load a new configuration\n        self.configuration = Configuration(\n            isolated=options.isolated_mode, load_only=load_only\n        )\n        self.configuration.load()\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handler_map[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def _determine_file(self, options: Values, need_value: bool) -> Kind | None:\n        file_options = [\n            key\n            for key, value in (\n                (kinds.USER, options.user_file),\n                (kinds.GLOBAL, options.global_file),\n                (kinds.SITE, options.site_file),\n            )\n            if value\n        ]\n\n        if not file_options:\n            if not need_value:\n                return None\n            # Default to user, unless there's a site file.\n            elif any(\n                os.path.exists(site_config_file)\n                for site_config_file in get_configuration_files()[kinds.SITE]\n            ):\n                return kinds.SITE\n            else:\n                return kinds.USER\n        elif len(file_options) == 1:\n            return file_options[0]\n\n        raise PipError(\n            \"Need exactly one file to operate upon \"\n            \"(--user, --site, --global) to perform.\"\n        )\n\n    def list_values(self, options: Values, args: list[str]) -> None:\n        self._get_n_args(args, \"list\", n=0)\n\n        for key, value in sorted(self.configuration.items()):\n            for key, value in sorted(value.items()):\n                write_output(\"%s=%r\", key, value)\n\n    def get_name(self, options: Values, args: list[str]) -> None:\n        key = self._get_n_args(args, \"get [name]\", n=1)\n        value = self.configuration.get_value(key)\n\n        write_output(\"%s\", value)\n\n    def set_name_value(self, options: Values, args: list[str]) -> None:\n        key, value = self._get_n_args(args, \"set [name] [value]\", n=2)\n        self.configuration.set_value(key, value)\n\n        self._save_configuration()\n\n    def unset_name(self, options: Values, args: list[str]) -> None:\n        key = self._get_n_args(args, \"unset [name]\", n=1)\n        self.configuration.unset_value(key)\n\n        self._save_configuration()\n\n    def list_config_values(self, options: Values, args: list[str]) -> None:\n        \"\"\"List config key-value pairs across different config files\"\"\"\n        self._get_n_args(args, \"debug\", n=0)\n\n        self.print_env_var_values()\n        # Iterate over config files and print if they exist, and the\n        # key-value pairs present in them if they do\n        for variant, files in sorted(self.configuration.iter_config_files()):\n            write_output(\"%s:\", variant)\n            for fname in files:\n                with indent_log():\n                    file_exists = os.path.exists(fname)\n                    write_output(\"%s, exists: %r\", fname, file_exists)\n                    if file_exists:\n                        self.print_config_file_values(variant, fname)\n\n    def print_config_file_values(self, variant: Kind, fname: str) -> None:\n        \"\"\"Get key-value pairs from the file of a variant\"\"\"\n        for name, value in self.configuration.get_values_in_config(variant).items():\n            with indent_log():\n                if name == fname:\n                    for confname, confvalue in value.items():\n                        write_output(\"%s: %s\", confname, confvalue)\n\n    def print_env_var_values(self) -> None:\n        \"\"\"Get key-values pairs present as environment variables\"\"\"\n        write_output(\"%s:\", \"env_var\")\n        with indent_log():\n            for key, value in sorted(self.configuration.get_environ_vars()):\n                env_var = f\"PIP_{key.upper()}\"\n                write_output(\"%s=%r\", env_var, value)\n\n    def open_in_editor(self, options: Values, args: list[str]) -> None:\n        editor = self._determine_editor(options)\n\n        fname = self.configuration.get_file_to_edit()\n        if fname is None:\n            raise PipError(\"Could not determine appropriate file.\")\n        elif '\"' in fname:\n            # This shouldn't happen, unless we see a username like that.\n            # If that happens, we'd appreciate a pull request fixing this.\n            raise PipError(\n                f'Can not open an editor for a file name containing \"\\n{fname}'\n            )\n\n        try:\n            subprocess.check_call(f'{editor} \"{fname}\"', shell=True)\n        except FileNotFoundError as e:\n            if not e.filename:\n                e.filename = editor\n            raise\n        except subprocess.CalledProcessError as e:\n            raise PipError(f\"Editor Subprocess exited with exit code {e.returncode}\")\n\n    def _get_n_args(self, args: list[str], example: str, n: int) -> Any:\n        \"\"\"Helper to make sure the command got the right number of arguments\"\"\"\n        if len(args) != n:\n            msg = (\n                f\"Got unexpected number of arguments, expected {n}. \"\n                f'(example: \"{get_prog()} config {example}\")'\n            )\n            raise PipError(msg)\n\n        if n == 1:\n            return args[0]\n        else:\n            return args\n\n    def _save_configuration(self) -> None:\n        # We successfully ran a modifying command. Need to save the\n        # configuration.\n        try:\n            self.configuration.save()\n        except Exception:\n            logger.exception(\n                \"Unable to save configuration. Please report this as a bug.\"\n            )\n            raise PipError(\"Internal Error.\")\n\n    def _determine_editor(self, options: Values) -> str:\n        if options.editor is not None:\n            return options.editor\n        elif \"VISUAL\" in os.environ:\n            return os.environ[\"VISUAL\"]\n        elif \"EDITOR\" in os.environ:\n            return os.environ[\"EDITOR\"]\n        else:\n            raise PipError(\"Could not determine editor to use.\")\n"
  },
  {
    "path": "src/pip/_internal/commands/debug.py",
    "content": "from __future__ import annotations\n\nimport locale\nimport logging\nimport os\nimport sys\nfrom optparse import Values\nfrom types import ModuleType\nfrom typing import Any\n\nimport pip._vendor\nfrom pip._vendor.certifi import where\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.configuration import Configuration\nfrom pip._internal.metadata import get_environment\nfrom pip._internal.utils.compat import open_text_resource\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import get_pip_version\n\nlogger = logging.getLogger(__name__)\n\n\ndef show_value(name: str, value: Any) -> None:\n    logger.info(\"%s: %s\", name, value)\n\n\ndef show_sys_implementation() -> None:\n    logger.info(\"sys.implementation:\")\n    implementation_name = sys.implementation.name\n    with indent_log():\n        show_value(\"name\", implementation_name)\n\n\ndef create_vendor_txt_map() -> dict[str, str]:\n    with open_text_resource(\"pip._vendor\", \"vendor.txt\") as f:\n        # Purge non version specifying lines.\n        # Also, remove any space prefix or suffixes (including comments).\n        lines = [\n            line.strip().split(\" \", 1)[0] for line in f.readlines() if \"==\" in line\n        ]\n\n    # Transform into \"module\" -> version dict.\n    return dict(line.split(\"==\", 1) for line in lines)\n\n\ndef get_module_from_module_name(module_name: str) -> ModuleType | None:\n    # Module name can be uppercase in vendor.txt for some reason...\n    module_name = module_name.lower().replace(\"-\", \"_\")\n    # PATCH: setuptools is actually only pkg_resources.\n    if module_name == \"setuptools\":\n        module_name = \"pkg_resources\"\n\n    try:\n        __import__(f\"pip._vendor.{module_name}\", globals(), locals(), level=0)\n        return getattr(pip._vendor, module_name)\n    except ImportError:\n        # We allow 'truststore' to fail to import due\n        # to being unavailable on Python 3.9 and earlier.\n        if module_name == \"truststore\" and sys.version_info < (3, 10):\n            return None\n        raise\n\n\ndef get_vendor_version_from_module(module_name: str) -> str | None:\n    module = get_module_from_module_name(module_name)\n    version = getattr(module, \"__version__\", None)\n\n    if module and not version:\n        # Try to find version in debundled module info.\n        assert module.__file__ is not None\n        env = get_environment([os.path.dirname(module.__file__)])\n        dist = env.get_distribution(module_name)\n        if dist:\n            version = str(dist.version)\n\n    return version\n\n\ndef show_actual_vendor_versions(vendor_txt_versions: dict[str, str]) -> None:\n    \"\"\"Log the actual version and print extra info if there is\n    a conflict or if the actual version could not be imported.\n    \"\"\"\n    for module_name, expected_version in vendor_txt_versions.items():\n        extra_message = \"\"\n        actual_version = get_vendor_version_from_module(module_name)\n        if not actual_version:\n            extra_message = (\n                \" (Unable to locate actual module version, using\"\n                \" vendor.txt specified version)\"\n            )\n            actual_version = expected_version\n        elif parse_version(actual_version) != parse_version(expected_version):\n            extra_message = (\n                \" (CONFLICT: vendor.txt suggests version should\"\n                f\" be {expected_version})\"\n            )\n        logger.info(\"%s==%s%s\", module_name, actual_version, extra_message)\n\n\ndef show_vendor_versions() -> None:\n    logger.info(\"vendored library versions:\")\n\n    vendor_txt_versions = create_vendor_txt_map()\n    with indent_log():\n        show_actual_vendor_versions(vendor_txt_versions)\n\n\ndef show_tags(options: Values) -> None:\n    tag_limit = 10\n\n    target_python = make_target_python(options)\n    tags = target_python.get_sorted_tags()\n\n    # Display the target options that were explicitly provided.\n    formatted_target = target_python.format_given()\n    suffix = \"\"\n    if formatted_target:\n        suffix = f\" (target: {formatted_target})\"\n\n    msg = f\"Compatible tags: {len(tags)}{suffix}\"\n    logger.info(msg)\n\n    if options.verbose < 1 and len(tags) > tag_limit:\n        tags_limited = True\n        tags = tags[:tag_limit]\n    else:\n        tags_limited = False\n\n    with indent_log():\n        for tag in tags:\n            logger.info(str(tag))\n\n        if tags_limited:\n            msg = f\"...\\n[First {tag_limit} tags shown. Pass --verbose to show all.]\"\n            logger.info(msg)\n\n\ndef ca_bundle_info(config: Configuration) -> str:\n    levels = {key.split(\".\", 1)[0] for key, _ in config.items()}\n    if not levels:\n        return \"Not specified\"\n\n    levels_that_override_global = [\"install\", \"wheel\", \"download\"]\n    global_overriding_level = [\n        level for level in levels if level in levels_that_override_global\n    ]\n    if not global_overriding_level:\n        return \"global\"\n\n    if \"global\" in levels:\n        levels.remove(\"global\")\n    return \", \".join(levels)\n\n\nclass DebugCommand(Command):\n    \"\"\"\n    Display debug information.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog <options>\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        cmdoptions.add_target_python_options(self.cmd_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n        self.parser.config.load()\n\n    def run(self, options: Values, args: list[str]) -> int:\n        logger.warning(\n            \"This command is only meant for debugging. \"\n            \"Do not use this with automation for parsing and getting these \"\n            \"details, since the output and options of this command may \"\n            \"change without notice.\"\n        )\n        show_value(\"pip version\", get_pip_version())\n        show_value(\"sys.version\", sys.version)\n        show_value(\"sys.executable\", sys.executable)\n        show_value(\"sys.getdefaultencoding\", sys.getdefaultencoding())\n        show_value(\"sys.getfilesystemencoding\", sys.getfilesystemencoding())\n        show_value(\n            \"locale.getpreferredencoding\",\n            locale.getpreferredencoding(),\n        )\n        show_value(\"sys.platform\", sys.platform)\n        show_sys_implementation()\n\n        show_value(\"'cert' config value\", ca_bundle_info(self.parser.config))\n        show_value(\"REQUESTS_CA_BUNDLE\", os.environ.get(\"REQUESTS_CA_BUNDLE\"))\n        show_value(\"CURL_CA_BUNDLE\", os.environ.get(\"CURL_CA_BUNDLE\"))\n        show_value(\"pip._vendor.certifi.where()\", where())\n        show_value(\"pip._vendor.DEBUNDLED\", pip._vendor.DEBUNDLED)\n\n        show_vendor_versions()\n\n        show_tags(options)\n\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/download.py",
    "content": "import logging\nimport os\nfrom optparse import Values\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.req_command import RequirementCommand, with_cleanup\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.utils.misc import ensure_dir, normalize_path, write_output\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\nclass DownloadCommand(RequirementCommand):\n    \"\"\"\n    Download packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports downloading from \"requirements files\", which provide\n    an easy way to specify a whole environment to be downloaded.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] <vcs project url> ...\n      %prog [options] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.build_constraints())\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n        self.cmd_opts.add_option(cmdoptions.src())\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n\n        self.cmd_opts.add_option(\n            \"-d\",\n            \"--dest\",\n            \"--destination-dir\",\n            \"--destination-directory\",\n            dest=\"download_dir\",\n            metavar=\"dir\",\n            default=os.curdir,\n            help=\"Download packages into <dir>.\",\n        )\n\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    @with_cleanup\n    def run(self, options: Values, args: list[str]) -> int:\n        options.ignore_installed = True\n        # editable doesn't really make sense for `pip download`, but the bowels\n        # of the RequirementSet code require that property.\n        options.editables = []\n\n        cmdoptions.check_dist_restriction(options)\n        cmdoptions.check_build_constraints(options)\n        cmdoptions.check_release_control_exclusive(options)\n\n        options.download_dir = normalize_path(options.download_dir)\n        ensure_dir(options.download_dir)\n\n        session = self.get_default_session(options)\n\n        target_python = make_target_python(options)\n        finder = self._build_package_finder(\n            options=options,\n            session=session,\n            target_python=target_python,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"download\",\n            globally_managed=True,\n        )\n\n        reqs = self.get_requirements(args, options, finder, session)\n\n        preparer = self.make_requirement_preparer(\n            temp_build_dir=directory,\n            options=options,\n            build_tracker=build_tracker,\n            session=session,\n            finder=finder,\n            download_dir=options.download_dir,\n            use_user_site=False,\n            verbosity=self.verbosity,\n        )\n\n        resolver = self.make_resolver(\n            preparer=preparer,\n            finder=finder,\n            options=options,\n            ignore_requires_python=options.ignore_requires_python,\n            py_version_info=options.python_version,\n        )\n\n        self.trace_basic_info(finder)\n\n        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)\n\n        preparer.prepare_linked_requirements_more(requirement_set.requirements.values())\n\n        downloaded: list[str] = []\n        for req in requirement_set.requirements.values():\n            if req.satisfied_by is None:\n                assert req.name is not None\n                preparer.save_linked_requirement(req)\n                downloaded.append(req.name)\n\n        if downloaded:\n            write_output(\"Successfully downloaded %s\", \" \".join(downloaded))\n\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/freeze.py",
    "content": "import sys\nfrom optparse import Values\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.operations.freeze import freeze\nfrom pip._internal.utils.compat import stdlib_pkgs\n\n\ndef _should_suppress_build_backends() -> bool:\n    return sys.version_info < (3, 12)\n\n\ndef _dev_pkgs() -> set[str]:\n    pkgs = {\"pip\"}\n\n    if _should_suppress_build_backends():\n        pkgs |= {\"setuptools\", \"distribute\", \"wheel\"}\n\n    return pkgs\n\n\nclass FreezeCommand(Command):\n    \"\"\"\n    Output installed packages in requirements format.\n\n    packages are listed in a case-insensitive sorted order.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-r\",\n            \"--requirement\",\n            dest=\"requirements\",\n            action=\"append\",\n            default=[],\n            metavar=\"file\",\n            help=(\n                \"Use the order in the given requirements file and its \"\n                \"comments when generating output. This option can be \"\n                \"used multiple times.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-l\",\n            \"--local\",\n            dest=\"local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not output \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n        self.cmd_opts.add_option(\n            \"--all\",\n            dest=\"freeze_all\",\n            action=\"store_true\",\n            help=(\n                \"Do not skip these packages in the output:\"\n                \" {}\".format(\", \".join(_dev_pkgs()))\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--exclude-editable\",\n            dest=\"exclude_editable\",\n            action=\"store_true\",\n            help=\"Exclude editable package from output.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_exclude())\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        skip = set(stdlib_pkgs)\n        if not options.freeze_all:\n            skip.update(_dev_pkgs())\n\n        if options.excludes:\n            skip.update(options.excludes)\n\n        cmdoptions.check_list_path_option(options)\n\n        for line in freeze(\n            requirement=options.requirements,\n            local_only=options.local,\n            user_only=options.user,\n            paths=options.path,\n            isolated=options.isolated_mode,\n            skip=skip,\n            exclude_editable=options.exclude_editable,\n        ):\n            sys.stdout.write(line + \"\\n\")\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/hash.py",
    "content": "import hashlib\nimport logging\nimport sys\nfrom optparse import Values\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES\nfrom pip._internal.utils.misc import read_chunks, write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass HashCommand(Command):\n    \"\"\"\n    Compute a hash of a local package archive.\n\n    These can be used with --hash in a requirements file to do repeatable\n    installs.\n    \"\"\"\n\n    usage = \"%prog [options] <file> ...\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-a\",\n            \"--algorithm\",\n            dest=\"algorithm\",\n            choices=STRONG_HASHES,\n            action=\"store\",\n            default=FAVORITE_HASH,\n            help=\"The hash algorithm to use: one of {}\".format(\n                \", \".join(STRONG_HASHES)\n            ),\n        )\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        if not args:\n            self.parser.print_usage(sys.stderr)\n            return ERROR\n\n        algorithm = options.algorithm\n        for path in args:\n            write_output(\n                \"%s:\\n--hash=%s:%s\", path, algorithm, _hash_of_file(path, algorithm)\n            )\n        return SUCCESS\n\n\ndef _hash_of_file(path: str, algorithm: str) -> str:\n    \"\"\"Return the hash digest of a file.\"\"\"\n    with open(path, \"rb\") as archive:\n        hash = hashlib.new(algorithm)\n        for chunk in read_chunks(archive):\n            hash.update(chunk)\n    return hash.hexdigest()\n"
  },
  {
    "path": "src/pip/_internal/commands/help.py",
    "content": "from optparse import Values\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\n\n\nclass HelpCommand(Command):\n    \"\"\"Show help for commands\"\"\"\n\n    usage = \"\"\"\n      %prog <command>\"\"\"\n    ignore_require_venv = True\n\n    def run(self, options: Values, args: list[str]) -> int:\n        from pip._internal.commands import (\n            commands_dict,\n            create_command,\n            get_similar_commands,\n        )\n\n        try:\n            # 'pip help' with no args is handled by pip.__init__.parseopt()\n            cmd_name = args[0]  # the command we need help for\n        except IndexError:\n            return SUCCESS\n\n        if cmd_name not in commands_dict:\n            guess = get_similar_commands(cmd_name)\n\n            msg = [f'unknown command \"{cmd_name}\"']\n            if guess:\n                msg.append(f'maybe you meant \"{guess}\"')\n\n            raise CommandError(\" - \".join(msg))\n\n        command = create_command(cmd_name)\n        command.parser.print_help()\n\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/index.py",
    "content": "from __future__ import annotations\n\nimport json\nimport logging\nfrom collections.abc import Iterable\nfrom optparse import Values\nfrom typing import Any, Callable\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import IndexGroupCommand\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.commands.search import (\n    get_installed_distribution,\n    print_dist_installation_info,\n)\nfrom pip._internal.exceptions import CommandError, DistributionNotFound, PipError\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass IndexCommand(IndexGroupCommand):\n    \"\"\"\n    Inspect information available from package indexes.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n        %prog versions <package>\n    \"\"\"\n\n    def add_options(self) -> None:\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.json())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:\n        return {\n            \"versions\": self.get_available_package_versions,\n        }\n\n    def run(self, options: Values, args: list[str]) -> int:\n        cmdoptions.check_release_control_exclusive(options)\n\n        handler_map = self.handler_map()\n\n        # Determine action\n        if not args or args[0] not in handler_map:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handler_map)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handler_map[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def _build_package_finder(\n        self,\n        options: Values,\n        session: PipSession,\n        target_python: TargetPython | None = None,\n        ignore_requires_python: bool | None = None,\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to the index command.\n        \"\"\"\n        link_collector = LinkCollector.create(session, options=options)\n\n        # Pass allow_yanked=False to ignore yanked versions.\n        selection_prefs = SelectionPreferences(\n            allow_yanked=False,\n            release_control=options.release_control,\n            format_control=options.format_control,\n            ignore_requires_python=ignore_requires_python,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n            target_python=target_python,\n            uploaded_prior_to=options.uploaded_prior_to,\n        )\n\n    def get_available_package_versions(self, options: Values, args: list[Any]) -> None:\n        if len(args) != 1:\n            raise CommandError(\"You need to specify exactly one argument\")\n\n        target_python = cmdoptions.make_target_python(options)\n        query = args[0]\n\n        with self._build_session(options) as session:\n            finder = self._build_package_finder(\n                options=options,\n                session=session,\n                target_python=target_python,\n                ignore_requires_python=options.ignore_requires_python,\n            )\n\n            versions: Iterable[Version] = (\n                candidate.version for candidate in finder.find_all_candidates(query)\n            )\n\n            if self.should_exclude_prerelease(options, canonicalize_name(query)):\n                versions = (\n                    version for version in versions if not version.is_prerelease\n                )\n            versions = set(versions)\n\n            if not versions:\n                raise DistributionNotFound(\n                    f\"No matching distribution found for {query}\"\n                )\n\n            formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]\n            latest = formatted_versions[0]\n\n        dist = get_installed_distribution(query)\n\n        if options.json:\n            structured_output = {\n                \"name\": query,\n                \"versions\": formatted_versions,\n                \"latest\": latest,\n            }\n\n            if dist is not None:\n                structured_output[\"installed_version\"] = str(dist.version)\n\n            write_output(json.dumps(structured_output))\n\n        else:\n            write_output(f\"{query} ({latest})\")\n            write_output(\"Available versions: {}\".format(\", \".join(formatted_versions)))\n            print_dist_installation_info(latest, dist)\n"
  },
  {
    "path": "src/pip/_internal/commands/inspect.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import Any\n\nfrom pip._vendor.packaging.markers import default_environment\nfrom pip._vendor.rich import print_json\n\nfrom pip import __version__\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.utils.compat import stdlib_pkgs\nfrom pip._internal.utils.urls import path_to_url\n\nlogger = logging.getLogger(__name__)\n\n\nclass InspectCommand(Command):\n    \"\"\"\n    Inspect the content of a Python environment and produce a report in JSON format.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not list \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        cmdoptions.check_list_path_option(options)\n        dists = get_environment(options.path).iter_installed_distributions(\n            local_only=options.local,\n            user_only=options.user,\n            skip=set(stdlib_pkgs),\n        )\n        output = {\n            \"version\": \"1\",\n            \"pip_version\": __version__,\n            \"installed\": [self._dist_to_dict(dist) for dist in dists],\n            \"environment\": default_environment(),\n            # TODO tags? scheme?\n        }\n        print_json(data=output)\n        return SUCCESS\n\n    def _dist_to_dict(self, dist: BaseDistribution) -> dict[str, Any]:\n        res: dict[str, Any] = {\n            \"metadata\": dist.metadata_dict,\n            \"metadata_location\": dist.info_location,\n        }\n        # direct_url. Note that we don't have download_info (as in the installation\n        # report) since it is not recorded in installed metadata.\n        direct_url = dist.direct_url\n        if direct_url is not None:\n            res[\"direct_url\"] = direct_url.to_dict()\n        else:\n            # Emulate direct_url for legacy editable installs.\n            editable_project_location = dist.editable_project_location\n            if editable_project_location is not None:\n                res[\"direct_url\"] = {\n                    \"url\": path_to_url(editable_project_location),\n                    \"dir_info\": {\n                        \"editable\": True,\n                    },\n                }\n        # installer\n        installer = dist.installer\n        if dist.installer:\n            res[\"installer\"] = installer\n        # requested\n        if dist.installed_with_dist_info:\n            res[\"requested\"] = dist.requested\n        return res\n"
  },
  {
    "path": "src/pip/_internal/commands/install.py",
    "content": "from __future__ import annotations\n\nimport errno\nimport json\nimport operator\nimport os\nimport shutil\nimport site\nfrom optparse import SUPPRESS_HELP, Values\nfrom pathlib import Path\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.requests.exceptions import InvalidProxyURL\nfrom pip._vendor.rich import print_json\n\n# Eagerly import self_outdated_check to avoid crashes. Otherwise,\n# this module would be imported *after* pip was replaced, resulting\n# in crashes if the new self_outdated_check module was incompatible\n# with the rest of pip that's already imported, or allowing a\n# wheel to execute arbitrary code on install by replacing\n# self_outdated_check.\nimport pip._internal.self_outdated_check  # noqa: F401\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.req_command import (\n    RequirementCommand,\n    with_cleanup,\n)\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.exceptions import (\n    CommandError,\n    InstallationError,\n    InstallWheelBuildError,\n)\nfrom pip._internal.locations import get_scheme\nfrom pip._internal.metadata import BaseEnvironment, get_environment\nfrom pip._internal.models.installation_report import InstallationReport\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.operations.check import ConflictDetails, check_install_conflicts\nfrom pip._internal.req import InstallationResult, install_given_reqs\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n)\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.filesystem import test_writable_dir\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import (\n    check_externally_managed,\n    ensure_dir,\n    get_pip_version,\n    protect_pip_from_modification_on_windows,\n    warn_if_run_as_root,\n    write_output,\n)\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.virtualenv import (\n    running_under_virtualenv,\n    virtualenv_no_global,\n)\nfrom pip._internal.wheel_builder import build\n\nlogger = getLogger(__name__)\n\n\nclass InstallCommand(RequirementCommand):\n    \"\"\"\n    Install packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports installing from \"requirements files\", which provide\n    an easy way to specify a whole environment to be installed.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.build_constraints())\n        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n\n        self.cmd_opts.add_option(cmdoptions.editable())\n        self.cmd_opts.add_option(\n            \"--dry-run\",\n            action=\"store_true\",\n            dest=\"dry_run\",\n            default=False,\n            help=(\n                \"Don't actually install anything, just print what would be. \"\n                \"Can be used in combination with --ignore-installed \"\n                \"to 'resolve' the requirements.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-t\",\n            \"--target\",\n            dest=\"target_dir\",\n            metavar=\"dir\",\n            default=None,\n            help=(\n                \"Install packages into <dir>. \"\n                \"By default this will not replace existing files/folders in \"\n                \"<dir>. Use --upgrade to replace existing packages in <dir> \"\n                \"with new versions.\"\n            ),\n        )\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"use_user_site\",\n            action=\"store_true\",\n            help=(\n                \"Install to the Python user install directory for your \"\n                \"platform. Typically ~/.local/, or %APPDATA%\\\\Python on \"\n                \"Windows. (See the Python documentation for site.USER_BASE \"\n                \"for full details.)\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--no-user\",\n            dest=\"use_user_site\",\n            action=\"store_false\",\n            help=SUPPRESS_HELP,\n        )\n        self.cmd_opts.add_option(\n            \"--root\",\n            dest=\"root_path\",\n            metavar=\"dir\",\n            default=None,\n            help=\"Install everything relative to this alternate root directory.\",\n        )\n        self.cmd_opts.add_option(\n            \"--prefix\",\n            dest=\"prefix_path\",\n            metavar=\"dir\",\n            default=None,\n            help=(\n                \"Installation prefix where lib, bin and other top-level \"\n                \"folders are placed. Note that the resulting installation may \"\n                \"contain scripts and other resources which reference the \"\n                \"Python interpreter of pip, and not that of ``--prefix``. \"\n                \"See also the ``--python`` option if the intention is to \"\n                \"install packages into another (possibly pip-free) \"\n                \"environment.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(cmdoptions.src())\n\n        self.cmd_opts.add_option(\n            \"-U\",\n            \"--upgrade\",\n            dest=\"upgrade\",\n            action=\"store_true\",\n            help=(\n                \"Upgrade all specified packages to the newest available \"\n                \"version. The handling of dependencies depends on the \"\n                \"upgrade-strategy used.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--upgrade-strategy\",\n            dest=\"upgrade_strategy\",\n            default=\"only-if-needed\",\n            choices=[\"only-if-needed\", \"eager\"],\n            help=(\n                \"Determines how dependency upgrading should be handled \"\n                \"[default: %default]. \"\n                '\"eager\" - dependencies are upgraded regardless of '\n                \"whether the currently installed version satisfies the \"\n                \"requirements of the upgraded package(s). \"\n                '\"only-if-needed\" -  are upgraded only when they do not '\n                \"satisfy the requirements of the upgraded package(s).\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--force-reinstall\",\n            dest=\"force_reinstall\",\n            action=\"store_true\",\n            help=\"Reinstall all packages even if they are already up-to-date.\",\n        )\n\n        self.cmd_opts.add_option(\n            \"-I\",\n            \"--ignore-installed\",\n            dest=\"ignore_installed\",\n            action=\"store_true\",\n            help=(\n                \"Ignore the installed packages, overwriting them. \"\n                \"This can break your system if the existing package \"\n                \"is of a different version or was installed \"\n                \"with a different package manager!\"\n            ),\n        )\n\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n        self.cmd_opts.add_option(cmdoptions.override_externally_managed())\n\n        self.cmd_opts.add_option(cmdoptions.config_settings())\n\n        self.cmd_opts.add_option(\n            \"--compile\",\n            action=\"store_true\",\n            dest=\"compile\",\n            default=True,\n            help=\"Compile Python source files to bytecode\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--no-compile\",\n            action=\"store_false\",\n            dest=\"compile\",\n            help=\"Do not compile Python source files to bytecode\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--no-warn-script-location\",\n            action=\"store_false\",\n            dest=\"warn_script_location\",\n            default=True,\n            help=\"Do not warn when installing scripts outside PATH\",\n        )\n        self.cmd_opts.add_option(\n            \"--no-warn-conflicts\",\n            action=\"store_false\",\n            dest=\"warn_about_conflicts\",\n            default=True,\n            help=\"Do not warn about broken dependencies\",\n        )\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n        self.cmd_opts.add_option(cmdoptions.root_user_action())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n        self.cmd_opts.add_option(\n            \"--report\",\n            dest=\"json_report_file\",\n            metavar=\"file\",\n            default=None,\n            help=(\n                \"Generate a JSON file describing what pip did to install \"\n                \"the provided requirements. \"\n                \"Can be used in combination with --dry-run and --ignore-installed \"\n                \"to 'resolve' the requirements. \"\n                \"When - is used as file name it writes to stdout. \"\n                \"When writing to stdout, please combine with the --quiet option \"\n                \"to avoid mixing pip logging output with JSON output.\"\n            ),\n        )\n\n    @with_cleanup\n    def run(self, options: Values, args: list[str]) -> int:\n        if options.use_user_site and options.target_dir is not None:\n            raise CommandError(\"Can not combine '--user' and '--target'\")\n\n        # Check whether the environment we're installing into is externally\n        # managed, as specified in PEP 668. Specifying --root, --target, or\n        # --prefix disables the check, since there's no reliable way to locate\n        # the EXTERNALLY-MANAGED file for those cases. An exception is also\n        # made specifically for \"--dry-run --report\" for convenience.\n        installing_into_current_environment = (\n            not (options.dry_run and options.json_report_file)\n            and options.root_path is None\n            and options.target_dir is None\n            and options.prefix_path is None\n        )\n        if (\n            installing_into_current_environment\n            and not options.override_externally_managed\n        ):\n            check_externally_managed()\n\n        upgrade_strategy = \"to-satisfy-only\"\n        if options.upgrade:\n            upgrade_strategy = options.upgrade_strategy\n\n        cmdoptions.check_build_constraints(options)\n        cmdoptions.check_dist_restriction(options, check_target=True)\n        cmdoptions.check_release_control_exclusive(options)\n\n        logger.verbose(\"Using %s\", get_pip_version())\n        options.use_user_site = decide_user_install(\n            options.use_user_site,\n            prefix_path=options.prefix_path,\n            target_dir=options.target_dir,\n            root_path=options.root_path,\n            isolated_mode=options.isolated_mode,\n        )\n\n        target_temp_dir: TempDirectory | None = None\n        target_temp_dir_path: str | None = None\n        if options.target_dir:\n            options.ignore_installed = True\n            options.target_dir = os.path.abspath(options.target_dir)\n            if (\n                # fmt: off\n                os.path.exists(options.target_dir) and\n                not os.path.isdir(options.target_dir)\n                # fmt: on\n            ):\n                raise CommandError(\n                    \"Target path exists but is not a directory, will not continue.\"\n                )\n\n            # Create a target directory for using with the target option\n            target_temp_dir = TempDirectory(kind=\"target\")\n            target_temp_dir_path = target_temp_dir.path\n            self.enter_context(target_temp_dir)\n\n        session = self.get_default_session(options)\n\n        target_python = make_target_python(options)\n        finder = self._build_package_finder(\n            options=options,\n            session=session,\n            target_python=target_python,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"install\",\n            globally_managed=True,\n        )\n\n        try:\n            reqs = self.get_requirements(args, options, finder, session)\n\n            wheel_cache = WheelCache(options.cache_dir)\n\n            # Only when installing is it permitted to use PEP 660.\n            # In other circumstances (pip wheel, pip download) we generate\n            # regular (i.e. non editable) metadata and wheels.\n            for req in reqs:\n                req.permit_editable_wheels = True\n\n            preparer = self.make_requirement_preparer(\n                temp_build_dir=directory,\n                options=options,\n                build_tracker=build_tracker,\n                session=session,\n                finder=finder,\n                use_user_site=options.use_user_site,\n                verbosity=self.verbosity,\n            )\n            resolver = self.make_resolver(\n                preparer=preparer,\n                finder=finder,\n                options=options,\n                wheel_cache=wheel_cache,\n                use_user_site=options.use_user_site,\n                ignore_installed=options.ignore_installed,\n                ignore_requires_python=options.ignore_requires_python,\n                force_reinstall=options.force_reinstall,\n                upgrade_strategy=upgrade_strategy,\n                py_version_info=options.python_version,\n            )\n\n            self.trace_basic_info(finder)\n\n            requirement_set = resolver.resolve(\n                reqs, check_supported_wheels=not options.target_dir\n            )\n\n            if options.json_report_file:\n                report = InstallationReport(requirement_set.requirements_to_install)\n                if options.json_report_file == \"-\":\n                    print_json(data=report.to_dict())\n                else:\n                    with open(options.json_report_file, \"w\", encoding=\"utf-8\") as f:\n                        json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)\n\n            if options.dry_run:\n                would_install_items = sorted(\n                    (r.metadata[\"name\"], r.metadata[\"version\"])\n                    for r in requirement_set.requirements_to_install\n                )\n                if would_install_items:\n                    write_output(\n                        \"Would install %s\",\n                        \" \".join(\"-\".join(item) for item in would_install_items),\n                    )\n                return SUCCESS\n\n            # If there is any more preparation to do for the actual installation, do\n            # so now. This includes actually downloading the files in the case that\n            # we have been using PEP-658 metadata so far.\n            preparer.prepare_linked_requirements_more(\n                requirement_set.requirements.values()\n            )\n\n            try:\n                pip_req = requirement_set.get_requirement(\"pip\")\n            except KeyError:\n                modifying_pip = False\n            else:\n                # If we're not replacing an already installed pip,\n                # we're not modifying it.\n                modifying_pip = pip_req.satisfied_by is None\n            protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)\n\n            reqs_to_build = [\n                r for r in requirement_set.requirements_to_install if not r.is_wheel\n            ]\n\n            _, build_failures = build(\n                reqs_to_build,\n                wheel_cache=wheel_cache,\n                verify=True,\n            )\n\n            if build_failures:\n                raise InstallWheelBuildError(build_failures)\n\n            to_install = resolver.get_installation_order(requirement_set)\n\n            # Check for conflicts in the package set we're installing.\n            conflicts: ConflictDetails | None = None\n            should_warn_about_conflicts = (\n                not options.ignore_dependencies and options.warn_about_conflicts\n            )\n            if should_warn_about_conflicts:\n                conflicts = self._determine_conflicts(to_install)\n\n            # Don't warn about script install locations if\n            # --target or --prefix has been specified\n            warn_script_location = options.warn_script_location\n            if options.target_dir or options.prefix_path:\n                warn_script_location = False\n\n            installed = install_given_reqs(\n                to_install,\n                root=options.root_path,\n                home=target_temp_dir_path,\n                prefix=options.prefix_path,\n                warn_script_location=warn_script_location,\n                use_user_site=options.use_user_site,\n                pycompile=options.compile,\n                progress_bar=options.progress_bar,\n            )\n\n            lib_locations = get_lib_location_guesses(\n                user=options.use_user_site,\n                home=target_temp_dir_path,\n                root=options.root_path,\n                prefix=options.prefix_path,\n                isolated=options.isolated_mode,\n            )\n            env = get_environment(lib_locations)\n\n            if conflicts is not None:\n                self._warn_about_conflicts(\n                    conflicts,\n                    resolver_variant=self.determine_resolver_variant(options),\n                )\n            if summary := installed_packages_summary(installed, env):\n                write_output(summary)\n        except OSError as error:\n            show_traceback = self.verbosity >= 1\n\n            message = create_os_error_message(\n                error,\n                show_traceback,\n                options.use_user_site,\n            )\n            logger.error(message, exc_info=show_traceback)\n\n            return ERROR\n\n        if options.target_dir:\n            assert target_temp_dir\n            self._handle_target_dir(\n                options.target_dir, target_temp_dir, options.upgrade\n            )\n        if options.root_user_action == \"warn\":\n            warn_if_run_as_root()\n        return SUCCESS\n\n    def _handle_target_dir(\n        self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool\n    ) -> None:\n        ensure_dir(target_dir)\n\n        # Checking both purelib and platlib directories for installed\n        # packages to be moved to target directory\n        lib_dir_list = []\n\n        # Checking both purelib and platlib directories for installed\n        # packages to be moved to target directory\n        scheme = get_scheme(\"\", home=target_temp_dir.path)\n        purelib_dir = scheme.purelib\n        platlib_dir = scheme.platlib\n        data_dir = scheme.data\n\n        if os.path.exists(purelib_dir):\n            lib_dir_list.append(purelib_dir)\n        if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:\n            lib_dir_list.append(platlib_dir)\n        if os.path.exists(data_dir):\n            lib_dir_list.append(data_dir)\n\n        for lib_dir in lib_dir_list:\n            for item in os.listdir(lib_dir):\n                if lib_dir == data_dir:\n                    ddir = os.path.join(data_dir, item)\n                    if any(s.startswith(ddir) for s in lib_dir_list[:-1]):\n                        continue\n                target_item_dir = os.path.join(target_dir, item)\n                if os.path.exists(target_item_dir):\n                    if not upgrade:\n                        logger.warning(\n                            \"Target directory %s already exists. Specify \"\n                            \"--upgrade to force replacement.\",\n                            target_item_dir,\n                        )\n                        continue\n                    if os.path.islink(target_item_dir):\n                        logger.warning(\n                            \"Target directory %s already exists and is \"\n                            \"a link. pip will not automatically replace \"\n                            \"links, please remove if replacement is \"\n                            \"desired.\",\n                            target_item_dir,\n                        )\n                        continue\n                    if os.path.isdir(target_item_dir):\n                        shutil.rmtree(target_item_dir)\n                    else:\n                        os.remove(target_item_dir)\n\n                shutil.move(os.path.join(lib_dir, item), target_item_dir)\n\n    def _determine_conflicts(\n        self, to_install: list[InstallRequirement]\n    ) -> ConflictDetails | None:\n        try:\n            return check_install_conflicts(to_install)\n        except Exception:\n            logger.exception(\n                \"Error while checking for conflicts. Please file an issue on \"\n                \"pip's issue tracker: https://github.com/pypa/pip/issues/new\"\n            )\n            return None\n\n    def _warn_about_conflicts(\n        self, conflict_details: ConflictDetails, resolver_variant: str\n    ) -> None:\n        package_set, (missing, conflicting) = conflict_details\n        if not missing and not conflicting:\n            return\n\n        parts: list[str] = []\n        if resolver_variant == \"legacy\":\n            parts.append(\n                \"pip's legacy dependency resolver does not consider dependency \"\n                \"conflicts when selecting packages. This behaviour is the \"\n                \"source of the following dependency conflicts.\"\n            )\n        else:\n            assert resolver_variant == \"resolvelib\"\n            parts.append(\n                \"pip's dependency resolver does not currently take into account \"\n                \"all the packages that are installed. This behaviour is the \"\n                \"source of the following dependency conflicts.\"\n            )\n\n        # NOTE: There is some duplication here, with commands/check.py\n        for project_name in missing:\n            version = package_set[project_name][0]\n            for dependency in missing[project_name]:\n                message = (\n                    f\"{project_name} {version} requires {dependency[1]}, \"\n                    \"which is not installed.\"\n                )\n                parts.append(message)\n\n        for project_name in conflicting:\n            version = package_set[project_name][0]\n            for dep_name, dep_version, req in conflicting[project_name]:\n                message = (\n                    \"{name} {version} requires {requirement}, but {you} have \"\n                    \"{dep_name} {dep_version} which is incompatible.\"\n                ).format(\n                    name=project_name,\n                    version=version,\n                    requirement=req,\n                    dep_name=dep_name,\n                    dep_version=dep_version,\n                    you=(\"you\" if resolver_variant == \"resolvelib\" else \"you'll\"),\n                )\n                parts.append(message)\n\n        logger.critical(\"\\n\".join(parts))\n\n\ndef installed_packages_summary(\n    installed: list[InstallationResult], env: BaseEnvironment\n) -> str:\n    # Format a summary of installed packages, with extra care to\n    # display a package name as it was requested by the user.\n    installed.sort(key=operator.attrgetter(\"name\"))\n    summary = []\n    installed_versions = {}\n    for distribution in env.iter_all_distributions():\n        installed_versions[distribution.canonical_name] = distribution.version\n    for package in installed:\n        display_name = package.name\n        version = installed_versions.get(canonicalize_name(display_name), None)\n        if version:\n            text = f\"{display_name}-{version}\"\n        else:\n            text = display_name\n        summary.append(text)\n\n    if not summary:\n        return \"\"\n    return f\"Successfully installed {' '.join(summary)}\"\n\n\ndef get_lib_location_guesses(\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    isolated: bool = False,\n    prefix: str | None = None,\n) -> list[str]:\n    scheme = get_scheme(\n        \"\",\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n    return [scheme.purelib, scheme.platlib]\n\n\ndef site_packages_writable(root: str | None, isolated: bool) -> bool:\n    return all(\n        test_writable_dir(d)\n        for d in set(get_lib_location_guesses(root=root, isolated=isolated))\n    )\n\n\ndef decide_user_install(\n    use_user_site: bool | None,\n    prefix_path: str | None = None,\n    target_dir: str | None = None,\n    root_path: str | None = None,\n    isolated_mode: bool = False,\n) -> bool:\n    \"\"\"Determine whether to do a user install based on the input options.\n\n    If use_user_site is False, no additional checks are done.\n    If use_user_site is True, it is checked for compatibility with other\n    options.\n    If use_user_site is None, the default behaviour depends on the environment,\n    which is provided by the other arguments.\n    \"\"\"\n    # In some cases (config from tox), use_user_site can be set to an integer\n    # rather than a bool, which 'use_user_site is False' wouldn't catch.\n    if (use_user_site is not None) and (not use_user_site):\n        logger.debug(\"Non-user install by explicit request\")\n        return False\n\n    # If we have been asked for a user install explicitly, check compatibility.\n    if use_user_site:\n        if prefix_path:\n            raise CommandError(\n                \"Can not combine '--user' and '--prefix' as they imply \"\n                \"different installation locations\"\n            )\n        if virtualenv_no_global():\n            raise InstallationError(\n                \"Can not perform a '--user' install. User site-packages \"\n                \"are not visible in this virtualenv.\"\n            )\n        # Catch all remaining cases which honour the site.ENABLE_USER_SITE\n        # value, such as a plain Python installation (e.g. no virtualenv).\n        if not site.ENABLE_USER_SITE:\n            raise InstallationError(\n                \"Can not perform a '--user' install. User site-packages \"\n                \"are disabled for this Python.\"\n            )\n        logger.debug(\"User install by explicit request\")\n        return True\n\n    # If we are here, user installs have not been explicitly requested/avoided\n    assert use_user_site is None\n\n    # user install incompatible with --prefix/--target\n    if prefix_path or target_dir:\n        logger.debug(\"Non-user install due to --prefix or --target option\")\n        return False\n\n    # If user installs are not enabled, choose a non-user install\n    if not site.ENABLE_USER_SITE:\n        logger.debug(\"Non-user install because user site-packages disabled\")\n        return False\n\n    # If we have permission for a non-user install, do that,\n    # otherwise do a user install.\n    if site_packages_writable(root=root_path, isolated=isolated_mode):\n        logger.debug(\"Non-user install because site-packages writeable\")\n        return False\n\n    logger.info(\n        \"Defaulting to user installation because normal site-packages \"\n        \"is not writeable\"\n    )\n    return True\n\n\ndef create_os_error_message(\n    error: OSError, show_traceback: bool, using_user_site: bool\n) -> str:\n    \"\"\"Format an error message for an OSError\n\n    It may occur anytime during the execution of the install command.\n    \"\"\"\n    parts = []\n\n    # Mention the error if we are not going to show a traceback\n    parts.append(\"Could not install packages due to an OSError\")\n    if not show_traceback:\n        parts.append(\": \")\n        parts.append(str(error))\n    else:\n        parts.append(\".\")\n\n    # Spilt the error indication from a helper message (if any)\n    parts[-1] += \"\\n\"\n\n    # Suggest useful actions to the user:\n    #  (1) using user site-packages or (2) verifying the permissions\n    if error.errno == errno.EACCES:\n        user_option_part = \"Consider using the `--user` option\"\n        permissions_part = \"Check the permissions\"\n\n        if not running_under_virtualenv() and not using_user_site:\n            parts.extend(\n                [\n                    user_option_part,\n                    \" or \",\n                    permissions_part.lower(),\n                ]\n            )\n        else:\n            parts.append(permissions_part)\n        parts.append(\".\\n\")\n\n    # Suggest to check \"pip config debug\" in case of invalid proxy\n    if type(error) is InvalidProxyURL:\n        parts.append(\n            'Consider checking your local proxy configuration with \"pip config debug\"'\n        )\n        parts.append(\".\\n\")\n\n    # On Windows, errors like EINVAL or ENOENT may occur\n    # if a file or folder name exceeds 255 characters,\n    # or if the full path exceeds 260 characters and long path support isn't enabled.\n    # This condition checks for such cases and adds a hint to the error output.\n\n    if WINDOWS and error.errno in (errno.EINVAL, errno.ENOENT) and error.filename:\n        if any(len(part) > 255 for part in Path(error.filename).parts):\n            parts.append(\n                \"HINT: This error might be caused by a file or folder name exceeding \"\n                \"255 characters, which is a Windows limitation even if long paths \"\n                \"are enabled.\\n \"\n            )\n        if len(error.filename) > 260:\n            parts.append(\n                \"HINT: This error might have occurred since \"\n                \"this system does not have Windows Long Path \"\n                \"support enabled. You can find information on \"\n                \"how to enable this at \"\n                \"https://pip.pypa.io/warnings/enable-long-paths\\n\"\n            )\n    return \"\".join(parts).strip() + \"\\n\"\n"
  },
  {
    "path": "src/pip/_internal/commands/list.py",
    "content": "from __future__ import annotations\n\nimport json\nimport logging\nfrom collections.abc import Generator, Sequence\nfrom email.parser import Parser\nfrom optparse import Values\nfrom typing import TYPE_CHECKING, cast\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import InvalidVersion, Version\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.index_command import IndexGroupCommand\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.utils.compat import stdlib_pkgs\nfrom pip._internal.utils.misc import tabulate, write_output\n\nif TYPE_CHECKING:\n    from pip._internal.index.package_finder import PackageFinder\n    from pip._internal.network.session import PipSession\n\n    class _DistWithLatestInfo(BaseDistribution):\n        \"\"\"Give the distribution object a couple of extra fields.\n\n        These will be populated during ``get_outdated()``. This is dirty but\n        makes the rest of the code much cleaner.\n        \"\"\"\n\n        latest_version: Version\n        latest_filetype: str\n\n    _ProcessedDists = Sequence[_DistWithLatestInfo]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ListCommand(IndexGroupCommand):\n    \"\"\"\n    List installed packages, including editables.\n\n    Packages are listed in a case-insensitive sorted order.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-o\",\n            \"--outdated\",\n            action=\"store_true\",\n            default=False,\n            help=\"List outdated packages\",\n        )\n        self.cmd_opts.add_option(\n            \"-u\",\n            \"--uptodate\",\n            action=\"store_true\",\n            default=False,\n            help=\"List uptodate packages\",\n        )\n        self.cmd_opts.add_option(\n            \"-e\",\n            \"--editable\",\n            action=\"store_true\",\n            default=False,\n            help=\"List editable projects.\",\n        )\n        self.cmd_opts.add_option(\n            \"-l\",\n            \"--local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not list \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n\n        self.cmd_opts.add_option(\n            \"--format\",\n            action=\"store\",\n            dest=\"list_format\",\n            default=\"columns\",\n            choices=(\"columns\", \"freeze\", \"json\"),\n            help=(\n                \"Select the output format among: columns (default), freeze, or json. \"\n                \"The 'freeze' format cannot be used with the --outdated option.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--not-required\",\n            action=\"store_true\",\n            dest=\"not_required\",\n            help=\"List packages that are not dependencies of installed packages.\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--exclude-editable\",\n            action=\"store_false\",\n            dest=\"include_editable\",\n            help=\"Exclude editable package from output.\",\n        )\n        self.cmd_opts.add_option(\n            \"--include-editable\",\n            action=\"store_true\",\n            dest=\"include_editable\",\n            help=\"Include editable package in output.\",\n            default=True,\n        )\n        self.cmd_opts.add_option(cmdoptions.list_exclude())\n        index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser)\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def handle_pip_version_check(self, options: Values) -> None:\n        if options.outdated or options.uptodate:\n            super().handle_pip_version_check(options)\n\n    def _build_package_finder(\n        self, options: Values, session: PipSession\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to this list command.\n        \"\"\"\n        # Lazy import the heavy index modules as most list invocations won't need 'em.\n        from pip._internal.index.collector import LinkCollector\n        from pip._internal.index.package_finder import PackageFinder\n\n        link_collector = LinkCollector.create(session, options=options)\n\n        # Pass allow_yanked=False to ignore yanked versions.\n        selection_prefs = SelectionPreferences(\n            allow_yanked=False,\n            release_control=options.release_control,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n\n    def run(self, options: Values, args: list[str]) -> int:\n        cmdoptions.check_release_control_exclusive(options)\n\n        if options.outdated and options.uptodate:\n            raise CommandError(\"Options --outdated and --uptodate cannot be combined.\")\n\n        if options.outdated and options.list_format == \"freeze\":\n            raise CommandError(\n                \"List format 'freeze' cannot be used with the --outdated option.\"\n            )\n\n        cmdoptions.check_list_path_option(options)\n\n        skip = set(stdlib_pkgs)\n        if options.excludes:\n            skip.update(canonicalize_name(n) for n in options.excludes)\n\n        packages: _ProcessedDists = [\n            cast(\"_DistWithLatestInfo\", d)\n            for d in get_environment(options.path).iter_installed_distributions(\n                local_only=options.local,\n                user_only=options.user,\n                editables_only=options.editable,\n                include_editables=options.include_editable,\n                skip=skip,\n            )\n        ]\n\n        # get_not_required must be called firstly in order to find and\n        # filter out all dependencies correctly. Otherwise a package\n        # can't be identified as requirement because some parent packages\n        # could be filtered out before.\n        if options.not_required:\n            packages = self.get_not_required(packages, options)\n\n        if options.outdated:\n            packages = self.get_outdated(packages, options)\n        elif options.uptodate:\n            packages = self.get_uptodate(packages, options)\n\n        self.output_package_listing(packages, options)\n        return SUCCESS\n\n    def get_outdated(\n        self, packages: _ProcessedDists, options: Values\n    ) -> _ProcessedDists:\n        return [\n            dist\n            for dist in self.iter_packages_latest_infos(packages, options)\n            if dist.latest_version > dist.version\n        ]\n\n    def get_uptodate(\n        self, packages: _ProcessedDists, options: Values\n    ) -> _ProcessedDists:\n        return [\n            dist\n            for dist in self.iter_packages_latest_infos(packages, options)\n            if dist.latest_version == dist.version\n        ]\n\n    def get_not_required(\n        self, packages: _ProcessedDists, options: Values\n    ) -> _ProcessedDists:\n        dep_keys = {\n            canonicalize_name(dep.name)\n            for dist in packages\n            for dep in (dist.iter_dependencies() or ())\n        }\n\n        # Create a set to remove duplicate packages, and cast it to a list\n        # to keep the return type consistent with get_outdated and\n        # get_uptodate\n        return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys})\n\n    def iter_packages_latest_infos(\n        self, packages: _ProcessedDists, options: Values\n    ) -> Generator[_DistWithLatestInfo, None, None]:\n        with self._build_session(options) as session:\n            finder = self._build_package_finder(options, session)\n\n            def latest_info(\n                dist: _DistWithLatestInfo,\n            ) -> _DistWithLatestInfo | None:\n                all_candidates = finder.find_all_candidates(dist.canonical_name)\n                if self.should_exclude_prerelease(options, dist.canonical_name):\n                    all_candidates = [\n                        candidate\n                        for candidate in all_candidates\n                        if not candidate.version.is_prerelease\n                    ]\n\n                evaluator = finder.make_candidate_evaluator(\n                    project_name=dist.canonical_name,\n                )\n                best_candidate = evaluator.sort_best_candidate(all_candidates)\n                if best_candidate is None:\n                    return None\n\n                remote_version = best_candidate.version\n                if best_candidate.link.is_wheel:\n                    typ = \"wheel\"\n                else:\n                    typ = \"sdist\"\n                dist.latest_version = remote_version\n                dist.latest_filetype = typ\n                return dist\n\n            for dist in map(latest_info, packages):\n                if dist is not None:\n                    yield dist\n\n    def output_package_listing(\n        self, packages: _ProcessedDists, options: Values\n    ) -> None:\n        packages = sorted(\n            packages,\n            key=lambda dist: dist.canonical_name,\n        )\n        if options.list_format == \"columns\" and packages:\n            data, header = format_for_columns(packages, options)\n            self.output_package_listing_columns(data, header)\n        elif options.list_format == \"freeze\":\n            for dist in packages:\n                try:\n                    req_string = f\"{dist.raw_name}=={dist.version}\"\n                except InvalidVersion:\n                    req_string = f\"{dist.raw_name}==={dist.raw_version}\"\n                if options.verbose >= 1:\n                    write_output(\"%s (%s)\", req_string, dist.location)\n                else:\n                    write_output(req_string)\n        elif options.list_format == \"json\":\n            write_output(format_for_json(packages, options))\n\n    def output_package_listing_columns(\n        self, data: list[list[str]], header: list[str]\n    ) -> None:\n        # insert the header first: we need to know the size of column names\n        if len(data) > 0:\n            data.insert(0, header)\n\n        pkg_strings, sizes = tabulate(data)\n\n        # Create and add a separator.\n        if len(data) > 0:\n            pkg_strings.insert(1, \" \".join(\"-\" * x for x in sizes))\n\n        for val in pkg_strings:\n            write_output(val)\n\n\ndef format_for_columns(\n    pkgs: _ProcessedDists, options: Values\n) -> tuple[list[list[str]], list[str]]:\n    \"\"\"\n    Convert the package data into something usable\n    by output_package_listing_columns.\n    \"\"\"\n    header = [\"Package\", \"Version\"]\n\n    running_outdated = options.outdated\n    if running_outdated:\n        header.extend([\"Latest\", \"Type\"])\n\n    def wheel_build_tag(dist: BaseDistribution) -> str | None:\n        try:\n            wheel_file = dist.read_text(\"WHEEL\")\n        except FileNotFoundError:\n            return None\n        return Parser().parsestr(wheel_file).get(\"Build\")\n\n    build_tags = [wheel_build_tag(p) for p in pkgs]\n    has_build_tags = any(build_tags)\n    if has_build_tags:\n        header.append(\"Build\")\n\n    has_editables = any(x.editable for x in pkgs)\n    if has_editables:\n        header.append(\"Editable project location\")\n\n    if options.verbose >= 1:\n        header.append(\"Location\")\n    if options.verbose >= 1:\n        header.append(\"Installer\")\n\n    data = []\n    for i, proj in enumerate(pkgs):\n        # if we're working on the 'outdated' list, separate out the\n        # latest_version and type\n        row = [proj.raw_name, proj.raw_version]\n\n        if running_outdated:\n            row.append(str(proj.latest_version))\n            row.append(proj.latest_filetype)\n\n        if has_build_tags:\n            row.append(build_tags[i] or \"\")\n\n        if has_editables:\n            row.append(proj.editable_project_location or \"\")\n\n        if options.verbose >= 1:\n            row.append(proj.location or \"\")\n        if options.verbose >= 1:\n            row.append(proj.installer)\n\n        data.append(row)\n\n    return data, header\n\n\ndef format_for_json(packages: _ProcessedDists, options: Values) -> str:\n    data = []\n    for dist in packages:\n        try:\n            version = str(dist.version)\n        except InvalidVersion:\n            version = dist.raw_version\n        info = {\n            \"name\": dist.raw_name,\n            \"version\": version,\n        }\n        if options.verbose >= 1:\n            info[\"location\"] = dist.location or \"\"\n            info[\"installer\"] = dist.installer\n        if options.outdated:\n            info[\"latest_version\"] = str(dist.latest_version)\n            info[\"latest_filetype\"] = dist.latest_filetype\n        editable_project_location = dist.editable_project_location\n        if editable_project_location:\n            info[\"editable_project_location\"] = editable_project_location\n        data.append(info)\n    return json.dumps(data)\n"
  },
  {
    "path": "src/pip/_internal/commands/lock.py",
    "content": "import sys\nfrom optparse import Values\nfrom pathlib import Path\n\nfrom pip._vendor import tomli_w\nfrom pip._vendor.packaging.pylock import is_valid_pylock_path\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import (\n    RequirementCommand,\n    with_cleanup,\n)\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import (\n    get_pip_version,\n)\nfrom pip._internal.utils.pylock import pylock_from_install_requirements\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = getLogger(__name__)\n\n\nclass LockCommand(RequirementCommand):\n    \"\"\"\n    EXPERIMENTAL - Lock packages and their dependencies from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports locking from \"requirements files\", which provide an easy\n    way to specify a whole environment to be installed.\n\n    The generated lock file is only guaranteed to be valid for the current\n    python version and platform.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            cmdoptions.PipOption(\n                \"--output\",\n                \"-o\",\n                dest=\"output_file\",\n                metavar=\"path\",\n                type=\"path\",\n                default=\"pylock.toml\",\n                help=\"Lock file name (default=pylock.toml). Use - for stdout.\",\n            )\n        )\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.build_constraints())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n\n        self.cmd_opts.add_option(cmdoptions.editable())\n\n        self.cmd_opts.add_option(cmdoptions.src())\n\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n\n        self.cmd_opts.add_option(cmdoptions.config_settings())\n\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    @with_cleanup\n    def run(self, options: Values, args: list[str]) -> int:\n        logger.verbose(\"Using %s\", get_pip_version())\n\n        logger.warning(\n            \"pip lock is currently an experimental command. \"\n            \"It may be removed/changed in a future release \"\n            \"without prior warning.\"\n        )\n\n        cmdoptions.check_build_constraints(options)\n        cmdoptions.check_release_control_exclusive(options)\n\n        session = self.get_default_session(options)\n\n        finder = self._build_package_finder(\n            options=options,\n            session=session,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"install\",\n            globally_managed=True,\n        )\n\n        reqs = self.get_requirements(args, options, finder, session)\n\n        wheel_cache = WheelCache(options.cache_dir)\n\n        # Only when installing is it permitted to use PEP 660.\n        # In other circumstances (pip wheel, pip download) we generate\n        # regular (i.e. non editable) metadata and wheels.\n        for req in reqs:\n            req.permit_editable_wheels = True\n\n        preparer = self.make_requirement_preparer(\n            temp_build_dir=directory,\n            options=options,\n            build_tracker=build_tracker,\n            session=session,\n            finder=finder,\n            use_user_site=False,\n            verbosity=self.verbosity,\n        )\n        resolver = self.make_resolver(\n            preparer=preparer,\n            finder=finder,\n            options=options,\n            wheel_cache=wheel_cache,\n            use_user_site=False,\n            ignore_installed=True,\n            ignore_requires_python=options.ignore_requires_python,\n            upgrade_strategy=\"to-satisfy-only\",\n        )\n\n        self.trace_basic_info(finder)\n\n        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)\n\n        if options.output_file == \"-\":\n            base_dir = Path.cwd()\n        else:\n            output_file_path = Path(options.output_file)\n            if not is_valid_pylock_path(output_file_path):\n                logger.warning(\n                    \"%s is not a valid lock file name.\",\n                    output_file_path,\n                )\n            base_dir = output_file_path.parent\n        pylock = pylock_from_install_requirements(\n            requirement_set.requirements.values(), base_dir=base_dir\n        )\n        pylock_toml = tomli_w.dumps(pylock.to_dict())\n        if options.output_file == \"-\":\n            sys.stdout.write(pylock_toml)\n        else:\n            output_file_path.write_text(pylock_toml, encoding=\"utf-8\")\n\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/search.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport shutil\nimport sys\nimport textwrap\nimport xmlrpc.client\nfrom collections import OrderedDict\nfrom optparse import Values\nfrom typing import TypedDict\n\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.req_command import SessionCommandMixin\nfrom pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.metadata.base import BaseDistribution\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.network.xmlrpc import PipXmlrpcTransport\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import write_output\n\n\nclass TransformedHit(TypedDict):\n    name: str\n    summary: str\n    versions: list[str]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SearchCommand(Command, SessionCommandMixin):\n    \"\"\"Search for PyPI packages whose name or summary contains <query>.\"\"\"\n\n    usage = \"\"\"\n      %prog [options] <query>\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-i\",\n            \"--index\",\n            dest=\"index\",\n            metavar=\"URL\",\n            default=PyPI.pypi_url,\n            help=\"Base URL of Python Package Index (default %default)\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        if not args:\n            raise CommandError(\"Missing required argument (search query).\")\n        query = args\n        pypi_hits = self.search(query, options)\n        hits = transform_hits(pypi_hits)\n\n        terminal_width = None\n        if sys.stdout.isatty():\n            terminal_width = shutil.get_terminal_size()[0]\n\n        print_results(hits, terminal_width=terminal_width)\n        if pypi_hits:\n            return SUCCESS\n        return NO_MATCHES_FOUND\n\n    def search(self, query: list[str], options: Values) -> list[dict[str, str]]:\n        index_url = options.index\n\n        session = self.get_default_session(options)\n\n        transport = PipXmlrpcTransport(index_url, session)\n        pypi = xmlrpc.client.ServerProxy(index_url, transport)\n        try:\n            hits = pypi.search({\"name\": query, \"summary\": query}, \"or\")\n        except xmlrpc.client.Fault as fault:\n            message = (\n                f\"XMLRPC request failed [code: {fault.faultCode}]\\n{fault.faultString}\"\n            )\n            raise CommandError(message)\n        assert isinstance(hits, list)\n        return hits\n\n\ndef transform_hits(hits: list[dict[str, str]]) -> list[TransformedHit]:\n    \"\"\"\n    The list from pypi is really a list of versions. We want a list of\n    packages with the list of versions stored inline. This converts the\n    list from pypi into one we can use.\n    \"\"\"\n    packages: dict[str, TransformedHit] = OrderedDict()\n    for hit in hits:\n        name = hit[\"name\"]\n        summary = hit[\"summary\"]\n        version = hit[\"version\"]\n\n        if name not in packages.keys():\n            packages[name] = {\n                \"name\": name,\n                \"summary\": summary,\n                \"versions\": [version],\n            }\n        else:\n            packages[name][\"versions\"].append(version)\n\n            # if this is the highest version, replace summary and score\n            if version == highest_version(packages[name][\"versions\"]):\n                packages[name][\"summary\"] = summary\n\n    return list(packages.values())\n\n\ndef print_dist_installation_info(latest: str, dist: BaseDistribution | None) -> None:\n    if dist is not None:\n        with indent_log():\n            if dist.version == latest:\n                write_output(\"INSTALLED: %s (latest)\", dist.version)\n            else:\n                write_output(\"INSTALLED: %s\", dist.version)\n                if parse_version(latest).pre:\n                    write_output(\n                        \"LATEST:    %s (pre-release; install\"\n                        \" with `pip install --pre`)\",\n                        latest,\n                    )\n                else:\n                    write_output(\"LATEST:    %s\", latest)\n\n\ndef get_installed_distribution(name: str) -> BaseDistribution | None:\n    env = get_default_environment()\n    return env.get_distribution(name)\n\n\ndef print_results(\n    hits: list[TransformedHit],\n    name_column_width: int | None = None,\n    terminal_width: int | None = None,\n) -> None:\n    if not hits:\n        return\n    if name_column_width is None:\n        name_column_width = (\n            max(\n                [\n                    len(hit[\"name\"]) + len(highest_version(hit.get(\"versions\", [\"-\"])))\n                    for hit in hits\n                ]\n            )\n            + 4\n        )\n\n    for hit in hits:\n        name = hit[\"name\"]\n        summary = hit[\"summary\"] or \"\"\n        latest = highest_version(hit.get(\"versions\", [\"-\"]))\n        if terminal_width is not None:\n            target_width = terminal_width - name_column_width - 5\n            if target_width > 10:\n                # wrap and indent summary to fit terminal\n                summary_lines = textwrap.wrap(summary, target_width)\n                summary = (\"\\n\" + \" \" * (name_column_width + 3)).join(summary_lines)\n\n        name_latest = f\"{name} ({latest})\"\n        line = f\"{name_latest:{name_column_width}} - {summary}\"\n        try:\n            write_output(line)\n            dist = get_installed_distribution(name)\n            print_dist_installation_info(latest, dist)\n        except UnicodeEncodeError:\n            pass\n\n\ndef highest_version(versions: list[str]) -> str:\n    return max(versions, key=parse_version)\n"
  },
  {
    "path": "src/pip/_internal/commands/show.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport string\nfrom collections.abc import Generator, Iterable, Iterator\nfrom optparse import Values\nfrom typing import NamedTuple\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.metadata import BaseDistribution, get_default_environment\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\ndef normalize_project_url_label(label: str) -> str:\n    # This logic is from PEP 753 (Well-known Project URLs in Metadata).\n    chars_to_remove = string.punctuation + string.whitespace\n    removal_map = str.maketrans(\"\", \"\", chars_to_remove)\n    return label.translate(removal_map).lower()\n\n\nclass ShowCommand(Command):\n    \"\"\"\n    Show information about one or more installed packages.\n\n    The output is in RFC-compliant mail header format.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <package> ...\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-f\",\n            \"--files\",\n            dest=\"files\",\n            action=\"store_true\",\n            default=False,\n            help=\"Show the full list of installed files for each package.\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        if not args:\n            logger.warning(\"ERROR: Please provide a package name or names.\")\n            return ERROR\n        query = args\n\n        results = search_packages_info(query)\n        if not print_results(\n            results, list_files=options.files, verbose=options.verbose\n        ):\n            return ERROR\n        return SUCCESS\n\n\nclass _PackageInfo(NamedTuple):\n    name: str\n    version: str\n    location: str\n    editable_project_location: str | None\n    requires: list[str]\n    required_by: list[str]\n    installer: str\n    metadata_version: str\n    classifiers: list[str]\n    summary: str\n    homepage: str\n    project_urls: list[str]\n    author: str\n    author_email: str\n    license: str\n    license_expression: str\n    entry_points: list[str]\n    files: list[str] | None\n\n\ndef search_packages_info(query: list[str]) -> Generator[_PackageInfo, None, None]:\n    \"\"\"\n    Gather details from installed distributions. Print distribution name,\n    version, location, and installed files. Installed files requires a\n    pip generated 'installed-files.txt' in the distributions '.egg-info'\n    directory.\n    \"\"\"\n    env = get_default_environment()\n\n    installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}\n    query_names = [canonicalize_name(name) for name in query]\n    missing = sorted(\n        [name for name, pkg in zip(query, query_names) if pkg not in installed]\n    )\n    if missing:\n        logger.warning(\"Package(s) not found: %s\", \", \".join(missing))\n\n    def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:\n        return (\n            dist.metadata[\"Name\"] or \"UNKNOWN\"\n            for dist in installed.values()\n            if current_dist.canonical_name\n            in {canonicalize_name(d.name) for d in dist.iter_dependencies()}\n        )\n\n    for query_name in query_names:\n        try:\n            dist = installed[query_name]\n        except KeyError:\n            continue\n\n        try:\n            requires = sorted(\n                # Avoid duplicates in requirements (e.g. due to environment markers).\n                {req.name for req in dist.iter_dependencies()},\n                key=str.lower,\n            )\n        except InvalidRequirement:\n            requires = sorted(dist.iter_raw_dependencies(), key=str.lower)\n\n        try:\n            required_by = sorted(_get_requiring_packages(dist), key=str.lower)\n        except InvalidRequirement:\n            required_by = [\"#N/A\"]\n\n        try:\n            entry_points_text = dist.read_text(\"entry_points.txt\")\n            entry_points = entry_points_text.splitlines(keepends=False)\n        except FileNotFoundError:\n            entry_points = []\n\n        files_iter = dist.iter_declared_entries()\n        if files_iter is None:\n            files: list[str] | None = None\n        else:\n            files = sorted(files_iter)\n\n        metadata = dist.metadata\n\n        project_urls = metadata.get_all(\"Project-URL\", [])\n        homepage = metadata.get(\"Home-page\", \"\")\n        if not homepage:\n            # It's common that there is a \"homepage\" Project-URL, but Home-page\n            # remains unset (especially as PEP 621 doesn't surface the field).\n            for url in project_urls:\n                url_label, url = url.split(\",\", maxsplit=1)\n                normalized_label = normalize_project_url_label(url_label)\n                if normalized_label == \"homepage\":\n                    homepage = url.strip()\n                    break\n\n        yield _PackageInfo(\n            name=dist.raw_name,\n            version=dist.raw_version,\n            location=dist.location or \"\",\n            editable_project_location=dist.editable_project_location,\n            requires=requires,\n            required_by=required_by,\n            installer=dist.installer,\n            metadata_version=dist.metadata_version or \"\",\n            classifiers=metadata.get_all(\"Classifier\", []),\n            summary=metadata.get(\"Summary\", \"\"),\n            homepage=homepage,\n            project_urls=project_urls,\n            author=metadata.get(\"Author\", \"\"),\n            author_email=metadata.get(\"Author-email\", \"\"),\n            license=metadata.get(\"License\", \"\"),\n            license_expression=metadata.get(\"License-Expression\", \"\"),\n            entry_points=entry_points,\n            files=files,\n        )\n\n\ndef print_results(\n    distributions: Iterable[_PackageInfo],\n    list_files: bool,\n    verbose: bool,\n) -> bool:\n    \"\"\"\n    Print the information from installed distributions found.\n    \"\"\"\n    results_printed = False\n    for i, dist in enumerate(distributions):\n        results_printed = True\n        if i > 0:\n            write_output(\"---\")\n\n        metadata_version_tuple = tuple(map(int, dist.metadata_version.split(\".\")))\n\n        write_output(\"Name: %s\", dist.name)\n        write_output(\"Version: %s\", dist.version)\n        write_output(\"Summary: %s\", dist.summary)\n        write_output(\"Home-page: %s\", dist.homepage)\n        write_output(\"Author: %s\", dist.author)\n        write_output(\"Author-email: %s\", dist.author_email)\n        if metadata_version_tuple >= (2, 4) and dist.license_expression:\n            write_output(\"License-Expression: %s\", dist.license_expression)\n        else:\n            write_output(\"License: %s\", dist.license)\n        write_output(\"Location: %s\", dist.location)\n        if dist.editable_project_location is not None:\n            write_output(\n                \"Editable project location: %s\", dist.editable_project_location\n            )\n        write_output(\"Requires: %s\", \", \".join(dist.requires))\n        write_output(\"Required-by: %s\", \", \".join(dist.required_by))\n\n        if verbose:\n            write_output(\"Metadata-Version: %s\", dist.metadata_version)\n            write_output(\"Installer: %s\", dist.installer)\n            write_output(\"Classifiers:\")\n            for classifier in dist.classifiers:\n                write_output(\"  %s\", classifier)\n            write_output(\"Entry-points:\")\n            for entry in dist.entry_points:\n                write_output(\"  %s\", entry.strip())\n            write_output(\"Project-URLs:\")\n            for project_url in dist.project_urls:\n                write_output(\"  %s\", project_url)\n        if list_files:\n            write_output(\"Files:\")\n            if dist.files is None:\n                write_output(\"Cannot locate RECORD or installed-files.txt\")\n            else:\n                for line in dist.files:\n                    write_output(\"  %s\", line.strip())\n    return results_printed\n"
  },
  {
    "path": "src/pip/_internal/commands/uninstall.py",
    "content": "import logging\nfrom optparse import Values\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.index_command import SessionCommandMixin\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.req import parse_requirements\nfrom pip._internal.req.constructors import (\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n)\nfrom pip._internal.utils.misc import (\n    check_externally_managed,\n    protect_pip_from_modification_on_windows,\n    warn_if_run_as_root,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass UninstallCommand(Command, SessionCommandMixin):\n    \"\"\"\n    Uninstall packages.\n\n    pip is able to uninstall most installed packages. Known exceptions are:\n\n    - Pure distutils packages installed with ``python setup.py install``, which\n      leave behind no metadata to determine what files were installed.\n    - Script wrappers installed by ``python setup.py develop``.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <package> ...\n      %prog [options] -r <requirements file> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-r\",\n            \"--requirement\",\n            dest=\"requirements\",\n            action=\"append\",\n            default=[],\n            metavar=\"file\",\n            help=(\n                \"Uninstall all the packages listed in the given requirements \"\n                \"file.  This option can be used multiple times.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-y\",\n            \"--yes\",\n            dest=\"yes\",\n            action=\"store_true\",\n            help=\"Don't ask for confirmation of uninstall deletions.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.root_user_action())\n        self.cmd_opts.add_option(cmdoptions.override_externally_managed())\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        session = self.get_default_session(options)\n\n        reqs_to_uninstall = {}\n        for name in args:\n            req = install_req_from_line(\n                name,\n                isolated=options.isolated_mode,\n            )\n            if req.name:\n                reqs_to_uninstall[canonicalize_name(req.name)] = req\n            else:\n                logger.warning(\n                    \"Invalid requirement: %r ignored -\"\n                    \" the uninstall command expects named\"\n                    \" requirements.\",\n                    name,\n                )\n        for filename in options.requirements:\n            for parsed_req in parse_requirements(\n                filename, options=options, session=session\n            ):\n                req = install_req_from_parsed_requirement(\n                    parsed_req, isolated=options.isolated_mode\n                )\n                if req.name:\n                    reqs_to_uninstall[canonicalize_name(req.name)] = req\n        if not reqs_to_uninstall:\n            raise InstallationError(\n                f\"You must give at least one requirement to {self.name} (see \"\n                f'\"pip help {self.name}\")'\n            )\n\n        if not options.override_externally_managed:\n            check_externally_managed()\n\n        protect_pip_from_modification_on_windows(\n            modifying_pip=\"pip\" in reqs_to_uninstall\n        )\n\n        for req in reqs_to_uninstall.values():\n            uninstall_pathset = req.uninstall(\n                auto_confirm=options.yes,\n                verbose=self.verbosity > 0,\n            )\n            if uninstall_pathset:\n                uninstall_pathset.commit()\n        if options.root_user_action == \"warn\":\n            warn_if_run_as_root()\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/commands/wheel.py",
    "content": "import logging\nimport os\nimport shutil\nfrom optparse import Values\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import RequirementCommand, with_cleanup\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n)\nfrom pip._internal.utils.misc import ensure_dir, normalize_path\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.wheel_builder import build\n\nlogger = logging.getLogger(__name__)\n\n\nclass WheelCommand(RequirementCommand):\n    \"\"\"\n    Build Wheel archives for your requirements and dependencies.\n\n    Wheel is a built-package format, and offers the advantage of not\n    recompiling your software during every install. For more details, see the\n    wheel docs: https://wheel.readthedocs.io/en/latest/\n\n    'pip wheel' uses the build system interface as described here:\n    https://pip.pypa.io/en/stable/reference/build-system/\n\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> ...\n      %prog [options] -r <requirements file> ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-w\",\n            \"--wheel-dir\",\n            dest=\"wheel_dir\",\n            metavar=\"dir\",\n            default=os.curdir,\n            help=(\n                \"Build wheels into <dir>, where the default is the \"\n                \"current working directory.\"\n            ),\n        )\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.build_constraints())\n        self.cmd_opts.add_option(cmdoptions.editable())\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())\n        self.cmd_opts.add_option(cmdoptions.src())\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n\n        self.cmd_opts.add_option(\n            \"--no-verify\",\n            dest=\"no_verify\",\n            action=\"store_true\",\n            default=False,\n            help=\"Don't verify if built wheel is valid.\",\n        )\n\n        self.cmd_opts.add_option(cmdoptions.config_settings())\n\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        selection_opts = cmdoptions.make_option_group(\n            cmdoptions.package_selection_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, selection_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    @with_cleanup\n    def run(self, options: Values, args: list[str]) -> int:\n        cmdoptions.check_build_constraints(options)\n        cmdoptions.check_release_control_exclusive(options)\n\n        session = self.get_default_session(options)\n\n        finder = self._build_package_finder(options, session)\n\n        options.wheel_dir = normalize_path(options.wheel_dir)\n        ensure_dir(options.wheel_dir)\n\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"wheel\",\n            globally_managed=True,\n        )\n\n        reqs = self.get_requirements(args, options, finder, session)\n\n        wheel_cache = WheelCache(options.cache_dir)\n\n        preparer = self.make_requirement_preparer(\n            temp_build_dir=directory,\n            options=options,\n            build_tracker=build_tracker,\n            session=session,\n            finder=finder,\n            download_dir=options.wheel_dir,\n            use_user_site=False,\n            verbosity=self.verbosity,\n        )\n\n        resolver = self.make_resolver(\n            preparer=preparer,\n            finder=finder,\n            options=options,\n            wheel_cache=wheel_cache,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n\n        self.trace_basic_info(finder)\n\n        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)\n\n        preparer.prepare_linked_requirements_more(requirement_set.requirements.values())\n\n        reqs_to_build: list[InstallRequirement] = []\n        for req in requirement_set.requirements.values():\n            if req.is_wheel:\n                preparer.save_linked_requirement(req)\n            else:\n                reqs_to_build.append(req)\n\n        # build wheels\n        build_successes, build_failures = build(\n            reqs_to_build,\n            wheel_cache=wheel_cache,\n            verify=(not options.no_verify),\n        )\n        for req in build_successes:\n            assert req.link and req.link.is_wheel\n            assert req.local_file_path\n            # copy from cache to target directory\n            try:\n                shutil.copy(req.local_file_path, options.wheel_dir)\n            except OSError as e:\n                logger.warning(\n                    \"Building wheel for %s failed: %s\",\n                    req.name,\n                    e,\n                )\n                build_failures.append(req)\n        if len(build_failures) != 0:\n            raise CommandError(\"Failed to build one or more wheels\")\n\n        return SUCCESS\n"
  },
  {
    "path": "src/pip/_internal/configuration.py",
    "content": "\"\"\"Configuration management setup\n\nSome terminology:\n- name\n  As written in config files.\n- value\n  Value associated with a name\n- key\n  Name combined with it's section (section.name)\n- variant\n  A single word describing where the configuration key-value pair came from\n\"\"\"\n\nfrom __future__ import annotations\n\nimport configparser\nimport locale\nimport os\nimport sys\nfrom collections.abc import Iterable\nfrom typing import Any, NewType\n\nfrom pip._internal.exceptions import (\n    ConfigurationError,\n    ConfigurationFileCouldNotBeLoaded,\n)\nfrom pip._internal.utils import appdirs\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import ensure_dir, enum\n\nRawConfigParser = configparser.RawConfigParser  # Shorthand\nKind = NewType(\"Kind\", str)\n\nCONFIG_BASENAME = \"pip.ini\" if WINDOWS else \"pip.conf\"\nENV_NAMES_IGNORED = \"version\", \"help\"\n\n# The kinds of configurations there are.\nkinds = enum(\n    USER=\"user\",  # User Specific\n    GLOBAL=\"global\",  # System Wide\n    SITE=\"site\",  # [Virtual] Environment Specific\n    ENV=\"env\",  # from PIP_CONFIG_FILE\n    ENV_VAR=\"env-var\",  # from Environment Variables\n)\nOVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR\nVALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE\n\nlogger = getLogger(__name__)\n\n\n# NOTE: Maybe use the optionx attribute to normalize keynames.\ndef _normalize_name(name: str) -> str:\n    \"\"\"Make a name consistent regardless of source (environment or file)\"\"\"\n    name = name.lower().replace(\"_\", \"-\")\n    name = name.removeprefix(\"--\")  # only prefer long opts\n    return name\n\n\ndef _disassemble_key(name: str) -> list[str]:\n    if \".\" not in name:\n        error_message = (\n            \"Key does not contain dot separated section and key. \"\n            f\"Perhaps you wanted to use 'global.{name}' instead?\"\n        )\n        raise ConfigurationError(error_message)\n    return name.split(\".\", 1)\n\n\ndef get_configuration_files() -> dict[Kind, list[str]]:\n    global_config_files = [\n        os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs(\"pip\")\n    ]\n\n    site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)\n    legacy_config_file = os.path.join(\n        os.path.expanduser(\"~\"),\n        \"pip\" if WINDOWS else \".pip\",\n        CONFIG_BASENAME,\n    )\n    new_config_file = os.path.join(appdirs.user_config_dir(\"pip\"), CONFIG_BASENAME)\n    return {\n        kinds.GLOBAL: global_config_files,\n        kinds.SITE: [site_config_file],\n        kinds.USER: [legacy_config_file, new_config_file],\n    }\n\n\nclass Configuration:\n    \"\"\"Handles management of configuration.\n\n    Provides an interface to accessing and managing configuration files.\n\n    This class converts provides an API that takes \"section.key-name\" style\n    keys and stores the value associated with it as \"key-name\" under the\n    section \"section\".\n\n    This allows for a clean interface wherein the both the section and the\n    key-name are preserved in an easy to manage form in the configuration files\n    and the data stored is also nice.\n    \"\"\"\n\n    def __init__(self, isolated: bool, load_only: Kind | None = None) -> None:\n        super().__init__()\n\n        if load_only is not None and load_only not in VALID_LOAD_ONLY:\n            raise ConfigurationError(\n                \"Got invalid value for load_only - should be one of {}\".format(\n                    \", \".join(map(repr, VALID_LOAD_ONLY))\n                )\n            )\n        self.isolated = isolated\n        self.load_only = load_only\n\n        # Because we keep track of where we got the data from\n        self._parsers: dict[Kind, list[tuple[str, RawConfigParser]]] = {\n            variant: [] for variant in OVERRIDE_ORDER\n        }\n        self._config: dict[Kind, dict[str, dict[str, Any]]] = {\n            variant: {} for variant in OVERRIDE_ORDER\n        }\n        self._modified_parsers: list[tuple[str, RawConfigParser]] = []\n\n    def load(self) -> None:\n        \"\"\"Loads configuration from configuration files and environment\"\"\"\n        self._load_config_files()\n        if not self.isolated:\n            self._load_environment_vars()\n\n    def get_file_to_edit(self) -> str | None:\n        \"\"\"Returns the file with highest priority in configuration\"\"\"\n        assert self.load_only is not None, \"Need to be specified a file to be editing\"\n\n        try:\n            return self._get_parser_to_modify()[0]\n        except IndexError:\n            return None\n\n    def items(self) -> Iterable[tuple[str, Any]]:\n        \"\"\"Returns key-value pairs like dict.items() representing the loaded\n        configuration\n        \"\"\"\n        return self._dictionary.items()\n\n    def get_value(self, key: str) -> Any:\n        \"\"\"Get a value from the configuration.\"\"\"\n        orig_key = key\n        key = _normalize_name(key)\n        try:\n            clean_config: dict[str, Any] = {}\n            for file_values in self._dictionary.values():\n                clean_config.update(file_values)\n            return clean_config[key]\n        except KeyError:\n            # disassembling triggers a more useful error message than simply\n            # \"No such key\" in the case that the key isn't in the form command.option\n            _disassemble_key(key)\n            raise ConfigurationError(f\"No such key - {orig_key}\")\n\n    def set_value(self, key: str, value: Any) -> None:\n        \"\"\"Modify a value in the configuration.\"\"\"\n        key = _normalize_name(key)\n        self._ensure_have_load_only()\n\n        assert self.load_only\n        fname, parser = self._get_parser_to_modify()\n\n        if parser is not None:\n            section, name = _disassemble_key(key)\n\n            # Modify the parser and the configuration\n            if not parser.has_section(section):\n                parser.add_section(section)\n            parser.set(section, name, value)\n\n        self._config[self.load_only].setdefault(fname, {})\n        self._config[self.load_only][fname][key] = value\n        self._mark_as_modified(fname, parser)\n\n    def unset_value(self, key: str) -> None:\n        \"\"\"Unset a value in the configuration.\"\"\"\n        orig_key = key\n        key = _normalize_name(key)\n        self._ensure_have_load_only()\n\n        assert self.load_only\n        fname, parser = self._get_parser_to_modify()\n\n        if (\n            key not in self._config[self.load_only][fname]\n            and key not in self._config[self.load_only]\n        ):\n            raise ConfigurationError(f\"No such key - {orig_key}\")\n\n        if parser is not None:\n            section, name = _disassemble_key(key)\n            if not (\n                parser.has_section(section) and parser.remove_option(section, name)\n            ):\n                # The option was not removed.\n                raise ConfigurationError(\n                    \"Fatal Internal error [id=1]. Please report as a bug.\"\n                )\n\n            # The section may be empty after the option was removed.\n            if not parser.items(section):\n                parser.remove_section(section)\n            self._mark_as_modified(fname, parser)\n        try:\n            del self._config[self.load_only][fname][key]\n        except KeyError:\n            del self._config[self.load_only][key]\n\n    def save(self) -> None:\n        \"\"\"Save the current in-memory state.\"\"\"\n        self._ensure_have_load_only()\n\n        for fname, parser in self._modified_parsers:\n            logger.info(\"Writing to %s\", fname)\n\n            # Ensure directory exists.\n            ensure_dir(os.path.dirname(fname))\n\n            # Ensure directory's permission(need to be writeable)\n            try:\n                with open(fname, \"w\") as f:\n                    parser.write(f)\n            except OSError as error:\n                raise ConfigurationError(\n                    f\"An error occurred while writing to the configuration file \"\n                    f\"{fname}: {error}\"\n                )\n\n    #\n    # Private routines\n    #\n\n    def _ensure_have_load_only(self) -> None:\n        if self.load_only is None:\n            raise ConfigurationError(\"Needed a specific file to be modifying.\")\n        logger.debug(\"Will be working with %s variant only\", self.load_only)\n\n    @property\n    def _dictionary(self) -> dict[str, dict[str, Any]]:\n        \"\"\"A dictionary representing the loaded configuration.\"\"\"\n        # NOTE: Dictionaries are not populated if not loaded. So, conditionals\n        #       are not needed here.\n        retval = {}\n\n        for variant in OVERRIDE_ORDER:\n            retval.update(self._config[variant])\n\n        return retval\n\n    def _load_config_files(self) -> None:\n        \"\"\"Loads configuration from configuration files\"\"\"\n        config_files = dict(self.iter_config_files())\n        if config_files[kinds.ENV][0:1] == [os.devnull]:\n            logger.debug(\n                \"Skipping loading configuration files due to \"\n                \"environment's PIP_CONFIG_FILE being os.devnull\"\n            )\n            return\n\n        for variant, files in config_files.items():\n            for fname in files:\n                # If there's specific variant set in `load_only`, load only\n                # that variant, not the others.\n                if self.load_only is not None and variant != self.load_only:\n                    logger.debug(\"Skipping file '%s' (variant: %s)\", fname, variant)\n                    continue\n\n                parser = self._load_file(variant, fname)\n\n                # Keeping track of the parsers used\n                self._parsers[variant].append((fname, parser))\n\n    def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:\n        logger.verbose(\"For variant '%s', will try loading '%s'\", variant, fname)\n        parser = self._construct_parser(fname)\n\n        for section in parser.sections():\n            items = parser.items(section)\n            self._config[variant].setdefault(fname, {})\n            self._config[variant][fname].update(self._normalized_keys(section, items))\n\n        return parser\n\n    def _construct_parser(self, fname: str) -> RawConfigParser:\n        parser = configparser.RawConfigParser()\n        # If there is no such file, don't bother reading it but create the\n        # parser anyway, to hold the data.\n        # Doing this is useful when modifying and saving files, where we don't\n        # need to construct a parser.\n        if os.path.exists(fname):\n            locale_encoding = locale.getpreferredencoding(False)\n            try:\n                parser.read(fname, encoding=locale_encoding)\n            except UnicodeDecodeError:\n                # See https://github.com/pypa/pip/issues/4963\n                raise ConfigurationFileCouldNotBeLoaded(\n                    reason=f\"contains invalid {locale_encoding} characters\",\n                    fname=fname,\n                )\n            except configparser.Error as error:\n                # See https://github.com/pypa/pip/issues/4893\n                raise ConfigurationFileCouldNotBeLoaded(error=error)\n        return parser\n\n    def _load_environment_vars(self) -> None:\n        \"\"\"Loads configuration from environment variables\"\"\"\n        self._config[kinds.ENV_VAR].setdefault(\":env:\", {})\n        self._config[kinds.ENV_VAR][\":env:\"].update(\n            self._normalized_keys(\":env:\", self.get_environ_vars())\n        )\n\n    def _normalized_keys(\n        self, section: str, items: Iterable[tuple[str, Any]]\n    ) -> dict[str, Any]:\n        \"\"\"Normalizes items to construct a dictionary with normalized keys.\n\n        This routine is where the names become keys and are made the same\n        regardless of source - configuration files or environment.\n        \"\"\"\n        normalized = {}\n        for name, val in items:\n            key = section + \".\" + _normalize_name(name)\n            normalized[key] = val\n        return normalized\n\n    def get_environ_vars(self) -> Iterable[tuple[str, str]]:\n        \"\"\"Returns a generator with all environmental vars with prefix PIP_\"\"\"\n        for key, val in os.environ.items():\n            if key.startswith(\"PIP_\"):\n                name = key[4:].lower()\n                if name not in ENV_NAMES_IGNORED:\n                    yield name, val\n\n    # XXX: This is patched in the tests.\n    def iter_config_files(self) -> Iterable[tuple[Kind, list[str]]]:\n        \"\"\"Yields variant and configuration files associated with it.\n\n        This should be treated like items of a dictionary. The order\n        here doesn't affect what gets overridden. That is controlled\n        by OVERRIDE_ORDER. However this does control the order they are\n        displayed to the user. It's probably most ergonomic to display\n        things in the same order as OVERRIDE_ORDER\n        \"\"\"\n        # SMELL: Move the conditions out of this function\n\n        env_config_file = os.environ.get(\"PIP_CONFIG_FILE\", None)\n        config_files = get_configuration_files()\n\n        yield kinds.GLOBAL, config_files[kinds.GLOBAL]\n\n        # per-user config is not loaded when env_config_file exists\n        should_load_user_config = not self.isolated and not (\n            env_config_file and os.path.exists(env_config_file)\n        )\n        if should_load_user_config:\n            # The legacy config file is overridden by the new config file\n            yield kinds.USER, config_files[kinds.USER]\n\n        # virtualenv config\n        yield kinds.SITE, config_files[kinds.SITE]\n\n        if env_config_file is not None:\n            yield kinds.ENV, [env_config_file]\n        else:\n            yield kinds.ENV, []\n\n    def get_values_in_config(self, variant: Kind) -> dict[str, Any]:\n        \"\"\"Get values present in a config file\"\"\"\n        return self._config[variant]\n\n    def _get_parser_to_modify(self) -> tuple[str, RawConfigParser]:\n        # Determine which parser to modify\n        assert self.load_only\n        parsers = self._parsers[self.load_only]\n        if not parsers:\n            # This should not happen if everything works correctly.\n            raise ConfigurationError(\n                \"Fatal Internal error [id=2]. Please report as a bug.\"\n            )\n\n        # Use the highest priority parser.\n        return parsers[-1]\n\n    # XXX: This is patched in the tests.\n    def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:\n        file_parser_tuple = (fname, parser)\n        if file_parser_tuple not in self._modified_parsers:\n            self._modified_parsers.append(file_parser_tuple)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self._dictionary!r})\"\n"
  },
  {
    "path": "src/pip/_internal/distributions/__init__.py",
    "content": "from pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.distributions.sdist import SourceDistribution\nfrom pip._internal.distributions.wheel import WheelDistribution\nfrom pip._internal.req.req_install import InstallRequirement\n\n\ndef make_distribution_for_install_requirement(\n    install_req: InstallRequirement,\n) -> AbstractDistribution:\n    \"\"\"Returns a Distribution for the given InstallRequirement\"\"\"\n    # Editable requirements will always be source distributions. They use the\n    # legacy logic until we create a modern standard for them.\n    if install_req.editable:\n        return SourceDistribution(install_req)\n\n    # If it's a wheel, it's a WheelDistribution\n    if install_req.is_wheel:\n        return WheelDistribution(install_req)\n\n    # Otherwise, a SourceDistribution\n    return SourceDistribution(install_req)\n"
  },
  {
    "path": "src/pip/_internal/distributions/base.py",
    "content": "from __future__ import annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nfrom pip._internal.metadata.base import BaseDistribution\nfrom pip._internal.req import InstallRequirement\n\nif TYPE_CHECKING:\n    from pip._internal.build_env import BuildEnvironmentInstaller\n\n\nclass AbstractDistribution(metaclass=abc.ABCMeta):\n    \"\"\"A base class for handling installable artifacts.\n\n    The requirements for anything installable are as follows:\n\n     - we must be able to determine the requirement name\n       (or we can't correctly handle the non-upgrade case).\n\n     - for packages with setup requirements, we must also be able\n       to determine their requirements without installing additional\n       packages (for the same reason as run-time dependencies)\n\n     - we must be able to create a Distribution object exposing the\n       above metadata.\n\n     - if we need to do work in the build tracker, we must be able to generate a unique\n       string to identify the requirement in the build tracker.\n    \"\"\"\n\n    def __init__(self, req: InstallRequirement) -> None:\n        super().__init__()\n        self.req = req\n\n    @abc.abstractproperty\n    def build_tracker_id(self) -> str | None:\n        \"\"\"A string that uniquely identifies this requirement to the build tracker.\n\n        If None, then this dist has no work to do in the build tracker, and\n        ``.prepare_distribution_metadata()`` will not be called.\"\"\"\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def get_metadata_distribution(self) -> BaseDistribution:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def prepare_distribution_metadata(\n        self,\n        build_env_installer: BuildEnvironmentInstaller,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        raise NotImplementedError()\n"
  },
  {
    "path": "src/pip/_internal/distributions/installed.py",
    "content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.metadata import BaseDistribution\n\nif TYPE_CHECKING:\n    from pip._internal.build_env import BuildEnvironmentInstaller\n\n\nclass InstalledDistribution(AbstractDistribution):\n    \"\"\"Represents an installed package.\n\n    This does not need any preparation as the required information has already\n    been computed.\n    \"\"\"\n\n    @property\n    def build_tracker_id(self) -> str | None:\n        return None\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        assert self.req.satisfied_by is not None, \"not actually installed\"\n        return self.req.satisfied_by\n\n    def prepare_distribution_metadata(\n        self,\n        build_env_installer: BuildEnvironmentInstaller,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        pass\n"
  },
  {
    "path": "src/pip/_internal/distributions/sdist.py",
    "content": "from __future__ import annotations\n\nimport logging\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nif TYPE_CHECKING:\n    from pip._internal.build_env import BuildEnvironmentInstaller\n\nlogger = logging.getLogger(__name__)\n\n\nclass SourceDistribution(AbstractDistribution):\n    \"\"\"Represents a source distribution.\n\n    The preparation step for these needs metadata for the packages to be\n    generated.\n    \"\"\"\n\n    @property\n    def build_tracker_id(self) -> str | None:\n        \"\"\"Identify this requirement uniquely by its link.\"\"\"\n        assert self.req.link\n        return self.req.link.url_without_fragment\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        return self.req.get_dist()\n\n    def prepare_distribution_metadata(\n        self,\n        build_env_installer: BuildEnvironmentInstaller,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        # Load pyproject.toml\n        self.req.load_pyproject_toml()\n\n        # Set up the build isolation, if this requirement should be isolated\n        if build_isolation:\n            # Setup an isolated environment and install the build backend static\n            # requirements in it.\n            self._prepare_build_backend(build_env_installer)\n            # Check that the build backend supports PEP 660. This cannot be done\n            # earlier because we need to setup the build backend to verify it\n            # supports build_editable, nor can it be done later, because we want\n            # to avoid installing build requirements needlessly.\n            self.req.editable_sanity_check()\n            # Install the dynamic build requirements.\n            self._install_build_reqs(build_env_installer)\n        else:\n            # When not using build isolation, we still need to check that\n            # the build backend supports PEP 660.\n            self.req.editable_sanity_check()\n        # Check if the current environment provides build dependencies\n        if check_build_deps:\n            pyproject_requires = self.req.pyproject_requires\n            assert pyproject_requires is not None\n            conflicting, missing = self.req.build_env.check_requirements(\n                pyproject_requires\n            )\n            if conflicting:\n                self._raise_conflicts(\"the backend dependencies\", conflicting)\n            if missing:\n                self._raise_missing_reqs(missing)\n        self.req.prepare_metadata()\n\n    def _prepare_build_backend(\n        self, build_env_installer: BuildEnvironmentInstaller\n    ) -> None:\n        # Isolate in a BuildEnvironment and install the build-time\n        # requirements.\n        pyproject_requires = self.req.pyproject_requires\n        assert pyproject_requires is not None\n\n        self.req.build_env = BuildEnvironment(build_env_installer)\n        self.req.build_env.install_requirements(\n            pyproject_requires, \"overlay\", kind=\"build dependencies\", for_req=self.req\n        )\n        conflicting, missing = self.req.build_env.check_requirements(\n            self.req.requirements_to_check\n        )\n        if conflicting:\n            self._raise_conflicts(\"PEP 517/518 supported requirements\", conflicting)\n        if missing:\n            logger.warning(\n                \"Missing build requirements in pyproject.toml for %s.\",\n                self.req,\n            )\n            logger.warning(\n                \"The project does not specify a build backend, and \"\n                \"pip cannot fall back to setuptools without %s.\",\n                \" and \".join(map(repr, sorted(missing))),\n            )\n\n    def _get_build_requires_wheel(self) -> Iterable[str]:\n        with self.req.build_env:\n            runner = runner_with_spinner_message(\"Getting requirements to build wheel\")\n            backend = self.req.pep517_backend\n            assert backend is not None\n            with backend.subprocess_runner(runner):\n                return backend.get_requires_for_build_wheel()\n\n    def _get_build_requires_editable(self) -> Iterable[str]:\n        with self.req.build_env:\n            runner = runner_with_spinner_message(\n                \"Getting requirements to build editable\"\n            )\n            backend = self.req.pep517_backend\n            assert backend is not None\n            with backend.subprocess_runner(runner):\n                return backend.get_requires_for_build_editable()\n\n    def _install_build_reqs(\n        self, build_env_installer: BuildEnvironmentInstaller\n    ) -> None:\n        # Install any extra build dependencies that the backend requests.\n        # This must be done in a second pass, as the pyproject.toml\n        # dependencies must be installed before we can call the backend.\n        if (\n            self.req.editable\n            and self.req.permit_editable_wheels\n            and self.req.supports_pyproject_editable\n        ):\n            build_reqs = self._get_build_requires_editable()\n        else:\n            build_reqs = self._get_build_requires_wheel()\n        conflicting, missing = self.req.build_env.check_requirements(build_reqs)\n        if conflicting:\n            self._raise_conflicts(\"the backend dependencies\", conflicting)\n        self.req.build_env.install_requirements(\n            missing, \"normal\", kind=\"backend dependencies\", for_req=self.req\n        )\n\n    def _raise_conflicts(\n        self, conflicting_with: str, conflicting_reqs: set[tuple[str, str]]\n    ) -> None:\n        format_string = (\n            \"Some build dependencies for {requirement} \"\n            \"conflict with {conflicting_with}: {description}.\"\n        )\n        error_message = format_string.format(\n            requirement=self.req,\n            conflicting_with=conflicting_with,\n            description=\", \".join(\n                f\"{installed} is incompatible with {wanted}\"\n                for installed, wanted in sorted(conflicting_reqs)\n            ),\n        )\n        raise InstallationError(error_message)\n\n    def _raise_missing_reqs(self, missing: set[str]) -> None:\n        format_string = (\n            \"Some build dependencies for {requirement} are missing: {missing}.\"\n        )\n        error_message = format_string.format(\n            requirement=self.req, missing=\", \".join(map(repr, sorted(missing)))\n        )\n        raise InstallationError(error_message)\n"
  },
  {
    "path": "src/pip/_internal/distributions/wheel.py",
    "content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    FilesystemWheel,\n    get_wheel_distribution,\n)\n\nif TYPE_CHECKING:\n    from pip._internal.build_env import BuildEnvironmentInstaller\n\n\nclass WheelDistribution(AbstractDistribution):\n    \"\"\"Represents a wheel distribution.\n\n    This does not need any preparation as wheels can be directly unpacked.\n    \"\"\"\n\n    @property\n    def build_tracker_id(self) -> str | None:\n        return None\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        \"\"\"Loads the metadata from the wheel file into memory and returns a\n        Distribution that uses it, not relying on the wheel file or\n        requirement.\n        \"\"\"\n        assert self.req.local_file_path, \"Set as part of preparation during download\"\n        assert self.req.name, \"Wheels are never unnamed\"\n        wheel = FilesystemWheel(self.req.local_file_path)\n        return get_wheel_distribution(wheel, canonicalize_name(self.req.name))\n\n    def prepare_distribution_metadata(\n        self,\n        build_env_installer: BuildEnvironmentInstaller,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        pass\n"
  },
  {
    "path": "src/pip/_internal/exceptions.py",
    "content": "\"\"\"Exceptions used throughout package.\n\nThis module MUST NOT try to import from anything within `pip._internal` to\noperate. This is expected to be importable from any/all files within the\nsubpackage and, thus, should not depend on them.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport configparser\nimport contextlib\nimport locale\nimport logging\nimport pathlib\nimport re\nimport sys\nimport traceback\nfrom collections.abc import Iterable, Iterator\nfrom itertools import chain, groupby, repeat\nfrom typing import TYPE_CHECKING, Literal\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\nfrom pip._vendor.packaging.version import InvalidVersion\nfrom pip._vendor.rich.console import Console, ConsoleOptions, RenderResult\nfrom pip._vendor.rich.markup import escape\nfrom pip._vendor.rich.text import Text\n\nif TYPE_CHECKING:\n    from hashlib import _Hash\n\n    from pip._vendor.requests.models import PreparedRequest, Request, Response\n\n    from pip._internal.metadata import BaseDistribution\n    from pip._internal.models.link import Link\n    from pip._internal.network.download import _FileDownload\n    from pip._internal.req.req_install import InstallRequirement\n\nlogger = logging.getLogger(__name__)\n\n\n#\n# Scaffolding\n#\ndef _is_kebab_case(s: str) -> bool:\n    return re.match(r\"^[a-z]+(-[a-z]+)*$\", s) is not None\n\n\ndef _prefix_with_indent(\n    s: Text | str,\n    console: Console,\n    *,\n    prefix: str,\n    indent: str,\n) -> Text:\n    if isinstance(s, Text):\n        text = s\n    else:\n        text = console.render_str(s)\n\n    return console.render_str(prefix, overflow=\"ignore\") + console.render_str(\n        f\"\\n{indent}\", overflow=\"ignore\"\n    ).join(text.split(allow_blank=True))\n\n\nclass PipError(Exception):\n    \"\"\"The base pip error.\"\"\"\n\n\nclass DiagnosticPipError(PipError):\n    \"\"\"An error, that presents diagnostic information to the user.\n\n    This contains a bunch of logic, to enable pretty presentation of our error\n    messages. Each error gets a unique reference. Each error can also include\n    additional context, a hint and/or a note -- which are presented with the\n    main error message in a consistent style.\n\n    This is adapted from the error output styling in `sphinx-theme-builder`.\n    \"\"\"\n\n    reference: str\n\n    def __init__(\n        self,\n        *,\n        kind: Literal[\"error\", \"warning\"] = \"error\",\n        reference: str | None = None,\n        message: str | Text,\n        context: str | Text | None,\n        hint_stmt: str | Text | None,\n        note_stmt: str | Text | None = None,\n        link: str | None = None,\n    ) -> None:\n        # Ensure a proper reference is provided.\n        if reference is None:\n            assert hasattr(self, \"reference\"), \"error reference not provided!\"\n            reference = self.reference\n        assert _is_kebab_case(reference), \"error reference must be kebab-case!\"\n\n        self.kind = kind\n        self.reference = reference\n\n        self.message = message\n        self.context = context\n\n        self.note_stmt = note_stmt\n        self.hint_stmt = hint_stmt\n\n        self.link = link\n\n        super().__init__(f\"<{self.__class__.__name__}: {self.reference}>\")\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__}(\"\n            f\"reference={self.reference!r}, \"\n            f\"message={self.message!r}, \"\n            f\"context={self.context!r}, \"\n            f\"note_stmt={self.note_stmt!r}, \"\n            f\"hint_stmt={self.hint_stmt!r}\"\n            \")>\"\n        )\n\n    def __rich_console__(\n        self,\n        console: Console,\n        options: ConsoleOptions,\n    ) -> RenderResult:\n        colour = \"red\" if self.kind == \"error\" else \"yellow\"\n\n        yield f\"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]\"\n        yield \"\"\n\n        if not options.ascii_only:\n            # Present the main message, with relevant context indented.\n            if self.context is not None:\n                yield _prefix_with_indent(\n                    self.message,\n                    console,\n                    prefix=f\"[{colour}]×[/] \",\n                    indent=f\"[{colour}]│[/] \",\n                )\n                yield _prefix_with_indent(\n                    self.context,\n                    console,\n                    prefix=f\"[{colour}]╰─>[/] \",\n                    indent=f\"[{colour}]   [/] \",\n                )\n            else:\n                yield _prefix_with_indent(\n                    self.message,\n                    console,\n                    prefix=\"[red]×[/] \",\n                    indent=\"  \",\n                )\n        else:\n            yield self.message\n            if self.context is not None:\n                yield \"\"\n                yield self.context\n\n        if self.note_stmt is not None or self.hint_stmt is not None:\n            yield \"\"\n\n        if self.note_stmt is not None:\n            yield _prefix_with_indent(\n                self.note_stmt,\n                console,\n                prefix=\"[magenta bold]note[/]: \",\n                indent=\"      \",\n            )\n        if self.hint_stmt is not None:\n            yield _prefix_with_indent(\n                self.hint_stmt,\n                console,\n                prefix=\"[cyan bold]hint[/]: \",\n                indent=\"      \",\n            )\n\n        if self.link is not None:\n            yield \"\"\n            yield f\"Link: {self.link}\"\n\n\n#\n# Actual Errors\n#\nclass ConfigurationError(PipError):\n    \"\"\"General exception in configuration\"\"\"\n\n\nclass InstallationError(PipError):\n    \"\"\"General exception during installation\"\"\"\n\n\nclass FailedToPrepareCandidate(InstallationError):\n    \"\"\"Raised when we fail to prepare a candidate (i.e. fetch and generate metadata).\n\n    This is intentionally not a diagnostic error, since the output will be presented\n    above this error, when this occurs. This should instead present information to the\n    user.\n    \"\"\"\n\n    def __init__(\n        self, *, package_name: str, requirement_chain: str, failed_step: str\n    ) -> None:\n        super().__init__(f\"Failed to build '{package_name}' when {failed_step.lower()}\")\n        self.package_name = package_name\n        self.requirement_chain = requirement_chain\n        self.failed_step = failed_step\n\n\nclass MissingPyProjectBuildRequires(DiagnosticPipError):\n    \"\"\"Raised when pyproject.toml has `build-system`, but no `build-system.requires`.\"\"\"\n\n    reference = \"missing-pyproject-build-system-requires\"\n\n    def __init__(self, *, package: str) -> None:\n        super().__init__(\n            message=f\"Can not process {escape(package)}\",\n            context=Text(\n                \"This package has an invalid pyproject.toml file.\\n\"\n                \"The [build-system] table is missing the mandatory `requires` key.\"\n            ),\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n            hint_stmt=Text(\"See PEP 518 for the detailed specification.\"),\n        )\n\n\nclass InvalidPyProjectBuildRequires(DiagnosticPipError):\n    \"\"\"Raised when pyproject.toml an invalid `build-system.requires`.\"\"\"\n\n    reference = \"invalid-pyproject-build-system-requires\"\n\n    def __init__(self, *, package: str, reason: str) -> None:\n        super().__init__(\n            message=f\"Can not process {escape(package)}\",\n            context=Text(\n                \"This package has an invalid `build-system.requires` key in \"\n                f\"pyproject.toml.\\n{reason}\"\n            ),\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n            hint_stmt=Text(\"See PEP 518 for the detailed specification.\"),\n        )\n\n\nclass NoneMetadataError(PipError):\n    \"\"\"Raised when accessing a Distribution's \"METADATA\" or \"PKG-INFO\".\n\n    This signifies an inconsistency, when the Distribution claims to have\n    the metadata file (if not, raise ``FileNotFoundError`` instead), but is\n    not actually able to produce its content. This may be due to permission\n    errors.\n    \"\"\"\n\n    def __init__(\n        self,\n        dist: BaseDistribution,\n        metadata_name: str,\n    ) -> None:\n        \"\"\"\n        :param dist: A Distribution object.\n        :param metadata_name: The name of the metadata being accessed\n            (can be \"METADATA\" or \"PKG-INFO\").\n        \"\"\"\n        self.dist = dist\n        self.metadata_name = metadata_name\n\n    def __str__(self) -> str:\n        # Use `dist` in the error message because its stringification\n        # includes more information, like the version and location.\n        return f\"None {self.metadata_name} metadata found for distribution: {self.dist}\"\n\n\nclass UserInstallationInvalid(InstallationError):\n    \"\"\"A --user install is requested on an environment without user site.\"\"\"\n\n    def __str__(self) -> str:\n        return \"User base directory is not specified\"\n\n\nclass InvalidSchemeCombination(InstallationError):\n    def __str__(self) -> str:\n        before = \", \".join(str(a) for a in self.args[:-1])\n        return f\"Cannot set {before} and {self.args[-1]} together\"\n\n\nclass DistributionNotFound(InstallationError):\n    \"\"\"Raised when a distribution cannot be found to satisfy a requirement\"\"\"\n\n\nclass RequirementsFileParseError(InstallationError):\n    \"\"\"Raised when a general error occurs parsing a requirements file line.\"\"\"\n\n\nclass BestVersionAlreadyInstalled(PipError):\n    \"\"\"Raised when the most up-to-date version of a package is already\n    installed.\"\"\"\n\n\nclass BadCommand(PipError):\n    \"\"\"Raised when virtualenv or a command is not found\"\"\"\n\n\nclass CommandError(PipError):\n    \"\"\"Raised when there is an error in command-line arguments\"\"\"\n\n\nclass PreviousBuildDirError(PipError):\n    \"\"\"Raised when there's a previous conflicting build directory\"\"\"\n\n\nclass NetworkConnectionError(PipError):\n    \"\"\"HTTP connection error\"\"\"\n\n    def __init__(\n        self,\n        error_msg: str,\n        response: Response | None = None,\n        request: Request | PreparedRequest | None = None,\n    ) -> None:\n        \"\"\"\n        Initialize NetworkConnectionError with  `request` and `response`\n        objects.\n        \"\"\"\n        self.response = response\n        self.request = request\n        self.error_msg = error_msg\n        if (\n            self.response is not None\n            and not self.request\n            and hasattr(response, \"request\")\n        ):\n            self.request = self.response.request\n        super().__init__(error_msg, response, request)\n\n    def __str__(self) -> str:\n        return str(self.error_msg)\n\n\nclass InvalidWheelFilename(InstallationError):\n    \"\"\"Invalid wheel filename.\"\"\"\n\n\nclass UnsupportedWheel(InstallationError):\n    \"\"\"Unsupported wheel.\"\"\"\n\n\nclass InvalidWheel(InstallationError):\n    \"\"\"Invalid (e.g. corrupt) wheel.\"\"\"\n\n    def __init__(self, location: str, name: str):\n        self.location = location\n        self.name = name\n\n    def __str__(self) -> str:\n        return f\"Wheel '{self.name}' located at {self.location} is invalid.\"\n\n\nclass MetadataInconsistent(InstallationError):\n    \"\"\"Built metadata contains inconsistent information.\n\n    This is raised when the metadata contains values (e.g. name and version)\n    that do not match the information previously obtained from sdist filename,\n    user-supplied ``#egg=`` value, or an install requirement name.\n    \"\"\"\n\n    def __init__(\n        self, ireq: InstallRequirement, field: str, f_val: str, m_val: str\n    ) -> None:\n        self.ireq = ireq\n        self.field = field\n        self.f_val = f_val\n        self.m_val = m_val\n\n    def __str__(self) -> str:\n        return (\n            f\"Requested {self.ireq} has inconsistent {self.field}: \"\n            f\"expected {self.f_val!r}, but metadata has {self.m_val!r}\"\n        )\n\n\nclass MetadataInvalid(InstallationError):\n    \"\"\"Metadata is invalid.\"\"\"\n\n    def __init__(self, ireq: InstallRequirement, error: str) -> None:\n        self.ireq = ireq\n        self.error = error\n\n    def __str__(self) -> str:\n        return f\"Requested {self.ireq} has invalid metadata: {self.error}\"\n\n\nclass InstallationSubprocessError(DiagnosticPipError, InstallationError):\n    \"\"\"A subprocess call failed.\"\"\"\n\n    reference = \"subprocess-exited-with-error\"\n\n    def __init__(\n        self,\n        *,\n        command_description: str,\n        exit_code: int,\n        output_lines: list[str] | None,\n    ) -> None:\n        if output_lines is None:\n            output_prompt = Text(\"No available output.\")\n        else:\n            output_prompt = (\n                Text.from_markup(f\"[red][{len(output_lines)} lines of output][/]\\n\")\n                + Text(\"\".join(output_lines))\n                + Text.from_markup(R\"[red]\\[end of output][/]\")\n            )\n\n        super().__init__(\n            message=(\n                f\"[green]{escape(command_description)}[/] did not run successfully.\\n\"\n                f\"exit code: {exit_code}\"\n            ),\n            context=output_prompt,\n            hint_stmt=None,\n            note_stmt=(\n                \"This error originates from a subprocess, and is likely not a \"\n                \"problem with pip.\"\n            ),\n        )\n\n        self.command_description = command_description\n        self.exit_code = exit_code\n\n    def __str__(self) -> str:\n        return f\"{self.command_description} exited with {self.exit_code}\"\n\n\nclass MetadataGenerationFailed(DiagnosticPipError, InstallationError):\n    reference = \"metadata-generation-failed\"\n\n    def __init__(\n        self,\n        *,\n        package_details: str,\n    ) -> None:\n        super().__init__(\n            message=\"Encountered error while generating package metadata.\",\n            context=escape(package_details),\n            hint_stmt=\"See above for details.\",\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n        )\n\n    def __str__(self) -> str:\n        return \"metadata generation failed\"\n\n\nclass HashErrors(InstallationError):\n    \"\"\"Multiple HashError instances rolled into one for reporting\"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[HashError] = []\n\n    def append(self, error: HashError) -> None:\n        self.errors.append(error)\n\n    def __str__(self) -> str:\n        lines = []\n        self.errors.sort(key=lambda e: e.order)\n        for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):\n            lines.append(cls.head)\n            lines.extend(e.body() for e in errors_of_cls)\n        if lines:\n            return \"\\n\".join(lines)\n        return \"\"\n\n    def __bool__(self) -> bool:\n        return bool(self.errors)\n\n\nclass HashError(InstallationError):\n    \"\"\"\n    A failure to verify a package against known-good hashes\n\n    :cvar order: An int sorting hash exception classes by difficulty of\n        recovery (lower being harder), so the user doesn't bother fretting\n        about unpinned packages when he has deeper issues, like VCS\n        dependencies, to deal with. Also keeps error reports in a\n        deterministic order.\n    :cvar head: A section heading for display above potentially many\n        exceptions of this kind\n    :ivar req: The InstallRequirement that triggered this error. This is\n        pasted on after the exception is instantiated, because it's not\n        typically available earlier.\n\n    \"\"\"\n\n    req: InstallRequirement | None = None\n    head = \"\"\n    order: int = -1\n\n    def body(self) -> str:\n        \"\"\"Return a summary of me for display under the heading.\n\n        This default implementation simply prints a description of the\n        triggering requirement.\n\n        :param req: The InstallRequirement that provoked this error, with\n            its link already populated by the resolver's _populate_link().\n\n        \"\"\"\n        return f\"    {self._requirement_name()}\"\n\n    def __str__(self) -> str:\n        return f\"{self.head}\\n{self.body()}\"\n\n    def _requirement_name(self) -> str:\n        \"\"\"Return a description of the requirement that triggered me.\n\n        This default implementation returns long description of the req, with\n        line numbers\n\n        \"\"\"\n        return str(self.req) if self.req else \"unknown package\"\n\n\nclass VcsHashUnsupported(HashError):\n    \"\"\"A hash was provided for a version-control-system-based requirement, but\n    we don't have a method for hashing those.\"\"\"\n\n    order = 0\n    head = (\n        \"Can't verify hashes for these requirements because we don't \"\n        \"have a way to hash version control repositories:\"\n    )\n\n\nclass DirectoryUrlHashUnsupported(HashError):\n    \"\"\"A hash was provided for a version-control-system-based requirement, but\n    we don't have a method for hashing those.\"\"\"\n\n    order = 1\n    head = (\n        \"Can't verify hashes for these file:// requirements because they \"\n        \"point to directories:\"\n    )\n\n\nclass HashMissing(HashError):\n    \"\"\"A hash was needed for a requirement but is absent.\"\"\"\n\n    order = 2\n    head = (\n        \"Hashes are required in --require-hashes mode, but they are \"\n        \"missing from some requirements. Here is a list of those \"\n        \"requirements along with the hashes their downloaded archives \"\n        \"actually had. Add lines like these to your requirements files to \"\n        \"prevent tampering. (If you did not enable --require-hashes \"\n        \"manually, note that it turns on automatically when any package \"\n        \"has a hash.)\"\n    )\n\n    def __init__(self, gotten_hash: str) -> None:\n        \"\"\"\n        :param gotten_hash: The hash of the (possibly malicious) archive we\n            just downloaded\n        \"\"\"\n        self.gotten_hash = gotten_hash\n\n    def body(self) -> str:\n        # Dodge circular import.\n        from pip._internal.utils.hashes import FAVORITE_HASH\n\n        package = None\n        if self.req:\n            # In the case of URL-based requirements, display the original URL\n            # seen in the requirements file rather than the package name,\n            # so the output can be directly copied into the requirements file.\n            package = (\n                self.req.original_link\n                if self.req.is_direct\n                # In case someone feeds something downright stupid\n                # to InstallRequirement's constructor.\n                else getattr(self.req, \"req\", None)\n            )\n        return \"    {} --hash={}:{}\".format(\n            package or \"unknown package\", FAVORITE_HASH, self.gotten_hash\n        )\n\n\nclass HashUnpinned(HashError):\n    \"\"\"A requirement had a hash specified but was not pinned to a specific\n    version.\"\"\"\n\n    order = 3\n    head = (\n        \"In --require-hashes mode, all requirements must have their \"\n        \"versions pinned with ==. These do not:\"\n    )\n\n\nclass HashMismatch(HashError):\n    \"\"\"\n    Distribution file hash values don't match.\n\n    :ivar package_name: The name of the package that triggered the hash\n        mismatch. Feel free to write to this after the exception is raise to\n        improve its error message.\n\n    \"\"\"\n\n    order = 4\n    head = (\n        \"THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS \"\n        \"FILE. If you have updated the package versions, please update \"\n        \"the hashes. Otherwise, examine the package contents carefully; \"\n        \"someone may have tampered with them.\"\n    )\n\n    def __init__(self, allowed: dict[str, list[str]], gots: dict[str, _Hash]) -> None:\n        \"\"\"\n        :param allowed: A dict of algorithm names pointing to lists of allowed\n            hex digests\n        :param gots: A dict of algorithm names pointing to hashes we\n            actually got from the files under suspicion\n        \"\"\"\n        self.allowed = allowed\n        self.gots = gots\n\n    def body(self) -> str:\n        return f\"    {self._requirement_name()}:\\n{self._hash_comparison()}\"\n\n    def _hash_comparison(self) -> str:\n        \"\"\"\n        Return a comparison of actual and expected hash values.\n\n        Example::\n\n               Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n                            or 123451234512345123451234512345123451234512345\n                    Got        bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef\n\n        \"\"\"\n\n        def hash_then_or(hash_name: str) -> chain[str]:\n            # For now, all the decent hashes have 6-char names, so we can get\n            # away with hard-coding space literals.\n            return chain([hash_name], repeat(\"    or\"))\n\n        lines: list[str] = []\n        for hash_name, expecteds in self.allowed.items():\n            prefix = hash_then_or(hash_name)\n            lines.extend((f\"        Expected {next(prefix)} {e}\") for e in expecteds)\n            lines.append(\n                f\"             Got        {self.gots[hash_name].hexdigest()}\\n\"\n            )\n        return \"\\n\".join(lines)\n\n\nclass UnsupportedPythonVersion(InstallationError):\n    \"\"\"Unsupported python version according to Requires-Python package\n    metadata.\"\"\"\n\n\nclass ConfigurationFileCouldNotBeLoaded(ConfigurationError):\n    \"\"\"When there are errors while loading a configuration file\"\"\"\n\n    def __init__(\n        self,\n        reason: str = \"could not be loaded\",\n        fname: str | None = None,\n        error: configparser.Error | None = None,\n    ) -> None:\n        super().__init__(error)\n        self.reason = reason\n        self.fname = fname\n        self.error = error\n\n    def __str__(self) -> str:\n        if self.fname is not None:\n            message_part = f\" in {self.fname}.\"\n        else:\n            assert self.error is not None\n            message_part = f\".\\n{self.error}\\n\"\n        return f\"Configuration file {self.reason}{message_part}\"\n\n\n_DEFAULT_EXTERNALLY_MANAGED_ERROR = f\"\"\"\\\nThe Python environment under {sys.prefix} is managed externally, and may not be\nmanipulated by the user. Please use specific tooling from the distributor of\nthe Python installation to interact with this environment instead.\n\"\"\"\n\n\nclass ExternallyManagedEnvironment(DiagnosticPipError):\n    \"\"\"The current environment is externally managed.\n\n    This is raised when the current environment is externally managed, as\n    defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked\n    and displayed when the error is bubbled up to the user.\n\n    :param error: The error message read from ``EXTERNALLY-MANAGED``.\n    \"\"\"\n\n    reference = \"externally-managed-environment\"\n\n    def __init__(self, error: str | None) -> None:\n        if error is None:\n            context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)\n        else:\n            context = Text(error)\n        super().__init__(\n            message=\"This environment is externally managed\",\n            context=context,\n            note_stmt=(\n                \"If you believe this is a mistake, please contact your \"\n                \"Python installation or OS distribution provider. \"\n                \"You can override this, at the risk of breaking your Python \"\n                \"installation or OS, by passing --break-system-packages.\"\n            ),\n            hint_stmt=Text(\"See PEP 668 for the detailed specification.\"),\n        )\n\n    @staticmethod\n    def _iter_externally_managed_error_keys() -> Iterator[str]:\n        # LC_MESSAGES is in POSIX, but not the C standard. The most common\n        # platform that does not implement this category is Windows, where\n        # using other categories for console message localization is equally\n        # unreliable, so we fall back to the locale-less vendor message. This\n        # can always be re-evaluated when a vendor proposes a new alternative.\n        try:\n            category = locale.LC_MESSAGES\n        except AttributeError:\n            lang: str | None = None\n        else:\n            lang, _ = locale.getlocale(category)\n        if lang is not None:\n            yield f\"Error-{lang}\"\n            for sep in (\"-\", \"_\"):\n                before, found, _ = lang.partition(sep)\n                if not found:\n                    continue\n                yield f\"Error-{before}\"\n        yield \"Error\"\n\n    @classmethod\n    def from_config(\n        cls,\n        config: pathlib.Path | str,\n    ) -> ExternallyManagedEnvironment:\n        parser = configparser.ConfigParser(interpolation=None)\n        try:\n            parser.read(config, encoding=\"utf-8\")\n            section = parser[\"externally-managed\"]\n            for key in cls._iter_externally_managed_error_keys():\n                with contextlib.suppress(KeyError):\n                    return cls(section[key])\n        except KeyError:\n            pass\n        except (OSError, UnicodeDecodeError, configparser.ParsingError):\n            from pip._internal.utils._log import VERBOSE\n\n            exc_info = logger.isEnabledFor(VERBOSE)\n            logger.warning(\"Failed to read %s\", config, exc_info=exc_info)\n        return cls(None)\n\n\nclass UninstallMissingRecord(DiagnosticPipError):\n    reference = \"uninstall-no-record-file\"\n\n    def __init__(self, *, distribution: BaseDistribution) -> None:\n        installer = distribution.installer\n        if not installer or installer == \"pip\":\n            dep = f\"{distribution.raw_name}=={distribution.version}\"\n            hint = Text.assemble(\n                \"You might be able to recover from this via: \",\n                (f\"pip install --force-reinstall --no-deps {dep}\", \"green\"),\n            )\n        else:\n            hint = Text(\n                f\"The package was installed by {installer}. \"\n                \"You should check if it can uninstall the package.\"\n            )\n\n        super().__init__(\n            message=Text(f\"Cannot uninstall {distribution}\"),\n            context=(\n                \"The package's contents are unknown: \"\n                f\"no RECORD file was found for {distribution.raw_name}.\"\n            ),\n            hint_stmt=hint,\n        )\n\n\nclass LegacyDistutilsInstall(DiagnosticPipError):\n    reference = \"uninstall-distutils-installed-package\"\n\n    def __init__(self, *, distribution: BaseDistribution) -> None:\n        super().__init__(\n            message=Text(f\"Cannot uninstall {distribution}\"),\n            context=(\n                \"It is a distutils installed project and thus we cannot accurately \"\n                \"determine which files belong to it which would lead to only a partial \"\n                \"uninstall.\"\n            ),\n            hint_stmt=None,\n        )\n\n\nclass InvalidInstalledPackage(DiagnosticPipError):\n    reference = \"invalid-installed-package\"\n\n    def __init__(\n        self,\n        *,\n        dist: BaseDistribution,\n        invalid_exc: InvalidRequirement | InvalidVersion,\n    ) -> None:\n        installed_location = dist.installed_location\n\n        if isinstance(invalid_exc, InvalidRequirement):\n            invalid_type = \"requirement\"\n        else:\n            invalid_type = \"version\"\n\n        super().__init__(\n            message=Text(\n                f\"Cannot process installed package {dist} \"\n                + (f\"in {installed_location!r} \" if installed_location else \"\")\n                + f\"because it has an invalid {invalid_type}:\\n{invalid_exc.args[0]}\"\n            ),\n            context=(\n                \"Starting with pip 24.1, packages with invalid \"\n                f\"{invalid_type}s can not be processed.\"\n            ),\n            hint_stmt=\"To proceed this package must be uninstalled.\",\n        )\n\n\nclass IncompleteDownloadError(DiagnosticPipError):\n    \"\"\"Raised when the downloader receives fewer bytes than advertised\n    in the Content-Length header.\"\"\"\n\n    reference = \"incomplete-download\"\n\n    def __init__(self, download: _FileDownload) -> None:\n        # Dodge circular import.\n        from pip._internal.utils.misc import format_size\n\n        assert download.size is not None\n        download_status = (\n            f\"{format_size(download.bytes_received)}/{format_size(download.size)}\"\n        )\n        if download.reattempts:\n            retry_status = f\"after {download.reattempts + 1} attempts \"\n            hint = \"Use --resume-retries to configure resume attempt limit.\"\n        else:\n            # Download retrying is not enabled.\n            retry_status = \"\"\n            hint = \"Consider using --resume-retries to enable download resumption.\"\n        message = Text(\n            f\"Download failed {retry_status}because not enough bytes \"\n            f\"were received ({download_status})\"\n        )\n\n        super().__init__(\n            message=message,\n            context=f\"URL: {download.link.redacted_url}\",\n            hint_stmt=hint,\n            note_stmt=\"This is an issue with network connectivity, not pip.\",\n        )\n\n\nclass ResolutionTooDeepError(DiagnosticPipError):\n    \"\"\"Raised when the dependency resolver exceeds the maximum recursion depth.\"\"\"\n\n    reference = \"resolution-too-deep\"\n\n    def __init__(self) -> None:\n        super().__init__(\n            message=\"Dependency resolution exceeded maximum depth\",\n            context=(\n                \"Pip cannot resolve the current dependencies as the dependency graph \"\n                \"is too complex for pip to solve efficiently.\"\n            ),\n            hint_stmt=(\n                \"Try adding lower bounds to constrain your dependencies, \"\n                \"for example: 'package>=2.0.0' instead of just 'package'. \"\n            ),\n            link=\"https://pip.pypa.io/en/stable/topics/dependency-resolution/#handling-resolution-too-deep-errors\",\n        )\n\n\nclass InstallWheelBuildError(DiagnosticPipError):\n    reference = \"failed-wheel-build-for-install\"\n\n    def __init__(self, failed: list[InstallRequirement]) -> None:\n        super().__init__(\n            message=(\n                \"Failed to build installable wheels for some \"\n                \"pyproject.toml based projects\"\n            ),\n            context=\", \".join(r.name for r in failed),  # type: ignore\n            hint_stmt=None,\n        )\n\n\nclass InvalidEggFragment(DiagnosticPipError):\n    reference = \"invalid-egg-fragment\"\n\n    def __init__(self, link: Link, fragment: str) -> None:\n        hint = \"\"\n        if \">\" in fragment or \"=\" in fragment or \"<\" in fragment:\n            hint = (\n                \"Version specifiers are silently ignored for URL references. \"\n                \"Remove them. \"\n            )\n        if \"[\" in fragment and \"]\" in fragment:\n            hint += \"Try using the Direct URL requirement syntax: 'name[extra] @ URL'\"\n\n        if not hint:\n            hint = \"Egg fragments can only be a valid project name.\"\n\n        super().__init__(\n            message=f\"The '{escape(fragment)}' egg fragment is invalid\",\n            context=f\"from '{escape(str(link))}'\",\n            hint_stmt=escape(hint),\n        )\n\n\nclass BuildDependencyInstallError(DiagnosticPipError):\n    \"\"\"Raised when build dependencies cannot be installed.\"\"\"\n\n    reference = \"failed-build-dependency-install\"\n\n    def __init__(\n        self,\n        req: InstallRequirement | None,\n        build_reqs: Iterable[str],\n        *,\n        cause: Exception,\n        log_lines: list[str] | None,\n    ) -> None:\n        if isinstance(cause, PipError):\n            note = \"This is likely not a problem with pip.\"\n        else:\n            note = (\n                \"pip crashed unexpectedly. Please file an issue on pip's issue \"\n                \"tracker: https://github.com/pypa/pip/issues/new\"\n            )\n\n        if log_lines is None:\n            # No logs are available, they must have been printed earlier.\n            context = Text(\"See above for more details.\")\n        else:\n            if isinstance(cause, PipError):\n                log_lines.append(f\"ERROR: {cause}\")\n            else:\n                # Split rendered error into real lines without trailing newlines.\n                log_lines.extend(\n                    \"\".join(traceback.format_exception(cause)).splitlines()\n                )\n\n            context = Text.assemble(\n                f\"Installing {' '.join(build_reqs)}\\n\",\n                (f\"[{len(log_lines)} lines of output]\\n\", \"red\"),\n                \"\\n\".join(log_lines),\n                (\"\\n[end of output]\", \"red\"),\n            )\n\n        message = Text(\"Cannot install build dependencies\", \"green\")\n        if req:\n            message += Text(f\" for {req}\")\n        super().__init__(\n            message=message, context=context, hint_stmt=None, note_stmt=note\n        )\n"
  },
  {
    "path": "src/pip/_internal/index/__init__.py",
    "content": "\"\"\"Index interaction code\"\"\"\n"
  },
  {
    "path": "src/pip/_internal/index/collector.py",
    "content": "\"\"\"\nThe main purpose of this module is to expose LinkCollector.collect_sources().\n\"\"\"\n\nfrom __future__ import annotations\n\nimport collections\nimport email.message\nimport functools\nimport itertools\nimport json\nimport logging\nimport os\nimport urllib.parse\nfrom collections.abc import Iterable, MutableMapping, Sequence\nfrom dataclasses import dataclass\nfrom html.parser import HTMLParser\nfrom optparse import Values\nfrom typing import (\n    Callable,\n    NamedTuple,\n    Protocol,\n)\n\nfrom pip._vendor import requests\nfrom pip._vendor.requests import Response\nfrom pip._vendor.requests.exceptions import RetryError, SSLError\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import raise_for_status\nfrom pip._internal.utils.filetypes import is_archive_file\nfrom pip._internal.utils.misc import redact_auth_from_url\nfrom pip._internal.utils.urls import url_to_path\nfrom pip._internal.vcs import vcs\n\nfrom .sources import CandidatesFromPage, LinkSource, build_source\n\nlogger = logging.getLogger(__name__)\n\nResponseHeaders = MutableMapping[str, str]\n\n\ndef _match_vcs_scheme(url: str) -> str | None:\n    \"\"\"Look for VCS schemes in the URL.\n\n    Returns the matched VCS scheme, or None if there's no match.\n    \"\"\"\n    for scheme in vcs.schemes:\n        if url.lower().startswith(scheme) and url[len(scheme)] in \"+:\":\n            return scheme\n    return None\n\n\nclass _NotAPIContent(Exception):\n    def __init__(self, content_type: str, request_desc: str) -> None:\n        super().__init__(content_type, request_desc)\n        self.content_type = content_type\n        self.request_desc = request_desc\n\n\ndef _ensure_api_header(response: Response) -> None:\n    \"\"\"\n    Check the Content-Type header to ensure the response contains a Simple\n    API Response.\n\n    Raises `_NotAPIContent` if the content type is not a valid content-type.\n    \"\"\"\n    content_type = response.headers.get(\"Content-Type\", \"Unknown\")\n\n    content_type_l = content_type.lower()\n    if content_type_l.startswith(\n        (\n            \"text/html\",\n            \"application/vnd.pypi.simple.v1+html\",\n            \"application/vnd.pypi.simple.v1+json\",\n        )\n    ):\n        return\n\n    raise _NotAPIContent(content_type, response.request.method)\n\n\nclass _NotHTTP(Exception):\n    pass\n\n\ndef _ensure_api_response(url: str, session: PipSession) -> None:\n    \"\"\"\n    Send a HEAD request to the URL, and ensure the response contains a simple\n    API Response.\n\n    Raises `_NotHTTP` if the URL is not available for a HEAD request, or\n    `_NotAPIContent` if the content type is not a valid content type.\n    \"\"\"\n    scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)\n    if scheme not in {\"http\", \"https\"}:\n        raise _NotHTTP()\n\n    resp = session.head(url, allow_redirects=True)\n    raise_for_status(resp)\n\n    _ensure_api_header(resp)\n\n\ndef _get_simple_response(url: str, session: PipSession) -> Response:\n    \"\"\"Access an Simple API response with GET, and return the response.\n\n    This consists of three parts:\n\n    1. If the URL looks suspiciously like an archive, send a HEAD first to\n       check the Content-Type is HTML or Simple API, to avoid downloading a\n       large file. Raise `_NotHTTP` if the content type cannot be determined, or\n       `_NotAPIContent` if it is not HTML or a Simple API.\n    2. Actually perform the request. Raise HTTP exceptions on network failures.\n    3. Check the Content-Type header to make sure we got a Simple API response,\n       and raise `_NotAPIContent` otherwise.\n    \"\"\"\n    if is_archive_file(Link(url).filename):\n        _ensure_api_response(url, session=session)\n\n    logger.debug(\"Getting page %s\", redact_auth_from_url(url))\n\n    resp = session.get(\n        url,\n        headers={\n            \"Accept\": \", \".join(\n                [\n                    \"application/vnd.pypi.simple.v1+json\",\n                    \"application/vnd.pypi.simple.v1+html; q=0.1\",\n                    \"text/html; q=0.01\",\n                ]\n            ),\n            # We don't want to blindly returned cached data for\n            # /simple/, because authors generally expecting that\n            # twine upload && pip install will function, but if\n            # they've done a pip install in the last ~10 minutes\n            # it won't. Thus by setting this to zero we will not\n            # blindly use any cached data, however the benefit of\n            # using max-age=0 instead of no-cache, is that we will\n            # still support conditional requests, so we will still\n            # minimize traffic sent in cases where the page hasn't\n            # changed at all, we will just always incur the round\n            # trip for the conditional GET now instead of only\n            # once per 10 minutes.\n            # For more information, please see pypa/pip#5670.\n            \"Cache-Control\": \"max-age=0\",\n        },\n    )\n    raise_for_status(resp)\n\n    # The check for archives above only works if the url ends with\n    # something that looks like an archive. However that is not a\n    # requirement of an url. Unless we issue a HEAD request on every\n    # url we cannot know ahead of time for sure if something is a\n    # Simple API response or not. However we can check after we've\n    # downloaded it.\n    _ensure_api_header(resp)\n\n    logger.debug(\n        \"Fetched page %s as %s\",\n        redact_auth_from_url(url),\n        resp.headers.get(\"Content-Type\", \"Unknown\"),\n    )\n\n    return resp\n\n\ndef _get_encoding_from_headers(headers: ResponseHeaders) -> str | None:\n    \"\"\"Determine if we have any encoding information in our headers.\"\"\"\n    if headers and \"Content-Type\" in headers:\n        m = email.message.Message()\n        m[\"content-type\"] = headers[\"Content-Type\"]\n        charset = m.get_param(\"charset\")\n        if charset:\n            return str(charset)\n    return None\n\n\nclass CacheablePageContent:\n    def __init__(self, page: IndexContent) -> None:\n        assert page.cache_link_parsing\n        self.page = page\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, type(self)) and self.page.url == other.page.url\n\n    def __hash__(self) -> int:\n        return hash(self.page.url)\n\n\nclass ParseLinks(Protocol):\n    def __call__(self, page: IndexContent) -> Iterable[Link]: ...\n\n\ndef with_cached_index_content(fn: ParseLinks) -> ParseLinks:\n    \"\"\"\n    Given a function that parses an Iterable[Link] from an IndexContent, cache the\n    function's result (keyed by CacheablePageContent), unless the IndexContent\n    `page` has `page.cache_link_parsing == False`.\n    \"\"\"\n\n    @functools.cache\n    def wrapper(cacheable_page: CacheablePageContent) -> list[Link]:\n        return list(fn(cacheable_page.page))\n\n    @functools.wraps(fn)\n    def wrapper_wrapper(page: IndexContent) -> list[Link]:\n        if page.cache_link_parsing:\n            return wrapper(CacheablePageContent(page))\n        return list(fn(page))\n\n    return wrapper_wrapper\n\n\n@with_cached_index_content\ndef parse_links(page: IndexContent) -> Iterable[Link]:\n    \"\"\"\n    Parse a Simple API's Index Content, and yield its anchor elements as Link objects.\n    \"\"\"\n\n    content_type_l = page.content_type.lower()\n    if content_type_l.startswith(\"application/vnd.pypi.simple.v1+json\"):\n        data = json.loads(page.content)\n        for file in data.get(\"files\", []):\n            link = Link.from_json(file, page.url)\n            if link is None:\n                continue\n            yield link\n        return\n\n    parser = HTMLLinkParser(page.url)\n    encoding = page.encoding or \"utf-8\"\n    parser.feed(page.content.decode(encoding))\n\n    url = page.url\n    base_url = parser.base_url or url\n    for anchor in parser.anchors:\n        link = Link.from_element(anchor, page_url=url, base_url=base_url)\n        if link is None:\n            continue\n        yield link\n\n\n@dataclass(frozen=True)\nclass IndexContent:\n    \"\"\"Represents one response (or page), along with its URL.\n\n    :param encoding: the encoding to decode the given content.\n    :param url: the URL from which the HTML was downloaded.\n    :param cache_link_parsing: whether links parsed from this page's url\n                               should be cached. PyPI index urls should\n                               have this set to False, for example.\n    \"\"\"\n\n    content: bytes\n    content_type: str\n    encoding: str | None\n    url: str\n    cache_link_parsing: bool = True\n\n    def __str__(self) -> str:\n        return redact_auth_from_url(self.url)\n\n\nclass HTMLLinkParser(HTMLParser):\n    \"\"\"\n    HTMLParser that keeps the first base HREF and a list of all anchor\n    elements' attributes.\n    \"\"\"\n\n    def __init__(self, url: str) -> None:\n        super().__init__(convert_charrefs=True)\n\n        self.url: str = url\n        self.base_url: str | None = None\n        self.anchors: list[dict[str, str | None]] = []\n\n    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:\n        if tag == \"base\" and self.base_url is None:\n            href = self.get_href(attrs)\n            if href is not None:\n                self.base_url = href\n        elif tag == \"a\":\n            self.anchors.append(dict(attrs))\n\n    def get_href(self, attrs: list[tuple[str, str | None]]) -> str | None:\n        for name, value in attrs:\n            if name == \"href\":\n                return value\n        return None\n\n\ndef _handle_get_simple_fail(\n    link: Link,\n    reason: str | Exception,\n    meth: Callable[..., None] | None = None,\n) -> None:\n    if meth is None:\n        meth = logger.debug\n    meth(\"Could not fetch URL %s: %s - skipping\", link, reason)\n\n\ndef _make_index_content(\n    response: Response, cache_link_parsing: bool = True\n) -> IndexContent:\n    encoding = _get_encoding_from_headers(response.headers)\n    return IndexContent(\n        response.content,\n        response.headers[\"Content-Type\"],\n        encoding=encoding,\n        url=response.url,\n        cache_link_parsing=cache_link_parsing,\n    )\n\n\ndef _get_index_content(link: Link, *, session: PipSession) -> IndexContent | None:\n    url = link.url.split(\"#\", 1)[0]\n\n    # Check for VCS schemes that do not support lookup as web pages.\n    vcs_scheme = _match_vcs_scheme(url)\n    if vcs_scheme:\n        logger.warning(\n            \"Cannot look at %s URL %s because it does not support lookup as web pages.\",\n            vcs_scheme,\n            link,\n        )\n        return None\n\n    # Tack index.html onto file:// URLs that point to directories\n    if url.startswith(\"file:\") and os.path.isdir(url_to_path(url)):\n        # add trailing slash if not present so urljoin doesn't trim\n        # final segment\n        if not url.endswith(\"/\"):\n            url += \"/\"\n        # TODO: In the future, it would be nice if pip supported PEP 691\n        #       style responses in the file:// URLs, however there's no\n        #       standard file extension for application/vnd.pypi.simple.v1+json\n        #       so we'll need to come up with something on our own.\n        url = urllib.parse.urljoin(url, \"index.html\")\n        logger.debug(\" file: URL is directory, getting %s\", url)\n\n    try:\n        resp = _get_simple_response(url, session=session)\n    except _NotHTTP:\n        logger.warning(\n            \"Skipping page %s because it looks like an archive, and cannot \"\n            \"be checked by a HTTP HEAD request.\",\n            link,\n        )\n    except _NotAPIContent as exc:\n        logger.warning(\n            \"Skipping page %s because the %s request got Content-Type: %s. \"\n            \"The only supported Content-Types are application/vnd.pypi.simple.v1+json, \"\n            \"application/vnd.pypi.simple.v1+html, and text/html\",\n            link,\n            exc.request_desc,\n            exc.content_type,\n        )\n    except NetworkConnectionError as exc:\n        _handle_get_simple_fail(link, exc)\n    except RetryError as exc:\n        _handle_get_simple_fail(link, exc)\n    except SSLError as exc:\n        reason = \"There was a problem confirming the ssl certificate: \"\n        reason += str(exc)\n        _handle_get_simple_fail(link, reason, meth=logger.info)\n    except requests.ConnectionError as exc:\n        _handle_get_simple_fail(link, f\"connection error: {exc}\")\n    except requests.Timeout:\n        _handle_get_simple_fail(link, \"timed out\")\n    else:\n        return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing)\n    return None\n\n\nclass CollectedSources(NamedTuple):\n    find_links: Sequence[LinkSource | None]\n    index_urls: Sequence[LinkSource | None]\n\n\nclass LinkCollector:\n    \"\"\"\n    Responsible for collecting Link objects from all configured locations,\n    making network requests as needed.\n\n    The class's main method is its collect_sources() method.\n    \"\"\"\n\n    def __init__(\n        self,\n        session: PipSession,\n        search_scope: SearchScope,\n    ) -> None:\n        self.search_scope = search_scope\n        self.session = session\n\n    @classmethod\n    def create(\n        cls,\n        session: PipSession,\n        options: Values,\n        suppress_no_index: bool = False,\n    ) -> LinkCollector:\n        \"\"\"\n        :param session: The Session to use to make requests.\n        :param suppress_no_index: Whether to ignore the --no-index option\n            when constructing the SearchScope object.\n        \"\"\"\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index and not suppress_no_index:\n            logger.debug(\n                \"Ignoring indexes: %s\",\n                \",\".join(redact_auth_from_url(url) for url in index_urls),\n            )\n            index_urls = []\n\n        # Make sure find_links is a list before passing to create().\n        find_links = options.find_links or []\n\n        search_scope = SearchScope.create(\n            find_links=find_links,\n            index_urls=index_urls,\n            no_index=options.no_index,\n        )\n        link_collector = LinkCollector(\n            session=session,\n            search_scope=search_scope,\n        )\n        return link_collector\n\n    @property\n    def find_links(self) -> list[str]:\n        return self.search_scope.find_links\n\n    def fetch_response(self, location: Link) -> IndexContent | None:\n        \"\"\"\n        Fetch an HTML page containing package links.\n        \"\"\"\n        return _get_index_content(location, session=self.session)\n\n    def collect_sources(\n        self,\n        project_name: str,\n        candidates_from_page: CandidatesFromPage,\n    ) -> CollectedSources:\n        # The OrderedDict calls deduplicate sources by URL.\n        index_url_sources = collections.OrderedDict(\n            build_source(\n                loc,\n                candidates_from_page=candidates_from_page,\n                page_validator=self.session.is_secure_origin,\n                expand_dir=False,\n                cache_link_parsing=False,\n                project_name=project_name,\n            )\n            for loc in self.search_scope.get_index_urls_locations(project_name)\n        ).values()\n        find_links_sources = collections.OrderedDict(\n            build_source(\n                loc,\n                candidates_from_page=candidates_from_page,\n                page_validator=self.session.is_secure_origin,\n                expand_dir=True,\n                cache_link_parsing=True,\n                project_name=project_name,\n            )\n            for loc in self.find_links\n        ).values()\n\n        if logger.isEnabledFor(logging.DEBUG):\n            lines = [\n                f\"* {s.link}\"\n                for s in itertools.chain(find_links_sources, index_url_sources)\n                if s is not None and s.link is not None\n            ]\n            lines = [\n                f\"{len(lines)} location(s) to search \"\n                f\"for versions of {project_name}:\"\n            ] + lines\n            logger.debug(\"\\n\".join(lines))\n\n        return CollectedSources(\n            find_links=list(find_links_sources),\n            index_urls=list(index_url_sources),\n        )\n"
  },
  {
    "path": "src/pip/_internal/index/package_finder.py",
    "content": "\"\"\"Routines related to PyPI, indexes\"\"\"\n\nfrom __future__ import annotations\n\nimport datetime\nimport enum\nimport functools\nimport itertools\nimport logging\nimport re\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom typing import (\n    TYPE_CHECKING,\n    Optional,\n    Union,\n)\n\nfrom pip._vendor.packaging import specifiers\nfrom pip._vendor.packaging.tags import Tag\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import InvalidVersion, Version, _BaseVersion\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import (\n    BestVersionAlreadyInstalled,\n    DistributionNotFound,\n    InstallationError,\n    InvalidWheelFilename,\n    UnsupportedWheel,\n)\nfrom pip._internal.index.collector import LinkCollector, parse_links\nfrom pip._internal.metadata import select_backend\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req import InstallRequirement\nfrom pip._internal.utils._log import getLogger\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import build_netloc\nfrom pip._internal.utils.packaging import check_requires_python\nfrom pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS\n\nif TYPE_CHECKING:\n    from typing_extensions import TypeGuard\n\n__all__ = [\"FormatControl\", \"BestCandidateResult\", \"PackageFinder\"]\n\n\nlogger = getLogger(__name__)\n\nBuildTag = Union[tuple[()], tuple[int, str]]\nCandidateSortingKey = tuple[int, int, int, _BaseVersion, Optional[int], BuildTag]\n\n\ndef _check_link_requires_python(\n    link: Link,\n    version_info: tuple[int, int, int],\n    ignore_requires_python: bool = False,\n) -> bool:\n    \"\"\"\n    Return whether the given Python version is compatible with a link's\n    \"Requires-Python\" value.\n\n    :param version_info: A 3-tuple of ints representing the Python\n        major-minor-micro version to check.\n    :param ignore_requires_python: Whether to ignore the \"Requires-Python\"\n        value if the given Python version isn't compatible.\n    \"\"\"\n    try:\n        is_compatible = check_requires_python(\n            link.requires_python,\n            version_info=version_info,\n        )\n    except specifiers.InvalidSpecifier:\n        logger.debug(\n            \"Ignoring invalid Requires-Python (%r) for link: %s\",\n            link.requires_python,\n            link,\n        )\n    else:\n        if not is_compatible:\n            version = \".\".join(map(str, version_info))\n            if not ignore_requires_python:\n                logger.verbose(\n                    \"Link requires a different Python (%s not in: %r): %s\",\n                    version,\n                    link.requires_python,\n                    link,\n                )\n                return False\n\n            logger.debug(\n                \"Ignoring failed Requires-Python check (%s not in: %r) for link: %s\",\n                version,\n                link.requires_python,\n                link,\n            )\n\n    return True\n\n\nclass LinkType(enum.Enum):\n    candidate = enum.auto()\n    different_project = enum.auto()\n    yanked = enum.auto()\n    format_unsupported = enum.auto()\n    format_invalid = enum.auto()\n    platform_mismatch = enum.auto()\n    requires_python_mismatch = enum.auto()\n    upload_too_late = enum.auto()\n    upload_time_missing = enum.auto()\n\n\nclass LinkEvaluator:\n    \"\"\"\n    Responsible for evaluating links for a particular project.\n    \"\"\"\n\n    _py_version_re = re.compile(r\"-py([123]\\.?[0-9]?)$\")\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    def __init__(\n        self,\n        project_name: str,\n        canonical_name: NormalizedName,\n        formats: frozenset[str],\n        target_python: TargetPython,\n        allow_yanked: bool,\n        ignore_requires_python: bool | None = None,\n        uploaded_prior_to: datetime.datetime | None = None,\n    ) -> None:\n        \"\"\"\n        :param project_name: The user supplied package name.\n        :param canonical_name: The canonical package name.\n        :param formats: The formats allowed for this package. Should be a set\n            with 'binary' or 'source' or both in it.\n        :param target_python: The target Python interpreter to use when\n            evaluating link compatibility. This is used, for example, to\n            check wheel compatibility, as well as when checking the Python\n            version, e.g. the Python version embedded in a link filename\n            (or egg fragment) and against an HTML link's optional PEP 503\n            \"data-requires-python\" attribute.\n        :param allow_yanked: Whether files marked as yanked (in the sense\n            of PEP 592) are permitted to be candidates for install.\n        :param ignore_requires_python: Whether to ignore incompatible\n            PEP 503 \"data-requires-python\" values in HTML links. Defaults\n            to False.\n        :param uploaded_prior_to: If set, only allow links uploaded prior to\n            the given datetime.\n        \"\"\"\n        if ignore_requires_python is None:\n            ignore_requires_python = False\n\n        self._allow_yanked = allow_yanked\n        self._canonical_name = canonical_name\n        self._ignore_requires_python = ignore_requires_python\n        self._formats = formats\n        self._target_python = target_python\n        self._uploaded_prior_to = uploaded_prior_to\n\n        self.project_name = project_name\n\n    def evaluate_link(self, link: Link) -> tuple[LinkType, str]:\n        \"\"\"\n        Determine whether a link is a candidate for installation.\n\n        :return: A tuple (result, detail), where *result* is an enum\n            representing whether the evaluation found a candidate, or the reason\n            why one is not found. If a candidate is found, *detail* will be the\n            candidate's version string; if one is not found, it contains the\n            reason the link fails to qualify.\n        \"\"\"\n        version = None\n        if link.is_yanked and not self._allow_yanked:\n            reason = link.yanked_reason or \"<none given>\"\n            return (LinkType.yanked, f\"yanked for reason: {reason}\")\n\n        if link.egg_fragment:\n            egg_info = link.egg_fragment\n            ext = link.ext\n        else:\n            egg_info, ext = link.splitext()\n            if not ext:\n                return (LinkType.format_unsupported, \"not a file\")\n            if ext not in SUPPORTED_EXTENSIONS:\n                return (\n                    LinkType.format_unsupported,\n                    f\"unsupported archive format: {ext}\",\n                )\n            if \"binary\" not in self._formats and ext == WHEEL_EXTENSION:\n                reason = f\"No binaries permitted for {self.project_name}\"\n                return (LinkType.format_unsupported, reason)\n            if \"macosx10\" in link.path and ext == \".zip\":\n                return (LinkType.format_unsupported, \"macosx10 one\")\n            if ext == WHEEL_EXTENSION:\n                try:\n                    wheel = Wheel(link.filename)\n                except InvalidWheelFilename:\n                    return (\n                        LinkType.format_invalid,\n                        \"invalid wheel filename\",\n                    )\n                if wheel.name != self._canonical_name:\n                    reason = f\"wrong project name (not {self.project_name})\"\n                    return (LinkType.different_project, reason)\n\n                supported_tags = self._target_python.get_unsorted_tags()\n                if not wheel.supported(supported_tags):\n                    # Include the wheel's tags in the reason string to\n                    # simplify troubleshooting compatibility issues.\n                    file_tags = \", \".join(wheel.get_formatted_file_tags())\n                    reason = (\n                        f\"none of the wheel's tags ({file_tags}) are compatible \"\n                        f\"(run pip debug --verbose to show compatible tags)\"\n                    )\n                    return (LinkType.platform_mismatch, reason)\n\n                version = wheel.version\n\n        # Check upload-time filter after verifying the link is a package file.\n        # Skip this check for local files, as --uploaded-prior-to only applies\n        # to packages from indexes.\n        if self._uploaded_prior_to is not None and not link.is_file:\n            if link.upload_time is None:\n                if link.comes_from:\n                    index_info = f\"Index {link.comes_from}\"\n                else:\n                    index_info = \"Index\"\n\n                return (\n                    LinkType.upload_time_missing,\n                    f\"{index_info} does not provide upload-time metadata.\",\n                )\n            elif link.upload_time >= self._uploaded_prior_to:\n                return (\n                    LinkType.upload_too_late,\n                    f\"Upload time {link.upload_time} not \"\n                    f\"prior to {self._uploaded_prior_to}\",\n                )\n\n        # This should be up by the self.ok_binary check, but see issue 2700.\n        if \"source\" not in self._formats and ext != WHEEL_EXTENSION:\n            reason = f\"No sources permitted for {self.project_name}\"\n            return (LinkType.format_unsupported, reason)\n\n        if not version:\n            version = _extract_version_from_fragment(\n                egg_info,\n                self._canonical_name,\n            )\n        if not version:\n            reason = f\"Missing project version for {self.project_name}\"\n            return (LinkType.format_invalid, reason)\n\n        match = self._py_version_re.search(version)\n        if match:\n            version = version[: match.start()]\n            py_version = match.group(1)\n            if py_version != self._target_python.py_version:\n                return (\n                    LinkType.platform_mismatch,\n                    \"Python version is incorrect\",\n                )\n\n        supports_python = _check_link_requires_python(\n            link,\n            version_info=self._target_python.py_version_info,\n            ignore_requires_python=self._ignore_requires_python,\n        )\n        if not supports_python:\n            requires_python = link.requires_python\n            if requires_python:\n\n                def get_version_sort_key(v: str) -> tuple[int, ...]:\n                    return tuple(int(s) for s in v.split(\".\") if s.isdigit())\n\n                requires_python = \",\".join(\n                    sorted(\n                        (str(s) for s in specifiers.SpecifierSet(requires_python)),\n                        key=get_version_sort_key,\n                    )\n                )\n            reason = f\"{version} Requires-Python {requires_python}\"\n            return (LinkType.requires_python_mismatch, reason)\n\n        logger.debug(\"Found link %s, version: %s\", link, version)\n\n        return (LinkType.candidate, version)\n\n\ndef filter_unallowed_hashes(\n    candidates: list[InstallationCandidate],\n    hashes: Hashes | None,\n    project_name: str,\n) -> list[InstallationCandidate]:\n    \"\"\"\n    Filter out candidates whose hashes aren't allowed, and return a new\n    list of candidates.\n\n    If at least one candidate has an allowed hash, then all candidates with\n    either an allowed hash or no hash specified are returned.  Otherwise,\n    the given candidates are returned.\n\n    Including the candidates with no hash specified when there is a match\n    allows a warning to be logged if there is a more preferred candidate\n    with no hash specified.  Returning all candidates in the case of no\n    matches lets pip report the hash of the candidate that would otherwise\n    have been installed (e.g. permitting the user to more easily update\n    their requirements file with the desired hash).\n    \"\"\"\n    if not hashes:\n        logger.debug(\n            \"Given no hashes to check %s links for project %r: \"\n            \"discarding no candidates\",\n            len(candidates),\n            project_name,\n        )\n        # Make sure we're not returning back the given value.\n        return list(candidates)\n\n    matches_or_no_digest = []\n    # Collect the non-matches for logging purposes.\n    non_matches = []\n    match_count = 0\n    for candidate in candidates:\n        link = candidate.link\n        if not link.has_hash:\n            pass\n        elif link.is_hash_allowed(hashes=hashes):\n            match_count += 1\n        else:\n            non_matches.append(candidate)\n            continue\n\n        matches_or_no_digest.append(candidate)\n\n    if match_count:\n        filtered = matches_or_no_digest\n    else:\n        # Make sure we're not returning back the given value.\n        filtered = list(candidates)\n\n    if len(filtered) == len(candidates):\n        discard_message = \"discarding no candidates\"\n    else:\n        discard_message = \"discarding {} non-matches:\\n  {}\".format(\n            len(non_matches),\n            \"\\n  \".join(str(candidate.link) for candidate in non_matches),\n        )\n\n    logger.debug(\n        \"Checked %s links for project %r against %s hashes \"\n        \"(%s matches, %s no digest): %s\",\n        len(candidates),\n        project_name,\n        hashes.digest_count,\n        match_count,\n        len(matches_or_no_digest) - match_count,\n        discard_message,\n    )\n\n    return filtered\n\n\n@dataclass\nclass CandidatePreferences:\n    \"\"\"\n    Encapsulates some of the preferences for filtering and sorting\n    InstallationCandidate objects.\n    \"\"\"\n\n    prefer_binary: bool = False\n    release_control: ReleaseControl | None = None\n\n\n@dataclass(frozen=True)\nclass BestCandidateResult:\n    \"\"\"A collection of candidates, returned by `PackageFinder.find_best_candidate`.\n\n    This class is only intended to be instantiated by CandidateEvaluator's\n    `compute_best_candidate()` method.\n\n    :param all_candidates: A sequence of all available candidates found.\n    :param applicable_candidates: The applicable candidates.\n    :param best_candidate: The most preferred candidate found, or None\n        if no applicable candidates were found.\n    \"\"\"\n\n    all_candidates: list[InstallationCandidate]\n    applicable_candidates: list[InstallationCandidate]\n    best_candidate: InstallationCandidate | None\n\n    def __post_init__(self) -> None:\n        assert set(self.applicable_candidates) <= set(self.all_candidates)\n\n        if self.best_candidate is None:\n            assert not self.applicable_candidates\n        else:\n            assert self.best_candidate in self.applicable_candidates\n\n\nclass CandidateEvaluator:\n    \"\"\"\n    Responsible for filtering and sorting candidates for installation based\n    on what tags are valid.\n    \"\"\"\n\n    @classmethod\n    def create(\n        cls,\n        project_name: str,\n        target_python: TargetPython | None = None,\n        prefer_binary: bool = False,\n        release_control: ReleaseControl | None = None,\n        specifier: specifiers.BaseSpecifier | None = None,\n        hashes: Hashes | None = None,\n    ) -> CandidateEvaluator:\n        \"\"\"Create a CandidateEvaluator object.\n\n        :param target_python: The target Python interpreter to use when\n            checking compatibility. If None (the default), a TargetPython\n            object will be constructed from the running Python.\n        :param specifier: An optional object implementing `filter`\n            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable\n            versions.\n        :param hashes: An optional collection of allowed hashes.\n        \"\"\"\n        if target_python is None:\n            target_python = TargetPython()\n        if specifier is None:\n            specifier = specifiers.SpecifierSet()\n\n        supported_tags = target_python.get_sorted_tags()\n\n        return cls(\n            project_name=project_name,\n            supported_tags=supported_tags,\n            specifier=specifier,\n            prefer_binary=prefer_binary,\n            release_control=release_control,\n            hashes=hashes,\n        )\n\n    def __init__(\n        self,\n        project_name: str,\n        supported_tags: list[Tag],\n        specifier: specifiers.BaseSpecifier,\n        prefer_binary: bool = False,\n        release_control: ReleaseControl | None = None,\n        hashes: Hashes | None = None,\n    ) -> None:\n        \"\"\"\n        :param supported_tags: The PEP 425 tags supported by the target\n            Python in order of preference (most preferred first).\n        \"\"\"\n        self._release_control = release_control\n        self._hashes = hashes\n        self._prefer_binary = prefer_binary\n        self._project_name = project_name\n        self._specifier = specifier\n        self._supported_tags = supported_tags\n        # Since the index of the tag in the _supported_tags list is used\n        # as a priority, precompute a map from tag to index/priority to be\n        # used in wheel.find_most_preferred_tag.\n        self._wheel_tag_preferences = {\n            tag: idx for idx, tag in enumerate(supported_tags)\n        }\n\n    def get_applicable_candidates(\n        self,\n        candidates: list[InstallationCandidate],\n    ) -> list[InstallationCandidate]:\n        \"\"\"\n        Return the applicable candidates from a list of candidates.\n        \"\"\"\n        # Using None infers from the specifier instead.\n        if self._release_control is not None:\n            allow_prereleases = self._release_control.allows_prereleases(\n                canonicalize_name(self._project_name)\n            )\n        else:\n            allow_prereleases = None\n        specifier = self._specifier\n\n        # When using the pkg_resources backend we turn the version object into\n        # a str here because otherwise when we're debundled but setuptools isn't,\n        # Python will see packaging.version.Version and\n        # pkg_resources._vendor.packaging.version.Version as different\n        # types. This way we'll use a str as a common data interchange\n        # format. If we stop using the pkg_resources provided specifier\n        # and start using our own, we can drop the cast to str().\n        if select_backend().NAME == \"pkg_resources\":\n            candidates_and_versions: list[\n                tuple[InstallationCandidate, str | Version]\n            ] = [(c, str(c.version)) for c in candidates]\n        else:\n            candidates_and_versions = [(c, c.version) for c in candidates]\n        versions = set(\n            specifier.filter(\n                (v for _, v in candidates_and_versions),\n                prereleases=allow_prereleases,\n            )\n        )\n\n        applicable_candidates = [c for c, v in candidates_and_versions if v in versions]\n        filtered_applicable_candidates = filter_unallowed_hashes(\n            candidates=applicable_candidates,\n            hashes=self._hashes,\n            project_name=self._project_name,\n        )\n\n        return sorted(filtered_applicable_candidates, key=self._sort_key)\n\n    def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:\n        \"\"\"\n        Function to pass as the `key` argument to a call to sorted() to sort\n        InstallationCandidates by preference.\n\n        Returns a tuple such that tuples sorting as greater using Python's\n        default comparison operator are more preferred.\n\n        The preference is as follows:\n\n        First and foremost, candidates with allowed (matching) hashes are\n        always preferred over candidates without matching hashes. This is\n        because e.g. if the only candidate with an allowed hash is yanked,\n        we still want to use that candidate.\n\n        Second, excepting hash considerations, candidates that have been\n        yanked (in the sense of PEP 592) are always less preferred than\n        candidates that haven't been yanked. Then:\n\n        If not finding wheels, they are sorted by version only.\n        If finding wheels, then the sort order is by version, then:\n          1. existing installs\n          2. wheels ordered via Wheel.support_index_min(self._supported_tags)\n          3. source archives\n        If prefer_binary was set, then all wheels are sorted above sources.\n\n        Note: it was considered to embed this logic into the Link\n              comparison operators, but then different sdist links\n              with the same version, would have to be considered equal\n        \"\"\"\n        valid_tags = self._supported_tags\n        support_num = len(valid_tags)\n        build_tag: BuildTag = ()\n        binary_preference = 0\n        link = candidate.link\n        if link.is_wheel:\n            # can raise InvalidWheelFilename\n            wheel = Wheel(link.filename)\n            try:\n                pri = -(\n                    wheel.find_most_preferred_tag(\n                        valid_tags, self._wheel_tag_preferences\n                    )\n                )\n            except ValueError:\n                raise UnsupportedWheel(\n                    f\"{wheel.filename} is not a supported wheel for this platform. It \"\n                    \"can't be sorted.\"\n                )\n            if self._prefer_binary:\n                binary_preference = 1\n            build_tag = wheel.build_tag\n        else:  # sdist\n            pri = -(support_num)\n        has_allowed_hash = int(link.is_hash_allowed(self._hashes))\n        yank_value = -1 * int(link.is_yanked)  # -1 for yanked.\n        return (\n            has_allowed_hash,\n            yank_value,\n            binary_preference,\n            candidate.version,\n            pri,\n            build_tag,\n        )\n\n    def sort_best_candidate(\n        self,\n        candidates: list[InstallationCandidate],\n    ) -> InstallationCandidate | None:\n        \"\"\"\n        Return the best candidate per the instance's sort order, or None if\n        no candidate is acceptable.\n        \"\"\"\n        if not candidates:\n            return None\n        best_candidate = max(candidates, key=self._sort_key)\n        return best_candidate\n\n    def compute_best_candidate(\n        self,\n        candidates: list[InstallationCandidate],\n    ) -> BestCandidateResult:\n        \"\"\"\n        Compute and return a `BestCandidateResult` instance.\n        \"\"\"\n        applicable_candidates = self.get_applicable_candidates(candidates)\n\n        best_candidate = self.sort_best_candidate(applicable_candidates)\n\n        return BestCandidateResult(\n            candidates,\n            applicable_candidates=applicable_candidates,\n            best_candidate=best_candidate,\n        )\n\n\nclass PackageFinder:\n    \"\"\"This finds packages.\n\n    This is meant to match easy_install's technique for looking for\n    packages, by reading pages and looking for appropriate links.\n    \"\"\"\n\n    def __init__(\n        self,\n        link_collector: LinkCollector,\n        target_python: TargetPython,\n        allow_yanked: bool,\n        format_control: FormatControl | None = None,\n        candidate_prefs: CandidatePreferences | None = None,\n        ignore_requires_python: bool | None = None,\n        uploaded_prior_to: datetime.datetime | None = None,\n    ) -> None:\n        \"\"\"\n        This constructor is primarily meant to be used by the create() class\n        method and from tests.\n\n        :param format_control: A FormatControl object, used to control\n            the selection of source packages / binary packages when consulting\n            the index and links.\n        :param candidate_prefs: Options to use when creating a\n            CandidateEvaluator object.\n        \"\"\"\n        if candidate_prefs is None:\n            candidate_prefs = CandidatePreferences()\n\n        format_control = format_control or FormatControl(set(), set())\n\n        self._allow_yanked = allow_yanked\n        self._candidate_prefs = candidate_prefs\n        self._ignore_requires_python = ignore_requires_python\n        self._link_collector = link_collector\n        self._target_python = target_python\n        self._uploaded_prior_to = uploaded_prior_to\n\n        self.format_control = format_control\n\n        # These are boring links that have already been logged somehow.\n        self._logged_links: set[tuple[Link, LinkType, str]] = set()\n\n        # Cache of the result of finding candidates\n        self._all_candidates: dict[str, list[InstallationCandidate]] = {}\n        self._best_candidates: dict[\n            tuple[str, specifiers.BaseSpecifier | None, Hashes | None],\n            BestCandidateResult,\n        ] = {}\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    @classmethod\n    def create(\n        cls,\n        link_collector: LinkCollector,\n        selection_prefs: SelectionPreferences,\n        target_python: TargetPython | None = None,\n        uploaded_prior_to: datetime.datetime | None = None,\n    ) -> PackageFinder:\n        \"\"\"Create a PackageFinder.\n\n        :param selection_prefs: The candidate selection preferences, as a\n            SelectionPreferences object.\n        :param target_python: The target Python interpreter to use when\n            checking compatibility. If None (the default), a TargetPython\n            object will be constructed from the running Python.\n        :param uploaded_prior_to: If set, only find links uploaded prior\n            to the given datetime.\n        \"\"\"\n        if target_python is None:\n            target_python = TargetPython()\n\n        candidate_prefs = CandidatePreferences(\n            prefer_binary=selection_prefs.prefer_binary,\n            release_control=selection_prefs.release_control,\n        )\n\n        return cls(\n            candidate_prefs=candidate_prefs,\n            link_collector=link_collector,\n            target_python=target_python,\n            allow_yanked=selection_prefs.allow_yanked,\n            format_control=selection_prefs.format_control,\n            ignore_requires_python=selection_prefs.ignore_requires_python,\n            uploaded_prior_to=uploaded_prior_to,\n        )\n\n    @property\n    def target_python(self) -> TargetPython:\n        return self._target_python\n\n    @property\n    def search_scope(self) -> SearchScope:\n        return self._link_collector.search_scope\n\n    @search_scope.setter\n    def search_scope(self, search_scope: SearchScope) -> None:\n        self._link_collector.search_scope = search_scope\n\n    @property\n    def find_links(self) -> list[str]:\n        return self._link_collector.find_links\n\n    @property\n    def index_urls(self) -> list[str]:\n        return self.search_scope.index_urls\n\n    @property\n    def proxy(self) -> str | None:\n        return self._link_collector.session.pip_proxy\n\n    @property\n    def trusted_hosts(self) -> Iterable[str]:\n        for host_port in self._link_collector.session.pip_trusted_origins:\n            yield build_netloc(*host_port)\n\n    @property\n    def custom_cert(self) -> str | None:\n        # session.verify is either a boolean (use default bundle/no SSL\n        # verification) or a string path to a custom CA bundle to use. We only\n        # care about the latter.\n        verify = self._link_collector.session.verify\n        return verify if isinstance(verify, str) else None\n\n    @property\n    def client_cert(self) -> str | None:\n        cert = self._link_collector.session.cert\n        assert not isinstance(cert, tuple), \"pip only supports PEM client certs\"\n        return cert\n\n    @property\n    def release_control(self) -> ReleaseControl | None:\n        return self._candidate_prefs.release_control\n\n    def set_release_control(self, release_control: ReleaseControl) -> None:\n        self._candidate_prefs.release_control = release_control\n\n    @property\n    def prefer_binary(self) -> bool:\n        return self._candidate_prefs.prefer_binary\n\n    def set_prefer_binary(self) -> None:\n        self._candidate_prefs.prefer_binary = True\n\n    @property\n    def uploaded_prior_to(self) -> datetime.datetime | None:\n        return self._uploaded_prior_to\n\n    def requires_python_skipped_reasons(self) -> list[str]:\n        reasons = {\n            detail\n            for _, result, detail in self._logged_links\n            if result == LinkType.requires_python_mismatch\n        }\n        return sorted(reasons)\n\n    def make_link_evaluator(self, project_name: str) -> LinkEvaluator:\n        canonical_name = canonicalize_name(project_name)\n        formats = self.format_control.get_allowed_formats(canonical_name)\n\n        return LinkEvaluator(\n            project_name=project_name,\n            canonical_name=canonical_name,\n            formats=formats,\n            target_python=self._target_python,\n            allow_yanked=self._allow_yanked,\n            ignore_requires_python=self._ignore_requires_python,\n            uploaded_prior_to=self._uploaded_prior_to,\n        )\n\n    def _sort_links(self, links: Iterable[Link]) -> list[Link]:\n        \"\"\"\n        Returns elements of links in order, non-egg links first, egg links\n        second, while eliminating duplicates\n        \"\"\"\n        eggs, no_eggs = [], []\n        seen: set[Link] = set()\n        for link in links:\n            if link not in seen:\n                seen.add(link)\n                if link.egg_fragment:\n                    eggs.append(link)\n                else:\n                    no_eggs.append(link)\n        return no_eggs + eggs\n\n    def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:\n        entry = (link, result, detail)\n        if entry not in self._logged_links:\n            # Put the link at the end so the reason is more visible and because\n            # the link string is usually very long.\n            logger.debug(\"Skipping link: %s: %s\", detail, link)\n            self._logged_links.add(entry)\n\n    def get_install_candidate(\n        self, link_evaluator: LinkEvaluator, link: Link\n    ) -> InstallationCandidate | None:\n        \"\"\"\n        If the link is a candidate for install, convert it to an\n        InstallationCandidate and return it. Otherwise, return None.\n        \"\"\"\n        result, detail = link_evaluator.evaluate_link(link)\n        if result == LinkType.upload_time_missing:\n            # Fail immediately if the index doesn't provide upload-time\n            # when --uploaded-prior-to is specified\n            raise InstallationError(detail)\n        if result != LinkType.candidate:\n            self._log_skipped_link(link, result, detail)\n            return None\n\n        try:\n            return InstallationCandidate(\n                name=link_evaluator.project_name,\n                link=link,\n                version=detail,\n            )\n        except InvalidVersion:\n            return None\n\n    def evaluate_links(\n        self, link_evaluator: LinkEvaluator, links: Iterable[Link]\n    ) -> list[InstallationCandidate]:\n        \"\"\"\n        Convert links that are candidates to InstallationCandidate objects.\n        \"\"\"\n        candidates = []\n        for link in self._sort_links(links):\n            candidate = self.get_install_candidate(link_evaluator, link)\n            if candidate is not None:\n                candidates.append(candidate)\n\n        return candidates\n\n    def process_project_url(\n        self, project_url: Link, link_evaluator: LinkEvaluator\n    ) -> list[InstallationCandidate]:\n        logger.debug(\n            \"Fetching project page and analyzing links: %s\",\n            project_url,\n        )\n        index_response = self._link_collector.fetch_response(project_url)\n        if index_response is None:\n            return []\n\n        page_links = list(parse_links(index_response))\n\n        with indent_log():\n            package_links = self.evaluate_links(\n                link_evaluator,\n                links=page_links,\n            )\n\n        return package_links\n\n    def find_all_candidates(self, project_name: str) -> list[InstallationCandidate]:\n        \"\"\"Find all available InstallationCandidate for project_name\n\n        This checks index_urls and find_links.\n        All versions found are returned as an InstallationCandidate list.\n\n        See LinkEvaluator.evaluate_link() for details on which files\n        are accepted.\n        \"\"\"\n        if project_name in self._all_candidates:\n            return self._all_candidates[project_name]\n\n        link_evaluator = self.make_link_evaluator(project_name)\n\n        collected_sources = self._link_collector.collect_sources(\n            project_name=project_name,\n            candidates_from_page=functools.partial(\n                self.process_project_url,\n                link_evaluator=link_evaluator,\n            ),\n        )\n\n        page_candidates_it = itertools.chain.from_iterable(\n            source.page_candidates()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        page_candidates = list(page_candidates_it)\n\n        file_links_it = itertools.chain.from_iterable(\n            source.file_links()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        file_candidates = self.evaluate_links(\n            link_evaluator,\n            sorted(file_links_it, reverse=True),\n        )\n\n        if logger.isEnabledFor(logging.DEBUG) and file_candidates:\n            paths = []\n            for candidate in file_candidates:\n                assert candidate.link.url  # we need to have a URL\n                try:\n                    paths.append(candidate.link.file_path)\n                except Exception:\n                    paths.append(candidate.link.url)  # it's not a local file\n\n            logger.debug(\"Local files found: %s\", \", \".join(paths))\n\n        # This is an intentional priority ordering\n        self._all_candidates[project_name] = file_candidates + page_candidates\n\n        return self._all_candidates[project_name]\n\n    def make_candidate_evaluator(\n        self,\n        project_name: str,\n        specifier: specifiers.BaseSpecifier | None = None,\n        hashes: Hashes | None = None,\n    ) -> CandidateEvaluator:\n        \"\"\"Create a CandidateEvaluator object to use.\"\"\"\n        candidate_prefs = self._candidate_prefs\n        return CandidateEvaluator.create(\n            project_name=project_name,\n            target_python=self._target_python,\n            prefer_binary=candidate_prefs.prefer_binary,\n            release_control=candidate_prefs.release_control,\n            specifier=specifier,\n            hashes=hashes,\n        )\n\n    def find_best_candidate(\n        self,\n        project_name: str,\n        specifier: specifiers.BaseSpecifier | None = None,\n        hashes: Hashes | None = None,\n    ) -> BestCandidateResult:\n        \"\"\"Find matches for the given project and specifier.\n\n        :param specifier: An optional object implementing `filter`\n            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable\n            versions.\n\n        :return: A `BestCandidateResult` instance.\n        \"\"\"\n        if (project_name, specifier, hashes) in self._best_candidates:\n            return self._best_candidates[project_name, specifier, hashes]\n\n        candidates = self.find_all_candidates(project_name)\n        candidate_evaluator = self.make_candidate_evaluator(\n            project_name=project_name,\n            specifier=specifier,\n            hashes=hashes,\n        )\n        self._best_candidates[project_name, specifier, hashes] = (\n            candidate_evaluator.compute_best_candidate(candidates)\n        )\n\n        return self._best_candidates[project_name, specifier, hashes]\n\n    def find_requirement(\n        self, req: InstallRequirement, upgrade: bool\n    ) -> InstallationCandidate | None:\n        \"\"\"Try to find a Link matching req\n\n        Expects req, an InstallRequirement and upgrade, a boolean\n        Returns a InstallationCandidate if found,\n        Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise\n        \"\"\"\n        name = req.name\n        assert name is not None, \"find_requirement() called with no name\"\n\n        hashes = req.hashes(trust_internet=False)\n        best_candidate_result = self.find_best_candidate(\n            name,\n            specifier=req.specifier,\n            hashes=hashes,\n        )\n        best_candidate = best_candidate_result.best_candidate\n\n        installed_version: _BaseVersion | None = None\n        if req.satisfied_by is not None:\n            installed_version = req.satisfied_by.version\n\n        def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:\n            # This repeated parse_version and str() conversion is needed to\n            # handle different vendoring sources from pip and pkg_resources.\n            # If we stop using the pkg_resources provided specifier and start\n            # using our own, we can drop the cast to str().\n            return (\n                \", \".join(\n                    sorted(\n                        {str(c.version) for c in cand_iter},\n                        key=parse_version,\n                    )\n                )\n                or \"none\"\n            )\n\n        if installed_version is None and best_candidate is None:\n            # Check if only final releases are allowed for this package\n            version_type = \"version\"\n            if self.release_control is not None:\n                allows_pre = self.release_control.allows_prereleases(\n                    canonicalize_name(name)\n                )\n                if allows_pre is False:\n                    version_type = \"final version\"\n\n            logger.critical(\n                \"Could not find a %s that satisfies the requirement %s \"\n                \"(from versions: %s)\",\n                version_type,\n                req,\n                _format_versions(best_candidate_result.all_candidates),\n            )\n\n            raise DistributionNotFound(f\"No matching distribution found for {req}\")\n\n        def _should_install_candidate(\n            candidate: InstallationCandidate | None,\n        ) -> TypeGuard[InstallationCandidate]:\n            if installed_version is None:\n                return True\n            if best_candidate is None:\n                return False\n            return best_candidate.version > installed_version\n\n        if not upgrade and installed_version is not None:\n            if _should_install_candidate(best_candidate):\n                logger.debug(\n                    \"Existing installed version (%s) satisfies requirement \"\n                    \"(most up-to-date version is %s)\",\n                    installed_version,\n                    best_candidate.version,\n                )\n            else:\n                logger.debug(\n                    \"Existing installed version (%s) is most up-to-date and \"\n                    \"satisfies requirement\",\n                    installed_version,\n                )\n            return None\n\n        if _should_install_candidate(best_candidate):\n            logger.debug(\n                \"Using version %s (newest of versions: %s)\",\n                best_candidate.version,\n                _format_versions(best_candidate_result.applicable_candidates),\n            )\n            return best_candidate\n\n        # We have an existing version, and its the best version\n        logger.debug(\n            \"Installed version (%s) is most up-to-date (past versions: %s)\",\n            installed_version,\n            _format_versions(best_candidate_result.applicable_candidates),\n        )\n        raise BestVersionAlreadyInstalled\n\n\ndef _find_name_version_sep(fragment: str, canonical_name: str) -> int:\n    \"\"\"Find the separator's index based on the package's canonical name.\n\n    :param fragment: A <package>+<version> filename \"fragment\" (stem) or\n        egg fragment.\n    :param canonical_name: The package's canonical name.\n\n    This function is needed since the canonicalized name does not necessarily\n    have the same length as the egg info's name part. An example::\n\n    >>> fragment = 'foo__bar-1.0'\n    >>> canonical_name = 'foo-bar'\n    >>> _find_name_version_sep(fragment, canonical_name)\n    8\n    \"\"\"\n    # Project name and version must be separated by one single dash. Find all\n    # occurrences of dashes; if the string in front of it matches the canonical\n    # name, this is the one separating the name and version parts.\n    for i, c in enumerate(fragment):\n        if c != \"-\":\n            continue\n        if canonicalize_name(fragment[:i]) == canonical_name:\n            return i\n    raise ValueError(f\"{fragment} does not match {canonical_name}\")\n\n\ndef _extract_version_from_fragment(fragment: str, canonical_name: str) -> str | None:\n    \"\"\"Parse the version string from a <package>+<version> filename\n    \"fragment\" (stem) or egg fragment.\n\n    :param fragment: The string to parse. E.g. foo-2.1\n    :param canonical_name: The canonicalized name of the package this\n        belongs to.\n    \"\"\"\n    try:\n        version_start = _find_name_version_sep(fragment, canonical_name) + 1\n    except ValueError:\n        return None\n    version = fragment[version_start:]\n    if not version:\n        return None\n    return version\n"
  },
  {
    "path": "src/pip/_internal/index/sources.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport mimetypes\nimport os\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom typing import Callable\n\nfrom pip._vendor.packaging.utils import (\n    InvalidSdistFilename,\n    InvalidWheelFilename,\n    canonicalize_name,\n    parse_sdist_filename,\n    parse_wheel_filename,\n)\n\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.urls import path_to_url, url_to_path\nfrom pip._internal.vcs import is_url\n\nlogger = logging.getLogger(__name__)\n\nFoundCandidates = Iterable[InstallationCandidate]\nFoundLinks = Iterable[Link]\nCandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]]\nPageValidator = Callable[[Link], bool]\n\n\nclass LinkSource:\n    @property\n    def link(self) -> Link | None:\n        \"\"\"Returns the underlying link, if there's one.\"\"\"\n        raise NotImplementedError()\n\n    def page_candidates(self) -> FoundCandidates:\n        \"\"\"Candidates found by parsing an archive listing HTML file.\"\"\"\n        raise NotImplementedError()\n\n    def file_links(self) -> FoundLinks:\n        \"\"\"Links found by specifying archives directly.\"\"\"\n        raise NotImplementedError()\n\n\ndef _is_html_file(file_url: str) -> bool:\n    return mimetypes.guess_type(file_url, strict=False)[0] == \"text/html\"\n\n\nclass _FlatDirectoryToUrls:\n    \"\"\"Scans directory and caches results\"\"\"\n\n    def __init__(self, path: str) -> None:\n        self._path = path\n        self._page_candidates: list[str] = []\n        self._project_name_to_urls: dict[str, list[str]] = defaultdict(list)\n        self._scanned_directory = False\n\n    def _scan_directory(self) -> None:\n        \"\"\"Scans directory once and populates both page_candidates\n        and project_name_to_urls at the same time\n        \"\"\"\n        for entry in os.scandir(self._path):\n            url = path_to_url(entry.path)\n            if _is_html_file(url):\n                self._page_candidates.append(url)\n                continue\n\n            # File must have a valid wheel or sdist name,\n            # otherwise not worth considering as a package\n            try:\n                project_filename = parse_wheel_filename(entry.name)[0]\n            except InvalidWheelFilename:\n                try:\n                    project_filename = parse_sdist_filename(entry.name)[0]\n                except InvalidSdistFilename:\n                    continue\n\n            self._project_name_to_urls[project_filename].append(url)\n        self._scanned_directory = True\n\n    @property\n    def page_candidates(self) -> list[str]:\n        if not self._scanned_directory:\n            self._scan_directory()\n\n        return self._page_candidates\n\n    @property\n    def project_name_to_urls(self) -> dict[str, list[str]]:\n        if not self._scanned_directory:\n            self._scan_directory()\n\n        return self._project_name_to_urls\n\n\nclass _FlatDirectorySource(LinkSource):\n    \"\"\"Link source specified by ``--find-links=<path-to-dir>``.\n\n    This looks the content of the directory, and returns:\n\n    * ``page_candidates``: Links listed on each HTML file in the directory.\n    * ``file_candidates``: Archives in the directory.\n    \"\"\"\n\n    _paths_to_urls: dict[str, _FlatDirectoryToUrls] = {}\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        path: str,\n        project_name: str,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._project_name = canonicalize_name(project_name)\n\n        # Get existing instance of _FlatDirectoryToUrls if it exists\n        if path in self._paths_to_urls:\n            self._path_to_urls = self._paths_to_urls[path]\n        else:\n            self._path_to_urls = _FlatDirectoryToUrls(path=path)\n            self._paths_to_urls[path] = self._path_to_urls\n\n    @property\n    def link(self) -> Link | None:\n        return None\n\n    def page_candidates(self) -> FoundCandidates:\n        for url in self._path_to_urls.page_candidates:\n            yield from self._candidates_from_page(Link(url))\n\n    def file_links(self) -> FoundLinks:\n        for url in self._path_to_urls.project_name_to_urls[self._project_name]:\n            yield Link(url)\n\n\nclass _LocalFileSource(LinkSource):\n    \"\"\"``--find-links=<path-or-url>`` or ``--[extra-]index-url=<path-or-url>``.\n\n    If a URL is supplied, it must be a ``file:`` URL. If a path is supplied to\n    the option, it is converted to a URL first. This returns:\n\n    * ``page_candidates``: Links listed on an HTML file.\n    * ``file_candidates``: The non-HTML file.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._link = link\n\n    @property\n    def link(self) -> Link | None:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        if not _is_html_file(self._link.url):\n            return\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        if _is_html_file(self._link.url):\n            return\n        yield self._link\n\n\nclass _RemoteFileSource(LinkSource):\n    \"\"\"``--find-links=<url>`` or ``--[extra-]index-url=<url>``.\n\n    This returns:\n\n    * ``page_candidates``: Links listed on an HTML file.\n    * ``file_candidates``: The non-HTML file.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        page_validator: PageValidator,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._page_validator = page_validator\n        self._link = link\n\n    @property\n    def link(self) -> Link | None:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        if not self._page_validator(self._link):\n            return\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        yield self._link\n\n\nclass _IndexDirectorySource(LinkSource):\n    \"\"\"``--[extra-]index-url=<path-to-directory>``.\n\n    This is treated like a remote URL; ``candidates_from_page`` contains logic\n    for this by appending ``index.html`` to the link.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._link = link\n\n    @property\n    def link(self) -> Link | None:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        return ()\n\n\ndef build_source(\n    location: str,\n    *,\n    candidates_from_page: CandidatesFromPage,\n    page_validator: PageValidator,\n    expand_dir: bool,\n    cache_link_parsing: bool,\n    project_name: str,\n) -> tuple[str | None, LinkSource | None]:\n    path: str | None = None\n    url: str | None = None\n    if os.path.exists(location):  # Is a local path.\n        url = path_to_url(location)\n        path = location\n    elif location.startswith(\"file:\"):  # A file: URL.\n        url = location\n        path = url_to_path(location)\n    elif is_url(location):\n        url = location\n\n    if url is None:\n        msg = (\n            \"Location '%s' is ignored: \"\n            \"it is either a non-existing path or lacks a specific scheme.\"\n        )\n        logger.warning(msg, location)\n        return (None, None)\n\n    if path is None:\n        source: LinkSource = _RemoteFileSource(\n            candidates_from_page=candidates_from_page,\n            page_validator=page_validator,\n            link=Link(url, cache_link_parsing=cache_link_parsing),\n        )\n        return (url, source)\n\n    if os.path.isdir(path):\n        if expand_dir:\n            source = _FlatDirectorySource(\n                candidates_from_page=candidates_from_page,\n                path=path,\n                project_name=project_name,\n            )\n        else:\n            source = _IndexDirectorySource(\n                candidates_from_page=candidates_from_page,\n                link=Link(url, cache_link_parsing=cache_link_parsing),\n            )\n        return (url, source)\n    elif os.path.isfile(path):\n        source = _LocalFileSource(\n            candidates_from_page=candidates_from_page,\n            link=Link(url, cache_link_parsing=cache_link_parsing),\n        )\n        return (url, source)\n    logger.warning(\n        \"Location '%s' is ignored: it is neither a file nor a directory.\",\n        location,\n    )\n    return (url, None)\n"
  },
  {
    "path": "src/pip/_internal/locations/__init__.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport logging\nimport os\nimport pathlib\nimport sys\nimport sysconfig\n\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom . import _sysconfig\nfrom .base import (\n    USER_CACHE_DIR,\n    get_major_minor_version,\n    get_src_prefix,\n    is_osx_framework,\n    site_packages,\n    user_site,\n)\n\n__all__ = [\n    \"USER_CACHE_DIR\",\n    \"get_bin_prefix\",\n    \"get_bin_user\",\n    \"get_major_minor_version\",\n    \"get_platlib\",\n    \"get_purelib\",\n    \"get_scheme\",\n    \"get_src_prefix\",\n    \"site_packages\",\n    \"user_site\",\n]\n\n\nlogger = logging.getLogger(__name__)\n\n\n_PLATLIBDIR: str = getattr(sys, \"platlibdir\", \"lib\")\n\n_USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10)\n\n\ndef _should_use_sysconfig() -> bool:\n    \"\"\"This function determines the value of _USE_SYSCONFIG.\n\n    By default, pip uses sysconfig on Python 3.10+.\n    But Python distributors can override this decision by setting:\n        sysconfig._PIP_USE_SYSCONFIG = True / False\n    Rationale in https://github.com/pypa/pip/issues/10647\n\n    This is a function for testability, but should be constant during any one\n    run.\n    \"\"\"\n    return bool(getattr(sysconfig, \"_PIP_USE_SYSCONFIG\", _USE_SYSCONFIG_DEFAULT))\n\n\n_USE_SYSCONFIG = _should_use_sysconfig()\n\nif not _USE_SYSCONFIG:\n    # Import distutils lazily to avoid deprecation warnings,\n    # but import it soon enough that it is in memory and available during\n    # a pip reinstall.\n    from . import _distutils\n\n# Be noisy about incompatibilities if this platforms \"should\" be using\n# sysconfig, but is explicitly opting out and using distutils instead.\nif _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG:\n    _MISMATCH_LEVEL = logging.WARNING\nelse:\n    _MISMATCH_LEVEL = logging.DEBUG\n\n\ndef _looks_like_bpo_44860() -> bool:\n    \"\"\"The resolution to bpo-44860 will change this incorrect platlib.\n\n    See <https://bugs.python.org/issue44860>.\n    \"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    try:\n        unix_user_platlib = INSTALL_SCHEMES[\"unix_user\"][\"platlib\"]\n    except KeyError:\n        return False\n    return unix_user_platlib == \"$usersite\"\n\n\ndef _looks_like_red_hat_patched_platlib_purelib(scheme: dict[str, str]) -> bool:\n    platlib = scheme[\"platlib\"]\n    if \"/$platlibdir/\" in platlib:\n        platlib = platlib.replace(\"/$platlibdir/\", f\"/{_PLATLIBDIR}/\")\n    if \"/lib64/\" not in platlib:\n        return False\n    unpatched = platlib.replace(\"/lib64/\", \"/lib/\")\n    return unpatched.replace(\"$platbase/\", \"$base/\") == scheme[\"purelib\"]\n\n\n@functools.cache\ndef _looks_like_red_hat_lib() -> bool:\n    \"\"\"Red Hat patches platlib in unix_prefix and unix_home, but not purelib.\n\n    This is the only way I can see to tell a Red Hat-patched Python.\n    \"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    return all(\n        k in INSTALL_SCHEMES\n        and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])\n        for k in (\"unix_prefix\", \"unix_home\")\n    )\n\n\n@functools.cache\ndef _looks_like_debian_scheme() -> bool:\n    \"\"\"Debian adds two additional schemes.\"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    return \"deb_system\" in INSTALL_SCHEMES and \"unix_local\" in INSTALL_SCHEMES\n\n\n@functools.cache\ndef _looks_like_red_hat_scheme() -> bool:\n    \"\"\"Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.\n\n    Red Hat's ``00251-change-user-install-location.patch`` changes the install\n    command's ``prefix`` and ``exec_prefix`` to append ``\"/local\"``. This is\n    (fortunately?) done quite unconditionally, so we create a default command\n    object without any configuration to detect this.\n    \"\"\"\n    from distutils.command.install import install\n    from distutils.dist import Distribution\n\n    cmd = install(Distribution())\n    cmd.finalize_options()\n    return (\n        cmd.exec_prefix == f\"{os.path.normpath(sys.exec_prefix)}/local\"\n        and cmd.prefix == f\"{os.path.normpath(sys.prefix)}/local\"\n    )\n\n\n@functools.cache\ndef _looks_like_slackware_scheme() -> bool:\n    \"\"\"Slackware patches sysconfig but fails to patch distutils and site.\n\n    Slackware changes sysconfig's user scheme to use ``\"lib64\"`` for the lib\n    path, but does not do the same to the site module.\n    \"\"\"\n    if user_site is None:  # User-site not available.\n        return False\n    try:\n        paths = sysconfig.get_paths(scheme=\"posix_user\", expand=False)\n    except KeyError:  # User-site not available.\n        return False\n    return \"/lib64/\" in paths[\"purelib\"] and \"/lib64/\" not in user_site\n\n\n@functools.cache\ndef _looks_like_msys2_mingw_scheme() -> bool:\n    \"\"\"MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.\n\n    However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is\n    likely going to be included in their 3.10 release, so we ignore the warning.\n    See msys2/MINGW-packages#9319.\n\n    MSYS2 MINGW's patch uses lowercase ``\"lib\"`` instead of the usual uppercase,\n    and is missing the final ``\"site-packages\"``.\n    \"\"\"\n    paths = sysconfig.get_paths(\"nt\", expand=False)\n    return all(\n        \"Lib\" not in p and \"lib\" in p and not p.endswith(\"site-packages\")\n        for p in (paths[key] for key in (\"platlib\", \"purelib\"))\n    )\n\n\n@functools.cache\ndef _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:\n    issue_url = \"https://github.com/pypa/pip/issues/10151\"\n    message = (\n        \"Value for %s does not match. Please report this to <%s>\"\n        \"\\ndistutils: %s\"\n        \"\\nsysconfig: %s\"\n    )\n    logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)\n\n\ndef _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:\n    if old == new:\n        return False\n    _warn_mismatched(old, new, key=key)\n    return True\n\n\n@functools.cache\ndef _log_context(\n    *,\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    prefix: str | None = None,\n) -> None:\n    parts = [\n        \"Additional context:\",\n        \"user = %r\",\n        \"home = %r\",\n        \"root = %r\",\n        \"prefix = %r\",\n    ]\n\n    logger.log(_MISMATCH_LEVEL, \"\\n\".join(parts), user, home, root, prefix)\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    isolated: bool = False,\n    prefix: str | None = None,\n) -> Scheme:\n    new = _sysconfig.get_scheme(\n        dist_name,\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_scheme(\n        dist_name,\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n\n    warning_contexts = []\n    for k in SCHEME_KEYS:\n        old_v = pathlib.Path(getattr(old, k))\n        new_v = pathlib.Path(getattr(new, k))\n\n        if old_v == new_v:\n            continue\n\n        # distutils incorrectly put PyPy packages under ``site-packages/python``\n        # in the ``posix_home`` scheme, but PyPy devs said they expect the\n        # directory name to be ``pypy`` instead. So we treat this as a bug fix\n        # and not warn about it. See bpo-43307 and python/cpython#24628.\n        skip_pypy_special_case = (\n            sys.implementation.name == \"pypy\"\n            and home is not None\n            and k in (\"platlib\", \"purelib\")\n            and old_v.parent == new_v.parent\n            and old_v.name.startswith(\"python\")\n            and new_v.name.startswith(\"pypy\")\n        )\n        if skip_pypy_special_case:\n            continue\n\n        # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in\n        # the ``include`` value, but distutils's ``headers`` does. We'll let\n        # CPython decide whether this is a bug or feature. See bpo-43948.\n        skip_osx_framework_user_special_case = (\n            user\n            and is_osx_framework()\n            and k == \"headers\"\n            and old_v.parent.parent == new_v.parent\n            and old_v.parent.name.startswith(\"python\")\n        )\n        if skip_osx_framework_user_special_case:\n            continue\n\n        # On Red Hat and derived Linux distributions, distutils is patched to\n        # use \"lib64\" instead of \"lib\" for platlib.\n        if k == \"platlib\" and _looks_like_red_hat_lib():\n            continue\n\n        # On Python 3.9+, sysconfig's posix_user scheme sets platlib against\n        # sys.platlibdir, but distutils's unix_user incorrectly continues\n        # using the same $usersite for both platlib and purelib. This creates a\n        # mismatch when sys.platlibdir is not \"lib\".\n        skip_bpo_44860 = (\n            user\n            and k == \"platlib\"\n            and not WINDOWS\n            and _PLATLIBDIR != \"lib\"\n            and _looks_like_bpo_44860()\n        )\n        if skip_bpo_44860:\n            continue\n\n        # Slackware incorrectly patches posix_user to use lib64 instead of lib,\n        # but not usersite to match the location.\n        skip_slackware_user_scheme = (\n            user\n            and k in (\"platlib\", \"purelib\")\n            and not WINDOWS\n            and _looks_like_slackware_scheme()\n        )\n        if skip_slackware_user_scheme:\n            continue\n\n        # Both Debian and Red Hat patch Python to place the system site under\n        # /usr/local instead of /usr. Debian also places lib in dist-packages\n        # instead of site-packages, but the /usr/local check should cover it.\n        skip_linux_system_special_case = (\n            not (user or home or prefix or running_under_virtualenv())\n            and old_v.parts[1:3] == (\"usr\", \"local\")\n            and len(new_v.parts) > 1\n            and new_v.parts[1] == \"usr\"\n            and (len(new_v.parts) < 3 or new_v.parts[2] != \"local\")\n            and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())\n        )\n        if skip_linux_system_special_case:\n            continue\n\n        # MSYS2 MINGW's sysconfig patch does not include the \"site-packages\"\n        # part of the path. This is incorrect and will be fixed in MSYS.\n        skip_msys2_mingw_bug = (\n            WINDOWS and k in (\"platlib\", \"purelib\") and _looks_like_msys2_mingw_scheme()\n        )\n        if skip_msys2_mingw_bug:\n            continue\n\n        # CPython's POSIX install script invokes pip (via ensurepip) against the\n        # interpreter located in the source tree, not the install site. This\n        # triggers special logic in sysconfig that's not present in distutils.\n        # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194\n        skip_cpython_build = (\n            sysconfig.is_python_build(check_home=True)\n            and not WINDOWS\n            and k in (\"headers\", \"include\", \"platinclude\")\n        )\n        if skip_cpython_build:\n            continue\n\n        warning_contexts.append((old_v, new_v, f\"scheme.{k}\"))\n\n    if not warning_contexts:\n        return old\n\n    # Check if this path mismatch is caused by distutils config files. Those\n    # files will no longer work once we switch to sysconfig, so this raises a\n    # deprecation message for them.\n    default_old = _distutils.distutils_scheme(\n        dist_name,\n        user,\n        home,\n        root,\n        isolated,\n        prefix,\n        ignore_config_files=True,\n    )\n    if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):\n        deprecated(\n            reason=(\n                \"Configuring installation scheme with distutils config files \"\n                \"is deprecated and will no longer work in the near future. If you \"\n                \"are using a Homebrew or Linuxbrew Python, please see discussion \"\n                \"at https://github.com/Homebrew/homebrew-core/issues/76621\"\n            ),\n            replacement=None,\n            gone_in=None,\n        )\n        return old\n\n    # Post warnings about this mismatch so user can report them back.\n    for old_v, new_v, key in warning_contexts:\n        _warn_mismatched(old_v, new_v, key=key)\n    _log_context(user=user, home=home, root=root, prefix=prefix)\n\n    return old\n\n\ndef get_bin_prefix() -> str:\n    new = _sysconfig.get_bin_prefix()\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_bin_prefix()\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"bin_prefix\"):\n        _log_context()\n    return old\n\n\ndef get_bin_user() -> str:\n    return _sysconfig.get_scheme(\"\", user=True).scripts\n\n\ndef _looks_like_deb_system_dist_packages(value: str) -> bool:\n    \"\"\"Check if the value is Debian's APT-controlled dist-packages.\n\n    Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the\n    default package path controlled by APT, but does not patch ``sysconfig`` to\n    do the same. This is similar to the bug worked around in ``get_scheme()``,\n    but here the default is ``deb_system`` instead of ``unix_local``. Ultimately\n    we can't do anything about this Debian bug, and this detection allows us to\n    skip the warning when needed.\n    \"\"\"\n    if not _looks_like_debian_scheme():\n        return False\n    if value == \"/usr/lib/python3/dist-packages\":\n        return True\n    return False\n\n\ndef get_purelib() -> str:\n    \"\"\"Return the default pure-Python lib location.\"\"\"\n    new = _sysconfig.get_purelib()\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_purelib()\n    if _looks_like_deb_system_dist_packages(old):\n        return old\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"purelib\"):\n        _log_context()\n    return old\n\n\ndef get_platlib() -> str:\n    \"\"\"Return the default platform-shared lib location.\"\"\"\n    new = _sysconfig.get_platlib()\n    if _USE_SYSCONFIG:\n        return new\n\n    from . import _distutils\n\n    old = _distutils.get_platlib()\n    if _looks_like_deb_system_dist_packages(old):\n        return old\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"platlib\"):\n        _log_context()\n    return old\n"
  },
  {
    "path": "src/pip/_internal/locations/_distutils.py",
    "content": "\"\"\"Locations where we look for configs, install stuff, etc\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\n# If pip's going to use distutils, it should not be using the copy that setuptools\n# might have injected into the environment. This is done by removing the injected\n# shim, if it's injected.\n#\n# See https://github.com/pypa/pip/issues/8761 for the original discussion and\n# rationale for why this is done within pip.\nfrom __future__ import annotations\n\ntry:\n    __import__(\"_distutils_hack\").remove_shim()\nexcept (ImportError, AttributeError):\n    pass\n\nimport logging\nimport os\nimport sys\nfrom distutils.cmd import Command as DistutilsCommand\nfrom distutils.command.install import SCHEME_KEYS\nfrom distutils.command.install import install as distutils_install_command\nfrom distutils.sysconfig import get_python_lib\n\nfrom pip._internal.models.scheme import Scheme\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import get_major_minor_version\n\nlogger = logging.getLogger(__name__)\n\n\ndef distutils_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    isolated: bool = False,\n    prefix: str | None = None,\n    *,\n    ignore_config_files: bool = False,\n) -> dict[str, str]:\n    \"\"\"\n    Return a distutils install scheme\n    \"\"\"\n    from distutils.dist import Distribution\n\n    dist_args: dict[str, str | list[str]] = {\"name\": dist_name}\n    if isolated:\n        dist_args[\"script_args\"] = [\"--no-user-cfg\"]\n\n    d = Distribution(dist_args)\n    if not ignore_config_files:\n        try:\n            d.parse_config_files()\n        except UnicodeDecodeError:\n            paths = d.find_config_files()\n            logger.warning(\n                \"Ignore distutils configs in %s due to encoding errors.\",\n                \", \".join(os.path.basename(p) for p in paths),\n            )\n    obj: DistutilsCommand | None = None\n    obj = d.get_command_obj(\"install\", create=True)\n    assert obj is not None\n    i: distutils_install_command = obj\n    # NOTE: setting user or home has the side-effect of creating the home dir\n    # or user base for installations during finalize_options()\n    # ideally, we'd prefer a scheme class that has no side-effects.\n    assert not (user and prefix), f\"user={user} prefix={prefix}\"\n    assert not (home and prefix), f\"home={home} prefix={prefix}\"\n    i.user = user or i.user\n    if user or home:\n        i.prefix = \"\"\n    i.prefix = prefix or i.prefix\n    i.home = home or i.home\n    i.root = root or i.root\n    i.finalize_options()\n\n    scheme: dict[str, str] = {}\n    for key in SCHEME_KEYS:\n        scheme[key] = getattr(i, \"install_\" + key)\n\n    # install_lib specified in setup.cfg should install *everything*\n    # into there (i.e. it takes precedence over both purelib and\n    # platlib).  Note, i.install_lib is *always* set after\n    # finalize_options(); we only want to override here if the user\n    # has explicitly requested it hence going back to the config\n    if \"install_lib\" in d.get_option_dict(\"install\"):\n        scheme.update({\"purelib\": i.install_lib, \"platlib\": i.install_lib})\n\n    if running_under_virtualenv():\n        if home:\n            prefix = home\n        elif user:\n            prefix = i.install_userbase\n        else:\n            prefix = i.prefix\n        scheme[\"headers\"] = os.path.join(\n            prefix,\n            \"include\",\n            \"site\",\n            f\"python{get_major_minor_version()}\",\n            dist_name,\n        )\n\n        if root is not None:\n            path_no_drive = os.path.splitdrive(os.path.abspath(scheme[\"headers\"]))[1]\n            scheme[\"headers\"] = os.path.join(root, path_no_drive[1:])\n\n    return scheme\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    isolated: bool = False,\n    prefix: str | None = None,\n) -> Scheme:\n    \"\"\"\n    Get the \"scheme\" corresponding to the input parameters. The distutils\n    documentation provides the context for the available schemes:\n    https://docs.python.org/3/install/index.html#alternate-installation\n\n    :param dist_name: the name of the package to retrieve the scheme for, used\n        in the headers scheme path\n    :param user: indicates to use the \"user\" scheme\n    :param home: indicates to use the \"home\" scheme and provides the base\n        directory for the same\n    :param root: root under which other directories are re-based\n    :param isolated: equivalent to --no-user-cfg, i.e. do not consider\n        ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for\n        scheme paths\n    :param prefix: indicates to use the \"prefix\" scheme and provides the\n        base directory for the same\n    \"\"\"\n    scheme = distutils_scheme(dist_name, user, home, root, isolated, prefix)\n    return Scheme(\n        platlib=scheme[\"platlib\"],\n        purelib=scheme[\"purelib\"],\n        headers=scheme[\"headers\"],\n        scripts=scheme[\"scripts\"],\n        data=scheme[\"data\"],\n    )\n\n\ndef get_bin_prefix() -> str:\n    # XXX: In old virtualenv versions, sys.prefix can contain '..' components,\n    # so we need to call normpath to eliminate them.\n    prefix = os.path.normpath(sys.prefix)\n    if WINDOWS:\n        bin_py = os.path.join(prefix, \"Scripts\")\n        # buildout uses 'bin' on Windows too?\n        if not os.path.exists(bin_py):\n            bin_py = os.path.join(prefix, \"bin\")\n        return bin_py\n    # Forcing to use /usr/local/bin for standard macOS framework installs\n    # Also log to ~/Library/Logs/ for use with the Console.app log viewer\n    if sys.platform[:6] == \"darwin\" and prefix[:16] == \"/System/Library/\":\n        return \"/usr/local/bin\"\n    return os.path.join(prefix, \"bin\")\n\n\ndef get_purelib() -> str:\n    return get_python_lib(plat_specific=False)\n\n\ndef get_platlib() -> str:\n    return get_python_lib(plat_specific=True)\n"
  },
  {
    "path": "src/pip/_internal/locations/_sysconfig.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport sys\nimport sysconfig\nfrom typing import Callable\n\nfrom pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import change_root, get_major_minor_version, is_osx_framework\n\nlogger = logging.getLogger(__name__)\n\n\n# Notes on _infer_* functions.\n# Unfortunately ``get_default_scheme()`` didn't exist before 3.10, so there's no\n# way to ask things like \"what is the '_prefix' scheme on this platform\". These\n# functions try to answer that with some heuristics while accounting for ad-hoc\n# platforms not covered by CPython's default sysconfig implementation. If the\n# ad-hoc implementation does not fully implement sysconfig, we'll fall back to\n# a POSIX scheme.\n\n_AVAILABLE_SCHEMES = set(sysconfig.get_scheme_names())\n\n_PREFERRED_SCHEME_API: Callable[[str], str] | None = getattr(\n    sysconfig, \"get_preferred_scheme\", None\n)\n\n\ndef _should_use_osx_framework_prefix() -> bool:\n    \"\"\"Check for Apple's ``osx_framework_library`` scheme.\n\n    Python distributed by Apple's Command Line Tools has this special scheme\n    that's used when:\n\n    * This is a framework build.\n    * We are installing into the system prefix.\n\n    This does not account for ``pip install --prefix`` (also means we're not\n    installing to the system prefix), which should use ``posix_prefix``, but\n    logic here means ``_infer_prefix()`` outputs ``osx_framework_library``. But\n    since ``prefix`` is not available for ``sysconfig.get_default_scheme()``,\n    which is the stdlib replacement for ``_infer_prefix()``, presumably Apple\n    wouldn't be able to magically switch between ``osx_framework_library`` and\n    ``posix_prefix``. ``_infer_prefix()`` returning ``osx_framework_library``\n    means its behavior is consistent whether we use the stdlib implementation\n    or our own, and we deal with this special case in ``get_scheme()`` instead.\n    \"\"\"\n    return (\n        \"osx_framework_library\" in _AVAILABLE_SCHEMES\n        and not running_under_virtualenv()\n        and is_osx_framework()\n    )\n\n\ndef _infer_prefix() -> str:\n    \"\"\"Try to find a prefix scheme for the current platform.\n\n    This tries:\n\n    * A special ``osx_framework_library`` for Python distributed by Apple's\n      Command Line Tools, when not running in a virtual environment.\n    * Implementation + OS, used by PyPy on Windows (``pypy_nt``).\n    * Implementation without OS, used by PyPy on POSIX (``pypy``).\n    * OS + \"prefix\", used by CPython on POSIX (``posix_prefix``).\n    * Just the OS name, used by CPython on Windows (``nt``).\n\n    If none of the above works, fall back to ``posix_prefix``.\n    \"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"prefix\")\n    if _should_use_osx_framework_prefix():\n        return \"osx_framework_library\"\n    implementation_suffixed = f\"{sys.implementation.name}_{os.name}\"\n    if implementation_suffixed in _AVAILABLE_SCHEMES:\n        return implementation_suffixed\n    if sys.implementation.name in _AVAILABLE_SCHEMES:\n        return sys.implementation.name\n    suffixed = f\"{os.name}_prefix\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    if os.name in _AVAILABLE_SCHEMES:  # On Windows, prefx is just called \"nt\".\n        return os.name\n    return \"posix_prefix\"\n\n\ndef _infer_user() -> str:\n    \"\"\"Try to find a user scheme for the current platform.\"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"user\")\n    if is_osx_framework() and not running_under_virtualenv():\n        suffixed = \"osx_framework_user\"\n    else:\n        suffixed = f\"{os.name}_user\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    if \"posix_user\" not in _AVAILABLE_SCHEMES:  # User scheme unavailable.\n        raise UserInstallationInvalid()\n    return \"posix_user\"\n\n\ndef _infer_home() -> str:\n    \"\"\"Try to find a home for the current platform.\"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"home\")\n    suffixed = f\"{os.name}_home\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    return \"posix_home\"\n\n\n# Update these keys if the user sets a custom home.\n_HOME_KEYS = [\n    \"installed_base\",\n    \"base\",\n    \"installed_platbase\",\n    \"platbase\",\n    \"prefix\",\n    \"exec_prefix\",\n]\nif sysconfig.get_config_var(\"userbase\") is not None:\n    _HOME_KEYS.append(\"userbase\")\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: str | None = None,\n    root: str | None = None,\n    isolated: bool = False,\n    prefix: str | None = None,\n) -> Scheme:\n    \"\"\"\n    Get the \"scheme\" corresponding to the input parameters.\n\n    :param dist_name: the name of the package to retrieve the scheme for, used\n        in the headers scheme path\n    :param user: indicates to use the \"user\" scheme\n    :param home: indicates to use the \"home\" scheme\n    :param root: root under which other directories are re-based\n    :param isolated: ignored, but kept for distutils compatibility (where\n        this controls whether the user-site pydistutils.cfg is honored)\n    :param prefix: indicates to use the \"prefix\" scheme and provides the\n        base directory for the same\n    \"\"\"\n    if user and prefix:\n        raise InvalidSchemeCombination(\"--user\", \"--prefix\")\n    if home and prefix:\n        raise InvalidSchemeCombination(\"--home\", \"--prefix\")\n\n    if home is not None:\n        scheme_name = _infer_home()\n    elif user:\n        scheme_name = _infer_user()\n    else:\n        scheme_name = _infer_prefix()\n\n    # Special case: When installing into a custom prefix, use posix_prefix\n    # instead of osx_framework_library. See _should_use_osx_framework_prefix()\n    # docstring for details.\n    if prefix is not None and scheme_name == \"osx_framework_library\":\n        scheme_name = \"posix_prefix\"\n\n    if home is not None:\n        variables = {k: home for k in _HOME_KEYS}\n    elif prefix is not None:\n        variables = {k: prefix for k in _HOME_KEYS}\n    else:\n        variables = {}\n\n    paths = sysconfig.get_paths(scheme=scheme_name, vars=variables)\n\n    # Logic here is very arbitrary, we're doing it for compatibility, don't ask.\n    # 1. Pip historically uses a special header path in virtual environments.\n    # 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We\n    #    only do the same when not running in a virtual environment because\n    #    pip's historical header path logic (see point 1) did not do this.\n    if running_under_virtualenv():\n        if user:\n            base = variables.get(\"userbase\", sys.prefix)\n        else:\n            base = variables.get(\"base\", sys.prefix)\n        python_xy = f\"python{get_major_minor_version()}\"\n        paths[\"include\"] = os.path.join(base, \"include\", \"site\", python_xy)\n    elif not dist_name:\n        dist_name = \"UNKNOWN\"\n\n    scheme = Scheme(\n        platlib=paths[\"platlib\"],\n        purelib=paths[\"purelib\"],\n        headers=os.path.join(paths[\"include\"], dist_name),\n        scripts=paths[\"scripts\"],\n        data=paths[\"data\"],\n    )\n    if root is not None:\n        converted_keys = {}\n        for key in SCHEME_KEYS:\n            converted_keys[key] = change_root(root, getattr(scheme, key))\n        scheme = Scheme(**converted_keys)\n    return scheme\n\n\ndef get_bin_prefix() -> str:\n    # Forcing to use /usr/local/bin for standard macOS framework installs.\n    if sys.platform[:6] == \"darwin\" and sys.prefix[:16] == \"/System/Library/\":\n        return \"/usr/local/bin\"\n    return sysconfig.get_paths()[\"scripts\"]\n\n\ndef get_purelib() -> str:\n    return sysconfig.get_paths()[\"purelib\"]\n\n\ndef get_platlib() -> str:\n    return sysconfig.get_paths()[\"platlib\"]\n"
  },
  {
    "path": "src/pip/_internal/locations/base.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport os\nimport site\nimport sys\nimport sysconfig\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils import appdirs\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n# Application Directories\nUSER_CACHE_DIR = appdirs.user_cache_dir(\"pip\")\n\n# FIXME doesn't account for venv linked to global site-packages\nsite_packages: str = sysconfig.get_path(\"purelib\")\n\n\ndef get_major_minor_version() -> str:\n    \"\"\"\n    Return the major-minor version of the current Python as a string, e.g.\n    \"3.7\" or \"3.10\".\n    \"\"\"\n    return \"{}.{}\".format(*sys.version_info)\n\n\ndef change_root(new_root: str, pathname: str) -> str:\n    \"\"\"Return 'pathname' with 'new_root' prepended.\n\n    If 'pathname' is relative, this is equivalent to os.path.join(new_root, pathname).\n    Otherwise, it requires making 'pathname' relative and then joining the\n    two, which is tricky on DOS/Windows and Mac OS.\n\n    This is borrowed from Python's standard library's distutils module.\n    \"\"\"\n    if os.name == \"posix\":\n        if not os.path.isabs(pathname):\n            return os.path.join(new_root, pathname)\n        else:\n            return os.path.join(new_root, pathname[1:])\n\n    elif os.name == \"nt\":\n        (drive, path) = os.path.splitdrive(pathname)\n        if path[0] == \"\\\\\":\n            path = path[1:]\n        return os.path.join(new_root, path)\n\n    else:\n        raise InstallationError(\n            f\"Unknown platform: {os.name}\\n\"\n            \"Can not change root path prefix on unknown platform.\"\n        )\n\n\ndef get_src_prefix() -> str:\n    if running_under_virtualenv():\n        src_prefix = os.path.join(sys.prefix, \"src\")\n    else:\n        # FIXME: keep src in cwd for now (it is not a temporary folder)\n        try:\n            src_prefix = os.path.join(os.getcwd(), \"src\")\n        except OSError:\n            # In case the current working directory has been renamed or deleted\n            sys.exit(\"The folder you are executing pip from can no longer be found.\")\n\n    # under macOS + virtualenv sys.prefix is not properly resolved\n    # it is something like /path/to/python/bin/..\n    return os.path.abspath(src_prefix)\n\n\ntry:\n    # Use getusersitepackages if this is present, as it ensures that the\n    # value is initialised properly.\n    user_site: str | None = site.getusersitepackages()\nexcept AttributeError:\n    user_site = site.USER_SITE\n\n\n@functools.cache\ndef is_osx_framework() -> bool:\n    return bool(sysconfig.get_config_var(\"PYTHONFRAMEWORK\"))\n"
  },
  {
    "path": "src/pip/_internal/main.py",
    "content": "from __future__ import annotations\n\n\ndef main(args: list[str] | None = None) -> int:\n    \"\"\"This is preserved for old console scripts that may still be referencing\n    it.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "src/pip/_internal/metadata/__init__.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport functools\nimport os\nimport sys\nfrom typing import TYPE_CHECKING, Literal, Protocol, cast\n\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.misc import strtobool\n\nfrom .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel\n\nif TYPE_CHECKING:\n    from pip._vendor.packaging.utils import NormalizedName\n\n__all__ = [\n    \"BaseDistribution\",\n    \"BaseEnvironment\",\n    \"FilesystemWheel\",\n    \"MemoryWheel\",\n    \"Wheel\",\n    \"get_default_environment\",\n    \"get_environment\",\n    \"get_wheel_distribution\",\n    \"select_backend\",\n]\n\n\ndef _should_use_importlib_metadata() -> bool:\n    \"\"\"Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.\n\n    By default, pip uses ``importlib.metadata`` on Python 3.11+, and\n    ``pkg_resources`` otherwise. Up to Python 3.13, This can be\n    overridden by a couple of ways:\n\n    * If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it\n      dictates whether ``importlib.metadata`` is used, for Python <3.14.\n    * On Python 3.11, 3.12 and 3.13, Python distributors can patch\n      ``importlib.metadata`` to add a global constant\n      ``_PIP_USE_IMPORTLIB_METADATA = False``. This makes pip use\n      ``pkg_resources`` (unless the user set the aforementioned environment\n      variable to *True*).\n\n    On Python 3.14+, the ``pkg_resources`` backend cannot be used.\n    \"\"\"\n    if sys.version_info >= (3, 14):\n        # On Python >=3.14 we only support importlib.metadata.\n        return True\n    with contextlib.suppress(KeyError, ValueError):\n        # On Python <3.14, if the environment variable is set, we obey what it says.\n        return bool(strtobool(os.environ[\"_PIP_USE_IMPORTLIB_METADATA\"]))\n    if sys.version_info < (3, 11):\n        # On Python <3.11, we always use pkg_resources, unless the environment\n        # variable was set.\n        return False\n    # On Python 3.11, 3.12 and 3.13, we check if the global constant is set.\n    import importlib.metadata\n\n    return bool(getattr(importlib.metadata, \"_PIP_USE_IMPORTLIB_METADATA\", True))\n\n\ndef _emit_pkg_resources_deprecation_if_needed() -> None:\n    if sys.version_info < (3, 11):\n        # All pip versions supporting Python<=3.11 will support pkg_resources,\n        # and pkg_resources is the default for these, so let's not bother users.\n        return\n\n    import importlib.metadata\n\n    if hasattr(importlib.metadata, \"_PIP_USE_IMPORTLIB_METADATA\"):\n        # The Python distributor has set the global constant, so we don't\n        # warn, since it is not a user decision.\n        return\n\n    # The user has decided to use pkg_resources, so we warn.\n    deprecated(\n        reason=\"Using the pkg_resources metadata backend is deprecated.\",\n        replacement=(\n            \"to use the default importlib.metadata backend, \"\n            \"by unsetting the _PIP_USE_IMPORTLIB_METADATA environment variable\"\n        ),\n        gone_in=\"26.3\",\n        issue=13317,\n    )\n\n\nclass Backend(Protocol):\n    NAME: Literal[\"importlib\", \"pkg_resources\"]\n    Distribution: type[BaseDistribution]\n    Environment: type[BaseEnvironment]\n\n\n@functools.cache\ndef select_backend() -> Backend:\n    if _should_use_importlib_metadata():\n        from . import importlib\n\n        return cast(Backend, importlib)\n\n    _emit_pkg_resources_deprecation_if_needed()\n\n    from . import pkg_resources\n\n    return cast(Backend, pkg_resources)\n\n\ndef get_default_environment() -> BaseEnvironment:\n    \"\"\"Get the default representation for the current environment.\n\n    This returns an Environment instance from the chosen backend. The default\n    Environment instance should be built from ``sys.path`` and may use caching\n    to share instance state across calls.\n    \"\"\"\n    return select_backend().Environment.default()\n\n\ndef get_environment(paths: list[str] | None) -> BaseEnvironment:\n    \"\"\"Get a representation of the environment specified by ``paths``.\n\n    This returns an Environment instance from the chosen backend based on the\n    given import paths. The backend must build a fresh instance representing\n    the state of installed distributions when this function is called.\n    \"\"\"\n    return select_backend().Environment.from_paths(paths)\n\n\ndef get_directory_distribution(directory: str) -> BaseDistribution:\n    \"\"\"Get the distribution metadata representation in the specified directory.\n\n    This returns a Distribution instance from the chosen backend based on\n    the given on-disk ``.dist-info`` directory.\n    \"\"\"\n    return select_backend().Distribution.from_directory(directory)\n\n\ndef get_wheel_distribution(\n    wheel: Wheel, canonical_name: NormalizedName\n) -> BaseDistribution:\n    \"\"\"Get the representation of the specified wheel's distribution metadata.\n\n    This returns a Distribution instance from the chosen backend based on\n    the given wheel's ``.dist-info`` directory.\n\n    :param canonical_name: Normalized project name of the given wheel.\n    \"\"\"\n    return select_backend().Distribution.from_wheel(wheel, canonical_name)\n\n\ndef get_metadata_distribution(\n    metadata_contents: bytes,\n    filename: str,\n    canonical_name: str,\n) -> BaseDistribution:\n    \"\"\"Get the dist representation of the specified METADATA file contents.\n\n    This returns a Distribution instance from the chosen backend sourced from the data\n    in `metadata_contents`.\n\n    :param metadata_contents: Contents of a METADATA file within a dist, or one served\n                              via PEP 658.\n    :param filename: Filename for the dist this metadata represents.\n    :param canonical_name: Normalized project name of the given dist.\n    \"\"\"\n    return select_backend().Distribution.from_metadata_file_contents(\n        metadata_contents,\n        filename,\n        canonical_name,\n    )\n"
  },
  {
    "path": "src/pip/_internal/metadata/_json.py",
    "content": "# Extracted from https://github.com/pfmoore/pkg_metadata\nfrom __future__ import annotations\n\nfrom email.header import Header, decode_header, make_header\nfrom email.message import Message\nfrom typing import Any, cast\n\nMETADATA_FIELDS = [\n    # Name, Multiple-Use\n    (\"Metadata-Version\", False),\n    (\"Name\", False),\n    (\"Version\", False),\n    (\"Dynamic\", True),\n    (\"Platform\", True),\n    (\"Supported-Platform\", True),\n    (\"Summary\", False),\n    (\"Description\", False),\n    (\"Description-Content-Type\", False),\n    (\"Keywords\", False),\n    (\"Home-page\", False),\n    (\"Download-URL\", False),\n    (\"Author\", False),\n    (\"Author-email\", False),\n    (\"Maintainer\", False),\n    (\"Maintainer-email\", False),\n    (\"License\", False),\n    (\"License-Expression\", False),\n    (\"License-File\", True),\n    (\"Classifier\", True),\n    (\"Requires-Dist\", True),\n    (\"Requires-Python\", False),\n    (\"Requires-External\", True),\n    (\"Project-URL\", True),\n    (\"Provides-Extra\", True),\n    (\"Provides-Dist\", True),\n    (\"Obsoletes-Dist\", True),\n]\n\n\ndef json_name(field: str) -> str:\n    return field.lower().replace(\"-\", \"_\")\n\n\ndef msg_to_json(msg: Message) -> dict[str, Any]:\n    \"\"\"Convert a Message object into a JSON-compatible dictionary.\"\"\"\n\n    def sanitise_header(h: Header | str) -> str:\n        if isinstance(h, Header):\n            chunks = []\n            for bytes, encoding in decode_header(h):\n                if encoding == \"unknown-8bit\":\n                    try:\n                        # See if UTF-8 works\n                        bytes.decode(\"utf-8\")\n                        encoding = \"utf-8\"\n                    except UnicodeDecodeError:\n                        # If not, latin1 at least won't fail\n                        encoding = \"latin1\"\n                chunks.append((bytes, encoding))\n            return str(make_header(chunks))\n        return str(h)\n\n    result = {}\n    for field, multi in METADATA_FIELDS:\n        if field not in msg:\n            continue\n        key = json_name(field)\n        if multi:\n            value: str | list[str] = [\n                sanitise_header(v) for v in msg.get_all(field)  # type: ignore\n            ]\n        else:\n            value = sanitise_header(msg.get(field))  # type: ignore\n            if key == \"keywords\":\n                # Accept both comma-separated and space-separated\n                # forms, for better compatibility with old data.\n                if \",\" in value:\n                    value = [v.strip() for v in value.split(\",\")]\n                else:\n                    value = value.split()\n        result[key] = value\n\n    payload = cast(str, msg.get_payload())\n    if payload:\n        result[\"description\"] = payload\n\n    return result\n"
  },
  {
    "path": "src/pip/_internal/metadata/base.py",
    "content": "from __future__ import annotations\n\nimport csv\nimport email.message\nimport functools\nimport json\nimport logging\nimport pathlib\nimport re\nimport zipfile\nfrom collections.abc import Collection, Container, Iterable, Iterator\nfrom typing import (\n    IO,\n    Any,\n    NamedTuple,\n    Protocol,\n    Union,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.exceptions import NoneMetadataError\nfrom pip._internal.locations import site_packages, user_site\nfrom pip._internal.models.direct_url import (\n    DIRECT_URL_METADATA_NAME,\n    DirectUrl,\n    DirectUrlValidationError,\n)\nfrom pip._internal.utils.compat import stdlib_pkgs  # TODO: Move definition here.\nfrom pip._internal.utils.egg_link import egg_link_path_from_sys_path\nfrom pip._internal.utils.misc import is_local, normalize_path\nfrom pip._internal.utils.urls import url_to_path\n\nfrom ._json import msg_to_json\n\nInfoPath = Union[str, pathlib.PurePath]\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseEntryPoint(Protocol):\n    @property\n    def name(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def value(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def group(self) -> str:\n        raise NotImplementedError()\n\n\ndef _convert_installed_files_path(\n    entry: tuple[str, ...],\n    info: tuple[str, ...],\n) -> str:\n    \"\"\"Convert a legacy installed-files.txt path into modern RECORD path.\n\n    The legacy format stores paths relative to the info directory, while the\n    modern format stores paths relative to the package root, e.g. the\n    site-packages directory.\n\n    :param entry: Path parts of the installed-files.txt entry.\n    :param info: Path parts of the egg-info directory relative to package root.\n    :returns: The converted entry.\n\n    For best compatibility with symlinks, this does not use ``abspath()`` or\n    ``Path.resolve()``, but tries to work with path parts:\n\n    1. While ``entry`` starts with ``..``, remove the equal amounts of parts\n       from ``info``; if ``info`` is empty, start appending ``..`` instead.\n    2. Join the two directly.\n    \"\"\"\n    while entry and entry[0] == \"..\":\n        if not info or info[-1] == \"..\":\n            info += (\"..\",)\n        else:\n            info = info[:-1]\n        entry = entry[1:]\n    return str(pathlib.Path(*info, *entry))\n\n\nclass RequiresEntry(NamedTuple):\n    requirement: str\n    extra: str\n    marker: str\n\n\nclass BaseDistribution(Protocol):\n    @classmethod\n    def from_directory(cls, directory: str) -> BaseDistribution:\n        \"\"\"Load the distribution from a metadata directory.\n\n        :param directory: Path to a metadata directory, e.g. ``.dist-info``.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> BaseDistribution:\n        \"\"\"Load the distribution from the contents of a METADATA file.\n\n        This is used to implement PEP 658 by generating a \"shallow\" dist object that can\n        be used for resolution without downloading or building the actual dist yet.\n\n        :param metadata_contents: The contents of a METADATA file.\n        :param filename: File name for the dist with this metadata.\n        :param project_name: Name of the project this dist represents.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:\n        \"\"\"Load the distribution from a given wheel.\n\n        :param wheel: A concrete wheel definition.\n        :param name: File name of the wheel.\n\n        :raises InvalidWheel: Whenever loading of the wheel causes a\n            :py:exc:`zipfile.BadZipFile` exception to be thrown.\n        :raises UnsupportedWheel: If the wheel is a valid zip, but malformed\n            internally.\n        \"\"\"\n        raise NotImplementedError()\n\n    def __repr__(self) -> str:\n        return f\"{self.raw_name} {self.raw_version} ({self.location})\"\n\n    def __str__(self) -> str:\n        return f\"{self.raw_name} {self.raw_version}\"\n\n    @property\n    def location(self) -> str | None:\n        \"\"\"Where the distribution is loaded from.\n\n        A string value is not necessarily a filesystem path, since distributions\n        can be loaded from other sources, e.g. arbitrary zip archives. ``None``\n        means the distribution is created in-memory.\n\n        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If\n        this is a symbolic link, we want to preserve the relative path between\n        it and files in the distribution.\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def editable_project_location(self) -> str | None:\n        \"\"\"The project location for editable distributions.\n\n        This is the directory where pyproject.toml or setup.py is located.\n        None if the distribution is not installed in editable mode.\n        \"\"\"\n        # TODO: this property is relatively costly to compute, memoize it ?\n        direct_url = self.direct_url\n        if direct_url:\n            if direct_url.is_local_editable():\n                return url_to_path(direct_url.url)\n        else:\n            # Search for an .egg-link file by walking sys.path, as it was\n            # done before by dist_is_editable().\n            egg_link_path = egg_link_path_from_sys_path(self.raw_name)\n            if egg_link_path:\n                # TODO: get project location from second line of egg_link file\n                #       (https://github.com/pypa/pip/issues/10243)\n                return self.location\n        return None\n\n    @property\n    def installed_location(self) -> str | None:\n        \"\"\"The distribution's \"installed\" location.\n\n        This should generally be a ``site-packages`` directory. This is\n        usually ``dist.location``, except for legacy develop-installed packages,\n        where ``dist.location`` is the source code location, and this is where\n        the ``.egg-link`` file is.\n\n        The returned location is normalized (in particular, with symlinks removed).\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def info_location(self) -> str | None:\n        \"\"\"Location of the .[egg|dist]-info directory or file.\n\n        Similarly to ``location``, a string value is not necessarily a\n        filesystem path. ``None`` means the distribution is created in-memory.\n\n        For a modern .dist-info installation on disk, this should be something\n        like ``{location}/{raw_name}-{version}.dist-info``.\n\n        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If\n        this is a symbolic link, we want to preserve the relative path between\n        it and other files in the distribution.\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def installed_by_distutils(self) -> bool:\n        \"\"\"Whether this distribution is installed with legacy distutils format.\n\n        A distribution installed with \"raw\" distutils not patched by setuptools\n        uses one single file at ``info_location`` to store metadata. We need to\n        treat this specially on uninstallation.\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        return pathlib.Path(info_location).is_file()\n\n    @property\n    def installed_as_egg(self) -> bool:\n        \"\"\"Whether this distribution is installed as an egg.\n\n        This usually indicates the distribution was installed by (older versions\n        of) easy_install.\n        \"\"\"\n        location = self.location\n        if not location:\n            return False\n        # XXX if the distribution is a zipped egg, location has a trailing /\n        # so we resort to pathlib.Path to check the suffix in a reliable way.\n        return pathlib.Path(location).suffix == \".egg\"\n\n    @property\n    def installed_with_setuptools_egg_info(self) -> bool:\n        \"\"\"Whether this distribution is installed with the ``.egg-info`` format.\n\n        This usually indicates the distribution was installed with setuptools\n        with an old pip version or with ``single-version-externally-managed``.\n\n        Note that this ensure the metadata store is a directory. distutils can\n        also installs an ``.egg-info``, but as a file, not a directory. This\n        property is *False* for that case. Also see ``installed_by_distutils``.\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        if not info_location.endswith(\".egg-info\"):\n            return False\n        return pathlib.Path(info_location).is_dir()\n\n    @property\n    def installed_with_dist_info(self) -> bool:\n        \"\"\"Whether this distribution is installed with the \"modern format\".\n\n        This indicates a \"modern\" installation, e.g. storing metadata in the\n        ``.dist-info`` directory. This applies to installations made by\n        setuptools (but through pip, not directly), or anything using the\n        standardized build backend interface (PEP 517).\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        if not info_location.endswith(\".dist-info\"):\n            return False\n        return pathlib.Path(info_location).is_dir()\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        raise NotImplementedError()\n\n    @property\n    def version(self) -> Version:\n        raise NotImplementedError()\n\n    @property\n    def raw_version(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def setuptools_filename(self) -> str:\n        \"\"\"Convert a project name to its setuptools-compatible filename.\n\n        This is a copy of ``pkg_resources.to_filename()`` for compatibility.\n        \"\"\"\n        return self.raw_name.replace(\"-\", \"_\")\n\n    @property\n    def direct_url(self) -> DirectUrl | None:\n        \"\"\"Obtain a DirectUrl from this distribution.\n\n        Returns None if the distribution has no `direct_url.json` metadata,\n        or if `direct_url.json` is invalid.\n        \"\"\"\n        try:\n            content = self.read_text(DIRECT_URL_METADATA_NAME)\n        except FileNotFoundError:\n            return None\n        try:\n            return DirectUrl.from_json(content)\n        except (\n            UnicodeDecodeError,\n            json.JSONDecodeError,\n            DirectUrlValidationError,\n        ) as e:\n            logger.warning(\n                \"Error parsing %s for %s: %s\",\n                DIRECT_URL_METADATA_NAME,\n                self.canonical_name,\n                e,\n            )\n            return None\n\n    @property\n    def installer(self) -> str:\n        try:\n            installer_text = self.read_text(\"INSTALLER\")\n        except (OSError, ValueError, NoneMetadataError):\n            return \"\"  # Fail silently if the installer file cannot be read.\n        for line in installer_text.splitlines():\n            cleaned_line = line.strip()\n            if cleaned_line:\n                return cleaned_line\n        return \"\"\n\n    @property\n    def requested(self) -> bool:\n        return self.is_file(\"REQUESTED\")\n\n    @property\n    def editable(self) -> bool:\n        return bool(self.editable_project_location)\n\n    @property\n    def local(self) -> bool:\n        \"\"\"If distribution is installed in the current virtual environment.\n\n        Always True if we're not in a virtualenv.\n        \"\"\"\n        if self.installed_location is None:\n            return False\n        return is_local(self.installed_location)\n\n    @property\n    def in_usersite(self) -> bool:\n        if self.installed_location is None or user_site is None:\n            return False\n        return self.installed_location.startswith(normalize_path(user_site))\n\n    @property\n    def in_site_packages(self) -> bool:\n        if self.installed_location is None or site_packages is None:\n            return False\n        return self.installed_location.startswith(normalize_path(site_packages))\n\n    def is_file(self, path: InfoPath) -> bool:\n        \"\"\"Check whether an entry in the info directory is a file.\"\"\"\n        raise NotImplementedError()\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        \"\"\"Find distutils 'scripts' entries metadata.\n\n        If 'scripts' is supplied in ``setup.py``, distutils records those in the\n        installed distribution's ``scripts`` directory, a file for each script.\n        \"\"\"\n        raise NotImplementedError()\n\n    def read_text(self, path: InfoPath) -> str:\n        \"\"\"Read a file in the info directory.\n\n        :raise FileNotFoundError: If ``path`` does not exist in the directory.\n        :raise NoneMetadataError: If ``path`` exists in the info directory, but\n            cannot be read.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        raise NotImplementedError()\n\n    def _metadata_impl(self) -> email.message.Message:\n        raise NotImplementedError()\n\n    @functools.cached_property\n    def metadata(self) -> email.message.Message:\n        \"\"\"Metadata of distribution parsed from e.g. METADATA or PKG-INFO.\n\n        This should return an empty message if the metadata file is unavailable.\n\n        :raises NoneMetadataError: If the metadata file is available, but does\n            not contain valid metadata.\n        \"\"\"\n        metadata = self._metadata_impl()\n        self._add_egg_info_requires(metadata)\n        return metadata\n\n    @property\n    def metadata_dict(self) -> dict[str, Any]:\n        \"\"\"PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.\n\n        This should return an empty dict if the metadata file is unavailable.\n\n        :raises NoneMetadataError: If the metadata file is available, but does\n            not contain valid metadata.\n        \"\"\"\n        return msg_to_json(self.metadata)\n\n    @property\n    def metadata_version(self) -> str | None:\n        \"\"\"Value of \"Metadata-Version:\" in distribution metadata, if available.\"\"\"\n        return self.metadata.get(\"Metadata-Version\")\n\n    @property\n    def raw_name(self) -> str:\n        \"\"\"Value of \"Name:\" in distribution metadata.\"\"\"\n        # The metadata should NEVER be missing the Name: key, but if it somehow\n        # does, fall back to the known canonical name.\n        return self.metadata.get(\"Name\", self.canonical_name)\n\n    @property\n    def requires_python(self) -> SpecifierSet:\n        \"\"\"Value of \"Requires-Python:\" in distribution metadata.\n\n        If the key does not exist or contains an invalid value, an empty\n        SpecifierSet should be returned.\n        \"\"\"\n        value = self.metadata.get(\"Requires-Python\")\n        if value is None:\n            return SpecifierSet()\n        try:\n            # Convert to str to satisfy the type checker; this can be a Header object.\n            spec = SpecifierSet(str(value))\n        except InvalidSpecifier as e:\n            message = \"Package %r has an invalid Requires-Python: %s\"\n            logger.warning(message, self.raw_name, e)\n            return SpecifierSet()\n        return spec\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        \"\"\"Dependencies of this distribution.\n\n        For modern .dist-info distributions, this is the collection of\n        \"Requires-Dist:\" entries in distribution metadata.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_raw_dependencies(self) -> Iterable[str]:\n        \"\"\"Raw Requires-Dist metadata.\"\"\"\n        return self.metadata.get_all(\"Requires-Dist\", [])\n\n    def iter_provided_extras(self) -> Iterable[NormalizedName]:\n        \"\"\"Extras provided by this distribution.\n\n        For modern .dist-info distributions, this is the collection of\n        \"Provides-Extra:\" entries in distribution metadata.\n\n        The return value of this function is expected to be normalised names,\n        per PEP 685, with the returned value being handled appropriately by\n        `iter_dependencies`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _iter_declared_entries_from_record(self) -> Iterator[str] | None:\n        try:\n            text = self.read_text(\"RECORD\")\n        except FileNotFoundError:\n            return None\n        # This extra Path-str cast normalizes entries.\n        return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))\n\n    def _iter_declared_entries_from_legacy(self) -> Iterator[str] | None:\n        try:\n            text = self.read_text(\"installed-files.txt\")\n        except FileNotFoundError:\n            return None\n        paths = (p for p in text.splitlines(keepends=False) if p)\n        root = self.location\n        info = self.info_location\n        if root is None or info is None:\n            return paths\n        try:\n            info_rel = pathlib.Path(info).relative_to(root)\n        except ValueError:  # info is not relative to root.\n            return paths\n        if not info_rel.parts:  # info *is* root.\n            return paths\n        return (\n            _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)\n            for p in paths\n        )\n\n    def iter_declared_entries(self) -> Iterator[str] | None:\n        \"\"\"Iterate through file entries declared in this distribution.\n\n        For modern .dist-info distributions, this is the files listed in the\n        ``RECORD`` metadata file. For legacy setuptools distributions, this\n        comes from ``installed-files.txt``, with entries normalized to be\n        compatible with the format used by ``RECORD``.\n\n        :return: An iterator for listed entries, or None if the distribution\n            contains neither ``RECORD`` nor ``installed-files.txt``.\n        \"\"\"\n        return (\n            self._iter_declared_entries_from_record()\n            or self._iter_declared_entries_from_legacy()\n        )\n\n    def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:\n        \"\"\"Parse a ``requires.txt`` in an egg-info directory.\n\n        This is an INI-ish format where an egg-info stores dependencies. A\n        section name describes extra other environment markers, while each entry\n        is an arbitrary string (not a key-value pair) representing a dependency\n        as a requirement string (no markers).\n\n        There is a construct in ``importlib.metadata`` called ``Sectioned`` that\n        does mostly the same, but the format is currently considered private.\n        \"\"\"\n        try:\n            content = self.read_text(\"requires.txt\")\n        except FileNotFoundError:\n            return\n        extra = marker = \"\"  # Section-less entries don't have markers.\n        for line in content.splitlines():\n            line = line.strip()\n            if not line or line.startswith(\"#\"):  # Comment; ignored.\n                continue\n            if line.startswith(\"[\") and line.endswith(\"]\"):  # A section header.\n                extra, _, marker = line.strip(\"[]\").partition(\":\")\n                continue\n            yield RequiresEntry(requirement=line, extra=extra, marker=marker)\n\n    def _iter_egg_info_extras(self) -> Iterable[str]:\n        \"\"\"Get extras from the egg-info directory.\"\"\"\n        known_extras = {\"\"}\n        for entry in self._iter_requires_txt_entries():\n            extra = canonicalize_name(entry.extra)\n            if extra in known_extras:\n                continue\n            known_extras.add(extra)\n            yield extra\n\n    def _iter_egg_info_dependencies(self) -> Iterable[str]:\n        \"\"\"Get distribution dependencies from the egg-info directory.\n\n        To ease parsing, this converts a legacy dependency entry into a PEP 508\n        requirement string. Like ``_iter_requires_txt_entries()``, there is code\n        in ``importlib.metadata`` that does mostly the same, but not do exactly\n        what we need.\n\n        Namely, ``importlib.metadata`` does not normalize the extra name before\n        putting it into the requirement string, which causes marker comparison\n        to fail because the dist-info format do normalize. This is consistent in\n        all currently available PEP 517 backends, although not standardized.\n        \"\"\"\n        for entry in self._iter_requires_txt_entries():\n            extra = canonicalize_name(entry.extra)\n            if extra and entry.marker:\n                marker = f'({entry.marker}) and extra == \"{extra}\"'\n            elif extra:\n                marker = f'extra == \"{extra}\"'\n            elif entry.marker:\n                marker = entry.marker\n            else:\n                marker = \"\"\n            if marker:\n                yield f\"{entry.requirement} ; {marker}\"\n            else:\n                yield entry.requirement\n\n    def _add_egg_info_requires(self, metadata: email.message.Message) -> None:\n        \"\"\"Add egg-info requires.txt information to the metadata.\"\"\"\n        if not metadata.get_all(\"Requires-Dist\"):\n            for dep in self._iter_egg_info_dependencies():\n                metadata[\"Requires-Dist\"] = dep\n        if not metadata.get_all(\"Provides-Extra\"):\n            for extra in self._iter_egg_info_extras():\n                metadata[\"Provides-Extra\"] = extra\n\n\nclass BaseEnvironment:\n    \"\"\"An environment containing distributions to introspect.\"\"\"\n\n    @classmethod\n    def default(cls) -> BaseEnvironment:\n        raise NotImplementedError()\n\n    @classmethod\n    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:\n        raise NotImplementedError()\n\n    def get_distribution(self, name: str) -> BaseDistribution | None:\n        \"\"\"Given a requirement name, return the installed distributions.\n\n        The name may not be normalized. The implementation must canonicalize\n        it for lookup.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _iter_distributions(self) -> Iterator[BaseDistribution]:\n        \"\"\"Iterate through installed distributions.\n\n        This function should be implemented by subclass, but never called\n        directly. Use the public ``iter_distribution()`` instead, which\n        implements additional logic to make sure the distributions are valid.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_all_distributions(self) -> Iterator[BaseDistribution]:\n        \"\"\"Iterate through all installed distributions without any filtering.\"\"\"\n        for dist in self._iter_distributions():\n            # Make sure the distribution actually comes from a valid Python\n            # packaging distribution. Pip's AdjacentTempDirectory leaves folders\n            # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The\n            # valid project name pattern is taken from PEP 508.\n            project_name_valid = re.match(\n                r\"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$\",\n                dist.canonical_name,\n                flags=re.IGNORECASE,\n            )\n            if not project_name_valid:\n                logger.warning(\n                    \"Ignoring invalid distribution %s (%s)\",\n                    dist.canonical_name,\n                    dist.location,\n                )\n                continue\n            yield dist\n\n    def iter_installed_distributions(\n        self,\n        local_only: bool = True,\n        skip: Container[str] = stdlib_pkgs,\n        include_editables: bool = True,\n        editables_only: bool = False,\n        user_only: bool = False,\n    ) -> Iterator[BaseDistribution]:\n        \"\"\"Return a list of installed distributions.\n\n        This is based on ``iter_all_distributions()`` with additional filtering\n        options. Note that ``iter_installed_distributions()`` without arguments\n        is *not* equal to ``iter_all_distributions()``, since some of the\n        configurations exclude packages by default.\n\n        :param local_only: If True (default), only return installations\n        local to the current virtualenv, if in a virtualenv.\n        :param skip: An iterable of canonicalized project names to ignore;\n            defaults to ``stdlib_pkgs``.\n        :param include_editables: If False, don't report editables.\n        :param editables_only: If True, only report editables.\n        :param user_only: If True, only report installations in the user\n        site directory.\n        \"\"\"\n        it = self.iter_all_distributions()\n        if local_only:\n            it = (d for d in it if d.local)\n        if not include_editables:\n            it = (d for d in it if not d.editable)\n        if editables_only:\n            it = (d for d in it if d.editable)\n        if user_only:\n            it = (d for d in it if d.in_usersite)\n        return (d for d in it if d.canonical_name not in skip)\n\n\nclass Wheel(Protocol):\n    location: str\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        raise NotImplementedError()\n\n\nclass FilesystemWheel(Wheel):\n    def __init__(self, location: str) -> None:\n        self.location = location\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        return zipfile.ZipFile(self.location, allowZip64=True)\n\n\nclass MemoryWheel(Wheel):\n    def __init__(self, location: str, stream: IO[bytes]) -> None:\n        self.location = location\n        self.stream = stream\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        return zipfile.ZipFile(self.stream, allowZip64=True)\n"
  },
  {
    "path": "src/pip/_internal/metadata/importlib/__init__.py",
    "content": "from ._dists import Distribution\nfrom ._envs import Environment\n\n__all__ = [\"NAME\", \"Distribution\", \"Environment\"]\n\nNAME = \"importlib\"\n"
  },
  {
    "path": "src/pip/_internal/metadata/importlib/_compat.py",
    "content": "from __future__ import annotations\n\nimport importlib.metadata\nimport os\nfrom typing import Any, Protocol, cast\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\n\nclass BadMetadata(ValueError):\n    def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:\n        self.dist = dist\n        self.reason = reason\n\n    def __str__(self) -> str:\n        return f\"Bad metadata in {self.dist} ({self.reason})\"\n\n\nclass BasePath(Protocol):\n    \"\"\"A protocol that various path objects conform.\n\n    This exists because importlib.metadata uses both ``pathlib.Path`` and\n    ``zipfile.Path``, and we need a common base for type hints (Union does not\n    work well since ``zipfile.Path`` is too new for our linter setup).\n\n    This does not mean to be exhaustive, but only contains things that present\n    in both classes *that we need*.\n    \"\"\"\n\n    @property\n    def name(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def parent(self) -> BasePath:\n        raise NotImplementedError()\n\n\ndef get_info_location(d: importlib.metadata.Distribution) -> BasePath | None:\n    \"\"\"Find the path to the distribution's metadata directory.\n\n    HACK: This relies on importlib.metadata's private ``_path`` attribute. Not\n    all distributions exist on disk, so importlib.metadata is correct to not\n    expose the attribute as public. But pip's code base is old and not as clean,\n    so we do this to avoid having to rewrite too many things. Hopefully we can\n    eliminate this some day.\n    \"\"\"\n    return getattr(d, \"_path\", None)\n\n\ndef parse_name_and_version_from_info_directory(\n    dist: importlib.metadata.Distribution,\n) -> tuple[str | None, str | None]:\n    \"\"\"Get a name and version from the metadata directory name.\n\n    This is much faster than reading distribution metadata.\n    \"\"\"\n    info_location = get_info_location(dist)\n    if info_location is None:\n        return None, None\n\n    stem, suffix = os.path.splitext(info_location.name)\n    if suffix == \".dist-info\":\n        name, sep, version = stem.partition(\"-\")\n        if sep:\n            return name, version\n\n    if suffix == \".egg-info\":\n        name = stem.split(\"-\", 1)[0]\n        return name, None\n\n    return None, None\n\n\ndef get_dist_canonical_name(dist: importlib.metadata.Distribution) -> NormalizedName:\n    \"\"\"Get the distribution's normalized name.\n\n    The ``name`` attribute is only available in Python 3.10 or later. We are\n    targeting exactly that, but Mypy does not know this.\n    \"\"\"\n    if name := parse_name_and_version_from_info_directory(dist)[0]:\n        return canonicalize_name(name)\n\n    name = cast(Any, dist).name\n    if not isinstance(name, str):\n        raise BadMetadata(dist, reason=\"invalid metadata entry 'name'\")\n    return canonicalize_name(name)\n"
  },
  {
    "path": "src/pip/_internal/metadata/importlib/_dists.py",
    "content": "from __future__ import annotations\n\nimport email.message\nimport importlib.metadata\nimport pathlib\nimport zipfile\nfrom collections.abc import Collection, Iterable, Iterator, Mapping, Sequence\nfrom os import PathLike\nfrom typing import (\n    cast,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import InvalidWheel, UnsupportedWheel\nfrom pip._internal.metadata.base import (\n    BaseDistribution,\n    BaseEntryPoint,\n    InfoPath,\n    Wheel,\n)\nfrom pip._internal.utils.misc import normalize_path\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file\n\nfrom ._compat import (\n    BadMetadata,\n    BasePath,\n    get_dist_canonical_name,\n    parse_name_and_version_from_info_directory,\n)\n\n\nclass WheelDistribution(importlib.metadata.Distribution):\n    \"\"\"An ``importlib.metadata.Distribution`` read from a wheel.\n\n    Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``,\n    its implementation is too \"lazy\" for pip's needs (we can't keep the ZipFile\n    handle open for the entire lifetime of the distribution object).\n\n    This implementation eagerly reads the entire metadata directory into the\n    memory instead, and operates from that.\n    \"\"\"\n\n    def __init__(\n        self,\n        files: Mapping[pathlib.PurePosixPath, bytes],\n        info_location: pathlib.PurePosixPath,\n    ) -> None:\n        self._files = files\n        self.info_location = info_location\n\n    @classmethod\n    def from_zipfile(\n        cls,\n        zf: zipfile.ZipFile,\n        name: str,\n        location: str,\n    ) -> WheelDistribution:\n        info_dir, _ = parse_wheel(zf, name)\n        paths = (\n            (name, pathlib.PurePosixPath(name.split(\"/\", 1)[-1]))\n            for name in zf.namelist()\n            if name.startswith(f\"{info_dir}/\")\n        )\n        files = {\n            relpath: read_wheel_metadata_file(zf, fullpath)\n            for fullpath, relpath in paths\n        }\n        info_location = pathlib.PurePosixPath(location, info_dir)\n        return cls(files, info_location)\n\n    def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:\n        # Only allow iterating through the metadata directory.\n        if pathlib.PurePosixPath(str(path)) in self._files:\n            return iter(self._files)\n        raise FileNotFoundError(path)\n\n    def read_text(self, filename: str) -> str | None:\n        try:\n            data = self._files[pathlib.PurePosixPath(filename)]\n        except KeyError:\n            return None\n        try:\n            text = data.decode(\"utf-8\")\n        except UnicodeDecodeError as e:\n            wheel = self.info_location.parent\n            error = f\"Error decoding metadata for {wheel}: {e} in {filename} file\"\n            raise UnsupportedWheel(error)\n        return text\n\n    def locate_file(self, path: str | PathLike[str]) -> pathlib.Path:\n        # This method doesn't make sense for our in-memory wheel, but the API\n        # requires us to define it.\n        raise NotImplementedError\n\n\nclass Distribution(BaseDistribution):\n    def __init__(\n        self,\n        dist: importlib.metadata.Distribution,\n        info_location: BasePath | None,\n        installed_location: BasePath | None,\n    ) -> None:\n        self._dist = dist\n        self._info_location = info_location\n        self._installed_location = installed_location\n\n    @classmethod\n    def from_directory(cls, directory: str) -> BaseDistribution:\n        info_location = pathlib.Path(directory)\n        dist = importlib.metadata.Distribution.at(info_location)\n        return cls(dist, info_location, info_location.parent)\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> BaseDistribution:\n        # Generate temp dir to contain the metadata file, and write the file contents.\n        temp_dir = pathlib.Path(\n            TempDirectory(kind=\"metadata\", globally_managed=True).path\n        )\n        metadata_path = temp_dir / \"METADATA\"\n        metadata_path.write_bytes(metadata_contents)\n        # Construct dist pointing to the newly created directory.\n        dist = importlib.metadata.Distribution.at(metadata_path.parent)\n        return cls(dist, metadata_path.parent, None)\n\n    @classmethod\n    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:\n        try:\n            with wheel.as_zipfile() as zf:\n                dist = WheelDistribution.from_zipfile(zf, name, wheel.location)\n        except zipfile.BadZipFile as e:\n            raise InvalidWheel(wheel.location, name) from e\n        return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location))\n\n    @property\n    def location(self) -> str | None:\n        if self._info_location is None:\n            return None\n        return str(self._info_location.parent)\n\n    @property\n    def info_location(self) -> str | None:\n        if self._info_location is None:\n            return None\n        return str(self._info_location)\n\n    @property\n    def installed_location(self) -> str | None:\n        if self._installed_location is None:\n            return None\n        return normalize_path(str(self._installed_location))\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        return get_dist_canonical_name(self._dist)\n\n    @property\n    def version(self) -> Version:\n        try:\n            version = (\n                parse_name_and_version_from_info_directory(self._dist)[1]\n                or self._dist.version\n            )\n            return parse_version(version)\n        except TypeError:\n            raise BadMetadata(self._dist, reason=\"invalid metadata entry `version`\")\n\n    @property\n    def raw_version(self) -> str:\n        return self._dist.version\n\n    def is_file(self, path: InfoPath) -> bool:\n        return self._dist.read_text(str(path)) is not None\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        # A distutils installation is always \"flat\" (not in e.g. egg form), so\n        # if this distribution's info location is NOT a pathlib.Path (but e.g.\n        # zipfile.Path), it can never contain any distutils scripts.\n        if not isinstance(self._info_location, pathlib.Path):\n            return\n        for child in self._info_location.joinpath(\"scripts\").iterdir():\n            yield child.name\n\n    def read_text(self, path: InfoPath) -> str:\n        content = self._dist.read_text(str(path))\n        if content is None:\n            raise FileNotFoundError(path)\n        return content\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        # importlib.metadata's EntryPoint structure satisfies BaseEntryPoint.\n        return self._dist.entry_points\n\n    def _metadata_impl(self) -> email.message.Message:\n        # From Python 3.10+, importlib.metadata declares PackageMetadata as the\n        # return type. This protocol is unfortunately a disaster now and misses\n        # a ton of fields that we need, including get() and get_payload(). We\n        # rely on the implementation that the object is actually a Message now,\n        # until upstream can improve the protocol. (python/cpython#94952)\n        metadata = self._dist.metadata\n        # From Python 3.15+, importlib.metadata may return None when no\n        # metadata file (METADATA or PKG-INFO) exists in the distribution\n        # directory. (python/cpython#132947)\n        if metadata is None:\n            return email.message.Message()\n        return cast(email.message.Message, metadata)\n\n    def iter_provided_extras(self) -> Iterable[NormalizedName]:\n        return [\n            canonicalize_name(extra)\n            for extra in self.metadata.get_all(\"Provides-Extra\", [])\n        ]\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        contexts: Sequence[dict[str, str]] = [{\"extra\": e} for e in extras]\n        for req_string in self.metadata.get_all(\"Requires-Dist\", []):\n            # strip() because email.message.Message.get_all() may return a leading \\n\n            # in case a long header was wrapped.\n            req = get_requirement(req_string.strip())\n            if not req.marker:\n                yield req\n            elif not extras and req.marker.evaluate({\"extra\": \"\"}):\n                yield req\n            elif any(req.marker.evaluate(context) for context in contexts):\n                yield req\n"
  },
  {
    "path": "src/pip/_internal/metadata/importlib/_envs.py",
    "content": "from __future__ import annotations\n\nimport importlib.metadata\nimport logging\nimport os\nimport pathlib\nimport sys\nimport zipfile\nfrom collections.abc import Iterator, Sequence\nfrom typing import Optional\n\nfrom pip._vendor.packaging.utils import (\n    InvalidWheelFilename,\n    NormalizedName,\n    canonicalize_name,\n    parse_wheel_filename,\n)\n\nfrom pip._internal.metadata.base import BaseDistribution, BaseEnvironment\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\n\nfrom ._compat import BadMetadata, BasePath, get_dist_canonical_name, get_info_location\nfrom ._dists import Distribution\n\nlogger = logging.getLogger(__name__)\n\n\ndef _looks_like_wheel(location: str) -> bool:\n    if not location.endswith(WHEEL_EXTENSION):\n        return False\n    if not os.path.isfile(location):\n        return False\n    try:\n        parse_wheel_filename(os.path.basename(location))\n    except InvalidWheelFilename:\n        return False\n    return zipfile.is_zipfile(location)\n\n\nclass _DistributionFinder:\n    \"\"\"Finder to locate distributions.\n\n    The main purpose of this class is to memoize found distributions' names, so\n    only one distribution is returned for each package name. At lot of pip code\n    assumes this (because it is setuptools's behavior), and not doing the same\n    can potentially cause a distribution in lower precedence path to override a\n    higher precedence one if the caller is not careful.\n\n    Eventually we probably want to make it possible to see lower precedence\n    installations as well. It's useful feature, after all.\n    \"\"\"\n\n    FoundResult = tuple[importlib.metadata.Distribution, Optional[BasePath]]\n\n    def __init__(self) -> None:\n        self._found_names: set[NormalizedName] = set()\n\n    def _find_impl(self, location: str) -> Iterator[FoundResult]:\n        \"\"\"Find distributions in a location.\"\"\"\n        # Skip looking inside a wheel. Since a package inside a wheel is not\n        # always valid (due to .data directories etc.), its .dist-info entry\n        # should not be considered an installed distribution.\n        if _looks_like_wheel(location):\n            return\n        # To know exactly where we find a distribution, we have to feed in the\n        # paths one by one, instead of dumping the list to importlib.metadata.\n        for dist in importlib.metadata.distributions(path=[location]):\n            info_location = get_info_location(dist)\n            try:\n                name = get_dist_canonical_name(dist)\n            except BadMetadata as e:\n                logger.warning(\"Skipping %s due to %s\", info_location, e.reason)\n                continue\n            if name in self._found_names:\n                continue\n            self._found_names.add(name)\n            yield dist, info_location\n\n    def find(self, location: str) -> Iterator[BaseDistribution]:\n        \"\"\"Find distributions in a location.\n\n        The path can be either a directory, or a ZIP archive.\n        \"\"\"\n        for dist, info_location in self._find_impl(location):\n            if info_location is None:\n                installed_location: BasePath | None = None\n            else:\n                installed_location = info_location.parent\n            yield Distribution(dist, info_location, installed_location)\n\n    def find_legacy_editables(self, location: str) -> Iterator[BaseDistribution]:\n        \"\"\"Read location in egg-link files and return distributions in there.\n\n        The path should be a directory; otherwise this returns nothing. This\n        follows how setuptools does this for compatibility. The first non-empty\n        line in the egg-link is read as a path (resolved against the egg-link's\n        containing directory if relative). Distributions found at that linked\n        location are returned.\n        \"\"\"\n        path = pathlib.Path(location)\n        if not path.is_dir():\n            return\n        for child in path.iterdir():\n            if child.suffix != \".egg-link\":\n                continue\n            with child.open() as f:\n                lines = (line.strip() for line in f)\n                target_rel = next((line for line in lines if line), \"\")\n            if not target_rel:\n                continue\n            target_location = str(path.joinpath(target_rel))\n            for dist, info_location in self._find_impl(target_location):\n                yield Distribution(dist, info_location, path)\n\n\nclass Environment(BaseEnvironment):\n    def __init__(self, paths: Sequence[str]) -> None:\n        self._paths = paths\n\n    @classmethod\n    def default(cls) -> BaseEnvironment:\n        return cls(sys.path)\n\n    @classmethod\n    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:\n        if paths is None:\n            return cls(sys.path)\n        return cls(paths)\n\n    def _iter_distributions(self) -> Iterator[BaseDistribution]:\n        finder = _DistributionFinder()\n        for location in self._paths:\n            yield from finder.find(location)\n            yield from finder.find_legacy_editables(location)\n\n    def get_distribution(self, name: str) -> BaseDistribution | None:\n        canonical_name = canonicalize_name(name)\n        matches = (\n            distribution\n            for distribution in self.iter_all_distributions()\n            if distribution.canonical_name == canonical_name\n        )\n        return next(matches, None)\n"
  },
  {
    "path": "src/pip/_internal/metadata/pkg_resources.py",
    "content": "from __future__ import annotations\n\nimport email.message\nimport email.parser\nimport logging\nimport os\nimport zipfile\nfrom collections.abc import Collection, Iterable, Iterator, Mapping\nfrom typing import (\n    NamedTuple,\n)\n\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel\nfrom pip._internal.utils.egg_link import egg_link_path_from_location\nfrom pip._internal.utils.misc import display_path, normalize_path\nfrom pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file\n\nfrom .base import (\n    BaseDistribution,\n    BaseEntryPoint,\n    BaseEnvironment,\n    InfoPath,\n    Wheel,\n)\n\n__all__ = [\"NAME\", \"Distribution\", \"Environment\"]\n\nlogger = logging.getLogger(__name__)\n\nNAME = \"pkg_resources\"\n\n\nclass EntryPoint(NamedTuple):\n    name: str\n    value: str\n    group: str\n\n\nclass InMemoryMetadata:\n    \"\"\"IMetadataProvider that reads metadata files from a dictionary.\n\n    This also maps metadata decoding exceptions to our internal exception type.\n    \"\"\"\n\n    def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:\n        self._metadata = metadata\n        self._wheel_name = wheel_name\n\n    def has_metadata(self, name: str) -> bool:\n        return name in self._metadata\n\n    def get_metadata(self, name: str) -> str:\n        try:\n            return self._metadata[name].decode()\n        except UnicodeDecodeError as e:\n            # Augment the default error with the origin of the file.\n            raise UnsupportedWheel(\n                f\"Error decoding metadata for {self._wheel_name}: {e} in {name} file\"\n            )\n\n    def get_metadata_lines(self, name: str) -> Iterable[str]:\n        return pkg_resources.yield_lines(self.get_metadata(name))\n\n    def metadata_isdir(self, name: str) -> bool:\n        return False\n\n    def metadata_listdir(self, name: str) -> list[str]:\n        return []\n\n    def run_script(self, script_name: str, namespace: str) -> None:\n        pass\n\n\nclass Distribution(BaseDistribution):\n    def __init__(self, dist: pkg_resources.Distribution) -> None:\n        self._dist = dist\n        # This is populated lazily, to avoid loading metadata for all possible\n        # distributions eagerly.\n        self.__extra_mapping: Mapping[NormalizedName, str] | None = None\n\n    @property\n    def _extra_mapping(self) -> Mapping[NormalizedName, str]:\n        if self.__extra_mapping is None:\n            self.__extra_mapping = {\n                canonicalize_name(extra): extra for extra in self._dist.extras\n            }\n\n        return self.__extra_mapping\n\n    @classmethod\n    def from_directory(cls, directory: str) -> BaseDistribution:\n        dist_dir = directory.rstrip(os.sep)\n\n        # Build a PathMetadata object, from path to metadata. :wink:\n        base_dir, dist_dir_name = os.path.split(dist_dir)\n        metadata = pkg_resources.PathMetadata(base_dir, dist_dir)\n\n        # Determine the correct Distribution object type.\n        if dist_dir.endswith(\".egg-info\"):\n            dist_cls = pkg_resources.Distribution\n            dist_name = os.path.splitext(dist_dir_name)[0]\n        else:\n            assert dist_dir.endswith(\".dist-info\")\n            dist_cls = pkg_resources.DistInfoDistribution\n            dist_name = os.path.splitext(dist_dir_name)[0].split(\"-\")[0]\n\n        dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)\n        return cls(dist)\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> BaseDistribution:\n        metadata_dict = {\n            \"METADATA\": metadata_contents,\n        }\n        dist = pkg_resources.DistInfoDistribution(\n            location=filename,\n            metadata=InMemoryMetadata(metadata_dict, filename),\n            project_name=project_name,\n        )\n        return cls(dist)\n\n    @classmethod\n    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:\n        try:\n            with wheel.as_zipfile() as zf:\n                info_dir, _ = parse_wheel(zf, name)\n                metadata_dict = {\n                    path.split(\"/\", 1)[-1]: read_wheel_metadata_file(zf, path)\n                    for path in zf.namelist()\n                    if path.startswith(f\"{info_dir}/\")\n                }\n        except zipfile.BadZipFile as e:\n            raise InvalidWheel(wheel.location, name) from e\n        except UnsupportedWheel as e:\n            raise UnsupportedWheel(f\"{name} has an invalid wheel, {e}\")\n        dist = pkg_resources.DistInfoDistribution(\n            location=wheel.location,\n            metadata=InMemoryMetadata(metadata_dict, wheel.location),\n            project_name=name,\n        )\n        return cls(dist)\n\n    @property\n    def location(self) -> str | None:\n        return self._dist.location\n\n    @property\n    def installed_location(self) -> str | None:\n        egg_link = egg_link_path_from_location(self.raw_name)\n        if egg_link:\n            location = egg_link\n        elif self.location:\n            location = self.location\n        else:\n            return None\n        return normalize_path(location)\n\n    @property\n    def info_location(self) -> str | None:\n        return self._dist.egg_info\n\n    @property\n    def installed_by_distutils(self) -> bool:\n        # A distutils-installed distribution is provided by FileMetadata. This\n        # provider has a \"path\" attribute not present anywhere else. Not the\n        # best introspection logic, but pip has been doing this for a long time.\n        try:\n            return bool(self._dist._provider.path)\n        except AttributeError:\n            return False\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        return canonicalize_name(self._dist.project_name)\n\n    @property\n    def version(self) -> Version:\n        return parse_version(self._dist.version)\n\n    @property\n    def raw_version(self) -> str:\n        return self._dist.version\n\n    def is_file(self, path: InfoPath) -> bool:\n        return self._dist.has_metadata(str(path))\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        yield from self._dist.metadata_listdir(\"scripts\")\n\n    def read_text(self, path: InfoPath) -> str:\n        name = str(path)\n        if not self._dist.has_metadata(name):\n            raise FileNotFoundError(name)\n        content = self._dist.get_metadata(name)\n        if content is None:\n            raise NoneMetadataError(self, name)\n        return content\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        for group, entries in self._dist.get_entry_map().items():\n            for name, entry_point in entries.items():\n                name, _, value = str(entry_point).partition(\"=\")\n                yield EntryPoint(name=name.strip(), value=value.strip(), group=group)\n\n    def _metadata_impl(self) -> email.message.Message:\n        \"\"\"\n        :raises NoneMetadataError: if the distribution reports `has_metadata()`\n            True but `get_metadata()` returns None.\n        \"\"\"\n        if isinstance(self._dist, pkg_resources.DistInfoDistribution):\n            metadata_name = \"METADATA\"\n        else:\n            metadata_name = \"PKG-INFO\"\n        try:\n            metadata = self.read_text(metadata_name)\n        except FileNotFoundError:\n            if self.location:\n                displaying_path = display_path(self.location)\n            else:\n                displaying_path = repr(self.location)\n            logger.warning(\"No metadata found in %s\", displaying_path)\n            metadata = \"\"\n        feed_parser = email.parser.FeedParser()\n        feed_parser.feed(metadata)\n        return feed_parser.close()\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        if extras:\n            relevant_extras = set(self._extra_mapping) & set(\n                map(canonicalize_name, extras)\n            )\n            extras = [self._extra_mapping[extra] for extra in relevant_extras]\n        return self._dist.requires(extras)\n\n    def iter_provided_extras(self) -> Iterable[NormalizedName]:\n        return self._extra_mapping.keys()\n\n\nclass Environment(BaseEnvironment):\n    def __init__(self, ws: pkg_resources.WorkingSet) -> None:\n        self._ws = ws\n\n    @classmethod\n    def default(cls) -> BaseEnvironment:\n        return cls(pkg_resources.working_set)\n\n    @classmethod\n    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:\n        return cls(pkg_resources.WorkingSet(paths))\n\n    def _iter_distributions(self) -> Iterator[BaseDistribution]:\n        for dist in self._ws:\n            yield Distribution(dist)\n\n    def _search_distribution(self, name: str) -> BaseDistribution | None:\n        \"\"\"Find a distribution matching the ``name`` in the environment.\n\n        This searches from *all* distributions available in the environment, to\n        match the behavior of ``pkg_resources.get_distribution()``.\n        \"\"\"\n        canonical_name = canonicalize_name(name)\n        for dist in self.iter_all_distributions():\n            if dist.canonical_name == canonical_name:\n                return dist\n        return None\n\n    def get_distribution(self, name: str) -> BaseDistribution | None:\n        # Search the distribution by looking through the working set.\n        dist = self._search_distribution(name)\n        if dist:\n            return dist\n\n        # If distribution could not be found, call working_set.require to\n        # update the working set, and try to find the distribution again.\n        # This might happen for e.g. when you install a package twice, once\n        # using setup.py develop and again using setup.py install. Now when\n        # running pip uninstall twice, the package gets removed from the\n        # working set in the first uninstall, so we have to populate the\n        # working set again so that pip knows about it and the packages gets\n        # picked up and is successfully uninstalled the second time too.\n        try:\n            # We didn't pass in any version specifiers, so this can never\n            # raise pkg_resources.VersionConflict.\n            self._ws.require(name)\n        except pkg_resources.DistributionNotFound:\n            return None\n        return self._search_distribution(name)\n"
  },
  {
    "path": "src/pip/_internal/models/__init__.py",
    "content": "\"\"\"A package that contains models that represent entities.\"\"\"\n"
  },
  {
    "path": "src/pip/_internal/models/candidate.py",
    "content": "from dataclasses import dataclass\n\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.models.link import Link\n\n\n@dataclass(frozen=True)\nclass InstallationCandidate:\n    \"\"\"Represents a potential \"candidate\" for installation.\"\"\"\n\n    __slots__ = [\"name\", \"version\", \"link\"]\n\n    name: str\n    version: Version\n    link: Link\n\n    def __init__(self, name: str, version: str, link: Link) -> None:\n        object.__setattr__(self, \"name\", name)\n        object.__setattr__(self, \"version\", parse_version(version))\n        object.__setattr__(self, \"link\", link)\n\n    def __str__(self) -> str:\n        return f\"{self.name!r} candidate (version {self.version} at {self.link})\"\n"
  },
  {
    "path": "src/pip/_internal/models/direct_url.py",
    "content": "\"\"\"PEP 610\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport re\nimport urllib.parse\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar, TypeVar, Union\n\n__all__ = [\n    \"DirectUrl\",\n    \"DirectUrlValidationError\",\n    \"DirInfo\",\n    \"ArchiveInfo\",\n    \"VcsInfo\",\n]\n\nT = TypeVar(\"T\")\n\nDIRECT_URL_METADATA_NAME = \"direct_url.json\"\nENV_VAR_RE = re.compile(r\"^\\$\\{[A-Za-z0-9-_]+\\}(:\\$\\{[A-Za-z0-9-_]+\\})?$\")\n\n\nclass DirectUrlValidationError(Exception):\n    pass\n\n\ndef _get(\n    d: dict[str, Any], expected_type: type[T], key: str, default: T | None = None\n) -> T | None:\n    \"\"\"Get value from dictionary and verify expected type.\"\"\"\n    if key not in d:\n        return default\n    value = d[key]\n    if not isinstance(value, expected_type):\n        raise DirectUrlValidationError(\n            f\"{value!r} has unexpected type for {key} (expected {expected_type})\"\n        )\n    return value\n\n\ndef _get_required(\n    d: dict[str, Any], expected_type: type[T], key: str, default: T | None = None\n) -> T:\n    value = _get(d, expected_type, key, default)\n    if value is None:\n        raise DirectUrlValidationError(f\"{key} must have a value\")\n    return value\n\n\ndef _exactly_one_of(infos: Iterable[InfoType | None]) -> InfoType:\n    infos = [info for info in infos if info is not None]\n    if not infos:\n        raise DirectUrlValidationError(\n            \"missing one of archive_info, dir_info, vcs_info\"\n        )\n    if len(infos) > 1:\n        raise DirectUrlValidationError(\n            \"more than one of archive_info, dir_info, vcs_info\"\n        )\n    assert infos[0] is not None\n    return infos[0]\n\n\ndef _filter_none(**kwargs: Any) -> dict[str, Any]:\n    \"\"\"Make dict excluding None values.\"\"\"\n    return {k: v for k, v in kwargs.items() if v is not None}\n\n\n@dataclass\nclass VcsInfo:\n    name: ClassVar = \"vcs_info\"\n\n    vcs: str\n    commit_id: str\n    requested_revision: str | None = None\n\n    @classmethod\n    def _from_dict(cls, d: dict[str, Any] | None) -> VcsInfo | None:\n        if d is None:\n            return None\n        return cls(\n            vcs=_get_required(d, str, \"vcs\"),\n            commit_id=_get_required(d, str, \"commit_id\"),\n            requested_revision=_get(d, str, \"requested_revision\"),\n        )\n\n    def _to_dict(self) -> dict[str, Any]:\n        return _filter_none(\n            vcs=self.vcs,\n            requested_revision=self.requested_revision,\n            commit_id=self.commit_id,\n        )\n\n\nclass ArchiveInfo:\n    name = \"archive_info\"\n\n    def __init__(\n        self,\n        hash: str | None = None,\n        hashes: dict[str, str] | None = None,\n    ) -> None:\n        # set hashes before hash, since the hash setter will further populate hashes\n        self.hashes = hashes\n        self.hash = hash\n\n    @property\n    def hash(self) -> str | None:\n        return self._hash\n\n    @hash.setter\n    def hash(self, value: str | None) -> None:\n        if value is not None:\n            # Auto-populate the hashes key to upgrade to the new format automatically.\n            # We don't back-populate the legacy hash key from hashes.\n            try:\n                hash_name, hash_value = value.split(\"=\", 1)\n            except ValueError:\n                raise DirectUrlValidationError(\n                    f\"invalid archive_info.hash format: {value!r}\"\n                )\n            if self.hashes is None:\n                self.hashes = {hash_name: hash_value}\n            elif hash_name not in self.hashes:\n                self.hashes = self.hashes.copy()\n                self.hashes[hash_name] = hash_value\n        self._hash = value\n\n    @classmethod\n    def _from_dict(cls, d: dict[str, Any] | None) -> ArchiveInfo | None:\n        if d is None:\n            return None\n        return cls(hash=_get(d, str, \"hash\"), hashes=_get(d, dict, \"hashes\"))\n\n    def _to_dict(self) -> dict[str, Any]:\n        return _filter_none(hash=self.hash, hashes=self.hashes)\n\n\n@dataclass\nclass DirInfo:\n    name: ClassVar = \"dir_info\"\n\n    editable: bool = False\n\n    @classmethod\n    def _from_dict(cls, d: dict[str, Any] | None) -> DirInfo | None:\n        if d is None:\n            return None\n        return cls(editable=_get_required(d, bool, \"editable\", default=False))\n\n    def _to_dict(self) -> dict[str, Any]:\n        return _filter_none(editable=self.editable or None)\n\n\nInfoType = Union[ArchiveInfo, DirInfo, VcsInfo]\n\n\n@dataclass\nclass DirectUrl:\n    url: str\n    info: InfoType\n    subdirectory: str | None = None\n\n    def _remove_auth_from_netloc(self, netloc: str) -> str:\n        if \"@\" not in netloc:\n            return netloc\n        user_pass, netloc_no_user_pass = netloc.split(\"@\", 1)\n        if (\n            isinstance(self.info, VcsInfo)\n            and self.info.vcs == \"git\"\n            and user_pass == \"git\"\n        ):\n            return netloc\n        if ENV_VAR_RE.match(user_pass):\n            return netloc\n        return netloc_no_user_pass\n\n    @property\n    def redacted_url(self) -> str:\n        \"\"\"url with user:password part removed unless it is formed with\n        environment variables as specified in PEP 610, or it is ``git``\n        in the case of a git URL.\n        \"\"\"\n        purl = urllib.parse.urlsplit(self.url)\n        netloc = self._remove_auth_from_netloc(purl.netloc)\n        surl = urllib.parse.urlunsplit(\n            (purl.scheme, netloc, purl.path, purl.query, purl.fragment)\n        )\n        return surl\n\n    def validate(self) -> None:\n        self.from_dict(self.to_dict())\n\n    @classmethod\n    def from_dict(cls, d: dict[str, Any]) -> DirectUrl:\n        return DirectUrl(\n            url=_get_required(d, str, \"url\"),\n            subdirectory=_get(d, str, \"subdirectory\"),\n            info=_exactly_one_of(\n                [\n                    ArchiveInfo._from_dict(_get(d, dict, \"archive_info\")),\n                    DirInfo._from_dict(_get(d, dict, \"dir_info\")),\n                    VcsInfo._from_dict(_get(d, dict, \"vcs_info\")),\n                ]\n            ),\n        )\n\n    def to_dict(self) -> dict[str, Any]:\n        res = _filter_none(\n            url=self.redacted_url,\n            subdirectory=self.subdirectory,\n        )\n        res[self.info.name] = self.info._to_dict()\n        return res\n\n    @classmethod\n    def from_json(cls, s: str) -> DirectUrl:\n        return cls.from_dict(json.loads(s))\n\n    def to_json(self) -> str:\n        return json.dumps(self.to_dict(), sort_keys=True)\n\n    def is_local_editable(self) -> bool:\n        return isinstance(self.info, DirInfo) and self.info.editable\n"
  },
  {
    "path": "src/pip/_internal/models/format_control.py",
    "content": "from __future__ import annotations\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import CommandError\n\n\nclass FormatControl:\n    \"\"\"Helper for managing formats from which a package can be installed.\"\"\"\n\n    __slots__ = [\"no_binary\", \"only_binary\"]\n\n    def __init__(\n        self,\n        no_binary: set[str] | None = None,\n        only_binary: set[str] | None = None,\n    ) -> None:\n        if no_binary is None:\n            no_binary = set()\n        if only_binary is None:\n            only_binary = set()\n\n        self.no_binary = no_binary\n        self.only_binary = only_binary\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, self.__class__):\n            return NotImplemented\n\n        if self.__slots__ != other.__slots__:\n            return False\n\n        return all(getattr(self, k) == getattr(other, k) for k in self.__slots__)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self.no_binary}, {self.only_binary})\"\n\n    @staticmethod\n    def handle_mutual_excludes(value: str, target: set[str], other: set[str]) -> None:\n        if value.startswith(\"-\"):\n            raise CommandError(\n                \"--no-binary / --only-binary option requires 1 argument.\"\n            )\n        new = value.split(\",\")\n        while \":all:\" in new:\n            other.clear()\n            target.clear()\n            target.add(\":all:\")\n            del new[: new.index(\":all:\") + 1]\n            # Without a none, we want to discard everything as :all: covers it\n            if \":none:\" not in new:\n                return\n        for name in new:\n            if name == \":none:\":\n                target.clear()\n                continue\n            name = canonicalize_name(name)\n            other.discard(name)\n            target.add(name)\n\n    def get_allowed_formats(self, canonical_name: str) -> frozenset[str]:\n        result = {\"binary\", \"source\"}\n        if canonical_name in self.only_binary:\n            result.discard(\"source\")\n        elif canonical_name in self.no_binary:\n            result.discard(\"binary\")\n        elif \":all:\" in self.only_binary:\n            result.discard(\"source\")\n        elif \":all:\" in self.no_binary:\n            result.discard(\"binary\")\n        return frozenset(result)\n\n    def disallow_binaries(self) -> None:\n        self.handle_mutual_excludes(\n            \":all:\",\n            self.no_binary,\n            self.only_binary,\n        )\n"
  },
  {
    "path": "src/pip/_internal/models/index.py",
    "content": "import urllib.parse\n\n\nclass PackageIndex:\n    \"\"\"Represents a Package Index and provides easier access to endpoints\"\"\"\n\n    __slots__ = [\"url\", \"netloc\", \"simple_url\", \"pypi_url\", \"file_storage_domain\"]\n\n    def __init__(self, url: str, file_storage_domain: str) -> None:\n        super().__init__()\n        self.url = url\n        self.netloc = urllib.parse.urlsplit(url).netloc\n        self.simple_url = self._url_for_path(\"simple\")\n        self.pypi_url = self._url_for_path(\"pypi\")\n\n        # This is part of a temporary hack used to block installs of PyPI\n        # packages which depend on external urls only necessary until PyPI can\n        # block such packages themselves\n        self.file_storage_domain = file_storage_domain\n\n    def _url_for_path(self, path: str) -> str:\n        return urllib.parse.urljoin(self.url, path)\n\n\nPyPI = PackageIndex(\"https://pypi.org/\", file_storage_domain=\"files.pythonhosted.org\")\nTestPyPI = PackageIndex(\n    \"https://test.pypi.org/\", file_storage_domain=\"test-files.pythonhosted.org\"\n)\n"
  },
  {
    "path": "src/pip/_internal/models/installation_report.py",
    "content": "from collections.abc import Sequence\nfrom typing import Any\n\nfrom pip._vendor.packaging.markers import default_environment\n\nfrom pip import __version__\nfrom pip._internal.req.req_install import InstallRequirement\n\n\nclass InstallationReport:\n    def __init__(self, install_requirements: Sequence[InstallRequirement]):\n        self._install_requirements = install_requirements\n\n    @classmethod\n    def _install_req_to_dict(cls, ireq: InstallRequirement) -> dict[str, Any]:\n        assert ireq.download_info, f\"No download_info for {ireq}\"\n        res = {\n            # PEP 610 json for the download URL. download_info.archive_info.hashes may\n            # be absent when the requirement was installed from the wheel cache\n            # and the cache entry was populated by an older pip version that did not\n            # record origin.json.\n            \"download_info\": ireq.download_info.to_dict(),\n            # is_direct is true if the requirement was a direct URL reference (which\n            # includes editable requirements), and false if the requirement was\n            # downloaded from a PEP 503 index or --find-links.\n            \"is_direct\": ireq.is_direct,\n            # is_yanked is true if the requirement was yanked from the index, but\n            # was still selected by pip to conform to PEP 592.\n            \"is_yanked\": ireq.link.is_yanked if ireq.link else False,\n            # requested is true if the requirement was specified by the user (aka\n            # top level requirement), and false if it was installed as a dependency of a\n            # requirement. https://peps.python.org/pep-0376/#requested\n            \"requested\": ireq.user_supplied,\n            # PEP 566 json encoding for metadata\n            # https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata\n            \"metadata\": ireq.get_dist().metadata_dict,\n        }\n        if ireq.user_supplied and ireq.extras:\n            # For top level requirements, the list of requested extras, if any.\n            res[\"requested_extras\"] = sorted(ireq.extras)\n        return res\n\n    def to_dict(self) -> dict[str, Any]:\n        return {\n            \"version\": \"1\",\n            \"pip_version\": __version__,\n            \"install\": [\n                self._install_req_to_dict(ireq) for ireq in self._install_requirements\n            ],\n            # https://peps.python.org/pep-0508/#environment-markers\n            # TODO: currently, the resolver uses the default environment to evaluate\n            # environment markers, so that is what we report here. In the future, it\n            # should also take into account options such as --python-version or\n            # --platform, perhaps under the form of an environment_override field?\n            # https://github.com/pypa/pip/issues/11198\n            \"environment\": default_environment(),\n        }\n"
  },
  {
    "path": "src/pip/_internal/models/link.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport functools\nimport itertools\nimport logging\nimport os\nimport posixpath\nimport re\nimport urllib.parse\nimport urllib.request\nfrom collections.abc import Mapping\nfrom dataclasses import dataclass\nfrom typing import (\n    Any,\n    NamedTuple,\n)\n\nfrom pip._internal.exceptions import InvalidEggFragment\nfrom pip._internal.utils.datetime import parse_iso_datetime\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.misc import (\n    pairwise,\n    redact_auth_from_url,\n    split_auth_from_netloc,\n    splitext,\n)\nfrom pip._internal.utils.urls import path_to_url, url_to_path\n\nlogger = logging.getLogger(__name__)\n\n\n# Order matters, earlier hashes have a precedence over later hashes for what\n# we will pick to use.\n_SUPPORTED_HASHES = (\"sha512\", \"sha384\", \"sha256\", \"sha224\", \"sha1\", \"md5\")\n\n\n@dataclass(frozen=True)\nclass LinkHash:\n    \"\"\"Links to content may have embedded hash values. This class parses those.\n\n    `name` must be any member of `_SUPPORTED_HASHES`.\n\n    This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to\n    be JSON-serializable to conform to PEP 610, this class contains the logic for\n    parsing a hash name and value for correctness, and then checking whether that hash\n    conforms to a schema with `.is_hash_allowed()`.\"\"\"\n\n    name: str\n    value: str\n\n    _hash_url_fragment_re = re.compile(\n        # NB: we do not validate that the second group (.*) is a valid hex\n        # digest. Instead, we simply keep that string in this class, and then check it\n        # against Hashes when hash-checking is needed. This is easier to debug than\n        # proactively discarding an invalid hex digest, as we handle incorrect hashes\n        # and malformed hashes in the same place.\n        r\"[#&]({choices})=([^&]*)\".format(\n            choices=\"|\".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES)\n        ),\n    )\n\n    def __post_init__(self) -> None:\n        assert self.name in _SUPPORTED_HASHES\n\n    @classmethod\n    @functools.cache\n    def find_hash_url_fragment(cls, url: str) -> LinkHash | None:\n        \"\"\"Search a string for a checksum algorithm name and encoded output value.\"\"\"\n        match = cls._hash_url_fragment_re.search(url)\n        if match is None:\n            return None\n        name, value = match.groups()\n        return cls(name=name, value=value)\n\n    def as_dict(self) -> dict[str, str]:\n        return {self.name: self.value}\n\n    def as_hashes(self) -> Hashes:\n        \"\"\"Return a Hashes instance which checks only for the current hash.\"\"\"\n        return Hashes({self.name: [self.value]})\n\n    def is_hash_allowed(self, hashes: Hashes | None) -> bool:\n        \"\"\"\n        Return True if the current hash is allowed by `hashes`.\n        \"\"\"\n        if hashes is None:\n            return False\n        return hashes.is_hash_allowed(self.name, hex_digest=self.value)\n\n\n@dataclass(frozen=True)\nclass MetadataFile:\n    \"\"\"Information about a core metadata file associated with a distribution.\"\"\"\n\n    hashes: dict[str, str] | None\n\n    def __post_init__(self) -> None:\n        if self.hashes is not None:\n            assert all(name in _SUPPORTED_HASHES for name in self.hashes)\n\n\ndef supported_hashes(hashes: dict[str, str] | None) -> dict[str, str] | None:\n    # Remove any unsupported hash types from the mapping. If this leaves no\n    # supported hashes, return None\n    if hashes is None:\n        return None\n    hashes = {n: v for n, v in hashes.items() if n in _SUPPORTED_HASHES}\n    if not hashes:\n        return None\n    return hashes\n\n\ndef _clean_url_path_part(part: str) -> str:\n    \"\"\"\n    Clean a \"part\" of a URL path (i.e. after splitting on \"@\" characters).\n    \"\"\"\n    # We unquote prior to quoting to make sure nothing is double quoted.\n    return urllib.parse.quote(urllib.parse.unquote(part))\n\n\ndef _clean_file_url_path(part: str) -> str:\n    \"\"\"\n    Clean the first part of a URL path that corresponds to a local\n    filesystem path (i.e. the first part after splitting on \"@\" characters).\n    \"\"\"\n    # We unquote prior to quoting to make sure nothing is double quoted.\n    # Also, on Windows the path part might contain a drive letter which\n    # should not be quoted. On Linux where drive letters do not\n    # exist, the colon should be quoted. We rely on urllib.request\n    # to do the right thing here.\n    ret = urllib.request.pathname2url(urllib.request.url2pathname(part))\n    if ret.startswith(\"///\"):\n        # Remove any URL authority section, leaving only the URL path.\n        ret = ret.removeprefix(\"//\")\n    return ret\n\n\n# percent-encoded:                   /\n_reserved_chars_re = re.compile(\"(@|%2F)\", re.IGNORECASE)\n\n\ndef _clean_url_path(path: str, is_local_path: bool) -> str:\n    \"\"\"\n    Clean the path portion of a URL.\n    \"\"\"\n    if is_local_path:\n        clean_func = _clean_file_url_path\n    else:\n        clean_func = _clean_url_path_part\n\n    # Split on the reserved characters prior to cleaning so that\n    # revision strings in VCS URLs are properly preserved.\n    parts = _reserved_chars_re.split(path)\n\n    cleaned_parts = []\n    for to_clean, reserved in pairwise(itertools.chain(parts, [\"\"])):\n        cleaned_parts.append(clean_func(to_clean))\n        # Normalize %xx escapes (e.g. %2f -> %2F)\n        cleaned_parts.append(reserved.upper())\n\n    return \"\".join(cleaned_parts)\n\n\ndef _ensure_quoted_url(url: str) -> str:\n    \"\"\"\n    Make sure a link is fully quoted.\n    For example, if ' ' occurs in the URL, it will be replaced with \"%20\",\n    and without double-quoting other characters.\n    \"\"\"\n    # Split the URL into parts according to the general structure\n    # `scheme://netloc/path?query#fragment`.\n    result = urllib.parse.urlsplit(url)\n    # If the netloc is empty, then the URL refers to a local filesystem path.\n    is_local_path = not result.netloc\n    path = _clean_url_path(result.path, is_local_path=is_local_path)\n    # Temporarily replace scheme with file to ensure the URL generated by\n    # urlunsplit() contains an empty netloc (file://) as per RFC 1738.\n    ret = urllib.parse.urlunsplit(result._replace(scheme=\"file\", path=path))\n    ret = result.scheme + ret[4:]  # Restore original scheme.\n    return ret\n\n\ndef _absolute_link_url(base_url: str, url: str) -> str:\n    \"\"\"\n    A faster implementation of urllib.parse.urljoin with a shortcut\n    for absolute http/https URLs.\n    \"\"\"\n    if url.startswith((\"https://\", \"http://\")):\n        return url\n    else:\n        return urllib.parse.urljoin(base_url, url)\n\n\n@functools.total_ordering\nclass Link:\n    \"\"\"Represents a parsed link from a Package Index's simple URL\"\"\"\n\n    __slots__ = [\n        \"_parsed_url\",\n        \"_url\",\n        \"_path\",\n        \"_hashes\",\n        \"comes_from\",\n        \"requires_python\",\n        \"yanked_reason\",\n        \"metadata_file_data\",\n        \"upload_time\",\n        \"cache_link_parsing\",\n        \"egg_fragment\",\n    ]\n\n    def __init__(\n        self,\n        url: str,\n        comes_from: str | None = None,\n        requires_python: str | None = None,\n        yanked_reason: str | None = None,\n        metadata_file_data: MetadataFile | None = None,\n        upload_time: datetime.datetime | None = None,\n        cache_link_parsing: bool = True,\n        hashes: Mapping[str, str] | None = None,\n    ) -> None:\n        \"\"\"\n        :param url: url of the resource pointed to (href of the link)\n        :param comes_from: URL or string indicating where the link was found.\n        :param requires_python: String containing the `Requires-Python`\n            metadata field, specified in PEP 345. This may be specified by\n            a data-requires-python attribute in the HTML link tag, as\n            described in PEP 503.\n        :param yanked_reason: the reason the file has been yanked, if the\n            file has been yanked, or None if the file hasn't been yanked.\n            This is the value of the \"data-yanked\" attribute, if present, in\n            a simple repository HTML link. If the file has been yanked but\n            no reason was provided, this should be the empty string. See\n            PEP 592 for more information and the specification.\n        :param metadata_file_data: the metadata attached to the file, or None if\n            no such metadata is provided. This argument, if not None, indicates\n            that a separate metadata file exists, and also optionally supplies\n            hashes for that file.\n        :param upload_time: upload time of the file, or None if the information\n            is not available from the server.\n        :param cache_link_parsing: A flag that is used elsewhere to determine\n            whether resources retrieved from this link should be cached. PyPI\n            URLs should generally have this set to False, for example.\n        :param hashes: A mapping of hash names to digests to allow us to\n            determine the validity of a download.\n        \"\"\"\n\n        # The comes_from, requires_python, and metadata_file_data arguments are\n        # only used by classmethods of this class, and are not used in client\n        # code directly.\n\n        # url can be a UNC windows share\n        if url.startswith(\"\\\\\\\\\"):\n            url = path_to_url(url)\n\n        self._parsed_url = urllib.parse.urlsplit(url)\n        # Store the url as a private attribute to prevent accidentally\n        # trying to set a new value.\n        self._url = url\n        # The .path property is hot, so calculate its value ahead of time.\n        self._path = urllib.parse.unquote(self._parsed_url.path)\n\n        link_hash = LinkHash.find_hash_url_fragment(url)\n        hashes_from_link = {} if link_hash is None else link_hash.as_dict()\n        if hashes is None:\n            self._hashes = hashes_from_link\n        else:\n            self._hashes = {**hashes, **hashes_from_link}\n\n        self.comes_from = comes_from\n        self.requires_python = requires_python if requires_python else None\n        self.yanked_reason = yanked_reason\n        self.metadata_file_data = metadata_file_data\n        self.upload_time = upload_time\n\n        self.cache_link_parsing = cache_link_parsing\n        self.egg_fragment = self._egg_fragment()\n\n    @classmethod\n    def from_json(\n        cls,\n        file_data: dict[str, Any],\n        page_url: str,\n    ) -> Link | None:\n        \"\"\"\n        Convert an pypi json document from a simple repository page into a Link.\n        \"\"\"\n        file_url = file_data.get(\"url\")\n        if file_url is None:\n            return None\n\n        url = _ensure_quoted_url(_absolute_link_url(page_url, file_url))\n        pyrequire = file_data.get(\"requires-python\")\n        yanked_reason = file_data.get(\"yanked\")\n        hashes = file_data.get(\"hashes\", {})\n\n        # PEP 714: Indexes must use the name core-metadata, but\n        # clients should support the old name as a fallback for compatibility.\n        metadata_info = file_data.get(\"core-metadata\")\n        if metadata_info is None:\n            metadata_info = file_data.get(\"dist-info-metadata\")\n\n        if upload_time_data := file_data.get(\"upload-time\"):\n            upload_time = parse_iso_datetime(upload_time_data)\n        else:\n            upload_time = None\n\n        # The metadata info value may be a boolean, or a dict of hashes.\n        if isinstance(metadata_info, dict):\n            # The file exists, and hashes have been supplied\n            metadata_file_data = MetadataFile(supported_hashes(metadata_info))\n        elif metadata_info:\n            # The file exists, but there are no hashes\n            metadata_file_data = MetadataFile(None)\n        else:\n            # False or not present: the file does not exist\n            metadata_file_data = None\n\n        # The Link.yanked_reason expects an empty string instead of a boolean.\n        if yanked_reason and not isinstance(yanked_reason, str):\n            yanked_reason = \"\"\n        # The Link.yanked_reason expects None instead of False.\n        elif not yanked_reason:\n            yanked_reason = None\n\n        return cls(\n            url,\n            comes_from=page_url,\n            requires_python=pyrequire,\n            yanked_reason=yanked_reason,\n            hashes=hashes,\n            metadata_file_data=metadata_file_data,\n            upload_time=upload_time,\n        )\n\n    @classmethod\n    def from_element(\n        cls,\n        anchor_attribs: dict[str, str | None],\n        page_url: str,\n        base_url: str,\n    ) -> Link | None:\n        \"\"\"\n        Convert an anchor element's attributes in a simple repository page to a Link.\n        \"\"\"\n        href = anchor_attribs.get(\"href\")\n        if not href:\n            return None\n\n        url = _ensure_quoted_url(_absolute_link_url(base_url, href))\n        pyrequire = anchor_attribs.get(\"data-requires-python\")\n        yanked_reason = anchor_attribs.get(\"data-yanked\")\n\n        # PEP 714: Indexes must use the name data-core-metadata, but\n        # clients should support the old name as a fallback for compatibility.\n        metadata_info = anchor_attribs.get(\"data-core-metadata\")\n        if metadata_info is None:\n            metadata_info = anchor_attribs.get(\"data-dist-info-metadata\")\n        # The metadata info value may be the string \"true\", or a string of\n        # the form \"hashname=hashval\"\n        if metadata_info == \"true\":\n            # The file exists, but there are no hashes\n            metadata_file_data = MetadataFile(None)\n        elif metadata_info is None:\n            # The file does not exist\n            metadata_file_data = None\n        else:\n            # The file exists, and hashes have been supplied\n            hashname, sep, hashval = metadata_info.partition(\"=\")\n            if sep == \"=\":\n                metadata_file_data = MetadataFile(supported_hashes({hashname: hashval}))\n            else:\n                # Error - data is wrong. Treat as no hashes supplied.\n                logger.debug(\n                    \"Index returned invalid data-dist-info-metadata value: %s\",\n                    metadata_info,\n                )\n                metadata_file_data = MetadataFile(None)\n\n        return cls(\n            url,\n            comes_from=page_url,\n            requires_python=pyrequire,\n            yanked_reason=yanked_reason,\n            metadata_file_data=metadata_file_data,\n        )\n\n    def __str__(self) -> str:\n        if self.requires_python:\n            rp = f\" (requires-python:{self.requires_python})\"\n        else:\n            rp = \"\"\n        if self.comes_from:\n            return f\"{self.redacted_url} (from {self.comes_from}){rp}\"\n        else:\n            return self.redacted_url\n\n    def __repr__(self) -> str:\n        return f\"<Link {self}>\"\n\n    def __hash__(self) -> int:\n        return hash(self.url)\n\n    def __eq__(self, other: Any) -> bool:\n        if not isinstance(other, Link):\n            return NotImplemented\n        return self.url == other.url\n\n    def __lt__(self, other: Any) -> bool:\n        if not isinstance(other, Link):\n            return NotImplemented\n        return self.url < other.url\n\n    @property\n    def url(self) -> str:\n        return self._url\n\n    @property\n    def redacted_url(self) -> str:\n        return redact_auth_from_url(self.url)\n\n    @property\n    def filename(self) -> str:\n        path = self.path.rstrip(\"/\")\n        name = posixpath.basename(path)\n        if not name:\n            # Make sure we don't leak auth information if the netloc\n            # includes a username and password.\n            netloc, user_pass = split_auth_from_netloc(self.netloc)\n            return netloc\n\n        name = urllib.parse.unquote(name)\n        assert name, f\"URL {self._url!r} produced no filename\"\n        return name\n\n    @property\n    def file_path(self) -> str:\n        return url_to_path(self.url)\n\n    @property\n    def scheme(self) -> str:\n        return self._parsed_url.scheme\n\n    @property\n    def netloc(self) -> str:\n        \"\"\"\n        This can contain auth information.\n        \"\"\"\n        return self._parsed_url.netloc\n\n    @property\n    def path(self) -> str:\n        return self._path\n\n    def splitext(self) -> tuple[str, str]:\n        return splitext(posixpath.basename(self.path.rstrip(\"/\")))\n\n    @property\n    def ext(self) -> str:\n        return self.splitext()[1]\n\n    @property\n    def url_without_fragment(self) -> str:\n        scheme, netloc, path, query, fragment = self._parsed_url\n        return urllib.parse.urlunsplit((scheme, netloc, path, query, \"\"))\n\n    _egg_fragment_re = re.compile(r\"[#&]egg=([^&]*)\")\n\n    # Per PEP 508.\n    _project_name_re = re.compile(\n        r\"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$\", re.IGNORECASE\n    )\n\n    def _egg_fragment(self) -> str | None:\n        match = self._egg_fragment_re.search(self._url)\n        if not match:\n            return None\n\n        # An egg fragment looks like a PEP 508 project name, along with\n        # an optional extras specifier. Anything else is invalid.\n        project_name = match.group(1)\n        if not self._project_name_re.match(project_name):\n            raise InvalidEggFragment(self, project_name)\n\n        return project_name\n\n    _subdirectory_fragment_re = re.compile(r\"[#&]subdirectory=([^&]*)\")\n\n    @property\n    def subdirectory_fragment(self) -> str | None:\n        match = self._subdirectory_fragment_re.search(self._url)\n        if not match:\n            return None\n        return match.group(1)\n\n    def metadata_link(self) -> Link | None:\n        \"\"\"Return a link to the associated core metadata file (if any).\"\"\"\n        if self.metadata_file_data is None:\n            return None\n        metadata_url = f\"{self.url_without_fragment}.metadata\"\n        if self.metadata_file_data.hashes is None:\n            return Link(metadata_url)\n        return Link(metadata_url, hashes=self.metadata_file_data.hashes)\n\n    def as_hashes(self) -> Hashes:\n        return Hashes({k: [v] for k, v in self._hashes.items()})\n\n    @property\n    def hash(self) -> str | None:\n        return next(iter(self._hashes.values()), None)\n\n    @property\n    def hash_name(self) -> str | None:\n        return next(iter(self._hashes), None)\n\n    @property\n    def show_url(self) -> str:\n        return posixpath.basename(self._url.split(\"#\", 1)[0].split(\"?\", 1)[0])\n\n    @property\n    def is_file(self) -> bool:\n        return self.scheme == \"file\"\n\n    def is_existing_dir(self) -> bool:\n        return self.is_file and os.path.isdir(self.file_path)\n\n    @property\n    def is_wheel(self) -> bool:\n        return self.ext == WHEEL_EXTENSION\n\n    @property\n    def is_vcs(self) -> bool:\n        from pip._internal.vcs import vcs\n\n        return self.scheme in vcs.all_schemes\n\n    @property\n    def is_yanked(self) -> bool:\n        return self.yanked_reason is not None\n\n    @property\n    def has_hash(self) -> bool:\n        return bool(self._hashes)\n\n    def is_hash_allowed(self, hashes: Hashes | None) -> bool:\n        \"\"\"\n        Return True if the link has a hash and it is allowed by `hashes`.\n        \"\"\"\n        if hashes is None:\n            return False\n        return any(hashes.is_hash_allowed(k, v) for k, v in self._hashes.items())\n\n\nclass _CleanResult(NamedTuple):\n    \"\"\"Convert link for equivalency check.\n\n    This is used in the resolver to check whether two URL-specified requirements\n    likely point to the same distribution and can be considered equivalent. This\n    equivalency logic avoids comparing URLs literally, which can be too strict\n    (e.g. \"a=1&b=2\" vs \"b=2&a=1\") and produce conflicts unexpecting to users.\n\n    Currently this does three things:\n\n    1. Drop the basic auth part. This is technically wrong since a server can\n       serve different content based on auth, but if it does that, it is even\n       impossible to guarantee two URLs without auth are equivalent, since\n       the user can input different auth information when prompted. So the\n       practical solution is to assume the auth doesn't affect the response.\n    2. Parse the query to avoid the ordering issue. Note that ordering under the\n       same key in the query are NOT cleaned; i.e. \"a=1&a=2\" and \"a=2&a=1\" are\n       still considered different.\n    3. Explicitly drop most of the fragment part, except ``subdirectory=`` and\n       hash values, since it should have no impact the downloaded content. Note\n       that this drops the \"egg=\" part historically used to denote the requested\n       project (and extras), which is wrong in the strictest sense, but too many\n       people are supplying it inconsistently to cause superfluous resolution\n       conflicts, so we choose to also ignore them.\n    \"\"\"\n\n    parsed: urllib.parse.SplitResult\n    query: dict[str, list[str]]\n    subdirectory: str\n    hashes: dict[str, str]\n\n\ndef _clean_link(link: Link) -> _CleanResult:\n    parsed = link._parsed_url\n    netloc = parsed.netloc.rsplit(\"@\", 1)[-1]\n    # According to RFC 8089, an empty host in file: means localhost.\n    if parsed.scheme == \"file\" and not netloc:\n        netloc = \"localhost\"\n    fragment = urllib.parse.parse_qs(parsed.fragment)\n    if \"egg\" in fragment:\n        logger.debug(\"Ignoring egg= fragment in %s\", link)\n    try:\n        # If there are multiple subdirectory values, use the first one.\n        # This matches the behavior of Link.subdirectory_fragment.\n        subdirectory = fragment[\"subdirectory\"][0]\n    except (IndexError, KeyError):\n        subdirectory = \"\"\n    # If there are multiple hash values under the same algorithm, use the\n    # first one. This matches the behavior of Link.hash_value.\n    hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}\n    return _CleanResult(\n        parsed=parsed._replace(netloc=netloc, query=\"\", fragment=\"\"),\n        query=urllib.parse.parse_qs(parsed.query),\n        subdirectory=subdirectory,\n        hashes=hashes,\n    )\n\n\n@functools.cache\ndef links_equivalent(link1: Link, link2: Link) -> bool:\n    return _clean_link(link1) == _clean_link(link2)\n"
  },
  {
    "path": "src/pip/_internal/models/release_control.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass, field\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.exceptions import CommandError\n\n\n# TODO: add slots=True when Python 3.9 is dropped\n@dataclass\nclass ReleaseControl:\n    \"\"\"Helper for managing which release types can be installed.\"\"\"\n\n    all_releases: set[str] = field(default_factory=set)\n    only_final: set[str] = field(default_factory=set)\n    _order: list[tuple[str, str]] = field(\n        init=False, default_factory=list, compare=False, repr=False\n    )\n\n    def handle_mutual_excludes(\n        self, value: str, target: set[str], other: set[str], attr_name: str\n    ) -> None:\n        \"\"\"Parse and apply release control option value.\n\n        Processes comma-separated package names or special values `:all:` and `:none:`.\n\n        When adding packages to target, they're removed from other to maintain mutual\n        exclusivity between all_releases and only_final. All operations are tracked in\n        order so that the original command-line argument sequence can be reconstructed\n        when passing options to build subprocesses.\n        \"\"\"\n        if value.startswith(\"-\"):\n            raise CommandError(\n                \"--all-releases / --only-final option requires 1 argument.\"\n            )\n        new = value.split(\",\")\n        while \":all:\" in new:\n            other.clear()\n            target.clear()\n            target.add(\":all:\")\n            # Track :all: in order\n            self._order.append((attr_name, \":all:\"))\n            del new[: new.index(\":all:\") + 1]\n            # Without a none, we want to discard everything as :all: covers it\n            if \":none:\" not in new:\n                return\n        for name in new:\n            if name == \":none:\":\n                target.clear()\n                # Track :none: in order\n                self._order.append((attr_name, \":none:\"))\n                continue\n            name = canonicalize_name(name)\n            other.discard(name)\n            target.add(name)\n            # Track package-specific setting in order\n            self._order.append((attr_name, name))\n\n    def get_ordered_args(self) -> list[tuple[str, str]]:\n        \"\"\"\n        Get ordered list of (flag_name, value) tuples for reconstructing CLI args.\n\n        Returns:\n            List of tuples where each tuple is (attribute_name, value).\n            The attribute_name is either 'all_releases' or 'only_final'.\n\n        Example:\n            [(\"all_releases\", \":all:\"), (\"only_final\", \"simple\")]\n            would be reconstructed as:\n            [\"--all-releases\", \":all:\", \"--only-final\", \"simple\"]\n        \"\"\"\n        return self._order[:]\n\n    def allows_prereleases(self, canonical_name: NormalizedName) -> bool | None:\n        \"\"\"\n        Determine if pre-releases are allowed for a package.\n\n        Returns:\n            True: Pre-releases are allowed (package in all_releases)\n            False: Only final releases allowed (package in only_final)\n            None: No specific setting, use default behavior\n        \"\"\"\n        if canonical_name in self.all_releases:\n            return True\n        elif canonical_name in self.only_final:\n            return False\n        elif \":all:\" in self.all_releases:\n            return True\n        elif \":all:\" in self.only_final:\n            return False\n        return None\n"
  },
  {
    "path": "src/pip/_internal/models/scheme.py",
    "content": "\"\"\"\nFor types associated with installation schemes.\n\nFor a general overview of available schemes and their context, see\nhttps://docs.python.org/3/install/index.html#alternate-installation.\n\"\"\"\n\nfrom dataclasses import dataclass\n\nSCHEME_KEYS = [\"platlib\", \"purelib\", \"headers\", \"scripts\", \"data\"]\n\n\n@dataclass(frozen=True)\nclass Scheme:\n    \"\"\"A Scheme holds paths which are used as the base directories for\n    artifacts associated with a Python package.\n    \"\"\"\n\n    __slots__ = SCHEME_KEYS\n\n    platlib: str\n    purelib: str\n    headers: str\n    scripts: str\n    data: str\n"
  },
  {
    "path": "src/pip/_internal/models/search_scope.py",
    "content": "import itertools\nimport logging\nimport os\nimport posixpath\nimport urllib.parse\nfrom dataclasses import dataclass\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.utils.compat import has_tls\nfrom pip._internal.utils.misc import normalize_path, redact_auth_from_url\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass SearchScope:\n    \"\"\"\n    Encapsulates the locations that pip is configured to search.\n    \"\"\"\n\n    __slots__ = [\"find_links\", \"index_urls\", \"no_index\"]\n\n    find_links: list[str]\n    index_urls: list[str]\n    no_index: bool\n\n    @classmethod\n    def create(\n        cls,\n        find_links: list[str],\n        index_urls: list[str],\n        no_index: bool,\n    ) -> \"SearchScope\":\n        \"\"\"\n        Create a SearchScope object after normalizing the `find_links`.\n        \"\"\"\n        # Build find_links. If an argument starts with ~, it may be\n        # a local file relative to a home directory. So try normalizing\n        # it and if it exists, use the normalized version.\n        # This is deliberately conservative - it might be fine just to\n        # blindly normalize anything starting with a ~...\n        built_find_links: list[str] = []\n        for link in find_links:\n            if link.startswith(\"~\"):\n                new_link = normalize_path(link)\n                if os.path.exists(new_link):\n                    link = new_link\n            built_find_links.append(link)\n\n        # If we don't have TLS enabled, then WARN if anyplace we're looking\n        # relies on TLS.\n        if not has_tls():\n            for link in itertools.chain(index_urls, built_find_links):\n                parsed = urllib.parse.urlparse(link)\n                if parsed.scheme == \"https\":\n                    logger.warning(\n                        \"pip is configured with locations that require \"\n                        \"TLS/SSL, however the ssl module in Python is not \"\n                        \"available.\"\n                    )\n                    break\n\n        return cls(\n            find_links=built_find_links,\n            index_urls=index_urls,\n            no_index=no_index,\n        )\n\n    def get_formatted_locations(self) -> str:\n        lines = []\n        redacted_index_urls = []\n        if self.index_urls and self.index_urls != [PyPI.simple_url]:\n            for url in self.index_urls:\n                redacted_index_url = redact_auth_from_url(url)\n\n                # Parse the URL\n                purl = urllib.parse.urlsplit(redacted_index_url)\n\n                # URL is generally invalid if scheme and netloc is missing\n                # there are issues with Python and URL parsing, so this test\n                # is a bit crude. See bpo-20271, bpo-23505. Python doesn't\n                # always parse invalid URLs correctly - it should raise\n                # exceptions for malformed URLs\n                if not purl.scheme and not purl.netloc:\n                    logger.warning(\n                        'The index url \"%s\" seems invalid, please provide a scheme.',\n                        redacted_index_url,\n                    )\n\n                redacted_index_urls.append(redacted_index_url)\n\n            lines.append(\n                \"Looking in indexes: {}\".format(\", \".join(redacted_index_urls))\n            )\n\n        if self.find_links:\n            lines.append(\n                \"Looking in links: {}\".format(\n                    \", \".join(redact_auth_from_url(url) for url in self.find_links)\n                )\n            )\n        return \"\\n\".join(lines)\n\n    def get_index_urls_locations(self, project_name: str) -> list[str]:\n        \"\"\"Returns the locations found via self.index_urls\n\n        Checks the url_name on the main (first in the list) index and\n        use this url_name to produce all locations\n        \"\"\"\n\n        def mkurl_pypi_url(url: str) -> str:\n            loc = posixpath.join(\n                url, urllib.parse.quote(canonicalize_name(project_name))\n            )\n            # For maximum compatibility with easy_install, ensure the path\n            # ends in a trailing slash.  Although this isn't in the spec\n            # (and PyPI can handle it without the slash) some other index\n            # implementations might break if they relied on easy_install's\n            # behavior.\n            if not loc.endswith(\"/\"):\n                loc = loc + \"/\"\n            return loc\n\n        return [mkurl_pypi_url(url) for url in self.index_urls]\n"
  },
  {
    "path": "src/pip/_internal/models/selection_prefs.py",
    "content": "from __future__ import annotations\n\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.release_control import ReleaseControl\n\n\n# TODO: This needs Python 3.10's improved slots support for dataclasses\n# to be converted into a dataclass.\nclass SelectionPreferences:\n    \"\"\"\n    Encapsulates the candidate selection preferences for downloading\n    and installing files.\n    \"\"\"\n\n    __slots__ = [\n        \"allow_yanked\",\n        \"release_control\",\n        \"format_control\",\n        \"prefer_binary\",\n        \"ignore_requires_python\",\n    ]\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    def __init__(\n        self,\n        allow_yanked: bool,\n        release_control: ReleaseControl | None = None,\n        format_control: FormatControl | None = None,\n        prefer_binary: bool = False,\n        ignore_requires_python: bool | None = None,\n    ) -> None:\n        \"\"\"Create a SelectionPreferences object.\n\n        :param allow_yanked: Whether files marked as yanked (in the sense\n            of PEP 592) are permitted to be candidates for install.\n        :param release_control: A ReleaseControl object or None. Used to control\n            whether pre-releases are allowed for specific packages.\n        :param format_control: A FormatControl object or None. Used to control\n            the selection of source packages / binary packages when consulting\n            the index and links.\n        :param prefer_binary: Whether to prefer an old, but valid, binary\n            dist over a new source dist.\n        :param ignore_requires_python: Whether to ignore incompatible\n            \"Requires-Python\" values in links. Defaults to False.\n        \"\"\"\n        if ignore_requires_python is None:\n            ignore_requires_python = False\n\n        self.allow_yanked = allow_yanked\n        self.release_control = release_control\n        self.format_control = format_control\n        self.prefer_binary = prefer_binary\n        self.ignore_requires_python = ignore_requires_python\n"
  },
  {
    "path": "src/pip/_internal/models/target_python.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nfrom pip._vendor.packaging.tags import Tag\n\nfrom pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot\nfrom pip._internal.utils.misc import normalize_version_info\n\n\nclass TargetPython:\n    \"\"\"\n    Encapsulates the properties of a Python interpreter one is targeting\n    for a package install, download, etc.\n    \"\"\"\n\n    __slots__ = [\n        \"_given_py_version_info\",\n        \"abis\",\n        \"implementation\",\n        \"platforms\",\n        \"py_version\",\n        \"py_version_info\",\n        \"_valid_tags\",\n        \"_valid_tags_set\",\n    ]\n\n    def __init__(\n        self,\n        platforms: list[str] | None = None,\n        py_version_info: tuple[int, ...] | None = None,\n        abis: list[str] | None = None,\n        implementation: str | None = None,\n    ) -> None:\n        \"\"\"\n        :param platforms: A list of strings or None. If None, searches for\n            packages that are supported by the current system. Otherwise, will\n            find packages that can be built on the platforms passed in. These\n            packages will only be downloaded for distribution: they will\n            not be built locally.\n        :param py_version_info: An optional tuple of ints representing the\n            Python version information to use (e.g. `sys.version_info[:3]`).\n            This can have length 1, 2, or 3 when provided.\n        :param abis: A list of strings or None. This is passed to\n            compatibility_tags.py's get_supported() function as is.\n        :param implementation: A string or None. This is passed to\n            compatibility_tags.py's get_supported() function as is.\n        \"\"\"\n        # Store the given py_version_info for when we call get_supported().\n        self._given_py_version_info = py_version_info\n\n        if py_version_info is None:\n            py_version_info = sys.version_info[:3]\n        else:\n            py_version_info = normalize_version_info(py_version_info)\n\n        py_version = \".\".join(map(str, py_version_info[:2]))\n\n        self.abis = abis\n        self.implementation = implementation\n        self.platforms = platforms\n        self.py_version = py_version\n        self.py_version_info = py_version_info\n\n        # This is used to cache the return value of get_(un)sorted_tags.\n        self._valid_tags: list[Tag] | None = None\n        self._valid_tags_set: set[Tag] | None = None\n\n    def format_given(self) -> str:\n        \"\"\"\n        Format the given, non-None attributes for display.\n        \"\"\"\n        display_version = None\n        if self._given_py_version_info is not None:\n            display_version = \".\".join(\n                str(part) for part in self._given_py_version_info\n            )\n\n        key_values = [\n            (\"platforms\", self.platforms),\n            (\"version_info\", display_version),\n            (\"abis\", self.abis),\n            (\"implementation\", self.implementation),\n        ]\n        return \" \".join(\n            f\"{key}={value!r}\" for key, value in key_values if value is not None\n        )\n\n    def get_sorted_tags(self) -> list[Tag]:\n        \"\"\"\n        Return the supported PEP 425 tags to check wheel candidates against.\n\n        The tags are returned in order of preference (most preferred first).\n        \"\"\"\n        if self._valid_tags is None:\n            # Pass versions=None if no py_version_info was given since\n            # versions=None uses special default logic.\n            py_version_info = self._given_py_version_info\n            if py_version_info is None:\n                version = None\n            else:\n                version = version_info_to_nodot(py_version_info)\n\n            tags = get_supported(\n                version=version,\n                platforms=self.platforms,\n                abis=self.abis,\n                impl=self.implementation,\n            )\n            self._valid_tags = tags\n\n        return self._valid_tags\n\n    def get_unsorted_tags(self) -> set[Tag]:\n        \"\"\"Exactly the same as get_sorted_tags, but returns a set.\n\n        This is important for performance.\n        \"\"\"\n        if self._valid_tags_set is None:\n            self._valid_tags_set = set(self.get_sorted_tags())\n\n        return self._valid_tags_set\n"
  },
  {
    "path": "src/pip/_internal/models/wheel.py",
    "content": "\"\"\"Represents a wheel file and provides access to the various parts of the\nname that have meaning.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\n\nfrom pip._vendor.packaging.tags import Tag\nfrom pip._vendor.packaging.utils import (\n    InvalidWheelFilename as _PackagingInvalidWheelFilename,\n)\nfrom pip._vendor.packaging.utils import parse_wheel_filename\n\nfrom pip._internal.exceptions import InvalidWheelFilename\n\n\nclass Wheel:\n    \"\"\"A wheel file\"\"\"\n\n    def __init__(self, filename: str) -> None:\n        self.filename = filename\n\n        try:\n            wheel_info = parse_wheel_filename(filename)\n        except _PackagingInvalidWheelFilename as e:\n            raise InvalidWheelFilename(e.args[0]) from None\n\n        self.name, _version, self.build_tag, self.file_tags = wheel_info\n        self.version = str(_version)\n\n    def get_formatted_file_tags(self) -> list[str]:\n        \"\"\"Return the wheel's tags as a sorted list of strings.\"\"\"\n        return sorted(str(tag) for tag in self.file_tags)\n\n    def support_index_min(self, tags: list[Tag]) -> int:\n        \"\"\"Return the lowest index that one of the wheel's file_tag combinations\n        achieves in the given list of supported tags.\n\n        For example, if there are 8 supported tags and one of the file tags\n        is first in the list, then return 0.\n\n        :param tags: the PEP 425 tags to check the wheel against, in order\n            with most preferred first.\n\n        :raises ValueError: If none of the wheel's file tags match one of\n            the supported tags.\n        \"\"\"\n        try:\n            return next(i for i, t in enumerate(tags) if t in self.file_tags)\n        except StopIteration:\n            raise ValueError()\n\n    def find_most_preferred_tag(\n        self, tags: list[Tag], tag_to_priority: dict[Tag, int]\n    ) -> int:\n        \"\"\"Return the priority of the most preferred tag that one of the wheel's file\n        tag combinations achieves in the given list of supported tags using the given\n        tag_to_priority mapping, where lower priorities are more-preferred.\n\n        This is used in place of support_index_min in some cases in order to avoid\n        an expensive linear scan of a large list of tags.\n\n        :param tags: the PEP 425 tags to check the wheel against.\n        :param tag_to_priority: a mapping from tag to priority of that tag, where\n            lower is more preferred.\n\n        :raises ValueError: If none of the wheel's file tags match one of\n            the supported tags.\n        \"\"\"\n        return min(\n            tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority\n        )\n\n    def supported(self, tags: Iterable[Tag]) -> bool:\n        \"\"\"Return whether the wheel is compatible with one of the given tags.\n\n        :param tags: the PEP 425 tags to check the wheel against.\n        \"\"\"\n        return not self.file_tags.isdisjoint(tags)\n"
  },
  {
    "path": "src/pip/_internal/network/__init__.py",
    "content": "\"\"\"Contains purely network-related utilities.\"\"\"\n"
  },
  {
    "path": "src/pip/_internal/network/auth.py",
    "content": "\"\"\"Network Authentication Helpers\n\nContains interface (MultiDomainBasicAuth) and associated glue code for\nproviding credentials in the context of network requests.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport sysconfig\nimport typing\nimport urllib.parse\nfrom abc import ABC, abstractmethod\nfrom functools import cache\nfrom os.path import commonprefix\nfrom pathlib import Path\nfrom typing import Any, NamedTuple\n\nfrom pip._vendor.requests.auth import AuthBase, HTTPBasicAuth\nfrom pip._vendor.requests.utils import get_netrc_auth\n\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import (\n    ask,\n    ask_input,\n    ask_password,\n    remove_auth_from_url,\n    split_auth_netloc_from_url,\n)\nfrom pip._internal.vcs.versioncontrol import AuthInfo\n\nif typing.TYPE_CHECKING:\n    from pip._vendor.requests import PreparedRequest\n    from pip._vendor.requests.models import Response\n\nlogger = getLogger(__name__)\n\nKEYRING_DISABLED = False\n\n\nclass Credentials(NamedTuple):\n    url: str\n    username: str\n    password: str\n\n\nclass KeyRingBaseProvider(ABC):\n    \"\"\"Keyring base provider interface\"\"\"\n\n    has_keyring: bool\n\n    @abstractmethod\n    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None: ...\n\n    @abstractmethod\n    def save_auth_info(self, url: str, username: str, password: str) -> None: ...\n\n\nclass KeyRingNullProvider(KeyRingBaseProvider):\n    \"\"\"Keyring null provider\"\"\"\n\n    has_keyring = False\n\n    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:\n        return None\n\n    def save_auth_info(self, url: str, username: str, password: str) -> None:\n        return None\n\n\nclass KeyRingPythonProvider(KeyRingBaseProvider):\n    \"\"\"Keyring interface which uses locally imported `keyring`\"\"\"\n\n    has_keyring = True\n\n    def __init__(self) -> None:\n        import keyring\n\n        self.keyring = keyring\n\n    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:\n        # Support keyring's get_credential interface which supports getting\n        # credentials without a username. This is only available for\n        # keyring>=15.2.0.\n        if hasattr(self.keyring, \"get_credential\"):\n            logger.debug(\"Getting credentials from keyring for %s\", url)\n            cred = self.keyring.get_credential(url, username)\n            if cred is not None:\n                return cred.username, cred.password\n            return None\n\n        if username is not None:\n            logger.debug(\"Getting password from keyring for %s\", url)\n            password = self.keyring.get_password(url, username)\n            if password:\n                return username, password\n        return None\n\n    def save_auth_info(self, url: str, username: str, password: str) -> None:\n        self.keyring.set_password(url, username, password)\n\n\nclass KeyRingCliProvider(KeyRingBaseProvider):\n    \"\"\"Provider which uses `keyring` cli\n\n    Instead of calling the keyring package installed alongside pip\n    we call keyring on the command line which will enable pip to\n    use which ever installation of keyring is available first in\n    PATH.\n    \"\"\"\n\n    has_keyring = True\n\n    def __init__(self, cmd: str) -> None:\n        self.keyring = cmd\n\n    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:\n        # This is the default implementation of keyring.get_credential\n        # https://github.com/jaraco/keyring/blob/97689324abcf01bd1793d49063e7ca01e03d7d07/keyring/backend.py#L134-L139\n        if username is not None:\n            password = self._get_password(url, username)\n            if password is not None:\n                return username, password\n        return None\n\n    def save_auth_info(self, url: str, username: str, password: str) -> None:\n        return self._set_password(url, username, password)\n\n    def _get_password(self, service_name: str, username: str) -> str | None:\n        \"\"\"Mirror the implementation of keyring.get_password using cli\"\"\"\n        if self.keyring is None:\n            return None\n\n        cmd = [self.keyring, \"get\", service_name, username]\n        env = os.environ.copy()\n        env[\"PYTHONIOENCODING\"] = \"utf-8\"\n        res = subprocess.run(\n            cmd,\n            stdin=subprocess.DEVNULL,\n            stdout=subprocess.PIPE,\n            env=env,\n        )\n        if res.returncode:\n            return None\n        return res.stdout.decode(\"utf-8\").strip(os.linesep)\n\n    def _set_password(self, service_name: str, username: str, password: str) -> None:\n        \"\"\"Mirror the implementation of keyring.set_password using cli\"\"\"\n        if self.keyring is None:\n            return None\n        env = os.environ.copy()\n        env[\"PYTHONIOENCODING\"] = \"utf-8\"\n        subprocess.run(\n            [self.keyring, \"set\", service_name, username],\n            input=f\"{password}{os.linesep}\".encode(),\n            env=env,\n            check=True,\n        )\n        return None\n\n\n@cache\ndef get_keyring_provider(provider: str) -> KeyRingBaseProvider:\n    logger.verbose(\"Keyring provider requested: %s\", provider)\n\n    # keyring has previously failed and been disabled\n    if KEYRING_DISABLED:\n        provider = \"disabled\"\n    if provider in [\"import\", \"auto\"]:\n        try:\n            impl = KeyRingPythonProvider()\n            logger.verbose(\"Keyring provider set: import\")\n            return impl\n        except ImportError:\n            pass\n        except Exception as exc:\n            # In the event of an unexpected exception\n            # we should warn the user\n            msg = \"Installed copy of keyring fails with exception %s\"\n            if provider == \"auto\":\n                msg = msg + \", trying to find a keyring executable as a fallback\"\n            logger.warning(msg, exc, exc_info=logger.isEnabledFor(logging.DEBUG))\n    if provider in [\"subprocess\", \"auto\"]:\n        cli = shutil.which(\"keyring\")\n        if cli and cli.startswith(sysconfig.get_path(\"scripts\")):\n            # all code within this function is stolen from shutil.which implementation\n            @typing.no_type_check\n            def PATH_as_shutil_which_determines_it() -> str:\n                path = os.environ.get(\"PATH\", None)\n                if path is None:\n                    try:\n                        path = os.confstr(\"CS_PATH\")\n                    except (AttributeError, ValueError):\n                        # os.confstr() or CS_PATH is not available\n                        path = os.defpath\n                # bpo-35755: Don't use os.defpath if the PATH environment variable is\n                # set to an empty string\n\n                return path\n\n            scripts = Path(sysconfig.get_path(\"scripts\"))\n\n            paths = []\n            for path in PATH_as_shutil_which_determines_it().split(os.pathsep):\n                p = Path(path)\n                try:\n                    if not p.samefile(scripts):\n                        paths.append(path)\n                except FileNotFoundError:\n                    pass\n\n            path = os.pathsep.join(paths)\n\n            cli = shutil.which(\"keyring\", path=path)\n\n        if cli:\n            logger.verbose(\"Keyring provider set: subprocess with executable %s\", cli)\n            return KeyRingCliProvider(cli)\n\n    logger.verbose(\"Keyring provider set: disabled\")\n    return KeyRingNullProvider()\n\n\nclass MultiDomainBasicAuth(AuthBase):\n    def __init__(\n        self,\n        prompting: bool = True,\n        index_urls: list[str] | None = None,\n        keyring_provider: str = \"auto\",\n    ) -> None:\n        self.prompting = prompting\n        self.index_urls = index_urls\n        self.keyring_provider = keyring_provider\n        self.passwords: dict[str, AuthInfo] = {}\n        # When the user is prompted to enter credentials and keyring is\n        # available, we will offer to save them. If the user accepts,\n        # this value is set to the credentials they entered. After the\n        # request authenticates, the caller should call\n        # ``save_credentials`` to save these.\n        self._credentials_to_save: Credentials | None = None\n\n    @property\n    def keyring_provider(self) -> KeyRingBaseProvider:\n        return get_keyring_provider(self._keyring_provider)\n\n    @keyring_provider.setter\n    def keyring_provider(self, provider: str) -> None:\n        # The free function get_keyring_provider has been decorated with\n        # functools.cache. If an exception occurs in get_keyring_auth that\n        # cache will be cleared and keyring disabled, take that into account\n        # if you want to remove this indirection.\n        self._keyring_provider = provider\n\n    @property\n    def use_keyring(self) -> bool:\n        # We won't use keyring when --no-input is passed unless\n        # a specific provider is requested because it might require\n        # user interaction\n        return self.prompting or self._keyring_provider not in [\"auto\", \"disabled\"]\n\n    def _get_keyring_auth(\n        self,\n        url: str | None,\n        username: str | None,\n    ) -> AuthInfo | None:\n        \"\"\"Return the tuple auth for a given url from keyring.\"\"\"\n        # Do nothing if no url was provided\n        if not url:\n            return None\n\n        try:\n            return self.keyring_provider.get_auth_info(url, username)\n        except Exception as exc:\n            # Log the full exception (with stacktrace) at debug, so it'll only\n            # show up when running in verbose mode.\n            logger.debug(\"Keyring is skipped due to an exception\", exc_info=True)\n            # Always log a shortened version of the exception.\n            logger.warning(\n                \"Keyring is skipped due to an exception: %s\",\n                str(exc),\n            )\n            global KEYRING_DISABLED\n            KEYRING_DISABLED = True\n            get_keyring_provider.cache_clear()\n            return None\n\n    def _get_index_url(self, url: str) -> str | None:\n        \"\"\"Return the original index URL matching the requested URL.\n\n        Cached or dynamically generated credentials may work against\n        the original index URL rather than just the netloc.\n\n        The provided url should have had its username and password\n        removed already. If the original index url had credentials then\n        they will be included in the return value.\n\n        Returns None if no matching index was found, or if --no-index\n        was specified by the user.\n        \"\"\"\n        if not url or not self.index_urls:\n            return None\n\n        url = remove_auth_from_url(url).rstrip(\"/\") + \"/\"\n        parsed_url = urllib.parse.urlsplit(url)\n\n        candidates = []\n\n        for index in self.index_urls:\n            index = index.rstrip(\"/\") + \"/\"\n            parsed_index = urllib.parse.urlsplit(remove_auth_from_url(index))\n            if parsed_url == parsed_index:\n                return index\n\n            if parsed_url.netloc != parsed_index.netloc:\n                continue\n\n            candidate = urllib.parse.urlsplit(index)\n            candidates.append(candidate)\n\n        if not candidates:\n            return None\n\n        candidates.sort(\n            reverse=True,\n            key=lambda candidate: commonprefix(\n                [\n                    parsed_url.path,\n                    candidate.path,\n                ]\n            ).rfind(\"/\"),\n        )\n\n        return urllib.parse.urlunsplit(candidates[0])\n\n    def _get_new_credentials(\n        self,\n        original_url: str,\n        *,\n        allow_netrc: bool = True,\n        allow_keyring: bool = False,\n    ) -> AuthInfo:\n        \"\"\"Find and return credentials for the specified URL.\"\"\"\n        # Split the credentials and netloc from the url.\n        url, netloc, url_user_password = split_auth_netloc_from_url(\n            original_url,\n        )\n\n        # Start with the credentials embedded in the url\n        username, password = url_user_password\n        if username is not None and password is not None:\n            logger.debug(\"Found credentials in url for %s\", netloc)\n            return url_user_password\n\n        # Find a matching index url for this request\n        index_url = self._get_index_url(url)\n        if index_url:\n            # Split the credentials from the url.\n            index_info = split_auth_netloc_from_url(index_url)\n            if index_info:\n                index_url, _, index_url_user_password = index_info\n                logger.debug(\"Found index url %s\", index_url)\n\n        # If an index URL was found, try its embedded credentials\n        if index_url and index_url_user_password[0] is not None:\n            username, password = index_url_user_password\n            if username is not None and password is not None:\n                logger.debug(\"Found credentials in index url for %s\", netloc)\n                return index_url_user_password\n\n        # Get creds from netrc if we still don't have them\n        if allow_netrc:\n            netrc_auth = get_netrc_auth(original_url)\n            if netrc_auth:\n                logger.debug(\"Found credentials in netrc for %s\", netloc)\n                return netrc_auth\n\n        # If we don't have a password and keyring is available, use it.\n        if allow_keyring:\n            # The index url is more specific than the netloc, so try it first\n            # fmt: off\n            kr_auth = (\n                self._get_keyring_auth(index_url, username) or\n                self._get_keyring_auth(netloc, username)\n            )\n            # fmt: on\n            if kr_auth:\n                logger.debug(\"Found credentials in keyring for %s\", netloc)\n                return kr_auth\n\n        return username, password\n\n    def _get_url_and_credentials(\n        self, original_url: str\n    ) -> tuple[str, str | None, str | None]:\n        \"\"\"Return the credentials to use for the provided URL.\n\n        If allowed, netrc and keyring may be used to obtain the\n        correct credentials.\n\n        Returns (url_without_credentials, username, password). Note\n        that even if the original URL contains credentials, this\n        function may return a different username and password.\n        \"\"\"\n        url, netloc, _ = split_auth_netloc_from_url(original_url)\n\n        # Try to get credentials from original url\n        username, password = self._get_new_credentials(original_url)\n\n        # If credentials not found, use any stored credentials for this netloc.\n        # Do this if either the username or the password is missing.\n        # This accounts for the situation in which the user has specified\n        # the username in the index url, but the password comes from keyring.\n        if (username is None or password is None) and netloc in self.passwords:\n            un, pw = self.passwords[netloc]\n            # It is possible that the cached credentials are for a different username,\n            # in which case the cache should be ignored.\n            if username is None or username == un:\n                username, password = un, pw\n\n        if username is not None or password is not None:\n            # Convert the username and password if they're None, so that\n            # this netloc will show up as \"cached\" in the conditional above.\n            # Further, HTTPBasicAuth doesn't accept None, so it makes sense to\n            # cache the value that is going to be used.\n            username = username or \"\"\n            password = password or \"\"\n\n            # Store any acquired credentials.\n            self.passwords[netloc] = (username, password)\n\n        assert (\n            # Credentials were found\n            (username is not None and password is not None)\n            # Credentials were not found\n            or (username is None and password is None)\n        ), f\"Could not load credentials from url: {original_url}\"\n\n        return url, username, password\n\n    def __call__(self, req: PreparedRequest) -> PreparedRequest:\n        # Get credentials for this request\n        assert req.url is not None\n        url, username, password = self._get_url_and_credentials(req.url)\n\n        # Set the url of the request to the url without any credentials\n        req.url = url\n\n        if username is not None and password is not None:\n            # Send the basic auth with this request\n            req = HTTPBasicAuth(username, password)(req)\n\n        # Attach a hook to handle 401 responses\n        req.register_hook(\"response\", self.handle_401)\n\n        return req\n\n    # Factored out to allow for easy patching in tests\n    def _prompt_for_password(self, netloc: str) -> tuple[str | None, str | None, bool]:\n        username = ask_input(f\"User for {netloc}: \") if self.prompting else None\n        if not username:\n            return None, None, False\n        if self.use_keyring:\n            auth = self._get_keyring_auth(netloc, username)\n            if auth and auth[0] is not None and auth[1] is not None:\n                return auth[0], auth[1], False\n        password = ask_password(\"Password: \")\n        return username, password, True\n\n    # Factored out to allow for easy patching in tests\n    def _should_save_password_to_keyring(self) -> bool:\n        if (\n            not self.prompting\n            or not self.use_keyring\n            or not self.keyring_provider.has_keyring\n        ):\n            return False\n        return ask(\"Save credentials to keyring [y/N]: \", [\"y\", \"n\"]) == \"y\"\n\n    def handle_401(self, resp: Response, **kwargs: Any) -> Response:\n        # We only care about 401 responses, anything else we want to just\n        #   pass through the actual response\n        if resp.status_code != 401:\n            return resp\n\n        username, password = None, None\n\n        # Query the keyring for credentials:\n        if self.use_keyring:\n            username, password = self._get_new_credentials(\n                resp.url,\n                allow_netrc=False,\n                allow_keyring=True,\n            )\n\n        # We are not able to prompt the user so simply return the response\n        if not self.prompting and not username and not password:\n            return resp\n\n        parsed = urllib.parse.urlparse(resp.url)\n\n        # Prompt the user for a new username and password\n        save = False\n        if not username and not password:\n            username, password, save = self._prompt_for_password(parsed.netloc)\n\n        # Store the new username and password to use for future requests\n        self._credentials_to_save = None\n        if username is not None and password is not None:\n            self.passwords[parsed.netloc] = (username, password)\n\n            # Prompt to save the password to keyring\n            if save and self._should_save_password_to_keyring():\n                self._credentials_to_save = Credentials(\n                    url=parsed.netloc,\n                    username=username,\n                    password=password,\n                )\n\n        # Consume content and release the original connection to allow our new\n        #   request to reuse the same one.\n        # The result of the assignment isn't used, it's just needed to consume\n        # the content.\n        _ = resp.content\n        resp.raw.release_conn()\n\n        # Add our new username and password to the request\n        req = HTTPBasicAuth(username or \"\", password or \"\")(resp.request)\n        req.register_hook(\"response\", self.warn_on_401)\n\n        # On successful request, save the credentials that were used to\n        # keyring. (Note that if the user responded \"no\" above, this member\n        # is not set and nothing will be saved.)\n        if self._credentials_to_save:\n            req.register_hook(\"response\", self.save_credentials)\n\n        # Send our new request\n        new_resp = resp.connection.send(req, **kwargs)\n        new_resp.history.append(resp)\n\n        return new_resp\n\n    def warn_on_401(self, resp: Response, **kwargs: Any) -> None:\n        \"\"\"Response callback to warn about incorrect credentials.\"\"\"\n        if resp.status_code == 401:\n            logger.warning(\n                \"401 Error, Credentials not correct for %s\",\n                resp.request.url,\n            )\n\n    def save_credentials(self, resp: Response, **kwargs: Any) -> None:\n        \"\"\"Response callback to save credentials on success.\"\"\"\n        assert (\n            self.keyring_provider.has_keyring\n        ), \"should never reach here without keyring\"\n\n        creds = self._credentials_to_save\n        self._credentials_to_save = None\n        if creds and resp.status_code < 400:\n            try:\n                logger.info(\"Saving credentials to keyring\")\n                self.keyring_provider.save_auth_info(\n                    creds.url, creds.username, creds.password\n                )\n            except Exception:\n                logger.exception(\"Failed to save credentials\")\n"
  },
  {
    "path": "src/pip/_internal/network/cache.py",
    "content": "\"\"\"HTTP cache implementation.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport shutil\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom datetime import datetime\nfrom typing import Any, BinaryIO, Callable\n\nfrom pip._vendor.cachecontrol.cache import SeparateBodyBaseCache\nfrom pip._vendor.cachecontrol.caches import SeparateBodyFileCache\nfrom pip._vendor.requests.models import Response\n\nfrom pip._internal.utils.filesystem import (\n    adjacent_tmp_file,\n    copy_directory_permissions,\n    replace,\n)\nfrom pip._internal.utils.misc import ensure_dir\n\n\ndef is_from_cache(response: Response) -> bool:\n    return getattr(response, \"from_cache\", False)\n\n\n@contextmanager\ndef suppressed_cache_errors() -> Generator[None, None, None]:\n    \"\"\"If we can't access the cache then we can just skip caching and process\n    requests as if caching wasn't enabled.\n    \"\"\"\n    try:\n        yield\n    except OSError:\n        pass\n\n\nclass SafeFileCache(SeparateBodyBaseCache):\n    \"\"\"\n    A file based cache which is safe to use even when the target directory may\n    not be accessible or writable.\n\n    There is a race condition when two processes try to write and/or read the\n    same entry at the same time, since each entry consists of two separate\n    files (https://github.com/psf/cachecontrol/issues/324).  We therefore have\n    additional logic that makes sure that both files to be present before\n    returning an entry; this fixes the read side of the race condition.\n\n    For the write side, we assume that the server will only ever return the\n    same data for the same URL, which ought to be the case for files pip is\n    downloading.  PyPI does not have a mechanism to swap out a wheel for\n    another wheel, for example.  If this assumption is not true, the\n    CacheControl issue will need to be fixed.\n    \"\"\"\n\n    def __init__(self, directory: str) -> None:\n        assert directory is not None, \"Cache directory must not be None.\"\n        super().__init__()\n        self.directory = directory\n\n    def _get_cache_path(self, name: str) -> str:\n        # From cachecontrol.caches.file_cache.FileCache._fn, brought into our\n        # class for backwards-compatibility and to avoid using a non-public\n        # method.\n        hashed = SeparateBodyFileCache.encode(name)\n        parts = list(hashed[:5]) + [hashed]\n        return os.path.join(self.directory, *parts)\n\n    def get(self, key: str) -> bytes | None:\n        # The cache entry is only valid if both metadata and body exist.\n        metadata_path = self._get_cache_path(key)\n        body_path = metadata_path + \".body\"\n        if not (os.path.exists(metadata_path) and os.path.exists(body_path)):\n            return None\n        with suppressed_cache_errors():\n            with open(metadata_path, \"rb\") as f:\n                return f.read()\n\n    def _write_to_file(self, path: str, writer_func: Callable[[BinaryIO], Any]) -> None:\n        \"\"\"Common file writing logic with proper permissions and atomic replacement.\"\"\"\n        with suppressed_cache_errors():\n            ensure_dir(os.path.dirname(path))\n\n            with adjacent_tmp_file(path) as f:\n                writer_func(f)\n                # Inherit the read/write permissions of the cache directory\n                # to enable multi-user cache use-cases.\n                copy_directory_permissions(self.directory, f)\n\n            replace(f.name, path)\n\n    def _write(self, path: str, data: bytes) -> None:\n        self._write_to_file(path, lambda f: f.write(data))\n\n    def _write_from_io(self, path: str, source_file: BinaryIO) -> None:\n        self._write_to_file(path, lambda f: shutil.copyfileobj(source_file, f))\n\n    def set(\n        self, key: str, value: bytes, expires: int | datetime | None = None\n    ) -> None:\n        path = self._get_cache_path(key)\n        self._write(path, value)\n\n    def delete(self, key: str) -> None:\n        path = self._get_cache_path(key)\n        with suppressed_cache_errors():\n            os.remove(path)\n        with suppressed_cache_errors():\n            os.remove(path + \".body\")\n\n    def get_body(self, key: str) -> BinaryIO | None:\n        # The cache entry is only valid if both metadata and body exist.\n        metadata_path = self._get_cache_path(key)\n        body_path = metadata_path + \".body\"\n        if not (os.path.exists(metadata_path) and os.path.exists(body_path)):\n            return None\n        with suppressed_cache_errors():\n            return open(body_path, \"rb\")\n\n    def set_body(self, key: str, body: bytes) -> None:\n        path = self._get_cache_path(key) + \".body\"\n        self._write(path, body)\n\n    def set_body_from_io(self, key: str, body_file: BinaryIO) -> None:\n        \"\"\"Set the body of the cache entry from a file object.\"\"\"\n        path = self._get_cache_path(key) + \".body\"\n        self._write_from_io(path, body_file)\n"
  },
  {
    "path": "src/pip/_internal/network/download.py",
    "content": "\"\"\"Download files with progress indicators.\"\"\"\n\nfrom __future__ import annotations\n\nimport email.message\nimport logging\nimport mimetypes\nimport os\nfrom collections.abc import Iterable, Mapping\nfrom dataclasses import dataclass\nfrom http import HTTPStatus\nfrom typing import BinaryIO\n\nfrom pip._vendor.requests import PreparedRequest\nfrom pip._vendor.requests.models import Response\nfrom pip._vendor.urllib3 import HTTPResponse as URLlib3Response\nfrom pip._vendor.urllib3._collections import HTTPHeaderDict\nfrom pip._vendor.urllib3.exceptions import ReadTimeoutError\n\nfrom pip._internal.cli.progress_bars import BarType, get_download_progress_renderer\nfrom pip._internal.exceptions import IncompleteDownloadError, NetworkConnectionError\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.cache import SafeFileCache, is_from_cache\nfrom pip._internal.network.session import CacheControlAdapter, PipSession\nfrom pip._internal.network.utils import HEADERS, raise_for_status, response_chunks\nfrom pip._internal.utils.misc import format_size, redact_auth_from_url, splitext\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_http_response_size(resp: Response) -> int | None:\n    try:\n        return int(resp.headers[\"content-length\"])\n    except (ValueError, KeyError, TypeError):\n        return None\n\n\ndef _get_http_response_etag_or_last_modified(resp: Response) -> str | None:\n    \"\"\"\n    Return either the ETag or Last-Modified header (or None if neither exists).\n    The return value can be used in an If-Range header.\n    \"\"\"\n    return resp.headers.get(\"etag\", resp.headers.get(\"last-modified\"))\n\n\ndef _log_download(\n    resp: Response,\n    link: Link,\n    progress_bar: BarType,\n    total_length: int | None,\n    range_start: int | None = 0,\n) -> Iterable[bytes]:\n    if link.netloc == PyPI.file_storage_domain:\n        url = link.show_url\n    else:\n        url = link.url_without_fragment\n\n    logged_url = redact_auth_from_url(url)\n\n    if total_length:\n        if range_start:\n            logged_url = (\n                f\"{logged_url} ({format_size(range_start)}/{format_size(total_length)})\"\n            )\n        else:\n            logged_url = f\"{logged_url} ({format_size(total_length)})\"\n\n    if is_from_cache(resp):\n        logger.info(\"Using cached %s\", logged_url)\n    elif range_start:\n        logger.info(\"Resuming download %s\", logged_url)\n    else:\n        logger.info(\"Downloading %s\", logged_url)\n\n    if logger.getEffectiveLevel() > logging.INFO:\n        show_progress = False\n    elif is_from_cache(resp):\n        show_progress = False\n    elif not total_length:\n        show_progress = True\n    elif total_length > (512 * 1024):\n        show_progress = True\n    else:\n        show_progress = False\n\n    chunks = response_chunks(resp)\n\n    if not show_progress:\n        return chunks\n\n    renderer = get_download_progress_renderer(\n        bar_type=progress_bar, size=total_length, initial_progress=range_start\n    )\n    return renderer(chunks)\n\n\ndef sanitize_content_filename(filename: str) -> str:\n    \"\"\"\n    Sanitize the \"filename\" value from a Content-Disposition header.\n    \"\"\"\n    return os.path.basename(filename)\n\n\ndef parse_content_disposition(content_disposition: str, default_filename: str) -> str:\n    \"\"\"\n    Parse the \"filename\" value from a Content-Disposition header, and\n    return the default filename if the result is empty.\n    \"\"\"\n    m = email.message.Message()\n    m[\"content-type\"] = content_disposition\n    filename = m.get_param(\"filename\")\n    if filename:\n        # We need to sanitize the filename to prevent directory traversal\n        # in case the filename contains \"..\" path parts.\n        filename = sanitize_content_filename(str(filename))\n    return filename or default_filename\n\n\ndef _get_http_response_filename(resp: Response, link: Link) -> str:\n    \"\"\"Get an ideal filename from the given HTTP response, falling back to\n    the link filename if not provided.\n    \"\"\"\n    filename = link.filename  # fallback\n    # Have a look at the Content-Disposition header for a better guess\n    content_disposition = resp.headers.get(\"content-disposition\")\n    if content_disposition:\n        filename = parse_content_disposition(content_disposition, filename)\n    ext: str | None = splitext(filename)[1]\n    if not ext:\n        ext = mimetypes.guess_extension(resp.headers.get(\"content-type\", \"\"))\n        if ext:\n            filename += ext\n    if not ext and link.url != resp.url:\n        ext = os.path.splitext(resp.url)[1]\n        if ext:\n            filename += ext\n    return filename\n\n\n@dataclass\nclass _FileDownload:\n    \"\"\"Stores the state of a single link download.\"\"\"\n\n    link: Link\n    output_file: BinaryIO\n    size: int | None\n    bytes_received: int = 0\n    reattempts: int = 0\n\n    def is_incomplete(self) -> bool:\n        return bool(self.size is not None and self.bytes_received < self.size)\n\n    def write_chunk(self, data: bytes) -> None:\n        self.bytes_received += len(data)\n        self.output_file.write(data)\n\n    def reset_file(self) -> None:\n        \"\"\"Delete any saved data and reset progress to zero.\"\"\"\n        self.output_file.seek(0)\n        self.output_file.truncate()\n        self.bytes_received = 0\n\n\nclass Downloader:\n    def __init__(\n        self,\n        session: PipSession,\n        progress_bar: BarType,\n    ) -> None:\n        self._session = session\n        self._progress_bar = progress_bar\n        self._resume_retries = session.resume_retries\n        assert (\n            self._resume_retries >= 0\n        ), \"Number of max resume retries must be bigger or equal to zero\"\n\n    def batch(\n        self, links: Iterable[Link], location: str\n    ) -> Iterable[tuple[Link, tuple[str, str]]]:\n        \"\"\"Convenience method to download multiple links.\"\"\"\n        for link in links:\n            filepath, content_type = self(link, location)\n            yield link, (filepath, content_type)\n\n    def __call__(self, link: Link, location: str) -> tuple[str, str]:\n        \"\"\"Download a link and save it under location.\"\"\"\n        resp = self._http_get(link)\n        download_size = _get_http_response_size(resp)\n\n        filepath = os.path.join(location, _get_http_response_filename(resp, link))\n        with open(filepath, \"wb\") as content_file:\n            download = _FileDownload(link, content_file, download_size)\n            self._process_response(download, resp)\n            if download.is_incomplete():\n                self._attempt_resumes_or_redownloads(download, resp)\n\n        content_type = resp.headers.get(\"Content-Type\", \"\")\n        return filepath, content_type\n\n    def _process_response(self, download: _FileDownload, resp: Response) -> None:\n        \"\"\"Download and save chunks from a response.\"\"\"\n        chunks = _log_download(\n            resp,\n            download.link,\n            self._progress_bar,\n            download.size,\n            range_start=download.bytes_received,\n        )\n        try:\n            for chunk in chunks:\n                download.write_chunk(chunk)\n        except ReadTimeoutError as e:\n            # If the download size is not known, then give up downloading the file.\n            if download.size is None:\n                raise e\n\n            logger.warning(\"Connection timed out while downloading.\")\n\n    def _attempt_resumes_or_redownloads(\n        self, download: _FileDownload, first_resp: Response\n    ) -> None:\n        \"\"\"Attempt to resume/restart the download if connection was dropped.\"\"\"\n\n        while download.reattempts < self._resume_retries and download.is_incomplete():\n            assert download.size is not None\n            download.reattempts += 1\n            logger.warning(\n                \"Attempting to resume incomplete download (%s/%s, attempt %d)\",\n                format_size(download.bytes_received),\n                format_size(download.size),\n                download.reattempts,\n            )\n\n            try:\n                resume_resp = self._http_get_resume(download, should_match=first_resp)\n                # Fallback: if the server responded with 200 (i.e., the file has\n                # since been modified or range requests are unsupported) or any\n                # other unexpected status, restart the download from the beginning.\n                must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT\n                if must_restart:\n                    download.reset_file()\n                    download.size = _get_http_response_size(resume_resp)\n                    first_resp = resume_resp\n\n                self._process_response(download, resume_resp)\n            except (ConnectionError, ReadTimeoutError, OSError):\n                continue\n\n        # No more resume attempts. Raise an error if the download is still incomplete.\n        if download.is_incomplete():\n            os.remove(download.output_file.name)\n            raise IncompleteDownloadError(download)\n\n        # If we successfully completed the download via resume, manually cache it\n        # as a complete response to enable future caching\n        if download.reattempts > 0:\n            self._cache_resumed_download(download, first_resp)\n\n    def _cache_resumed_download(\n        self, download: _FileDownload, original_response: Response\n    ) -> None:\n        \"\"\"\n        Manually cache a file that was successfully downloaded via resume retries.\n\n        cachecontrol doesn't cache 206 (Partial Content) responses, since they\n        are not complete files. This method manually adds the final file to the\n        cache as though it was downloaded in a single request, so that future\n        requests can use the cache.\n        \"\"\"\n        url = download.link.url_without_fragment\n        adapter = self._session.get_adapter(url)\n\n        # Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)\n        if not isinstance(adapter, CacheControlAdapter):\n            logger.debug(\n                \"Skipping resume download caching: no cache controller for %s\", url\n            )\n            return\n\n        # Check SafeFileCache is being used\n        assert isinstance(\n            adapter.cache, SafeFileCache\n        ), \"separate body cache not in use!\"\n\n        synthetic_request = PreparedRequest()\n        synthetic_request.prepare(method=\"GET\", url=url, headers={})\n\n        synthetic_response_headers = HTTPHeaderDict()\n        for key, value in original_response.headers.items():\n            if key.lower() not in [\"content-range\", \"content-length\"]:\n                synthetic_response_headers[key] = value\n        synthetic_response_headers[\"content-length\"] = str(download.size)\n\n        synthetic_response = URLlib3Response(\n            body=\"\",\n            headers=synthetic_response_headers,\n            status=200,\n            preload_content=False,\n        )\n\n        # Save metadata and then stream the file contents to cache.\n        cache_url = adapter.controller.cache_url(url)\n        metadata_blob = adapter.controller.serializer.dumps(\n            synthetic_request, synthetic_response, b\"\"\n        )\n        adapter.cache.set(cache_url, metadata_blob)\n        download.output_file.flush()\n        with open(download.output_file.name, \"rb\") as f:\n            adapter.cache.set_body_from_io(cache_url, f)\n\n        logger.debug(\n            \"Cached resumed download as complete response for future use: %s\", url\n        )\n\n    def _http_get_resume(\n        self, download: _FileDownload, should_match: Response\n    ) -> Response:\n        \"\"\"Issue a HTTP range request to resume the download.\"\"\"\n        # To better understand the download resumption logic, see the mdn web docs:\n        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests\n        headers = HEADERS.copy()\n        headers[\"Range\"] = f\"bytes={download.bytes_received}-\"\n        # If possible, use a conditional range request to avoid corrupted\n        # downloads caused by the remote file changing in-between.\n        if identifier := _get_http_response_etag_or_last_modified(should_match):\n            headers[\"If-Range\"] = identifier\n        return self._http_get(download.link, headers)\n\n    def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:\n        target_url = link.url_without_fragment\n        try:\n            resp = self._session.get(target_url, headers=headers, stream=True)\n            raise_for_status(resp)\n        except NetworkConnectionError as e:\n            assert e.response is not None\n            logger.critical(\n                \"HTTP error %s while getting %s\", e.response.status_code, link\n            )\n            raise\n        return resp\n"
  },
  {
    "path": "src/pip/_internal/network/lazy_wheel.py",
    "content": "\"\"\"Lazy ZIP over HTTP\"\"\"\n\nfrom __future__ import annotations\n\n__all__ = [\"HTTPRangeRequestUnsupported\", \"dist_from_wheel_url\"]\n\nfrom bisect import bisect_left, bisect_right\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom tempfile import NamedTemporaryFile\nfrom typing import Any\nfrom zipfile import BadZipFile, ZipFile\n\nfrom pip._vendor.packaging.utils import NormalizedName\nfrom pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response\n\nfrom pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import HEADERS, raise_for_status, response_chunks\n\n\nclass HTTPRangeRequestUnsupported(Exception):\n    pass\n\n\ndef dist_from_wheel_url(\n    name: NormalizedName, url: str, session: PipSession\n) -> BaseDistribution:\n    \"\"\"Return a distribution object from the given wheel URL.\n\n    This uses HTTP range requests to only fetch the portion of the wheel\n    containing metadata, just enough for the object to be constructed.\n    If such requests are not supported, HTTPRangeRequestUnsupported\n    is raised.\n    \"\"\"\n    with LazyZipOverHTTP(url, session) as zf:\n        # For read-only ZIP files, ZipFile only needs methods read,\n        # seek, seekable and tell, not the whole IO protocol.\n        wheel = MemoryWheel(zf.name, zf)  # type: ignore\n        # After context manager exit, wheel.name\n        # is an invalid file by intention.\n        return get_wheel_distribution(wheel, name)\n\n\nclass LazyZipOverHTTP:\n    \"\"\"File-like object mapped to a ZIP file over HTTP.\n\n    This uses HTTP range requests to lazily fetch the file's content,\n    which is supposed to be fed to ZipFile.  If such requests are not\n    supported by the server, raise HTTPRangeRequestUnsupported\n    during initialization.\n    \"\"\"\n\n    def __init__(\n        self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE\n    ) -> None:\n        head = session.head(url, headers=HEADERS)\n        raise_for_status(head)\n        assert head.status_code == 200\n        self._session, self._url, self._chunk_size = session, url, chunk_size\n        self._length = int(head.headers[\"Content-Length\"])\n        self._file = NamedTemporaryFile()\n        self.truncate(self._length)\n        self._left: list[int] = []\n        self._right: list[int] = []\n        if \"bytes\" not in head.headers.get(\"Accept-Ranges\", \"none\"):\n            raise HTTPRangeRequestUnsupported(\"range request is not supported\")\n        self._check_zip()\n\n    @property\n    def mode(self) -> str:\n        \"\"\"Opening mode, which is always rb.\"\"\"\n        return \"rb\"\n\n    @property\n    def name(self) -> str:\n        \"\"\"Path to the underlying file.\"\"\"\n        return self._file.name\n\n    def seekable(self) -> bool:\n        \"\"\"Return whether random access is supported, which is True.\"\"\"\n        return True\n\n    def close(self) -> None:\n        \"\"\"Close the file.\"\"\"\n        self._file.close()\n\n    @property\n    def closed(self) -> bool:\n        \"\"\"Whether the file is closed.\"\"\"\n        return self._file.closed\n\n    def read(self, size: int = -1) -> bytes:\n        \"\"\"Read up to size bytes from the object and return them.\n\n        As a convenience, if size is unspecified or -1,\n        all bytes until EOF are returned.  Fewer than\n        size bytes may be returned if EOF is reached.\n        \"\"\"\n        download_size = max(size, self._chunk_size)\n        start, length = self.tell(), self._length\n        stop = length if size < 0 else min(start + download_size, length)\n        start = max(0, stop - download_size)\n        self._download(start, stop - 1)\n        return self._file.read(size)\n\n    def readable(self) -> bool:\n        \"\"\"Return whether the file is readable, which is True.\"\"\"\n        return True\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        \"\"\"Change stream position and return the new absolute position.\n\n        Seek to offset relative position indicated by whence:\n        * 0: Start of stream (the default).  pos should be >= 0;\n        * 1: Current position - pos may be negative;\n        * 2: End of stream - pos usually negative.\n        \"\"\"\n        return self._file.seek(offset, whence)\n\n    def tell(self) -> int:\n        \"\"\"Return the current position.\"\"\"\n        return self._file.tell()\n\n    def truncate(self, size: int | None = None) -> int:\n        \"\"\"Resize the stream to the given size in bytes.\n\n        If size is unspecified resize to the current position.\n        The current stream position isn't changed.\n\n        Return the new file size.\n        \"\"\"\n        return self._file.truncate(size)\n\n    def writable(self) -> bool:\n        \"\"\"Return False.\"\"\"\n        return False\n\n    def __enter__(self) -> LazyZipOverHTTP:\n        self._file.__enter__()\n        return self\n\n    def __exit__(self, *exc: Any) -> None:\n        self._file.__exit__(*exc)\n\n    @contextmanager\n    def _stay(self) -> Generator[None, None, None]:\n        \"\"\"Return a context manager keeping the position.\n\n        At the end of the block, seek back to original position.\n        \"\"\"\n        pos = self.tell()\n        try:\n            yield\n        finally:\n            self.seek(pos)\n\n    def _check_zip(self) -> None:\n        \"\"\"Check and download until the file is a valid ZIP.\"\"\"\n        end = self._length - 1\n        for start in reversed(range(0, end, self._chunk_size)):\n            self._download(start, end)\n            with self._stay():\n                try:\n                    # For read-only ZIP files, ZipFile only needs\n                    # methods read, seek, seekable and tell.\n                    ZipFile(self)\n                except BadZipFile:\n                    pass\n                else:\n                    break\n\n    def _stream_response(\n        self, start: int, end: int, base_headers: dict[str, str] = HEADERS\n    ) -> Response:\n        \"\"\"Return HTTP response to a range request from start to end.\"\"\"\n        headers = base_headers.copy()\n        headers[\"Range\"] = f\"bytes={start}-{end}\"\n        # TODO: Get range requests to be correctly cached\n        headers[\"Cache-Control\"] = \"no-cache\"\n        return self._session.get(self._url, headers=headers, stream=True)\n\n    def _merge(\n        self, start: int, end: int, left: int, right: int\n    ) -> Generator[tuple[int, int], None, None]:\n        \"\"\"Return a generator of intervals to be fetched.\n\n        Args:\n            start (int): Start of needed interval\n            end (int): End of needed interval\n            left (int): Index of first overlapping downloaded data\n            right (int): Index after last overlapping downloaded data\n        \"\"\"\n        lslice, rslice = self._left[left:right], self._right[left:right]\n        i = start = min([start] + lslice[:1])\n        end = max([end] + rslice[-1:])\n        for j, k in zip(lslice, rslice):\n            if j > i:\n                yield i, j - 1\n            i = k + 1\n        if i <= end:\n            yield i, end\n        self._left[left:right], self._right[left:right] = [start], [end]\n\n    def _download(self, start: int, end: int) -> None:\n        \"\"\"Download bytes from start to end inclusively.\"\"\"\n        with self._stay():\n            left = bisect_left(self._right, start)\n            right = bisect_right(self._left, end)\n            for start, end in self._merge(start, end, left, right):\n                response = self._stream_response(start, end)\n                response.raise_for_status()\n                self.seek(start)\n                for chunk in response_chunks(response, self._chunk_size):\n                    self._file.write(chunk)\n"
  },
  {
    "path": "src/pip/_internal/network/session.py",
    "content": "\"\"\"PipSession and supporting code, containing all pip-specific\nnetwork request configuration and behavior.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport email.utils\nimport functools\nimport io\nimport ipaddress\nimport json\nimport logging\nimport mimetypes\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport urllib.parse\nimport warnings\nfrom collections.abc import Generator, Mapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Optional,\n    Union,\n)\n\nfrom pip._vendor import requests, urllib3\nfrom pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter\nfrom pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter\nfrom pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter\nfrom pip._vendor.requests.models import PreparedRequest, Response\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\nfrom pip._vendor.urllib3.connectionpool import ConnectionPool\nfrom pip._vendor.urllib3.exceptions import InsecureRequestWarning\n\nfrom pip import __version__\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.auth import MultiDomainBasicAuth\nfrom pip._internal.network.cache import SafeFileCache\n\n# Import ssl from compat so the initial import occurs in only one place.\nfrom pip._internal.utils.compat import has_tls\nfrom pip._internal.utils.glibc import libc_ver\nfrom pip._internal.utils.misc import build_url_from_netloc, parse_netloc\nfrom pip._internal.utils.urls import url_to_path\n\nif TYPE_CHECKING:\n    from ssl import SSLContext\n\n    from pip._vendor.urllib3 import ProxyManager\n    from pip._vendor.urllib3.poolmanager import PoolManager\n\n\nlogger = logging.getLogger(__name__)\n\nSecureOrigin = tuple[str, str, Optional[Union[int, str]]]\n\n\n# Ignore warning raised when using --trusted-host.\nwarnings.filterwarnings(\"ignore\", category=InsecureRequestWarning)\n\n\nSECURE_ORIGINS: list[SecureOrigin] = [\n    # protocol, hostname, port\n    # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)\n    (\"https\", \"*\", \"*\"),\n    (\"*\", \"localhost\", \"*\"),\n    (\"*\", \"127.0.0.0/8\", \"*\"),\n    (\"*\", \"::1/128\", \"*\"),\n    (\"file\", \"*\", None),\n    # ssh is always secure.\n    (\"ssh\", \"*\", \"*\"),\n]\n\n\n# These are environment variables present when running under various\n# CI systems.  For each variable, some CI systems that use the variable\n# are indicated.  The collection was chosen so that for each of a number\n# of popular systems, at least one of the environment variables is used.\n# This list is used to provide some indication of and lower bound for\n# CI traffic to PyPI.  Thus, it is okay if the list is not comprehensive.\n# For more background, see: https://github.com/pypa/pip/issues/5499\nCI_ENVIRONMENT_VARIABLES = (\n    # Azure Pipelines\n    \"BUILD_BUILDID\",\n    # Jenkins\n    \"BUILD_ID\",\n    # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI\n    \"CI\",\n    # Explicit environment variable.\n    \"PIP_IS_CI\",\n)\n\n\ndef looks_like_ci() -> bool:\n    \"\"\"\n    Return whether it looks like pip is running under CI.\n    \"\"\"\n    # We don't use the method of checking for a tty (e.g. using isatty())\n    # because some CI systems mimic a tty (e.g. Travis CI).  Thus that\n    # method doesn't provide definitive information in either direction.\n    return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)\n\n\n@functools.lru_cache(maxsize=1)\ndef user_agent() -> str:\n    \"\"\"\n    Return a string representing the user agent.\n    \"\"\"\n    data: dict[str, Any] = {\n        \"installer\": {\"name\": \"pip\", \"version\": __version__},\n        \"python\": platform.python_version(),\n        \"implementation\": {\n            \"name\": platform.python_implementation(),\n        },\n    }\n\n    if data[\"implementation\"][\"name\"] == \"CPython\":\n        data[\"implementation\"][\"version\"] = platform.python_version()\n    elif data[\"implementation\"][\"name\"] == \"PyPy\":\n        pypy_version_info = sys.pypy_version_info  # type: ignore\n        if pypy_version_info.releaselevel == \"final\":\n            pypy_version_info = pypy_version_info[:3]\n        data[\"implementation\"][\"version\"] = \".\".join(\n            [str(x) for x in pypy_version_info]\n        )\n    elif data[\"implementation\"][\"name\"] == \"Jython\":\n        # Complete Guess\n        data[\"implementation\"][\"version\"] = platform.python_version()\n    elif data[\"implementation\"][\"name\"] == \"IronPython\":\n        # Complete Guess\n        data[\"implementation\"][\"version\"] = platform.python_version()\n\n    if sys.platform.startswith(\"linux\"):\n        from pip._vendor import distro\n\n        linux_distribution = distro.name(), distro.version(), distro.codename()\n        distro_infos: dict[str, Any] = dict(\n            filter(\n                lambda x: x[1],\n                zip([\"name\", \"version\", \"id\"], linux_distribution),\n            )\n        )\n        libc = dict(\n            filter(\n                lambda x: x[1],\n                zip([\"lib\", \"version\"], libc_ver()),\n            )\n        )\n        if libc:\n            distro_infos[\"libc\"] = libc\n        if distro_infos:\n            data[\"distro\"] = distro_infos\n\n    if sys.platform.startswith(\"darwin\") and platform.mac_ver()[0]:\n        data[\"distro\"] = {\"name\": \"macOS\", \"version\": platform.mac_ver()[0]}\n\n    if platform.system():\n        data.setdefault(\"system\", {})[\"name\"] = platform.system()\n\n    if platform.release():\n        data.setdefault(\"system\", {})[\"release\"] = platform.release()\n\n    if platform.machine():\n        data[\"cpu\"] = platform.machine()\n\n    if has_tls():\n        import _ssl as ssl\n\n        data[\"openssl_version\"] = ssl.OPENSSL_VERSION\n\n    setuptools_dist = get_default_environment().get_distribution(\"setuptools\")\n    if setuptools_dist is not None:\n        data[\"setuptools_version\"] = str(setuptools_dist.version)\n\n    if shutil.which(\"rustc\") is not None:\n        # If for any reason `rustc --version` fails, silently ignore it\n        try:\n            rustc_output = subprocess.check_output(\n                [\"rustc\", \"--version\"], stderr=subprocess.STDOUT, timeout=0.5\n            )\n        except Exception:\n            pass\n        else:\n            if rustc_output.startswith(b\"rustc \"):\n                # The format of `rustc --version` is:\n                # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\\n'`\n                # We extract just the middle (1.52.1) part\n                data[\"rustc_version\"] = rustc_output.split(b\" \")[1].decode()\n\n    # Use None rather than False so as not to give the impression that\n    # pip knows it is not being run under CI.  Rather, it is a null or\n    # inconclusive result.  Also, we include some value rather than no\n    # value to make it easier to know that the check has been run.\n    data[\"ci\"] = True if looks_like_ci() else None\n\n    user_data = os.environ.get(\"PIP_USER_AGENT_USER_DATA\")\n    if user_data is not None:\n        data[\"user_data\"] = user_data\n\n    return \"{data[installer][name]}/{data[installer][version]} {json}\".format(\n        data=data,\n        json=json.dumps(data, separators=(\",\", \":\"), sort_keys=True),\n    )\n\n\nclass LocalFSAdapter(BaseAdapter):\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: float | tuple[float, float] | tuple[float, None] | None = None,\n        verify: bool | str = True,\n        cert: bytes | str | tuple[bytes | str, bytes | str] | None = None,\n        proxies: Mapping[str, str] | None = None,\n    ) -> Response:\n        assert request.url is not None\n        pathname = url_to_path(request.url)\n\n        resp = Response()\n        resp.status_code = 200\n        resp.url = request.url\n\n        try:\n            stats = os.stat(pathname)\n        except OSError as exc:\n            # format the exception raised as a io.BytesIO object,\n            # to return a better error message:\n            resp.status_code = 404\n            resp.reason = type(exc).__name__\n            resp.raw = io.BytesIO(f\"{resp.reason}: {exc}\".encode())\n        else:\n            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)\n            content_type = mimetypes.guess_type(pathname)[0] or \"text/plain\"\n            resp.headers = CaseInsensitiveDict(\n                {\n                    \"Content-Type\": content_type,\n                    \"Content-Length\": str(stats.st_size),\n                    \"Last-Modified\": modified,\n                }\n            )\n\n            resp.raw = open(pathname, \"rb\")\n            resp.close = resp.raw.close  # type: ignore[method-assign]\n\n        return resp\n\n    def close(self) -> None:\n        pass\n\n\nclass _SSLContextAdapterMixin:\n    \"\"\"Mixin to add the ``ssl_context`` constructor argument to HTTP adapters.\n\n    The additional argument is forwarded directly to the pool manager. This allows us\n    to dynamically decide what SSL store to use at runtime, which is used to implement\n    the optional ``truststore`` backend.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        ssl_context: SSLContext | None = None,\n        **kwargs: Any,\n    ) -> None:\n        self._ssl_context = ssl_context\n        super().__init__(**kwargs)\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> PoolManager:\n        if self._ssl_context is not None:\n            pool_kwargs.setdefault(\"ssl_context\", self._ssl_context)\n        return super().init_poolmanager(  # type: ignore[misc, no-any-return]\n            connections=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> ProxyManager:\n        # Proxy manager replaces the pool manager, so inject our SSL\n        # context here too. https://github.com/pypa/pip/issues/13288\n        if self._ssl_context is not None:\n            proxy_kwargs.setdefault(\"ssl_context\", self._ssl_context)\n        return super().proxy_manager_for(proxy, **proxy_kwargs)  # type: ignore[misc, no-any-return]\n\n\nclass HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter):\n    pass\n\n\nclass CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter):\n    pass\n\n\nclass InsecureHTTPAdapter(HTTPAdapter):\n    def cert_verify(\n        self,\n        conn: ConnectionPool,\n        url: str,\n        verify: bool | str,\n        cert: str | tuple[str, str] | None,\n    ) -> None:\n        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)\n\n\nclass InsecureCacheControlAdapter(CacheControlAdapter):\n    def cert_verify(\n        self,\n        conn: ConnectionPool,\n        url: str,\n        verify: bool | str,\n        cert: str | tuple[str, str] | None,\n    ) -> None:\n        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)\n\n\nclass PipSession(requests.Session):\n    timeout: int | None = None\n\n    def __init__(\n        self,\n        *args: Any,\n        retries: int = 0,\n        resume_retries: int = 0,\n        cache: str | None = None,\n        trusted_hosts: Sequence[str] = (),\n        index_urls: list[str] | None = None,\n        ssl_context: SSLContext | None = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"\n        :param trusted_hosts: Domains not to emit warnings for when not using\n            HTTPS.\n        \"\"\"\n        super().__init__(*args, **kwargs)\n\n        # Namespace the attribute with \"pip_\" just in case to prevent\n        # possible conflicts with the base class.\n        self.pip_trusted_origins: list[tuple[str, int | None]] = []\n        self.pip_proxy = None\n\n        # Attach our User Agent to the request\n        self.headers[\"User-Agent\"] = user_agent()\n\n        # Attach our Authentication handler to the session\n        self.auth: MultiDomainBasicAuth = MultiDomainBasicAuth(index_urls=index_urls)\n\n        # Create our urllib3.Retry instance which will allow us to customize\n        # how we handle retries.\n        retries = urllib3.Retry(\n            # Set the total number of retries that a particular request can\n            # have.\n            total=retries,\n            # A 503 error from PyPI typically means that the Fastly -> Origin\n            # connection got interrupted in some way. A 503 error in general\n            # is typically considered a transient error so we'll go ahead and\n            # retry it.\n            # A 500 may indicate transient error in Amazon S3\n            # A 502 may be a transient error from a CDN like CloudFlare or CloudFront\n            # A 520 or 527 - may indicate transient error in CloudFlare\n            status_forcelist=[500, 502, 503, 520, 527],\n            # Add a small amount of back off between failed requests in\n            # order to prevent hammering the service.\n            backoff_factor=0.25,\n        )  # type: ignore\n        self.resume_retries = resume_retries\n\n        # Our Insecure HTTPAdapter disables HTTPS validation. It does not\n        # support caching so we'll use it for all http:// URLs.\n        # If caching is disabled, we will also use it for\n        # https:// hosts that we've marked as ignoring\n        # TLS errors for (trusted-hosts).\n        insecure_adapter = InsecureHTTPAdapter(max_retries=retries)\n\n        # We want to _only_ cache responses on securely fetched origins or when\n        # the host is specified as trusted. We do this because\n        # we can't validate the response of an insecurely/untrusted fetched\n        # origin, and we don't want someone to be able to poison the cache and\n        # require manual eviction from the cache to fix it.\n        self._trusted_host_adapter: InsecureCacheControlAdapter | InsecureHTTPAdapter\n        if cache:\n            secure_adapter: _BaseHTTPAdapter = CacheControlAdapter(\n                cache=SafeFileCache(cache),\n                max_retries=retries,\n                ssl_context=ssl_context,\n            )\n            self._trusted_host_adapter = InsecureCacheControlAdapter(\n                cache=SafeFileCache(cache),\n                max_retries=retries,\n            )\n        else:\n            secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context)\n            self._trusted_host_adapter = insecure_adapter\n\n        self.mount(\"https://\", secure_adapter)\n        self.mount(\"http://\", insecure_adapter)\n\n        # Enable file:// urls\n        self.mount(\"file://\", LocalFSAdapter())\n\n        for host in trusted_hosts:\n            self.add_trusted_host(host, suppress_logging=True)\n\n    def update_index_urls(self, new_index_urls: list[str]) -> None:\n        \"\"\"\n        :param new_index_urls: New index urls to update the authentication\n            handler with.\n        \"\"\"\n        self.auth.index_urls = new_index_urls\n\n    def add_trusted_host(\n        self, host: str, source: str | None = None, suppress_logging: bool = False\n    ) -> None:\n        \"\"\"\n        :param host: It is okay to provide a host that has previously been\n            added.\n        :param source: An optional source string, for logging where the host\n            string came from.\n        \"\"\"\n        if not suppress_logging:\n            msg = f\"adding trusted host: {host!r}\"\n            if source is not None:\n                msg += f\" (from {source})\"\n            logger.info(msg)\n\n        parsed_host, parsed_port = parse_netloc(host)\n        if parsed_host is None:\n            raise ValueError(f\"Trusted host URL must include a host part: {host!r}\")\n        if (parsed_host, parsed_port) not in self.pip_trusted_origins:\n            self.pip_trusted_origins.append((parsed_host, parsed_port))\n\n        self.mount(\n            build_url_from_netloc(host, scheme=\"http\") + \"/\", self._trusted_host_adapter\n        )\n        self.mount(build_url_from_netloc(host) + \"/\", self._trusted_host_adapter)\n        if not parsed_port:\n            self.mount(\n                build_url_from_netloc(host, scheme=\"http\") + \":\",\n                self._trusted_host_adapter,\n            )\n            # Mount wildcard ports for the same host.\n            self.mount(build_url_from_netloc(host) + \":\", self._trusted_host_adapter)\n\n    def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:\n        yield from SECURE_ORIGINS\n        for host, port in self.pip_trusted_origins:\n            yield (\"*\", host, \"*\" if port is None else port)\n\n    def is_secure_origin(self, location: Link) -> bool:\n        # Determine if this url used a secure transport mechanism\n        parsed = urllib.parse.urlparse(str(location))\n        origin_protocol, origin_host, origin_port = (\n            parsed.scheme,\n            parsed.hostname,\n            parsed.port,\n        )\n\n        # The protocol to use to see if the protocol matches.\n        # Don't count the repository type as part of the protocol: in\n        # cases such as \"git+ssh\", only use \"ssh\". (I.e., Only verify against\n        # the last scheme.)\n        origin_protocol = origin_protocol.rsplit(\"+\", 1)[-1]\n\n        # Determine if our origin is a secure origin by looking through our\n        # hardcoded list of secure origins, as well as any additional ones\n        # configured on this PackageFinder instance.\n        for secure_origin in self.iter_secure_origins():\n            secure_protocol, secure_host, secure_port = secure_origin\n            if origin_protocol != secure_protocol and secure_protocol != \"*\":\n                continue\n\n            try:\n                addr = ipaddress.ip_address(origin_host or \"\")\n                network = ipaddress.ip_network(secure_host)\n            except ValueError:\n                # We don't have both a valid address or a valid network, so\n                # we'll check this origin against hostnames.\n                if (\n                    origin_host\n                    and origin_host.lower() != secure_host.lower()\n                    and secure_host != \"*\"\n                ):\n                    continue\n            else:\n                # We have a valid address and network, so see if the address\n                # is contained within the network.\n                if addr not in network:\n                    continue\n\n            # Check to see if the port matches.\n            if (\n                origin_port != secure_port\n                and secure_port != \"*\"\n                and secure_port is not None\n            ):\n                continue\n\n            # If we've gotten here, then this origin matches the current\n            # secure origin and we should return True\n            return True\n\n        # If we've gotten to this point, then the origin isn't secure and we\n        # will not accept it as a valid location to search. We will however\n        # log a warning that we are ignoring it.\n        logger.warning(\n            \"The repository located at %s is not a trusted or secure host and \"\n            \"is being ignored. If this repository is available via HTTPS we \"\n            \"recommend you use HTTPS instead, otherwise you may silence \"\n            \"this warning and allow it anyway with '--trusted-host %s'.\",\n            origin_host,\n            origin_host,\n        )\n\n        return False\n\n    def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:  # type: ignore[override]\n        # Allow setting a default timeout on a session\n        kwargs.setdefault(\"timeout\", self.timeout)\n        # Allow setting a default proxies on a session\n        kwargs.setdefault(\"proxies\", self.proxies)\n\n        # Dispatch the actual request\n        return super().request(method, url, *args, **kwargs)\n"
  },
  {
    "path": "src/pip/_internal/network/utils.py",
    "content": "from collections.abc import Generator\n\nfrom pip._vendor.requests.models import Response\n\nfrom pip._internal.exceptions import NetworkConnectionError\n\n# The following comments and HTTP headers were originally added by\n# Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.\n#\n# We use Accept-Encoding: identity here because requests defaults to\n# accepting compressed responses. This breaks in a variety of ways\n# depending on how the server is configured.\n# - Some servers will notice that the file isn't a compressible file\n#   and will leave the file alone and with an empty Content-Encoding\n# - Some servers will notice that the file is already compressed and\n#   will leave the file alone, adding a Content-Encoding: gzip header\n# - Some servers won't notice anything at all and will take a file\n#   that's already been compressed and compress it again, and set\n#   the Content-Encoding: gzip header\n# By setting this to request only the identity encoding we're hoping\n# to eliminate the third case.  Hopefully there does not exist a server\n# which when given a file will notice it is already compressed and that\n# you're not asking for a compressed file and will then decompress it\n# before sending because if that's the case I don't think it'll ever be\n# possible to make this work.\nHEADERS: dict[str, str] = {\"Accept-Encoding\": \"identity\"}\n\nDOWNLOAD_CHUNK_SIZE = 256 * 1024\n\n\ndef raise_for_status(resp: Response) -> None:\n    http_error_msg = \"\"\n    if isinstance(resp.reason, bytes):\n        # We attempt to decode utf-8 first because some servers\n        # choose to localize their reason strings. If the string\n        # isn't utf-8, we fall back to iso-8859-1 for all other\n        # encodings.\n        try:\n            reason = resp.reason.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            reason = resp.reason.decode(\"iso-8859-1\")\n    else:\n        reason = resp.reason\n\n    if 400 <= resp.status_code < 500:\n        http_error_msg = (\n            f\"{resp.status_code} Client Error: {reason} for url: {resp.url}\"\n        )\n\n    elif 500 <= resp.status_code < 600:\n        http_error_msg = (\n            f\"{resp.status_code} Server Error: {reason} for url: {resp.url}\"\n        )\n\n    if http_error_msg:\n        raise NetworkConnectionError(http_error_msg, response=resp)\n\n\ndef response_chunks(\n    response: Response, chunk_size: int = DOWNLOAD_CHUNK_SIZE\n) -> Generator[bytes, None, None]:\n    \"\"\"Given a requests Response, provide the data chunks.\"\"\"\n    try:\n        # Special case for urllib3.\n        for chunk in response.raw.stream(\n            chunk_size,\n            # We use decode_content=False here because we don't\n            # want urllib3 to mess with the raw bytes we get\n            # from the server. If we decompress inside of\n            # urllib3 then we cannot verify the checksum\n            # because the checksum will be of the compressed\n            # file. This breakage will only occur if the\n            # server adds a Content-Encoding header, which\n            # depends on how the server was configured:\n            # - Some servers will notice that the file isn't a\n            #   compressible file and will leave the file alone\n            #   and with an empty Content-Encoding\n            # - Some servers will notice that the file is\n            #   already compressed and will leave the file\n            #   alone and will add a Content-Encoding: gzip\n            #   header\n            # - Some servers won't notice anything at all and\n            #   will take a file that's already been compressed\n            #   and compress it again and set the\n            #   Content-Encoding: gzip header\n            #\n            # By setting this not to decode automatically we\n            # hope to eliminate problems with the second case.\n            decode_content=False,\n        ):\n            yield chunk\n    except AttributeError:\n        # Standard file-like object.\n        while True:\n            chunk = response.raw.read(chunk_size)\n            if not chunk:\n                break\n            yield chunk\n"
  },
  {
    "path": "src/pip/_internal/network/xmlrpc.py",
    "content": "\"\"\"xmlrpclib.Transport implementation\"\"\"\n\nimport logging\nimport urllib.parse\nimport xmlrpc.client\nfrom typing import TYPE_CHECKING\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import raise_for_status\n\nif TYPE_CHECKING:\n    from xmlrpc.client import _HostType, _Marshallable\n\n    from _typeshed import SizedBuffer\n\nlogger = logging.getLogger(__name__)\n\n\nclass PipXmlrpcTransport(xmlrpc.client.Transport):\n    \"\"\"Provide a `xmlrpclib.Transport` implementation via a `PipSession`\n    object.\n    \"\"\"\n\n    def __init__(\n        self, index_url: str, session: PipSession, use_datetime: bool = False\n    ) -> None:\n        super().__init__(use_datetime)\n        index_parts = urllib.parse.urlparse(index_url)\n        self._scheme = index_parts.scheme\n        self._session = session\n\n    def request(\n        self,\n        host: \"_HostType\",\n        handler: str,\n        request_body: \"SizedBuffer\",\n        verbose: bool = False,\n    ) -> tuple[\"_Marshallable\", ...]:\n        assert isinstance(host, str)\n        parts = (self._scheme, host, handler, None, None, None)\n        url = urllib.parse.urlunparse(parts)\n        try:\n            headers = {\"Content-Type\": \"text/xml\"}\n            response = self._session.post(\n                url,\n                data=request_body,\n                headers=headers,\n                stream=True,\n            )\n            raise_for_status(response)\n            self.verbose = verbose\n            return self.parse_response(response.raw)\n        except NetworkConnectionError as exc:\n            assert exc.response\n            logger.critical(\n                \"HTTP error %s while getting %s\",\n                exc.response.status_code,\n                url,\n            )\n            raise\n"
  },
  {
    "path": "src/pip/_internal/operations/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/operations/build/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/operations/build/build_tracker.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport hashlib\nimport logging\nimport os\nfrom collections.abc import Generator\nfrom types import TracebackType\n\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\n@contextlib.contextmanager\ndef update_env_context_manager(**changes: str) -> Generator[None, None, None]:\n    target = os.environ\n\n    # Save values from the target and change them.\n    non_existent_marker = object()\n    saved_values: dict[str, object | str] = {}\n    for name, new_value in changes.items():\n        try:\n            saved_values[name] = target[name]\n        except KeyError:\n            saved_values[name] = non_existent_marker\n        target[name] = new_value\n\n    try:\n        yield\n    finally:\n        # Restore original values in the target.\n        for name, original_value in saved_values.items():\n            if original_value is non_existent_marker:\n                del target[name]\n            else:\n                assert isinstance(original_value, str)  # for mypy\n                target[name] = original_value\n\n\n@contextlib.contextmanager\ndef get_build_tracker() -> Generator[BuildTracker, None, None]:\n    root = os.environ.get(\"PIP_BUILD_TRACKER\")\n    with contextlib.ExitStack() as ctx:\n        if root is None:\n            root = ctx.enter_context(TempDirectory(kind=\"build-tracker\")).path\n            ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root))\n            logger.debug(\"Initialized build tracking at %s\", root)\n\n        with BuildTracker(root) as tracker:\n            yield tracker\n\n\nclass TrackerId(str):\n    \"\"\"Uniquely identifying string provided to the build tracker.\"\"\"\n\n\nclass BuildTracker:\n    \"\"\"Ensure that an sdist cannot request itself as a setup requirement.\n\n    When an sdist is prepared, it identifies its setup requirements in the\n    context of ``BuildTracker.track()``. If a requirement shows up recursively, this\n    raises an exception.\n\n    This stops fork bombs embedded in malicious packages.\"\"\"\n\n    def __init__(self, root: str) -> None:\n        self._root = root\n        self._entries: dict[TrackerId, InstallRequirement] = {}\n        logger.debug(\"Created build tracker: %s\", self._root)\n\n    def __enter__(self) -> BuildTracker:\n        logger.debug(\"Entered build tracker: %s\", self._root)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        self.cleanup()\n\n    def _entry_path(self, key: TrackerId) -> str:\n        hashed = hashlib.sha224(key.encode()).hexdigest()\n        return os.path.join(self._root, hashed)\n\n    def add(self, req: InstallRequirement, key: TrackerId) -> None:\n        \"\"\"Add an InstallRequirement to build tracking.\"\"\"\n\n        # Get the file to write information about this requirement.\n        entry_path = self._entry_path(key)\n\n        # Try reading from the file. If it exists and can be read from, a build\n        # is already in progress, so a LookupError is raised.\n        try:\n            with open(entry_path) as fp:\n                contents = fp.read()\n        except FileNotFoundError:\n            pass\n        else:\n            message = f\"{req.link} is already being built: {contents}\"\n            raise LookupError(message)\n\n        # If we're here, req should really not be building already.\n        assert key not in self._entries\n\n        # Start tracking this requirement.\n        with open(entry_path, \"w\", encoding=\"utf-8\") as fp:\n            fp.write(str(req))\n        self._entries[key] = req\n\n        logger.debug(\"Added %s to build tracker %r\", req, self._root)\n\n    def remove(self, req: InstallRequirement, key: TrackerId) -> None:\n        \"\"\"Remove an InstallRequirement from build tracking.\"\"\"\n\n        # Delete the created file and the corresponding entry.\n        os.unlink(self._entry_path(key))\n        del self._entries[key]\n\n        logger.debug(\"Removed %s from build tracker %r\", req, self._root)\n\n    def cleanup(self) -> None:\n        for key, req in list(self._entries.items()):\n            self.remove(req, key)\n\n        logger.debug(\"Removed build tracker: %r\", self._root)\n\n    @contextlib.contextmanager\n    def track(self, req: InstallRequirement, key: str) -> Generator[None, None, None]:\n        \"\"\"Ensure that `key` cannot install itself as a setup requirement.\n\n        :raises LookupError: If `key` was already provided in a parent invocation of\n                             the context introduced by this method.\"\"\"\n        tracker_id = TrackerId(key)\n        self.add(req, tracker_id)\n        yield\n        self.remove(req, tracker_id)\n"
  },
  {
    "path": "src/pip/_internal/operations/build/metadata.py",
    "content": "\"\"\"Metadata generation logic for source distributions.\"\"\"\n\nimport os\n\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.exceptions import (\n    InstallationSubprocessError,\n    MetadataGenerationFailed,\n)\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory\n\n\ndef generate_metadata(\n    build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str\n) -> str:\n    \"\"\"Generate metadata using mechanisms described in PEP 517.\n\n    Returns the generated metadata directory.\n    \"\"\"\n    metadata_tmpdir = TempDirectory(kind=\"modern-metadata\", globally_managed=True)\n\n    metadata_dir = metadata_tmpdir.path\n\n    with build_env:\n        # Note that BuildBackendHookCaller implements a fallback for\n        # prepare_metadata_for_build_wheel, so we don't have to\n        # consider the possibility that this hook doesn't exist.\n        runner = runner_with_spinner_message(\"Preparing metadata (pyproject.toml)\")\n        with backend.subprocess_runner(runner):\n            try:\n                distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)\n            except InstallationSubprocessError as error:\n                raise MetadataGenerationFailed(package_details=details) from error\n\n    return os.path.join(metadata_dir, distinfo_dir)\n"
  },
  {
    "path": "src/pip/_internal/operations/build/metadata_editable.py",
    "content": "\"\"\"Metadata generation logic for source distributions.\"\"\"\n\nimport os\n\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.exceptions import (\n    InstallationSubprocessError,\n    MetadataGenerationFailed,\n)\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory\n\n\ndef generate_editable_metadata(\n    build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str\n) -> str:\n    \"\"\"Generate metadata using mechanisms described in PEP 660.\n\n    Returns the generated metadata directory.\n    \"\"\"\n    metadata_tmpdir = TempDirectory(kind=\"modern-metadata\", globally_managed=True)\n\n    metadata_dir = metadata_tmpdir.path\n\n    with build_env:\n        # Note that BuildBackendHookCaller implements a fallback for\n        # prepare_metadata_for_build_wheel/editable, so we don't have to\n        # consider the possibility that this hook doesn't exist.\n        runner = runner_with_spinner_message(\n            \"Preparing editable metadata (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            try:\n                distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir)\n            except InstallationSubprocessError as error:\n                raise MetadataGenerationFailed(package_details=details) from error\n\n    assert distinfo_dir is not None\n    return os.path.join(metadata_dir, distinfo_dir)\n"
  },
  {
    "path": "src/pip/_internal/operations/build/wheel.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\n\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller\n\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_wheel_pep517(\n    name: str,\n    backend: BuildBackendHookCaller,\n    metadata_directory: str,\n    wheel_directory: str,\n) -> str | None:\n    \"\"\"Build one InstallRequirement using the PEP 517 build process.\n\n    Returns path to wheel if successfully built. Otherwise, returns None.\n    \"\"\"\n    assert metadata_directory is not None\n    try:\n        logger.debug(\"Destination directory: %s\", wheel_directory)\n\n        runner = runner_with_spinner_message(\n            f\"Building wheel for {name} (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            wheel_name = backend.build_wheel(\n                wheel_directory=wheel_directory,\n                metadata_directory=metadata_directory,\n            )\n    except Exception:\n        logger.error(\"Failed building wheel for %s\", name)\n        return None\n    return os.path.join(wheel_directory, wheel_name)\n"
  },
  {
    "path": "src/pip/_internal/operations/build/wheel_editable.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\n\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller, HookMissing\n\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_wheel_editable(\n    name: str,\n    backend: BuildBackendHookCaller,\n    metadata_directory: str,\n    wheel_directory: str,\n) -> str | None:\n    \"\"\"Build one InstallRequirement using the PEP 660 build process.\n\n    Returns path to wheel if successfully built. Otherwise, returns None.\n    \"\"\"\n    assert metadata_directory is not None\n    try:\n        logger.debug(\"Destination directory: %s\", wheel_directory)\n\n        runner = runner_with_spinner_message(\n            f\"Building editable for {name} (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            try:\n                wheel_name = backend.build_editable(\n                    wheel_directory=wheel_directory,\n                    metadata_directory=metadata_directory,\n                )\n            except HookMissing as e:\n                logger.error(\n                    \"Cannot build editable %s because the build \"\n                    \"backend does not have the %s hook\",\n                    name,\n                    e,\n                )\n                return None\n    except Exception:\n        logger.error(\"Failed building editable for %s\", name)\n        return None\n    return os.path.join(wheel_directory, wheel_name)\n"
  },
  {
    "path": "src/pip/_internal/operations/check.py",
    "content": "\"\"\"Validation of dependencies of packages\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nfrom collections.abc import Generator, Iterable\nfrom contextlib import suppress\nfrom email.parser import Parser\nfrom functools import reduce\nfrom typing import (\n    Callable,\n    NamedTuple,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.tags import Tag, parse_tag\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.distributions import make_distribution_for_install_requirement\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.metadata.base import BaseDistribution\nfrom pip._internal.req.req_install import InstallRequirement\n\nlogger = logging.getLogger(__name__)\n\n\nclass PackageDetails(NamedTuple):\n    version: Version\n    dependencies: list[Requirement]\n\n\n# Shorthands\nPackageSet = dict[NormalizedName, PackageDetails]\nMissing = tuple[NormalizedName, Requirement]\nConflicting = tuple[NormalizedName, Version, Requirement]\n\nMissingDict = dict[NormalizedName, list[Missing]]\nConflictingDict = dict[NormalizedName, list[Conflicting]]\nCheckResult = tuple[MissingDict, ConflictingDict]\nConflictDetails = tuple[PackageSet, CheckResult]\n\n\ndef create_package_set_from_installed() -> tuple[PackageSet, bool]:\n    \"\"\"Converts a list of distributions into a PackageSet.\"\"\"\n    package_set = {}\n    problems = False\n    env = get_default_environment()\n    for dist in env.iter_installed_distributions(local_only=False, skip=()):\n        name = dist.canonical_name\n        try:\n            dependencies = list(dist.iter_dependencies())\n            package_set[name] = PackageDetails(dist.version, dependencies)\n        except (OSError, ValueError) as e:\n            # Don't crash on unreadable or broken metadata.\n            logger.warning(\"Error parsing dependencies of %s: %s\", name, e)\n            problems = True\n    return package_set, problems\n\n\ndef check_package_set(\n    package_set: PackageSet, should_ignore: Callable[[str], bool] | None = None\n) -> CheckResult:\n    \"\"\"Check if a package set is consistent\n\n    If should_ignore is passed, it should be a callable that takes a\n    package name and returns a boolean.\n    \"\"\"\n\n    missing = {}\n    conflicting = {}\n\n    for package_name, package_detail in package_set.items():\n        # Info about dependencies of package_name\n        missing_deps: set[Missing] = set()\n        conflicting_deps: set[Conflicting] = set()\n\n        if should_ignore and should_ignore(package_name):\n            continue\n\n        for req in package_detail.dependencies:\n            name = canonicalize_name(req.name)\n\n            # Check if it's missing\n            if name not in package_set:\n                missed = True\n                if req.marker is not None:\n                    missed = req.marker.evaluate({\"extra\": \"\"})\n                if missed:\n                    missing_deps.add((name, req))\n                continue\n\n            # Check if there's a conflict\n            version = package_set[name].version\n            if not req.specifier.contains(version, prereleases=True):\n                conflicting_deps.add((name, version, req))\n\n        if missing_deps:\n            missing[package_name] = sorted(missing_deps, key=str)\n        if conflicting_deps:\n            conflicting[package_name] = sorted(conflicting_deps, key=str)\n\n    return missing, conflicting\n\n\ndef check_install_conflicts(to_install: list[InstallRequirement]) -> ConflictDetails:\n    \"\"\"For checking if the dependency graph would be consistent after \\\n    installing given requirements\n    \"\"\"\n    # Start from the current state\n    package_set, _ = create_package_set_from_installed()\n    # Install packages\n    would_be_installed = _simulate_installation_of(to_install, package_set)\n\n    # Only warn about directly-dependent packages; create a whitelist of them\n    whitelist = _create_whitelist(would_be_installed, package_set)\n\n    return (\n        package_set,\n        check_package_set(\n            package_set, should_ignore=lambda name: name not in whitelist\n        ),\n    )\n\n\ndef check_unsupported(\n    packages: Iterable[BaseDistribution],\n    supported_tags: Iterable[Tag],\n) -> Generator[BaseDistribution, None, None]:\n    for p in packages:\n        with suppress(FileNotFoundError):\n            wheel_file = p.read_text(\"WHEEL\")\n            wheel_tags: frozenset[Tag] = reduce(\n                frozenset.union,\n                map(parse_tag, Parser().parsestr(wheel_file).get_all(\"Tag\", [])),\n                frozenset(),\n            )\n            if wheel_tags.isdisjoint(supported_tags):\n                yield p\n\n\ndef _simulate_installation_of(\n    to_install: list[InstallRequirement], package_set: PackageSet\n) -> set[NormalizedName]:\n    \"\"\"Computes the version of packages after installing to_install.\"\"\"\n    # Keep track of packages that were installed\n    installed = set()\n\n    # Modify it as installing requirement_set would (assuming no errors)\n    for inst_req in to_install:\n        abstract_dist = make_distribution_for_install_requirement(inst_req)\n        dist = abstract_dist.get_metadata_distribution()\n        name = dist.canonical_name\n        package_set[name] = PackageDetails(dist.version, list(dist.iter_dependencies()))\n\n        installed.add(name)\n\n    return installed\n\n\ndef _create_whitelist(\n    would_be_installed: set[NormalizedName], package_set: PackageSet\n) -> set[NormalizedName]:\n    packages_affected = set(would_be_installed)\n\n    for package_name in package_set:\n        if package_name in packages_affected:\n            continue\n\n        for req in package_set[package_name].dependencies:\n            if canonicalize_name(req.name) in packages_affected:\n                packages_affected.add(package_name)\n                break\n\n    return packages_affected\n"
  },
  {
    "path": "src/pip/_internal/operations/freeze.py",
    "content": "from __future__ import annotations\n\nimport collections\nimport logging\nimport os\nfrom collections.abc import Container, Generator, Iterable\nfrom dataclasses import dataclass, field\nfrom typing import NamedTuple\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import InvalidVersion\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n)\nfrom pip._internal.req.req_file import COMMENT_RE\nfrom pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference\n\nlogger = logging.getLogger(__name__)\n\n\nclass _EditableInfo(NamedTuple):\n    requirement: str\n    comments: list[str]\n\n\ndef freeze(\n    requirement: list[str] | None = None,\n    local_only: bool = False,\n    user_only: bool = False,\n    paths: list[str] | None = None,\n    isolated: bool = False,\n    exclude_editable: bool = False,\n    skip: Container[str] = (),\n) -> Generator[str, None, None]:\n    installations: dict[str, FrozenRequirement] = {}\n\n    dists = get_environment(paths).iter_installed_distributions(\n        local_only=local_only,\n        skip=(),\n        user_only=user_only,\n    )\n    for dist in dists:\n        req = FrozenRequirement.from_dist(dist)\n        if exclude_editable and req.editable:\n            continue\n        installations[req.canonical_name] = req\n\n    if requirement:\n        # the options that don't get turned into an InstallRequirement\n        # should only be emitted once, even if the same option is in multiple\n        # requirements files, so we need to keep track of what has been emitted\n        # so that we don't emit it again if it's seen again\n        emitted_options: set[str] = set()\n        # keep track of which files a requirement is in so that we can\n        # give an accurate warning if a requirement appears multiple times.\n        req_files: dict[str, list[str]] = collections.defaultdict(list)\n        for req_file_path in requirement:\n            with open(req_file_path) as req_file:\n                for line in req_file:\n                    if (\n                        not line.strip()\n                        or line.strip().startswith(\"#\")\n                        or line.startswith(\n                            (\n                                \"-r\",\n                                \"--requirement\",\n                                \"-f\",\n                                \"--find-links\",\n                                \"-i\",\n                                \"--index-url\",\n                                \"--pre\",\n                                \"--trusted-host\",\n                                \"--process-dependency-links\",\n                                \"--extra-index-url\",\n                                \"--use-feature\",\n                            )\n                        )\n                    ):\n                        line = line.rstrip()\n                        if line not in emitted_options:\n                            emitted_options.add(line)\n                            yield line\n                        continue\n\n                    if line.startswith((\"-e\", \"--editable\")):\n                        if line.startswith(\"-e\"):\n                            line = line[2:].strip()\n                        else:\n                            line = line[len(\"--editable\") :].strip().lstrip(\"=\")\n                        line_req = install_req_from_editable(\n                            line,\n                            isolated=isolated,\n                        )\n                    else:\n                        line_req = install_req_from_line(\n                            COMMENT_RE.sub(\"\", line).strip(),\n                            isolated=isolated,\n                        )\n\n                    if not line_req.name:\n                        logger.info(\n                            \"Skipping line in requirement file [%s] because \"\n                            \"it's not clear what it would install: %s\",\n                            req_file_path,\n                            line.strip(),\n                        )\n                        logger.info(\n                            \"  (add #egg=PackageName to the URL to avoid\"\n                            \" this warning)\"\n                        )\n                    else:\n                        line_req_canonical_name = canonicalize_name(line_req.name)\n                        if line_req_canonical_name not in installations:\n                            # either it's not installed, or it is installed\n                            # but has been processed already\n                            if not req_files[line_req.name]:\n                                logger.warning(\n                                    \"Requirement file [%s] contains %s, but \"\n                                    \"package %r is not installed\",\n                                    req_file_path,\n                                    COMMENT_RE.sub(\"\", line).strip(),\n                                    line_req.name,\n                                )\n                            else:\n                                req_files[line_req.name].append(req_file_path)\n                        else:\n                            yield str(installations[line_req_canonical_name]).rstrip()\n                            del installations[line_req_canonical_name]\n                            req_files[line_req.name].append(req_file_path)\n\n        # Warn about requirements that were included multiple times (in a\n        # single requirements file or in different requirements files).\n        for name, files in req_files.items():\n            if len(files) > 1:\n                logger.warning(\n                    \"Requirement %s included multiple times [%s]\",\n                    name,\n                    \", \".join(sorted(set(files))),\n                )\n\n        yield (\"## The following requirements were added by pip freeze:\")\n    for installation in sorted(installations.values(), key=lambda x: x.name.lower()):\n        if installation.canonical_name not in skip:\n            yield str(installation).rstrip()\n\n\ndef _format_as_name_version(dist: BaseDistribution) -> str:\n    try:\n        dist_version = dist.version\n    except InvalidVersion:\n        # legacy version\n        return f\"{dist.raw_name}==={dist.raw_version}\"\n    else:\n        return f\"{dist.raw_name}=={dist_version}\"\n\n\ndef _get_editable_info(dist: BaseDistribution) -> _EditableInfo:\n    \"\"\"\n    Compute and return values (req, comments) for use in\n    FrozenRequirement.from_dist().\n    \"\"\"\n    editable_project_location = dist.editable_project_location\n    assert editable_project_location\n    location = os.path.normcase(os.path.abspath(editable_project_location))\n\n    from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs\n\n    vcs_backend = vcs.get_backend_for_dir(location)\n\n    if vcs_backend is None:\n        display = _format_as_name_version(dist)\n        logger.debug(\n            'No VCS found for editable requirement \"%s\" in: %r',\n            display,\n            location,\n        )\n        return _EditableInfo(\n            requirement=location,\n            comments=[f\"# Editable install with no version control ({display})\"],\n        )\n\n    vcs_name = type(vcs_backend).__name__\n\n    try:\n        req = vcs_backend.get_src_requirement(location, dist.raw_name)\n    except RemoteNotFoundError:\n        display = _format_as_name_version(dist)\n        return _EditableInfo(\n            requirement=location,\n            comments=[f\"# Editable {vcs_name} install with no remote ({display})\"],\n        )\n    except RemoteNotValidError as ex:\n        display = _format_as_name_version(dist)\n        return _EditableInfo(\n            requirement=location,\n            comments=[\n                f\"# Editable {vcs_name} install ({display}) with either a deleted \"\n                f\"local remote or invalid URI:\",\n                f\"# '{ex.url}'\",\n            ],\n        )\n    except BadCommand:\n        logger.warning(\n            \"cannot determine version of editable source in %s \"\n            \"(%s command not found in path)\",\n            location,\n            vcs_backend.name,\n        )\n        return _EditableInfo(requirement=location, comments=[])\n    except InstallationError as exc:\n        logger.warning(\"Error when trying to get requirement for VCS system %s\", exc)\n    else:\n        return _EditableInfo(requirement=req, comments=[])\n\n    logger.warning(\"Could not determine repository location of %s\", location)\n\n    return _EditableInfo(\n        requirement=location,\n        comments=[\"## !! Could not determine repository location\"],\n    )\n\n\n@dataclass(frozen=True)\nclass FrozenRequirement:\n    name: str\n    req: str\n    editable: bool\n    comments: Iterable[str] = field(default_factory=tuple)\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        return canonicalize_name(self.name)\n\n    @classmethod\n    def from_dist(cls, dist: BaseDistribution) -> FrozenRequirement:\n        editable = dist.editable\n        if editable:\n            req, comments = _get_editable_info(dist)\n        else:\n            comments = []\n            direct_url = dist.direct_url\n            if direct_url:\n                # if PEP 610 metadata is present, use it\n                req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name)\n            else:\n                # name==version requirement\n                req = _format_as_name_version(dist)\n\n        return cls(dist.raw_name, req, editable, comments=comments)\n\n    def __str__(self) -> str:\n        req = self.req\n        if self.editable:\n            req = f\"-e {req}\"\n        return \"\\n\".join(list(self.comments) + [str(req)]) + \"\\n\"\n"
  },
  {
    "path": "src/pip/_internal/operations/install/__init__.py",
    "content": "\"\"\"For modules related to installing packages.\"\"\"\n"
  },
  {
    "path": "src/pip/_internal/operations/install/wheel.py",
    "content": "\"\"\"Support for installing and building the \"wheel\" binary package format.\"\"\"\n\nfrom __future__ import annotations\n\nimport collections\nimport compileall\nimport contextlib\nimport csv\nimport importlib\nimport logging\nimport os.path\nimport re\nimport shutil\nimport sys\nimport textwrap\nimport warnings\nfrom base64 import urlsafe_b64encode\nfrom collections.abc import Generator, Iterable, Iterator, Sequence\nfrom email.message import Message\nfrom itertools import chain, filterfalse, starmap\nfrom typing import (\n    IO,\n    Any,\n    BinaryIO,\n    Callable,\n    NewType,\n    Protocol,\n    Union,\n    cast,\n)\nfrom zipfile import ZipFile, ZipInfo\n\nfrom pip._vendor.distlib.scripts import ScriptMaker\nfrom pip._vendor.distlib.util import get_export_entry\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.locations import get_major_minor_version\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    FilesystemWheel,\n    get_wheel_distribution,\n)\nfrom pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.filesystem import adjacent_tmp_file, replace\nfrom pip._internal.utils.misc import StreamWrapper, ensure_dir, hash_file, partition\nfrom pip._internal.utils.unpacking import (\n    current_umask,\n    is_within_directory,\n    set_extracted_file_to_default_mode_plus_executable,\n    zip_item_is_executable,\n)\nfrom pip._internal.utils.wheel import parse_wheel\n\n\nclass File(Protocol):\n    src_record_path: RecordPath\n    dest_path: str\n    changed: bool\n\n    def save(self) -> None:\n        pass\n\n\nlogger = logging.getLogger(__name__)\n\nRecordPath = NewType(\"RecordPath\", str)\nInstalledCSVRow = tuple[RecordPath, str, Union[int, str]]\n\n\ndef rehash(path: str, blocksize: int = 1 << 20) -> tuple[str, str]:\n    \"\"\"Return (encoded_digest, length) for path using hashlib.sha256()\"\"\"\n    h, length = hash_file(path, blocksize)\n    digest = \"sha256=\" + urlsafe_b64encode(h.digest()).decode(\"latin1\").rstrip(\"=\")\n    return (digest, str(length))\n\n\ndef csv_io_kwargs(mode: str) -> dict[str, Any]:\n    \"\"\"Return keyword arguments to properly open a CSV file\n    in the given mode.\n    \"\"\"\n    return {\"mode\": mode, \"newline\": \"\", \"encoding\": \"utf-8\"}\n\n\ndef fix_script(path: str) -> bool:\n    \"\"\"Replace #!python with #!/path/to/python\n    Return True if file was changed.\n    \"\"\"\n    # XXX RECORD hashes will need to be updated\n    assert os.path.isfile(path)\n\n    with open(path, \"rb\") as script:\n        firstline = script.readline()\n        if not firstline.startswith(b\"#!python\"):\n            return False\n        exename = sys.executable.encode(sys.getfilesystemencoding())\n        firstline = b\"#!\" + exename + os.linesep.encode(\"ascii\")\n        rest = script.read()\n    with open(path, \"wb\") as script:\n        script.write(firstline)\n        script.write(rest)\n    return True\n\n\ndef wheel_root_is_purelib(metadata: Message) -> bool:\n    return metadata.get(\"Root-Is-Purelib\", \"\").lower() == \"true\"\n\n\ndef get_entrypoints(dist: BaseDistribution) -> tuple[dict[str, str], dict[str, str]]:\n    console_scripts = {}\n    gui_scripts = {}\n    for entry_point in dist.iter_entry_points():\n        if entry_point.group == \"console_scripts\":\n            console_scripts[entry_point.name] = entry_point.value\n        elif entry_point.group == \"gui_scripts\":\n            gui_scripts[entry_point.name] = entry_point.value\n    return console_scripts, gui_scripts\n\n\ndef message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> str | None:\n    \"\"\"Determine if any scripts are not on PATH and format a warning.\n    Returns a warning message if one or more scripts are not on PATH,\n    otherwise None.\n    \"\"\"\n    if not scripts:\n        return None\n\n    # Group scripts by the path they were installed in\n    grouped_by_dir: dict[str, set[str]] = collections.defaultdict(set)\n    for destfile in scripts:\n        parent_dir = os.path.dirname(destfile)\n        script_name = os.path.basename(destfile)\n        grouped_by_dir[parent_dir].add(script_name)\n\n    # We don't want to warn for directories that are on PATH.\n    not_warn_dirs = [\n        os.path.normcase(os.path.normpath(i)).rstrip(os.sep)\n        for i in os.environ.get(\"PATH\", \"\").split(os.pathsep)\n    ]\n    # If an executable sits with sys.executable, we don't warn for it.\n    #     This covers the case of venv invocations without activating the venv.\n    not_warn_dirs.append(\n        os.path.normcase(os.path.normpath(os.path.dirname(sys.executable)))\n    )\n    warn_for: dict[str, set[str]] = {\n        parent_dir: scripts\n        for parent_dir, scripts in grouped_by_dir.items()\n        if os.path.normcase(os.path.normpath(parent_dir)) not in not_warn_dirs\n    }\n    if not warn_for:\n        return None\n\n    # Format a message\n    msg_lines = []\n    for parent_dir, dir_scripts in warn_for.items():\n        sorted_scripts: list[str] = sorted(dir_scripts)\n        if len(sorted_scripts) == 1:\n            start_text = f\"script {sorted_scripts[0]} is\"\n        else:\n            start_text = \"scripts {} are\".format(\n                \", \".join(sorted_scripts[:-1]) + \" and \" + sorted_scripts[-1]\n            )\n\n        msg_lines.append(\n            f\"The {start_text} installed in '{parent_dir}' which is not on PATH.\"\n        )\n\n    last_line_fmt = (\n        \"Consider adding {} to PATH or, if you prefer \"\n        \"to suppress this warning, use --no-warn-script-location.\"\n    )\n    if len(msg_lines) == 1:\n        msg_lines.append(last_line_fmt.format(\"this directory\"))\n    else:\n        msg_lines.append(last_line_fmt.format(\"these directories\"))\n\n    # Add a note if any directory starts with ~\n    warn_for_tilde = any(\n        i[0] == \"~\" for i in os.environ.get(\"PATH\", \"\").split(os.pathsep) if i\n    )\n    if warn_for_tilde:\n        tilde_warning_msg = (\n            \"NOTE: The current PATH contains path(s) starting with `~`, \"\n            \"which may not be expanded by all applications.\"\n        )\n        msg_lines.append(tilde_warning_msg)\n\n    # Returns the formatted multiline message\n    return \"\\n\".join(msg_lines)\n\n\ndef _normalized_outrows(\n    outrows: Iterable[InstalledCSVRow],\n) -> list[tuple[str, str, str]]:\n    \"\"\"Normalize the given rows of a RECORD file.\n\n    Items in each row are converted into str. Rows are then sorted to make\n    the value more predictable for tests.\n\n    Each row is a 3-tuple (path, hash, size) and corresponds to a record of\n    a RECORD file (see PEP 376 and PEP 427 for details).  For the rows\n    passed to this function, the size can be an integer as an int or string,\n    or the empty string.\n    \"\"\"\n    # Normally, there should only be one row per path, in which case the\n    # second and third elements don't come into play when sorting.\n    # However, in cases in the wild where a path might happen to occur twice,\n    # we don't want the sort operation to trigger an error (but still want\n    # determinism).  Since the third element can be an int or string, we\n    # coerce each element to a string to avoid a TypeError in this case.\n    # For additional background, see--\n    # https://github.com/pypa/pip/issues/5868\n    return sorted(\n        (record_path, hash_, str(size)) for record_path, hash_, size in outrows\n    )\n\n\ndef _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str:\n    return os.path.join(lib_dir, record_path)\n\n\ndef _fs_to_record_path(path: str, lib_dir: str) -> RecordPath:\n    # On Windows, do not handle relative paths if they belong to different\n    # logical disks\n    if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower():\n        path = os.path.relpath(path, lib_dir)\n\n    path = path.replace(os.path.sep, \"/\")\n    return cast(\"RecordPath\", path)\n\n\ndef get_csv_rows_for_installed(\n    old_csv_rows: list[list[str]],\n    installed: dict[RecordPath, RecordPath],\n    changed: set[RecordPath],\n    generated: list[str],\n    lib_dir: str,\n) -> list[InstalledCSVRow]:\n    \"\"\"\n    :param installed: A map from archive RECORD path to installation RECORD\n        path.\n    \"\"\"\n    installed_rows: list[InstalledCSVRow] = []\n    for row in old_csv_rows:\n        if len(row) > 3:\n            logger.warning(\"RECORD line has more than three elements: %s\", row)\n        old_record_path = cast(\"RecordPath\", row[0])\n        new_record_path = installed.pop(old_record_path, old_record_path)\n        if new_record_path in changed:\n            digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir))\n        else:\n            digest = row[1] if len(row) > 1 else \"\"\n            length = row[2] if len(row) > 2 else \"\"\n        installed_rows.append((new_record_path, digest, length))\n    for f in generated:\n        path = _fs_to_record_path(f, lib_dir)\n        digest, length = rehash(f)\n        installed_rows.append((path, digest, length))\n    return installed_rows + [\n        (installed_record_path, \"\", \"\") for installed_record_path in installed.values()\n    ]\n\n\ndef get_console_script_specs(console: dict[str, str]) -> list[str]:\n    \"\"\"\n    Given the mapping from entrypoint name to callable, return the relevant\n    console script specs.\n    \"\"\"\n    # Don't mutate caller's version\n    console = console.copy()\n\n    scripts_to_generate = []\n\n    # Special case pip and setuptools to generate versioned wrappers\n    #\n    # The issue is that some projects (specifically, pip and setuptools) use\n    # code in setup.py to create \"versioned\" entry points - pip2.7 on Python\n    # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into\n    # the wheel metadata at build time, and so if the wheel is installed with\n    # a *different* version of Python the entry points will be wrong. The\n    # correct fix for this is to enhance the metadata to be able to describe\n    # such versioned entry points.\n    # Currently, projects using versioned entry points will either have\n    # incorrect versioned entry points, or they will not be able to distribute\n    # \"universal\" wheels (i.e., they will need a wheel per Python version).\n    #\n    # Because setuptools and pip are bundled with _ensurepip and virtualenv,\n    # we need to use universal wheels. As a workaround, we\n    # override the versioned entry points in the wheel and generate the\n    # correct ones.\n    #\n    # To add the level of hack in this section of code, in order to support\n    # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment\n    # variable which will control which version scripts get installed.\n    #\n    # ENSUREPIP_OPTIONS=altinstall\n    #   - Only pipX.Y and easy_install-X.Y will be generated and installed\n    # ENSUREPIP_OPTIONS=install\n    #   - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note\n    #     that this option is technically if ENSUREPIP_OPTIONS is set and is\n    #     not altinstall\n    # DEFAULT\n    #   - The default behavior is to install pip, pipX, pipX.Y, easy_install\n    #     and easy_install-X.Y.\n    pip_script = console.pop(\"pip\", None)\n    if pip_script:\n        if \"ENSUREPIP_OPTIONS\" not in os.environ:\n            scripts_to_generate.append(\"pip = \" + pip_script)\n\n        if os.environ.get(\"ENSUREPIP_OPTIONS\", \"\") != \"altinstall\":\n            scripts_to_generate.append(f\"pip{sys.version_info[0]} = {pip_script}\")\n\n        scripts_to_generate.append(f\"pip{get_major_minor_version()} = {pip_script}\")\n        # Delete any other versioned pip entry points\n        pip_ep = [k for k in console if re.match(r\"pip(\\d+(\\.\\d+)?)?$\", k)]\n        for k in pip_ep:\n            del console[k]\n    easy_install_script = console.pop(\"easy_install\", None)\n    if easy_install_script:\n        if \"ENSUREPIP_OPTIONS\" not in os.environ:\n            scripts_to_generate.append(\"easy_install = \" + easy_install_script)\n\n        scripts_to_generate.append(\n            f\"easy_install-{get_major_minor_version()} = {easy_install_script}\"\n        )\n        # Delete any other versioned easy_install entry points\n        easy_install_ep = [\n            k for k in console if re.match(r\"easy_install(-\\d+\\.\\d+)?$\", k)\n        ]\n        for k in easy_install_ep:\n            del console[k]\n\n    # Generate the console entry points specified in the wheel\n    scripts_to_generate.extend(starmap(\"{} = {}\".format, console.items()))\n\n    return scripts_to_generate\n\n\nclass ZipBackedFile:\n    def __init__(\n        self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile\n    ) -> None:\n        self.src_record_path = src_record_path\n        self.dest_path = dest_path\n        self._zip_file = zip_file\n        self.changed = False\n\n    def _getinfo(self) -> ZipInfo:\n        return self._zip_file.getinfo(self.src_record_path)\n\n    def save(self) -> None:\n        # When we open the output file below, any existing file is truncated\n        # before we start writing the new contents. This is fine in most\n        # cases, but can cause a segfault if pip has loaded a shared\n        # object (e.g. from pyopenssl through its vendored urllib3)\n        # Since the shared object is mmap'd an attempt to call a\n        # symbol in it will then cause a segfault. Unlinking the file\n        # allows writing of new contents while allowing the process to\n        # continue to use the old copy.\n        if os.path.exists(self.dest_path):\n            os.unlink(self.dest_path)\n\n        zipinfo = self._getinfo()\n\n        # optimization: the file is created by open(),\n        # skip the decompression when there is 0 bytes to decompress.\n        with open(self.dest_path, \"wb\") as dest:\n            if zipinfo.file_size > 0:\n                with self._zip_file.open(zipinfo) as f:\n                    blocksize = min(zipinfo.file_size, 1024 * 1024)\n                    shutil.copyfileobj(f, dest, blocksize)\n\n        if zip_item_is_executable(zipinfo):\n            set_extracted_file_to_default_mode_plus_executable(self.dest_path)\n\n\nclass ScriptFile:\n    def __init__(self, file: File) -> None:\n        self._file = file\n        self.src_record_path = self._file.src_record_path\n        self.dest_path = self._file.dest_path\n        self.changed = False\n\n    def save(self) -> None:\n        self._file.save()\n        self.changed = fix_script(self.dest_path)\n\n\nclass MissingCallableSuffix(InstallationError):\n    def __init__(self, entry_point: str) -> None:\n        super().__init__(\n            f\"Invalid script entry point: {entry_point} - A callable \"\n            \"suffix is required. See https://packaging.python.org/\"\n            \"specifications/entry-points/#use-for-scripts for more \"\n            \"information.\"\n        )\n\n\ndef _raise_for_invalid_entrypoint(specification: str) -> None:\n    entry = get_export_entry(specification)\n    if entry is not None and entry.suffix is None:\n        raise MissingCallableSuffix(str(entry))\n\n\nclass PipScriptMaker(ScriptMaker):\n    # Override distlib's default script template with one that\n    # doesn't import `re` module, allowing scripts to load faster.\n    script_template = textwrap.dedent(\n        \"\"\"\\\n        import sys\n        from %(module)s import %(import_name)s\n        if __name__ == '__main__':\n            sys.argv[0] = sys.argv[0].removesuffix('.exe')\n            sys.exit(%(func)s())\n\"\"\"\n    )\n\n    def make(\n        self, specification: str, options: dict[str, Any] | None = None\n    ) -> list[str]:\n        _raise_for_invalid_entrypoint(specification)\n        return super().make(specification, options)\n\n\ndef _install_wheel(  # noqa: C901, PLR0915 function is too long\n    name: str,\n    wheel_zip: ZipFile,\n    wheel_path: str,\n    scheme: Scheme,\n    pycompile: bool = True,\n    warn_script_location: bool = True,\n    direct_url: DirectUrl | None = None,\n    requested: bool = False,\n) -> None:\n    \"\"\"Install a wheel.\n\n    :param name: Name of the project to install\n    :param wheel_zip: open ZipFile for wheel being installed\n    :param scheme: Distutils scheme dictating the install directories\n    :param req_description: String used in place of the requirement, for\n        logging\n    :param pycompile: Whether to byte-compile installed Python files\n    :param warn_script_location: Whether to check that scripts are installed\n        into a directory on PATH\n    :raises UnsupportedWheel:\n        * when the directory holds an unpacked wheel with incompatible\n          Wheel-Version\n        * when the .dist-info dir does not match the wheel\n    \"\"\"\n    info_dir, metadata = parse_wheel(wheel_zip, name)\n\n    if wheel_root_is_purelib(metadata):\n        lib_dir = scheme.purelib\n    else:\n        lib_dir = scheme.platlib\n\n    # Record details of the files moved\n    #   installed = files copied from the wheel to the destination\n    #   changed = files changed while installing (scripts #! line typically)\n    #   generated = files newly generated during the install (script wrappers)\n    installed: dict[RecordPath, RecordPath] = {}\n    changed: set[RecordPath] = set()\n    generated: list[str] = []\n\n    def record_installed(\n        srcfile: RecordPath, destfile: str, modified: bool = False\n    ) -> None:\n        \"\"\"Map archive RECORD paths to installation RECORD paths.\"\"\"\n        newpath = _fs_to_record_path(destfile, lib_dir)\n        installed[srcfile] = newpath\n        if modified:\n            changed.add(newpath)\n\n    def is_dir_path(path: RecordPath) -> bool:\n        return path.endswith(\"/\")\n\n    def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None:\n        if not is_within_directory(dest_dir_path, target_path):\n            message = (\n                \"The wheel {!r} has a file {!r} trying to install\"\n                \" outside the target directory {!r}\"\n            )\n            raise InstallationError(\n                message.format(wheel_path, target_path, dest_dir_path)\n            )\n\n    def root_scheme_file_maker(\n        zip_file: ZipFile, dest: str\n    ) -> Callable[[RecordPath], File]:\n        def make_root_scheme_file(record_path: RecordPath) -> File:\n            normed_path = os.path.normpath(record_path)\n            dest_path = os.path.join(dest, normed_path)\n            assert_no_path_traversal(dest, dest_path)\n            return ZipBackedFile(record_path, dest_path, zip_file)\n\n        return make_root_scheme_file\n\n    def data_scheme_file_maker(\n        zip_file: ZipFile, scheme: Scheme\n    ) -> Callable[[RecordPath], File]:\n        scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS}\n\n        def make_data_scheme_file(record_path: RecordPath) -> File:\n            normed_path = os.path.normpath(record_path)\n            try:\n                _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)\n            except ValueError:\n                message = (\n                    f\"Unexpected file in {wheel_path}: {record_path!r}. .data directory\"\n                    \" contents should be named like: '<scheme key>/<path>'.\"\n                )\n                raise InstallationError(message)\n\n            try:\n                scheme_path = scheme_paths[scheme_key]\n            except KeyError:\n                valid_scheme_keys = \", \".join(sorted(scheme_paths))\n                message = (\n                    f\"Unknown scheme key used in {wheel_path}: {scheme_key} \"\n                    f\"(for file {record_path!r}). .data directory contents \"\n                    f\"should be in subdirectories named with a valid scheme \"\n                    f\"key ({valid_scheme_keys})\"\n                )\n                raise InstallationError(message)\n\n            dest_path = os.path.join(scheme_path, dest_subpath)\n            assert_no_path_traversal(scheme_path, dest_path)\n            return ZipBackedFile(record_path, dest_path, zip_file)\n\n        return make_data_scheme_file\n\n    def is_data_scheme_path(path: RecordPath) -> bool:\n        return path.split(\"/\", 1)[0].endswith(\".data\")\n\n    paths = cast(list[RecordPath], wheel_zip.namelist())\n    file_paths = filterfalse(is_dir_path, paths)\n    root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths)\n\n    make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir)\n    files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths)\n\n    def is_script_scheme_path(path: RecordPath) -> bool:\n        parts = path.split(\"/\", 2)\n        return len(parts) > 2 and parts[0].endswith(\".data\") and parts[1] == \"scripts\"\n\n    other_scheme_paths, script_scheme_paths = partition(\n        is_script_scheme_path, data_scheme_paths\n    )\n\n    make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)\n    other_scheme_files = map(make_data_scheme_file, other_scheme_paths)\n    files = chain(files, other_scheme_files)\n\n    # Get the defined entry points\n    distribution = get_wheel_distribution(\n        FilesystemWheel(wheel_path),\n        canonicalize_name(name),\n    )\n    console, gui = get_entrypoints(distribution)\n\n    def is_entrypoint_wrapper(file: File) -> bool:\n        # EP, EP.exe and EP-script.py are scripts generated for\n        # entry point EP by setuptools\n        path = file.dest_path\n        name = os.path.basename(path)\n        if name.lower().endswith(\".exe\"):\n            matchname = name[:-4]\n        elif name.lower().endswith(\"-script.py\"):\n            matchname = name[:-10]\n        elif name.lower().endswith(\".pya\"):\n            matchname = name[:-4]\n        else:\n            matchname = name\n        # Ignore setuptools-generated scripts\n        return matchname in console or matchname in gui\n\n    script_scheme_files: Iterator[File] = map(\n        make_data_scheme_file, script_scheme_paths\n    )\n    script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files)\n    script_scheme_files = map(ScriptFile, script_scheme_files)\n    files = chain(files, script_scheme_files)\n\n    existing_parents = set()\n    for file in files:\n        # directory creation is lazy and after file filtering\n        # to ensure we don't install empty dirs; empty dirs can't be\n        # uninstalled.\n        parent_dir = os.path.dirname(file.dest_path)\n        if parent_dir not in existing_parents:\n            ensure_dir(parent_dir)\n            existing_parents.add(parent_dir)\n        file.save()\n        record_installed(file.src_record_path, file.dest_path, file.changed)\n\n    def pyc_source_file_paths() -> Generator[str, None, None]:\n        # We de-duplicate installation paths, since there can be overlap (e.g.\n        # file in .data maps to same location as file in wheel root).\n        # Sorting installation paths makes it easier to reproduce and debug\n        # issues related to permissions on existing files.\n        for installed_path in sorted(set(installed.values())):\n            full_installed_path = os.path.join(lib_dir, installed_path)\n            if not os.path.isfile(full_installed_path):\n                continue\n            if not full_installed_path.endswith(\".py\"):\n                continue\n            yield full_installed_path\n\n    def pyc_output_path(path: str) -> str:\n        \"\"\"Return the path the pyc file would have been written to.\"\"\"\n        return importlib.util.cache_from_source(path)\n\n    # Compile all of the pyc files for the installed files\n    if pycompile:\n        with contextlib.redirect_stdout(\n            StreamWrapper.from_stream(sys.stdout)\n        ) as stdout:\n            with warnings.catch_warnings():\n                warnings.filterwarnings(\"ignore\")\n                for path in pyc_source_file_paths():\n                    success = compileall.compile_file(path, force=True, quiet=True)\n                    if success:\n                        pyc_path = pyc_output_path(path)\n                        assert os.path.exists(pyc_path)\n                        pyc_record_path = cast(\n                            \"RecordPath\", pyc_path.replace(os.path.sep, \"/\")\n                        )\n                        record_installed(pyc_record_path, pyc_path)\n        logger.debug(stdout.getvalue())\n\n    maker = PipScriptMaker(None, scheme.scripts)\n\n    # Ensure old scripts are overwritten.\n    # See https://github.com/pypa/pip/issues/1800\n    maker.clobber = True\n\n    # Ensure we don't generate any variants for scripts because this is almost\n    # never what somebody wants.\n    # See https://bitbucket.org/pypa/distlib/issue/35/\n    maker.variants = {\"\"}\n\n    # This is required because otherwise distlib creates scripts that are not\n    # executable.\n    # See https://bitbucket.org/pypa/distlib/issue/32/\n    maker.set_mode = True\n\n    # Generate the console and GUI entry points specified in the wheel\n    scripts_to_generate = get_console_script_specs(console)\n\n    gui_scripts_to_generate = list(starmap(\"{} = {}\".format, gui.items()))\n\n    generated_console_scripts = maker.make_multiple(scripts_to_generate)\n    generated.extend(generated_console_scripts)\n\n    generated.extend(maker.make_multiple(gui_scripts_to_generate, {\"gui\": True}))\n\n    if warn_script_location:\n        msg = message_about_scripts_not_on_PATH(generated_console_scripts)\n        if msg is not None:\n            logger.warning(msg)\n\n    generated_file_mode = 0o666 & ~current_umask()\n\n    @contextlib.contextmanager\n    def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:\n        with adjacent_tmp_file(path, **kwargs) as f:\n            yield f\n        os.chmod(f.name, generated_file_mode)\n        replace(f.name, path)\n\n    dest_info_dir = os.path.join(lib_dir, info_dir)\n\n    # Record pip as the installer\n    installer_path = os.path.join(dest_info_dir, \"INSTALLER\")\n    with _generate_file(installer_path) as installer_file:\n        installer_file.write(b\"pip\\n\")\n    generated.append(installer_path)\n\n    # Record the PEP 610 direct URL reference\n    if direct_url is not None:\n        direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)\n        with _generate_file(direct_url_path) as direct_url_file:\n            direct_url_file.write(direct_url.to_json().encode(\"utf-8\"))\n        generated.append(direct_url_path)\n\n    # Record the REQUESTED file\n    if requested:\n        requested_path = os.path.join(dest_info_dir, \"REQUESTED\")\n        with open(requested_path, \"wb\"):\n            pass\n        generated.append(requested_path)\n\n    record_text = distribution.read_text(\"RECORD\")\n    record_rows = list(csv.reader(record_text.splitlines()))\n\n    rows = get_csv_rows_for_installed(\n        record_rows,\n        installed=installed,\n        changed=changed,\n        generated=generated,\n        lib_dir=lib_dir,\n    )\n\n    # Record details of all files installed\n    record_path = os.path.join(dest_info_dir, \"RECORD\")\n\n    with _generate_file(record_path, **csv_io_kwargs(\"w\")) as record_file:\n        # Explicitly cast to typing.IO[str] as a workaround for the mypy error:\n        # \"writer\" has incompatible type \"BinaryIO\"; expected \"_Writer\"\n        writer = csv.writer(cast(\"IO[str]\", record_file))\n        writer.writerows(_normalized_outrows(rows))\n\n\n@contextlib.contextmanager\ndef req_error_context(req_description: str) -> Generator[None, None, None]:\n    try:\n        yield\n    except InstallationError as e:\n        message = f\"For req: {req_description}. {e.args[0]}\"\n        raise InstallationError(message) from e\n\n\ndef install_wheel(\n    name: str,\n    wheel_path: str,\n    scheme: Scheme,\n    req_description: str,\n    pycompile: bool = True,\n    warn_script_location: bool = True,\n    direct_url: DirectUrl | None = None,\n    requested: bool = False,\n) -> None:\n    with ZipFile(wheel_path, allowZip64=True) as z:\n        with req_error_context(req_description):\n            _install_wheel(\n                name=name,\n                wheel_zip=z,\n                wheel_path=wheel_path,\n                scheme=scheme,\n                pycompile=pycompile,\n                warn_script_location=warn_script_location,\n                direct_url=direct_url,\n                requested=requested,\n            )\n"
  },
  {
    "path": "src/pip/_internal/operations/prepare.py",
    "content": "\"\"\"Prepares a distribution for installation\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\nfrom __future__ import annotations\n\nimport mimetypes\nimport os\nimport shutil\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.build_env import BuildEnvironmentInstaller\nfrom pip._internal.distributions import make_distribution_for_install_requirement\nfrom pip._internal.distributions.installed import InstalledDistribution\nfrom pip._internal.exceptions import (\n    DirectoryUrlHashUnsupported,\n    HashMismatch,\n    HashUnpinned,\n    InstallationError,\n    MetadataInconsistent,\n    NetworkConnectionError,\n    VcsHashUnsupported,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution, get_metadata_distribution\nfrom pip._internal.models.direct_url import ArchiveInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.network.download import Downloader\nfrom pip._internal.network.lazy_wheel import (\n    HTTPRangeRequestUnsupported,\n    dist_from_wheel_url,\n)\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import BuildTracker\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils._log import getLogger\nfrom pip._internal.utils.direct_url_helpers import (\n    direct_url_for_editable,\n    direct_url_from_link,\n)\nfrom pip._internal.utils.hashes import Hashes, MissingHashes\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import (\n    display_path,\n    hash_file,\n    hide_url,\n    redact_auth_from_requirement,\n)\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.unpacking import unpack_file\nfrom pip._internal.vcs import vcs\n\nif TYPE_CHECKING:\n    from pip._internal.cli.progress_bars import BarType\n\nlogger = getLogger(__name__)\n\n\ndef _get_prepared_distribution(\n    req: InstallRequirement,\n    build_tracker: BuildTracker,\n    build_env_installer: BuildEnvironmentInstaller,\n    build_isolation: bool,\n    check_build_deps: bool,\n) -> BaseDistribution:\n    \"\"\"Prepare a distribution for installation.\"\"\"\n    abstract_dist = make_distribution_for_install_requirement(req)\n    tracker_id = abstract_dist.build_tracker_id\n    if tracker_id is not None:\n        with build_tracker.track(req, tracker_id):\n            abstract_dist.prepare_distribution_metadata(\n                build_env_installer, build_isolation, check_build_deps\n            )\n    return abstract_dist.get_metadata_distribution()\n\n\ndef unpack_vcs_link(link: Link, location: str, verbosity: int) -> None:\n    vcs_backend = vcs.get_backend_for_scheme(link.scheme)\n    assert vcs_backend is not None\n    vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)\n\n\n@dataclass\nclass File:\n    path: str\n    content_type: str | None = None\n\n    def __post_init__(self) -> None:\n        if self.content_type is None:\n            # Try to guess the file's MIME type. If the system MIME tables\n            # can't be loaded, give up.\n            try:\n                self.content_type = mimetypes.guess_type(self.path)[0]\n            except OSError:\n                pass\n\n\ndef get_http_url(\n    link: Link,\n    download: Downloader,\n    download_dir: str | None = None,\n    hashes: Hashes | None = None,\n) -> File:\n    temp_dir = TempDirectory(kind=\"unpack\", globally_managed=True)\n    # If a download dir is specified, is the file already downloaded there?\n    already_downloaded_path = None\n    if download_dir:\n        already_downloaded_path = _check_download_dir(link, download_dir, hashes)\n\n    if already_downloaded_path:\n        from_path = already_downloaded_path\n        content_type = None\n    else:\n        # let's download to a tmp dir\n        from_path, content_type = download(link, temp_dir.path)\n        if hashes:\n            hashes.check_against_path(from_path)\n\n    return File(from_path, content_type)\n\n\ndef get_file_url(\n    link: Link, download_dir: str | None = None, hashes: Hashes | None = None\n) -> File:\n    \"\"\"Get file and optionally check its hash.\"\"\"\n    # If a download dir is specified, is the file already there and valid?\n    already_downloaded_path = None\n    if download_dir:\n        already_downloaded_path = _check_download_dir(link, download_dir, hashes)\n\n    if already_downloaded_path:\n        from_path = already_downloaded_path\n    else:\n        from_path = link.file_path\n\n    # If --require-hashes is off, `hashes` is either empty, the\n    # link's embedded hash, or MissingHashes; it is required to\n    # match. If --require-hashes is on, we are satisfied by any\n    # hash in `hashes` matching: a URL-based or an option-based\n    # one; no internet-sourced hash will be in `hashes`.\n    if hashes:\n        hashes.check_against_path(from_path)\n    return File(from_path, None)\n\n\ndef unpack_url(\n    link: Link,\n    location: str,\n    download: Downloader,\n    verbosity: int,\n    download_dir: str | None = None,\n    hashes: Hashes | None = None,\n) -> File | None:\n    \"\"\"Unpack link into location, downloading if required.\n\n    :param hashes: A Hashes object, one of whose embedded hashes must match,\n        or HashMismatch will be raised. If the Hashes is empty, no matches are\n        required, and unhashable types of requirements (like VCS ones, which\n        would ordinarily raise HashUnsupported) are allowed.\n    \"\"\"\n    # non-editable vcs urls\n    if link.is_vcs:\n        unpack_vcs_link(link, location, verbosity=verbosity)\n        return None\n\n    assert not link.is_existing_dir()\n\n    # file urls\n    if link.is_file:\n        file = get_file_url(link, download_dir, hashes=hashes)\n\n    # http urls\n    else:\n        file = get_http_url(\n            link,\n            download,\n            download_dir,\n            hashes=hashes,\n        )\n\n    # unpack the archive to the build dir location. even when only downloading\n    # archives, they have to be unpacked to parse dependencies, except wheels\n    if not link.is_wheel:\n        unpack_file(file.path, location, file.content_type)\n\n    return file\n\n\ndef _check_download_dir(\n    link: Link,\n    download_dir: str,\n    hashes: Hashes | None,\n    warn_on_hash_mismatch: bool = True,\n) -> str | None:\n    \"\"\"Check download_dir for previously downloaded file with correct hash\n    If a correct file is found return its path else None\n    \"\"\"\n    download_path = os.path.join(download_dir, link.filename)\n\n    if not os.path.exists(download_path):\n        return None\n\n    # If already downloaded, does its hash match?\n    logger.info(\"File was already downloaded %s\", download_path)\n    if hashes:\n        try:\n            hashes.check_against_path(download_path)\n        except HashMismatch:\n            if warn_on_hash_mismatch:\n                logger.warning(\n                    \"Previously-downloaded file %s has bad hash. Re-downloading.\",\n                    download_path,\n                )\n            os.unlink(download_path)\n            return None\n    return download_path\n\n\nclass RequirementPreparer:\n    \"\"\"Prepares a Requirement\"\"\"\n\n    def __init__(\n        self,\n        *,\n        build_dir: str,\n        download_dir: str | None,\n        src_dir: str,\n        build_isolation: bool,\n        build_isolation_installer: BuildEnvironmentInstaller,\n        check_build_deps: bool,\n        build_tracker: BuildTracker,\n        session: PipSession,\n        progress_bar: BarType,\n        finder: PackageFinder,\n        require_hashes: bool,\n        use_user_site: bool,\n        lazy_wheel: bool,\n        verbosity: int,\n        legacy_resolver: bool,\n    ) -> None:\n        super().__init__()\n\n        self.src_dir = src_dir\n        self.build_dir = build_dir\n        self.build_tracker = build_tracker\n        self._session = session\n        self._download = Downloader(session, progress_bar)\n        self.finder = finder\n\n        # Where still-packed archives should be written to. If None, they are\n        # not saved, and are deleted immediately after unpacking.\n        self.download_dir = download_dir\n\n        # Is build isolation allowed?\n        self.build_isolation = build_isolation\n        self.build_env_installer = build_isolation_installer\n\n        # Should check build dependencies?\n        self.check_build_deps = check_build_deps\n\n        # Should hash-checking be required?\n        self.require_hashes = require_hashes\n\n        # Should install in user site-packages?\n        self.use_user_site = use_user_site\n\n        # Should wheels be downloaded lazily?\n        self.use_lazy_wheel = lazy_wheel\n\n        # How verbose should underlying tooling be?\n        self.verbosity = verbosity\n\n        # Are we using the legacy resolver?\n        self.legacy_resolver = legacy_resolver\n\n        # Memoized downloaded files, as mapping of url: path.\n        self._downloaded: dict[str, str] = {}\n\n        # Previous \"header\" printed for a link-based InstallRequirement\n        self._previous_requirement_header = (\"\", \"\")\n\n    def _log_preparing_link(self, req: InstallRequirement) -> None:\n        \"\"\"Provide context for the requirement being prepared.\"\"\"\n        if req.link.is_file and not req.is_wheel_from_cache:\n            message = \"Processing %s\"\n            information = str(display_path(req.link.file_path))\n        else:\n            message = \"Collecting %s\"\n            information = redact_auth_from_requirement(req.req) if req.req else str(req)\n\n        # If we used req.req, inject requirement source if available (this\n        # would already be included if we used req directly)\n        if req.req and req.comes_from:\n            if isinstance(req.comes_from, str):\n                comes_from: str | None = req.comes_from\n            else:\n                comes_from = req.comes_from.from_path()\n            if comes_from:\n                information += f\" (from {comes_from})\"\n\n        if (message, information) != self._previous_requirement_header:\n            self._previous_requirement_header = (message, information)\n            logger.info(message, information)\n\n        if req.is_wheel_from_cache:\n            with indent_log():\n                logger.info(\"Using cached %s\", req.link.filename)\n\n    def _ensure_link_req_src_dir(\n        self, req: InstallRequirement, parallel_builds: bool\n    ) -> None:\n        \"\"\"Ensure source_dir of a linked InstallRequirement.\"\"\"\n        # Since source_dir is only set for editable requirements.\n        if req.link.is_wheel:\n            # We don't need to unpack wheels, so no need for a source\n            # directory.\n            return\n        assert req.source_dir is None\n        if req.link.is_existing_dir():\n            # build local directories in-tree\n            req.source_dir = req.link.file_path\n            return\n\n        # We always delete unpacked sdists after pip runs.\n        req.ensure_has_source_dir(\n            self.build_dir,\n            autodelete=True,\n            parallel_builds=parallel_builds,\n        )\n        req.ensure_pristine_source_checkout()\n\n    def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes:\n        # By the time this is called, the requirement's link should have\n        # been checked so we can tell what kind of requirements req is\n        # and raise some more informative errors than otherwise.\n        # (For example, we can raise VcsHashUnsupported for a VCS URL\n        # rather than HashMissing.)\n        if not self.require_hashes:\n            return req.hashes(trust_internet=True)\n\n        # We could check these first 2 conditions inside unpack_url\n        # and save repetition of conditions, but then we would\n        # report less-useful error messages for unhashable\n        # requirements, complaining that there's no hash provided.\n        if req.link.is_vcs:\n            raise VcsHashUnsupported()\n        if req.link.is_existing_dir():\n            raise DirectoryUrlHashUnsupported()\n\n        # Unpinned packages are asking for trouble when a new version\n        # is uploaded.  This isn't a security check, but it saves users\n        # a surprising hash mismatch in the future.\n        # file:/// URLs aren't pinnable, so don't complain about them\n        # not being pinned.\n        if not req.is_direct and not req.is_pinned:\n            raise HashUnpinned()\n\n        # If known-good hashes are missing for this requirement,\n        # shim it with a facade object that will provoke hash\n        # computation and then raise a HashMissing exception\n        # showing the user what the hash should be.\n        return req.hashes(trust_internet=False) or MissingHashes()\n\n    def _fetch_metadata_only(\n        self,\n        req: InstallRequirement,\n    ) -> BaseDistribution | None:\n        if self.legacy_resolver:\n            logger.debug(\n                \"Metadata-only fetching is not used in the legacy resolver\",\n            )\n            return None\n        if self.require_hashes:\n            logger.debug(\n                \"Metadata-only fetching is not used as hash checking is required\",\n            )\n            return None\n        # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable.\n        return self._fetch_metadata_using_link_data_attr(\n            req\n        ) or self._fetch_metadata_using_lazy_wheel(req.link)\n\n    def _fetch_metadata_using_link_data_attr(\n        self,\n        req: InstallRequirement,\n    ) -> BaseDistribution | None:\n        \"\"\"Fetch metadata from the data-dist-info-metadata attribute, if possible.\"\"\"\n        # (1) Get the link to the metadata file, if provided by the backend.\n        metadata_link = req.link.metadata_link()\n        if metadata_link is None:\n            return None\n        assert req.req is not None\n        logger.verbose(\n            \"Obtaining dependency information for %s from %s\",\n            req.req,\n            metadata_link,\n        )\n        # (2) Download the contents of the METADATA file, separate from the dist itself.\n        metadata_file = get_http_url(\n            metadata_link,\n            self._download,\n            hashes=metadata_link.as_hashes(),\n        )\n        with open(metadata_file.path, \"rb\") as f:\n            metadata_contents = f.read()\n        # (3) Generate a dist just from those file contents.\n        metadata_dist = get_metadata_distribution(\n            metadata_contents,\n            req.link.filename,\n            req.req.name,\n        )\n        # (4) Ensure the Name: field from the METADATA file matches the name from the\n        #     install requirement.\n        #\n        #     NB: raw_name will fall back to the name from the install requirement if\n        #     the Name: field is not present, but it's noted in the raw_name docstring\n        #     that that should NEVER happen anyway.\n        if canonicalize_name(metadata_dist.raw_name) != canonicalize_name(req.req.name):\n            raise MetadataInconsistent(\n                req, \"Name\", req.req.name, metadata_dist.raw_name\n            )\n        return metadata_dist\n\n    def _fetch_metadata_using_lazy_wheel(\n        self,\n        link: Link,\n    ) -> BaseDistribution | None:\n        \"\"\"Fetch metadata using lazy wheel, if possible.\"\"\"\n        # --use-feature=fast-deps must be provided.\n        if not self.use_lazy_wheel:\n            return None\n        if link.is_file or not link.is_wheel:\n            logger.debug(\n                \"Lazy wheel is not used as %r does not point to a remote wheel\",\n                link,\n            )\n            return None\n\n        wheel = Wheel(link.filename)\n        name = wheel.name\n        logger.info(\n            \"Obtaining dependency information from %s %s\",\n            name,\n            wheel.version,\n        )\n        url = link.url.split(\"#\", 1)[0]\n        try:\n            return dist_from_wheel_url(name, url, self._session)\n        except HTTPRangeRequestUnsupported:\n            logger.debug(\"%s does not support range requests\", url)\n            return None\n\n    def _complete_partial_requirements(\n        self,\n        partially_downloaded_reqs: Iterable[InstallRequirement],\n        parallel_builds: bool = False,\n    ) -> None:\n        \"\"\"Download any requirements which were only fetched by metadata.\"\"\"\n        # Download to a temporary directory. These will be copied over as\n        # needed for downstream 'download', 'wheel', and 'install' commands.\n        temp_dir = TempDirectory(kind=\"unpack\", globally_managed=True).path\n\n        # Map each link to the requirement that owns it. This allows us to set\n        # `req.local_file_path` on the appropriate requirement after passing\n        # all the links at once into BatchDownloader.\n        links_to_fully_download: dict[Link, InstallRequirement] = {}\n        for req in partially_downloaded_reqs:\n            assert req.link\n            links_to_fully_download[req.link] = req\n\n        batch_download = self._download.batch(links_to_fully_download.keys(), temp_dir)\n        for link, (filepath, _) in batch_download:\n            logger.debug(\"Downloading link %s to %s\", link, filepath)\n            req = links_to_fully_download[link]\n            # Record the downloaded file path so wheel reqs can extract a Distribution\n            # in .get_dist().\n            req.local_file_path = filepath\n            # Record that the file is downloaded so we don't do it again in\n            # _prepare_linked_requirement().\n            self._downloaded[req.link.url] = filepath\n\n            # If this is an sdist, we need to unpack it after downloading, but the\n            # .source_dir won't be set up until we are in _prepare_linked_requirement().\n            # Add the downloaded archive to the install requirement to unpack after\n            # preparing the source dir.\n            if not req.is_wheel:\n                req.needs_unpacked_archive(Path(filepath))\n\n        # This step is necessary to ensure all lazy wheels are processed\n        # successfully by the 'download', 'wheel', and 'install' commands.\n        for req in partially_downloaded_reqs:\n            self._prepare_linked_requirement(req, parallel_builds)\n\n    def prepare_linked_requirement(\n        self, req: InstallRequirement, parallel_builds: bool = False\n    ) -> BaseDistribution:\n        \"\"\"Prepare a requirement to be obtained from req.link.\"\"\"\n        assert req.link\n        self._log_preparing_link(req)\n        with indent_log():\n            # Check if the relevant file is already available\n            # in the download directory\n            file_path = None\n            if self.download_dir is not None and req.link.is_wheel:\n                hashes = self._get_linked_req_hashes(req)\n                file_path = _check_download_dir(\n                    req.link,\n                    self.download_dir,\n                    hashes,\n                    # When a locally built wheel has been found in cache, we don't warn\n                    # about re-downloading when the already downloaded wheel hash does\n                    # not match. This is because the hash must be checked against the\n                    # original link, not the cached link. It that case the already\n                    # downloaded file will be removed and re-fetched from cache (which\n                    # implies a hash check against the cache entry's origin.json).\n                    warn_on_hash_mismatch=not req.is_wheel_from_cache,\n                )\n\n            if file_path is not None:\n                # The file is already available, so mark it as downloaded\n                self._downloaded[req.link.url] = file_path\n            else:\n                # The file is not available, attempt to fetch only metadata\n                metadata_dist = self._fetch_metadata_only(req)\n                if metadata_dist is not None:\n                    req.needs_more_preparation = True\n                    req.set_dist(metadata_dist)\n                    # Ensure download_info is available even in dry-run mode\n                    if req.download_info is None:\n                        req.download_info = direct_url_from_link(\n                            req.link, req.source_dir\n                        )\n                    return metadata_dist\n\n            # None of the optimizations worked, fully prepare the requirement\n            return self._prepare_linked_requirement(req, parallel_builds)\n\n    def prepare_linked_requirements_more(\n        self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False\n    ) -> None:\n        \"\"\"Prepare linked requirements more, if needed.\"\"\"\n        reqs = [req for req in reqs if req.needs_more_preparation]\n        for req in reqs:\n            # Determine if any of these requirements were already downloaded.\n            if self.download_dir is not None and req.link.is_wheel:\n                hashes = self._get_linked_req_hashes(req)\n                file_path = _check_download_dir(req.link, self.download_dir, hashes)\n                if file_path is not None:\n                    self._downloaded[req.link.url] = file_path\n                    req.needs_more_preparation = False\n\n        # Prepare requirements we found were already downloaded for some\n        # reason. The other downloads will be completed separately.\n        partially_downloaded_reqs: list[InstallRequirement] = []\n        for req in reqs:\n            if req.needs_more_preparation:\n                partially_downloaded_reqs.append(req)\n            else:\n                self._prepare_linked_requirement(req, parallel_builds)\n\n        # TODO: separate this part out from RequirementPreparer when the v1\n        # resolver can be removed!\n        self._complete_partial_requirements(\n            partially_downloaded_reqs,\n            parallel_builds=parallel_builds,\n        )\n\n    def _prepare_linked_requirement(\n        self, req: InstallRequirement, parallel_builds: bool\n    ) -> BaseDistribution:\n        assert req.link\n        link = req.link\n\n        hashes = self._get_linked_req_hashes(req)\n\n        if hashes and req.is_wheel_from_cache:\n            assert req.download_info is not None\n            assert link.is_wheel\n            assert link.is_file\n            # We need to verify hashes, and we have found the requirement in the cache\n            # of locally built wheels.\n            if (\n                isinstance(req.download_info.info, ArchiveInfo)\n                and req.download_info.info.hashes\n                and hashes.has_one_of(req.download_info.info.hashes)\n            ):\n                # At this point we know the requirement was built from a hashable source\n                # artifact, and we verified that the cache entry's hash of the original\n                # artifact matches one of the hashes we expect. We don't verify hashes\n                # against the cached wheel, because the wheel is not the original.\n                hashes = None\n            else:\n                logger.warning(\n                    \"The hashes of the source archive found in cache entry \"\n                    \"don't match, ignoring cached built wheel \"\n                    \"and re-downloading source.\"\n                )\n                req.link = req.cached_wheel_source_link\n                link = req.link\n\n        self._ensure_link_req_src_dir(req, parallel_builds)\n\n        if link.is_existing_dir():\n            local_file = None\n        elif link.url not in self._downloaded:\n            try:\n                local_file = unpack_url(\n                    link,\n                    req.source_dir,\n                    self._download,\n                    self.verbosity,\n                    self.download_dir,\n                    hashes,\n                )\n            except NetworkConnectionError as exc:\n                raise InstallationError(\n                    f\"Could not install requirement {req} because of HTTP \"\n                    f\"error {exc} for URL {link}\"\n                )\n        else:\n            file_path = self._downloaded[link.url]\n            if hashes:\n                hashes.check_against_path(file_path)\n            local_file = File(file_path, content_type=None)\n\n        # If download_info is set, we got it from the wheel cache.\n        if req.download_info is None:\n            # Editables don't go through this function (see\n            # prepare_editable_requirement).\n            assert not req.editable\n            req.download_info = direct_url_from_link(link, req.source_dir)\n            # Make sure we have a hash in download_info. If we got it as part of the\n            # URL, it will have been verified and we can rely on it. Otherwise we\n            # compute it from the downloaded file.\n            # FIXME: https://github.com/pypa/pip/issues/11943\n            if (\n                isinstance(req.download_info.info, ArchiveInfo)\n                and not req.download_info.info.hashes\n                and local_file\n            ):\n                hash = hash_file(local_file.path)[0].hexdigest()\n                # We populate info.hash for backward compatibility.\n                # This will automatically populate info.hashes.\n                req.download_info.info.hash = f\"sha256={hash}\"\n\n        # For use in later processing,\n        # preserve the file path on the requirement.\n        if local_file:\n            req.local_file_path = local_file.path\n\n        dist = _get_prepared_distribution(\n            req,\n            self.build_tracker,\n            self.build_env_installer,\n            self.build_isolation,\n            self.check_build_deps,\n        )\n        return dist\n\n    def save_linked_requirement(self, req: InstallRequirement) -> None:\n        assert self.download_dir is not None\n        assert req.link is not None\n        link = req.link\n        if link.is_vcs or (link.is_existing_dir() and req.editable):\n            # Make a .zip of the source_dir we already created.\n            req.archive(self.download_dir)\n            return\n\n        if link.is_existing_dir():\n            logger.debug(\n                \"Not copying link to destination directory \"\n                \"since it is a directory: %s\",\n                link,\n            )\n            return\n        if req.local_file_path is None:\n            # No distribution was downloaded for this requirement.\n            return\n\n        download_location = os.path.join(self.download_dir, link.filename)\n        if not os.path.exists(download_location):\n            shutil.copy(req.local_file_path, download_location)\n            download_path = display_path(download_location)\n            logger.info(\"Saved %s\", download_path)\n\n    def prepare_editable_requirement(\n        self,\n        req: InstallRequirement,\n    ) -> BaseDistribution:\n        \"\"\"Prepare an editable requirement.\"\"\"\n        assert req.editable, \"cannot prepare a non-editable req as editable\"\n\n        logger.info(\"Obtaining %s\", req)\n\n        with indent_log():\n            if self.require_hashes:\n                raise InstallationError(\n                    f\"The editable requirement {req} cannot be installed when \"\n                    \"requiring hashes, because there is no single file to \"\n                    \"hash.\"\n                )\n            req.ensure_has_source_dir(self.src_dir)\n            req.update_editable()\n            assert req.source_dir\n            req.download_info = direct_url_for_editable(req.unpacked_source_directory)\n\n            dist = _get_prepared_distribution(\n                req,\n                self.build_tracker,\n                self.build_env_installer,\n                self.build_isolation,\n                self.check_build_deps,\n            )\n\n            req.check_if_exists(self.use_user_site)\n\n        return dist\n\n    def prepare_installed_requirement(\n        self,\n        req: InstallRequirement,\n        skip_reason: str,\n    ) -> BaseDistribution:\n        \"\"\"Prepare an already-installed requirement.\"\"\"\n        assert req.satisfied_by, \"req should have been satisfied but isn't\"\n        assert skip_reason is not None, (\n            \"did not get skip reason skipped but req.satisfied_by \"\n            f\"is set to {req.satisfied_by}\"\n        )\n        logger.info(\n            \"Requirement %s: %s (%s)\", skip_reason, req, req.satisfied_by.version\n        )\n        with indent_log():\n            if self.require_hashes:\n                logger.debug(\n                    \"Since it is already installed, we are trusting this \"\n                    \"package without checking its hash. To ensure a \"\n                    \"completely repeatable environment, install into an \"\n                    \"empty virtualenv.\"\n                )\n            return InstalledDistribution(req).get_metadata_distribution()\n"
  },
  {
    "path": "src/pip/_internal/pyproject.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom collections import namedtuple\nfrom typing import Any\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\n\nfrom pip._internal.exceptions import (\n    InstallationError,\n    InvalidPyProjectBuildRequires,\n    MissingPyProjectBuildRequires,\n)\nfrom pip._internal.utils.compat import tomllib\nfrom pip._internal.utils.packaging import get_requirement\n\n\ndef _is_list_of_str(obj: Any) -> bool:\n    return isinstance(obj, list) and all(isinstance(item, str) for item in obj)\n\n\ndef make_pyproject_path(unpacked_source_directory: str) -> str:\n    return os.path.join(unpacked_source_directory, \"pyproject.toml\")\n\n\nBuildSystemDetails = namedtuple(\n    \"BuildSystemDetails\", [\"requires\", \"backend\", \"check\", \"backend_path\"]\n)\n\n\ndef load_pyproject_toml(\n    pyproject_toml: str, setup_py: str, req_name: str\n) -> BuildSystemDetails:\n    \"\"\"Load the pyproject.toml file.\n\n    Parameters:\n        pyproject_toml - Location of the project's pyproject.toml file\n        setup_py - Location of the project's setup.py file\n        req_name - The name of the requirement we're processing (for\n                   error reporting)\n\n    Returns:\n        None if we should use the legacy code path, otherwise a tuple\n        (\n            requirements from pyproject.toml,\n            name of PEP 517 backend,\n            requirements we should check are installed after setting\n                up the build environment\n            directory paths to import the backend from (backend-path),\n                relative to the project root.\n        )\n    \"\"\"\n    has_pyproject = os.path.isfile(pyproject_toml)\n    has_setup = os.path.isfile(setup_py)\n\n    if not has_pyproject and not has_setup:\n        raise InstallationError(\n            f\"{req_name} does not appear to be a Python project: \"\n            f\"neither 'setup.py' nor 'pyproject.toml' found.\"\n        )\n\n    if has_pyproject:\n        with open(pyproject_toml, encoding=\"utf-8\") as f:\n            pp_toml = tomllib.loads(f.read())\n        build_system = pp_toml.get(\"build-system\")\n    else:\n        build_system = None\n\n    if build_system is None:\n        # In the absence of any explicit backend specification, we\n        # assume the setuptools backend that most closely emulates the\n        # traditional direct setup.py execution, and require wheel and\n        # a version of setuptools that supports that backend.\n\n        build_system = {\n            \"requires\": [\"setuptools>=40.8.0\"],\n            \"build-backend\": \"setuptools.build_meta:__legacy__\",\n        }\n\n    # Ensure that the build-system section in pyproject.toml conforms\n    # to PEP 518.\n\n    # Specifying the build-system table but not the requires key is invalid\n    if \"requires\" not in build_system:\n        raise MissingPyProjectBuildRequires(package=req_name)\n\n    # Error out if requires is not a list of strings\n    requires = build_system[\"requires\"]\n    if not _is_list_of_str(requires):\n        raise InvalidPyProjectBuildRequires(\n            package=req_name,\n            reason=\"It is not a list of strings.\",\n        )\n\n    # Each requirement must be valid as per PEP 508\n    for requirement in requires:\n        try:\n            get_requirement(requirement)\n        except InvalidRequirement as error:\n            raise InvalidPyProjectBuildRequires(\n                package=req_name,\n                reason=f\"It contains an invalid requirement: {requirement!r}\",\n            ) from error\n\n    backend = build_system.get(\"build-backend\")\n    backend_path = build_system.get(\"backend-path\", [])\n    check: list[str] = []\n    if backend is None:\n        # If the user didn't specify a backend, we assume they want to use\n        # the setuptools backend. But we can't be sure they have included\n        # a version of setuptools which supplies the backend. So we\n        # make a note to check that this requirement is present once\n        # we have set up the environment.\n        # This is quite a lot of work to check for a very specific case. But\n        # the problem is, that case is potentially quite common - projects that\n        # adopted PEP 518 early for the ability to specify requirements to\n        # execute setup.py, but never considered needing to mention the build\n        # tools themselves. The original PEP 518 code had a similar check (but\n        # implemented in a different way).\n        backend = \"setuptools.build_meta:__legacy__\"\n        check = [\"setuptools>=40.8.0\"]\n\n    return BuildSystemDetails(requires, backend, check, backend_path)\n"
  },
  {
    "path": "src/pip/_internal/req/__init__.py",
    "content": "from __future__ import annotations\n\nimport collections\nimport logging\nfrom collections.abc import Generator\nfrom dataclasses import dataclass\n\nfrom pip._internal.cli.progress_bars import BarType, get_install_progress_renderer\nfrom pip._internal.utils.logging import indent_log\n\nfrom .req_file import parse_requirements\nfrom .req_install import InstallRequirement\nfrom .req_set import RequirementSet\n\n__all__ = [\n    \"RequirementSet\",\n    \"InstallRequirement\",\n    \"parse_requirements\",\n    \"install_given_reqs\",\n]\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass InstallationResult:\n    name: str\n\n\ndef _validate_requirements(\n    requirements: list[InstallRequirement],\n) -> Generator[tuple[str, InstallRequirement], None, None]:\n    for req in requirements:\n        assert req.name, f\"invalid to-be-installed requirement: {req}\"\n        yield req.name, req\n\n\ndef install_given_reqs(\n    requirements: list[InstallRequirement],\n    root: str | None,\n    home: str | None,\n    prefix: str | None,\n    warn_script_location: bool,\n    use_user_site: bool,\n    pycompile: bool,\n    progress_bar: BarType,\n) -> list[InstallationResult]:\n    \"\"\"\n    Install everything in the given list.\n\n    (to be called after having downloaded and unpacked the packages)\n    \"\"\"\n    to_install = collections.OrderedDict(_validate_requirements(requirements))\n\n    if to_install:\n        logger.info(\n            \"Installing collected packages: %s\",\n            \", \".join(to_install.keys()),\n        )\n\n    installed = []\n\n    show_progress = logger.isEnabledFor(logging.INFO) and len(to_install) > 1\n\n    items = iter(to_install.values())\n    if show_progress:\n        renderer = get_install_progress_renderer(\n            bar_type=progress_bar, total=len(to_install)\n        )\n        items = renderer(items)\n\n    with indent_log():\n        for requirement in items:\n            req_name = requirement.name\n            assert req_name is not None\n            if requirement.should_reinstall:\n                logger.info(\"Attempting uninstall: %s\", req_name)\n                with indent_log():\n                    uninstalled_pathset = requirement.uninstall(auto_confirm=True)\n            else:\n                uninstalled_pathset = None\n\n            try:\n                requirement.install(\n                    root=root,\n                    home=home,\n                    prefix=prefix,\n                    warn_script_location=warn_script_location,\n                    use_user_site=use_user_site,\n                    pycompile=pycompile,\n                )\n            except Exception:\n                # if install did not succeed, rollback previous uninstall\n                if uninstalled_pathset and not requirement.install_succeeded:\n                    uninstalled_pathset.rollback()\n                raise\n            else:\n                if uninstalled_pathset and requirement.install_succeeded:\n                    uninstalled_pathset.commit()\n\n            installed.append(InstallationResult(req_name))\n\n    return installed\n"
  },
  {
    "path": "src/pip/_internal/req/constructors.py",
    "content": "\"\"\"Backing implementation for InstallRequirement's various constructors\n\nThe idea here is that these formed a major chunk of InstallRequirement's size\nso, moving them and support code dedicated to them outside of that class\nhelps creates for better understandability for the rest of the code.\n\nThese are meant to be used elsewhere within pip to create instances of\nInstallRequirement.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport copy\nimport logging\nimport os\nimport re\nfrom collections.abc import Collection\nfrom dataclasses import dataclass\n\nfrom pip._vendor.packaging.markers import Marker\nfrom pip._vendor.packaging.requirements import InvalidRequirement, Requirement\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.models.index import PyPI, TestPyPI\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req.req_file import ParsedRequirement\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.filetypes import is_archive_file\nfrom pip._internal.utils.misc import is_installable_dir\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import is_url, vcs\n\n__all__ = [\n    \"install_req_from_editable\",\n    \"install_req_from_line\",\n    \"parse_editable\",\n]\n\nlogger = logging.getLogger(__name__)\n\n# All standard version specifier operators\n# https://packaging.python.org/en/latest/specifications/version-specifiers/#id5\noperators = (\"~=\", \"==\", \"!=\", \"<=\", \">=\", \"<\", \">\", \"===\")\n\n\ndef _strip_extras(path: str) -> tuple[str, str | None]:\n    m = re.match(r\"^(.+)(\\[[^\\]]+\\])$\", path)\n    extras = None\n    if m:\n        path_no_extras = m.group(1).rstrip()\n        extras = m.group(2)\n    else:\n        path_no_extras = path\n\n    return path_no_extras, extras\n\n\ndef convert_extras(extras: str | None) -> set[str]:\n    if not extras:\n        return set()\n    return get_requirement(\"placeholder\" + extras.lower()).extras\n\n\ndef _set_requirement_extras(req: Requirement, new_extras: set[str]) -> Requirement:\n    \"\"\"\n    Returns a new requirement based on the given one, with the supplied extras. If the\n    given requirement already has extras those are replaced (or dropped if no new extras\n    are given).\n    \"\"\"\n    match: re.Match[str] | None = re.fullmatch(\n        # see https://peps.python.org/pep-0508/#complete-grammar\n        r\"([\\w\\t .-]+)(\\[[^\\]]*\\])?(.*)\",\n        str(req),\n        flags=re.ASCII,\n    )\n    # ireq.req is a valid requirement so the regex should always match\n    assert (\n        match is not None\n    ), f\"regex match on requirement {req} failed, this should never happen\"\n    pre: str | None = match.group(1)\n    post: str | None = match.group(3)\n    assert (\n        pre is not None and post is not None\n    ), f\"regex group selection for requirement {req} failed, this should never happen\"\n    extras: str = \"[{}]\".format(\",\".join(sorted(new_extras)) if new_extras else \"\")\n    return get_requirement(f\"{pre}{extras}{post}\")\n\n\ndef _parse_direct_url_editable(editable_req: str) -> tuple[str | None, str, set[str]]:\n    try:\n        req = Requirement(editable_req)\n    except InvalidRequirement:\n        pass\n    else:\n        if req.url:\n            # Join the marker back into the name part. This will be parsed out\n            # later into a Requirement again.\n            if req.marker:\n                name = f\"{req.name} ; {req.marker}\"\n            else:\n                name = req.name\n            return (name, req.url, req.extras)\n\n    raise ValueError\n\n\ndef _parse_pip_syntax_editable(editable_req: str) -> tuple[str | None, str, set[str]]:\n    url = editable_req\n\n    # If a file path is specified with extras, strip off the extras.\n    url_no_extras, extras = _strip_extras(url)\n\n    if os.path.isdir(url_no_extras):\n        # Treating it as code that has already been checked out\n        url_no_extras = path_to_url(url_no_extras)\n\n    if url_no_extras.lower().startswith(\"file:\"):\n        package_name = Link(url_no_extras).egg_fragment\n        if extras:\n            return (\n                package_name,\n                url_no_extras,\n                get_requirement(\"placeholder\" + extras.lower()).extras,\n            )\n        else:\n            return package_name, url_no_extras, set()\n\n    for version_control in vcs:\n        if url.lower().startswith(f\"{version_control}:\"):\n            url = f\"{version_control}+{url}\"\n            break\n\n    return Link(url).egg_fragment, url, set()\n\n\ndef parse_editable(editable_req: str) -> tuple[str | None, str, set[str]]:\n    \"\"\"Parses an editable requirement into:\n        - a requirement name with environment markers\n        - an URL\n        - extras\n    Accepted requirements:\n        - svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir\n        - local_path[some_extra]\n        - Foobar[extra] @ svn+http://blahblah@rev#subdirectory=subdir ; markers\n    \"\"\"\n    try:\n        package_name, url, extras = _parse_direct_url_editable(editable_req)\n    except ValueError:\n        package_name, url, extras = _parse_pip_syntax_editable(editable_req)\n\n    link = Link(url)\n\n    if not link.is_vcs and not link.url.startswith(\"file:\"):\n        backends = \", \".join(vcs.all_schemes)\n        raise InstallationError(\n            f\"{editable_req} is not a valid editable requirement. \"\n            f\"It should either be a path to a local project or a VCS URL \"\n            f\"(beginning with {backends}).\"\n        )\n\n    # The project name can be inferred from local file URIs easily.\n    if not package_name and not link.url.startswith(\"file:\"):\n        raise InstallationError(\n            f\"Could not detect requirement name for '{editable_req}', \"\n            \"please specify one with your_package_name @ URL\"\n        )\n    return package_name, url, extras\n\n\ndef check_first_requirement_in_file(filename: str) -> None:\n    \"\"\"Check if file is parsable as a requirements file.\n\n    This is heavily based on ``pkg_resources.parse_requirements``, but\n    simplified to just check the first meaningful line.\n\n    :raises InvalidRequirement: If the first meaningful line cannot be parsed\n        as an requirement.\n    \"\"\"\n    with open(filename, encoding=\"utf-8\", errors=\"ignore\") as f:\n        # Create a steppable iterator, so we can handle \\-continuations.\n        lines = (\n            line\n            for line in (line.strip() for line in f)\n            if line and not line.startswith(\"#\")  # Skip blank lines/comments.\n        )\n\n        for line in lines:\n            # Drop comments -- a hash without a space may be in a URL.\n            if \" #\" in line:\n                line = line[: line.find(\" #\")]\n            # If there is a line continuation, drop it, and append the next line.\n            if line.endswith(\"\\\\\"):\n                line = line[:-2].strip() + next(lines, \"\")\n            get_requirement(line)\n            return\n\n\ndef deduce_helpful_msg(req: str) -> str:\n    \"\"\"Returns helpful msg in case requirements file does not exist,\n    or cannot be parsed.\n\n    :params req: Requirements file path\n    \"\"\"\n    if not os.path.exists(req):\n        return f\" File '{req}' does not exist.\"\n    msg = \" The path does exist. \"\n    # Try to parse and check if it is a requirements file.\n    try:\n        check_first_requirement_in_file(req)\n    except InvalidRequirement:\n        logger.debug(\"Cannot parse '%s' as requirements file\", req)\n    else:\n        msg += (\n            f\"The argument you provided \"\n            f\"({req}) appears to be a\"\n            f\" requirements file. If that is the\"\n            f\" case, use the '-r' flag to install\"\n            f\" the packages specified within it.\"\n        )\n    return msg\n\n\n@dataclass(frozen=True)\nclass RequirementParts:\n    requirement: Requirement | None\n    link: Link | None\n    markers: Marker | None\n    extras: set[str]\n\n\ndef parse_req_from_editable(editable_req: str) -> RequirementParts:\n    name, url, extras_override = parse_editable(editable_req)\n\n    if name is not None:\n        try:\n            req: Requirement | None = get_requirement(name)\n        except InvalidRequirement as exc:\n            raise InstallationError(f\"Invalid requirement: {name!r}: {exc}\")\n    else:\n        req = None\n\n    link = Link(url)\n\n    return RequirementParts(req, link, None, extras_override)\n\n\n# ---- The actual constructors follow ----\n\n\ndef install_req_from_editable(\n    editable_req: str,\n    comes_from: InstallRequirement | str | None = None,\n    *,\n    isolated: bool = False,\n    hash_options: dict[str, list[str]] | None = None,\n    constraint: bool = False,\n    user_supplied: bool = False,\n    permit_editable_wheels: bool = False,\n    config_settings: dict[str, str | list[str]] | None = None,\n) -> InstallRequirement:\n    if constraint:\n        raise InstallationError(\"Editable requirements are not allowed as constraints\")\n\n    parts = parse_req_from_editable(editable_req)\n    return InstallRequirement(\n        parts.requirement,\n        comes_from=comes_from,\n        user_supplied=user_supplied,\n        editable=True,\n        permit_editable_wheels=permit_editable_wheels,\n        link=parts.link,\n        constraint=constraint,\n        isolated=isolated,\n        hash_options=hash_options,\n        config_settings=config_settings,\n        extras=parts.extras,\n    )\n\n\ndef _looks_like_path(name: str) -> bool:\n    \"\"\"Checks whether the string \"looks like\" a path on the filesystem.\n\n    This does not check whether the target actually exists, only judge from the\n    appearance.\n\n    Returns true if any of the following conditions is true:\n    * a path separator is found (either os.path.sep or os.path.altsep);\n    * a dot is found (which represents the current directory).\n    \"\"\"\n    if os.path.sep in name:\n        return True\n    if os.path.altsep is not None and os.path.altsep in name:\n        return True\n    if name.startswith(\".\"):\n        return True\n    return False\n\n\ndef _get_url_from_path(path: str, name: str) -> str | None:\n    \"\"\"\n    First, it checks whether a provided path is an installable directory. If it\n    is, returns the path.\n\n    If false, check if the path is an archive file (such as a .whl).\n    The function checks if the path is a file. If false, if the path has\n    an @, it will treat it as a PEP 440 URL requirement and return the path.\n    \"\"\"\n    if _looks_like_path(name) and os.path.isdir(path):\n        if is_installable_dir(path):\n            return path_to_url(path)\n        # TODO: The is_installable_dir test here might not be necessary\n        #       now that it is done in load_pyproject_toml too.\n        raise InstallationError(\n            f\"Directory {name!r} is not installable. Neither 'setup.py' \"\n            \"nor 'pyproject.toml' found.\"\n        )\n    if not is_archive_file(path):\n        return None\n    if os.path.isfile(path):\n        return path_to_url(path)\n    urlreq_parts = name.split(\"@\", 1)\n    if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]):\n        # If the path contains '@' and the part before it does not look\n        # like a path, try to treat it as a PEP 440 URL req instead.\n        return None\n    logger.warning(\n        \"Requirement %r looks like a filename, but the file does not exist\",\n        name,\n    )\n    return path_to_url(path)\n\n\ndef parse_req_from_line(name: str, line_source: str | None) -> RequirementParts:\n    if is_url(name):\n        marker_sep = \"; \"\n    else:\n        marker_sep = \";\"\n    if marker_sep in name:\n        name, markers_as_string = name.split(marker_sep, 1)\n        markers_as_string = markers_as_string.strip()\n        if not markers_as_string:\n            markers = None\n        else:\n            markers = Marker(markers_as_string)\n    else:\n        markers = None\n    name = name.strip()\n    req_as_string = None\n    path = os.path.normpath(os.path.abspath(name))\n    link = None\n    extras_as_string = None\n\n    if is_url(name):\n        link = Link(name)\n    else:\n        p, extras_as_string = _strip_extras(path)\n        url = _get_url_from_path(p, name)\n        if url is not None:\n            link = Link(url)\n\n    # it's a local file, dir, or url\n    if link:\n        # Handle relative file URLs\n        if link.scheme == \"file\" and re.search(r\"\\.\\./\", link.url):\n            link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path))))\n        # wheel file\n        if link.is_wheel:\n            wheel = Wheel(link.filename)  # can raise InvalidWheelFilename\n            req_as_string = f\"{wheel.name}=={wheel.version}\"\n        else:\n            # set the req to the egg fragment.  when it's not there, this\n            # will become an 'unnamed' requirement\n            req_as_string = link.egg_fragment\n\n    # a requirement specifier\n    else:\n        req_as_string = name\n\n    extras = convert_extras(extras_as_string)\n\n    def with_source(text: str) -> str:\n        if not line_source:\n            return text\n        return f\"{text} (from {line_source})\"\n\n    def _parse_req_string(req_as_string: str) -> Requirement:\n        try:\n            return get_requirement(req_as_string)\n        except InvalidRequirement as exc:\n            if os.path.sep in req_as_string:\n                add_msg = \"It looks like a path.\"\n                add_msg += deduce_helpful_msg(req_as_string)\n            elif \"=\" in req_as_string and not any(\n                op in req_as_string for op in operators\n            ):\n                add_msg = \"= is not a valid operator. Did you mean == ?\"\n            else:\n                add_msg = \"\"\n            msg = with_source(f\"Invalid requirement: {req_as_string!r}: {exc}\")\n            if add_msg:\n                msg += f\"\\nHint: {add_msg}\"\n            raise InstallationError(msg)\n\n    if req_as_string is not None:\n        req: Requirement | None = _parse_req_string(req_as_string)\n    else:\n        req = None\n\n    return RequirementParts(req, link, markers, extras)\n\n\ndef install_req_from_line(\n    name: str,\n    comes_from: str | InstallRequirement | None = None,\n    *,\n    isolated: bool = False,\n    hash_options: dict[str, list[str]] | None = None,\n    constraint: bool = False,\n    line_source: str | None = None,\n    user_supplied: bool = False,\n    config_settings: dict[str, str | list[str]] | None = None,\n) -> InstallRequirement:\n    \"\"\"Creates an InstallRequirement from a name, which might be a\n    requirement, directory containing 'setup.py', filename, or URL.\n\n    :param line_source: An optional string describing where the line is from,\n        for logging purposes in case of an error.\n    \"\"\"\n    parts = parse_req_from_line(name, line_source)\n\n    return InstallRequirement(\n        parts.requirement,\n        comes_from,\n        link=parts.link,\n        markers=parts.markers,\n        isolated=isolated,\n        hash_options=hash_options,\n        config_settings=config_settings,\n        constraint=constraint,\n        extras=parts.extras,\n        user_supplied=user_supplied,\n    )\n\n\ndef install_req_from_req_string(\n    req_string: str,\n    comes_from: InstallRequirement | None = None,\n    isolated: bool = False,\n    user_supplied: bool = False,\n) -> InstallRequirement:\n    try:\n        req = get_requirement(req_string)\n    except InvalidRequirement as exc:\n        raise InstallationError(f\"Invalid requirement: {req_string!r}: {exc}\")\n\n    domains_not_allowed = [\n        PyPI.file_storage_domain,\n        TestPyPI.file_storage_domain,\n    ]\n    if (\n        req.url\n        and comes_from\n        and comes_from.link\n        and comes_from.link.netloc in domains_not_allowed\n    ):\n        # Explicitly disallow pypi packages that depend on external urls\n        raise InstallationError(\n            \"Packages installed from PyPI cannot depend on packages \"\n            \"which are not also hosted on PyPI.\\n\"\n            f\"{comes_from.name} depends on {req} \"\n        )\n\n    return InstallRequirement(\n        req,\n        comes_from,\n        isolated=isolated,\n        user_supplied=user_supplied,\n    )\n\n\ndef install_req_from_parsed_requirement(\n    parsed_req: ParsedRequirement,\n    isolated: bool = False,\n    user_supplied: bool = False,\n    config_settings: dict[str, str | list[str]] | None = None,\n) -> InstallRequirement:\n    if parsed_req.is_editable:\n        req = install_req_from_editable(\n            parsed_req.requirement,\n            comes_from=parsed_req.comes_from,\n            constraint=parsed_req.constraint,\n            isolated=isolated,\n            user_supplied=user_supplied,\n            config_settings=config_settings,\n        )\n\n    else:\n        req = install_req_from_line(\n            parsed_req.requirement,\n            comes_from=parsed_req.comes_from,\n            isolated=isolated,\n            hash_options=(\n                parsed_req.options.get(\"hashes\", {}) if parsed_req.options else {}\n            ),\n            constraint=parsed_req.constraint,\n            line_source=parsed_req.line_source,\n            user_supplied=user_supplied,\n            config_settings=config_settings,\n        )\n    return req\n\n\ndef install_req_from_link_and_ireq(\n    link: Link, ireq: InstallRequirement\n) -> InstallRequirement:\n    return InstallRequirement(\n        req=ireq.req,\n        comes_from=ireq.comes_from,\n        editable=ireq.editable,\n        link=link,\n        markers=ireq.markers,\n        isolated=ireq.isolated,\n        hash_options=ireq.hash_options,\n        config_settings=ireq.config_settings,\n        user_supplied=ireq.user_supplied,\n    )\n\n\ndef install_req_drop_extras(ireq: InstallRequirement) -> InstallRequirement:\n    \"\"\"\n    Creates a new InstallationRequirement using the given template but without\n    any extras. Sets the original requirement as the new one's parent\n    (comes_from).\n    \"\"\"\n    return InstallRequirement(\n        req=(\n            _set_requirement_extras(ireq.req, set()) if ireq.req is not None else None\n        ),\n        comes_from=ireq,\n        editable=ireq.editable,\n        link=ireq.link,\n        markers=ireq.markers,\n        isolated=ireq.isolated,\n        hash_options=ireq.hash_options,\n        constraint=ireq.constraint,\n        extras=[],\n        config_settings=ireq.config_settings,\n        user_supplied=ireq.user_supplied,\n        permit_editable_wheels=ireq.permit_editable_wheels,\n    )\n\n\ndef install_req_extend_extras(\n    ireq: InstallRequirement,\n    extras: Collection[str],\n) -> InstallRequirement:\n    \"\"\"\n    Returns a copy of an installation requirement with some additional extras.\n    Makes a shallow copy of the ireq object.\n    \"\"\"\n    result = copy.copy(ireq)\n    result.extras = {*ireq.extras, *extras}\n    result.req = (\n        _set_requirement_extras(ireq.req, result.extras)\n        if ireq.req is not None\n        else None\n    )\n    return result\n"
  },
  {
    "path": "src/pip/_internal/req/pep723.py",
    "content": "import re\nfrom typing import Any\n\nfrom pip._internal.utils.compat import tomllib\n\nREGEX = r\"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\\s(?P<content>(^#(| .*)$\\s)+)^# ///$\"\n\n\nclass PEP723Exception(ValueError):\n    \"\"\"Raised to indicate a problem when parsing PEP 723 metadata from a script\"\"\"\n\n    def __init__(self, msg: str) -> None:\n        self.msg = msg\n\n\ndef pep723_metadata(scriptfile: str) -> dict[str, Any]:\n    with open(scriptfile) as f:\n        script = f.read()\n\n    name = \"script\"\n    matches = list(\n        filter(lambda m: m.group(\"type\") == name, re.finditer(REGEX, script))\n    )\n\n    if len(matches) > 1:\n        raise PEP723Exception(f\"Multiple {name!r} blocks found in {scriptfile!r}\")\n    elif len(matches) == 1:\n        content = \"\".join(\n            line[2:] if line.startswith(\"# \") else line[1:]\n            for line in matches[0].group(\"content\").splitlines(keepends=True)\n        )\n        try:\n            metadata = tomllib.loads(content)\n        except Exception as exc:\n            raise PEP723Exception(f\"Failed to parse TOML in {scriptfile!r}\") from exc\n    else:\n        raise PEP723Exception(\n            f\"File does not contain {name!r} metadata: {scriptfile!r}\"\n        )\n\n    return metadata\n"
  },
  {
    "path": "src/pip/_internal/req/req_dependency_group.py",
    "content": "from collections.abc import Iterable, Iterator\nfrom typing import Any\n\nfrom pip._vendor.dependency_groups import DependencyGroupResolver\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils.compat import tomllib\n\n\ndef parse_dependency_groups(groups: list[tuple[str, str]]) -> list[str]:\n    \"\"\"\n    Parse dependency groups data as provided via the CLI, in a `[path:]group` syntax.\n\n    Raises InstallationErrors if anything goes wrong.\n    \"\"\"\n    resolvers = _build_resolvers(path for (path, _) in groups)\n    return list(_resolve_all_groups(resolvers, groups))\n\n\ndef _resolve_all_groups(\n    resolvers: dict[str, DependencyGroupResolver], groups: list[tuple[str, str]]\n) -> Iterator[str]:\n    \"\"\"\n    Run all resolution, converting any error from `DependencyGroupResolver` into\n    an InstallationError.\n    \"\"\"\n    for path, groupname in groups:\n        resolver = resolvers[path]\n        try:\n            yield from (str(req) for req in resolver.resolve(groupname))\n        except (ValueError, TypeError, LookupError) as e:\n            raise InstallationError(\n                f\"[dependency-groups] resolution failed for '{groupname}' \"\n                f\"from '{path}': {e}\"\n            ) from e\n\n\ndef _build_resolvers(paths: Iterable[str]) -> dict[str, Any]:\n    resolvers = {}\n    for path in paths:\n        if path in resolvers:\n            continue\n\n        pyproject = _load_pyproject(path)\n        if \"dependency-groups\" not in pyproject:\n            raise InstallationError(\n                f\"[dependency-groups] table was missing from '{path}'. \"\n                \"Cannot resolve '--group' option.\"\n            )\n        raw_dependency_groups = pyproject[\"dependency-groups\"]\n        if not isinstance(raw_dependency_groups, dict):\n            raise InstallationError(\n                f\"[dependency-groups] table was malformed in {path}. \"\n                \"Cannot resolve '--group' option.\"\n            )\n\n        resolvers[path] = DependencyGroupResolver(raw_dependency_groups)\n    return resolvers\n\n\ndef _load_pyproject(path: str) -> dict[str, Any]:\n    \"\"\"\n    This helper loads a pyproject.toml as TOML.\n\n    It raises an InstallationError if the operation fails.\n    \"\"\"\n    try:\n        with open(path, \"rb\") as fp:\n            return tomllib.load(fp)\n    except FileNotFoundError:\n        raise InstallationError(f\"{path} not found. Cannot resolve '--group' option.\")\n    except tomllib.TOMLDecodeError as e:\n        raise InstallationError(f\"Error parsing {path}: {e}\") from e\n    except OSError as e:\n        raise InstallationError(f\"Error reading {path}: {e}\") from e\n"
  },
  {
    "path": "src/pip/_internal/req/req_file.py",
    "content": "\"\"\"\nRequirements file parsing\n\"\"\"\n\nfrom __future__ import annotations\n\nimport codecs\nimport locale\nimport logging\nimport optparse\nimport os\nimport re\nimport shlex\nimport sys\nimport urllib.parse\nfrom collections.abc import Generator, Iterable\nfrom dataclasses import dataclass\nfrom optparse import Values\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    NoReturn,\n)\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.exceptions import InstallationError, RequirementsFileParseError\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.search_scope import SearchScope\n\nif TYPE_CHECKING:\n    from pip._internal.index.package_finder import PackageFinder\n    from pip._internal.network.session import PipSession\n\n__all__ = [\"parse_requirements\"]\n\nReqFileLines = Iterable[tuple[int, str]]\n\nLineParser = Callable[[str], tuple[str, Values]]\n\nSCHEME_RE = re.compile(r\"^(http|https|file):\", re.I)\nCOMMENT_RE = re.compile(r\"(^|\\s+)#.*$\")\n\n# Matches environment variable-style values in '${MY_VARIABLE_1}' with the\n# variable name consisting of only uppercase letters, digits or the '_'\n# (underscore). This follows the POSIX standard defined in IEEE Std 1003.1,\n# 2013 Edition.\nENV_VAR_RE = re.compile(r\"(?P<var>\\$\\{(?P<name>[A-Z0-9_]+)\\})\")\n\nSUPPORTED_OPTIONS: list[Callable[..., optparse.Option]] = [\n    cmdoptions.index_url,\n    cmdoptions.extra_index_url,\n    cmdoptions.no_index,\n    cmdoptions.constraints,\n    cmdoptions.requirements,\n    cmdoptions.editable,\n    cmdoptions.find_links,\n    cmdoptions.no_binary,\n    cmdoptions.only_binary,\n    cmdoptions.prefer_binary,\n    cmdoptions.require_hashes,\n    cmdoptions.pre,\n    cmdoptions.all_releases,\n    cmdoptions.only_final,\n    cmdoptions.trusted_host,\n    cmdoptions.use_new_feature,\n]\n\n# options to be passed to requirements\nSUPPORTED_OPTIONS_REQ: list[Callable[..., optparse.Option]] = [\n    cmdoptions.hash,\n    cmdoptions.config_settings,\n]\n\nSUPPORTED_OPTIONS_EDITABLE_REQ: list[Callable[..., optparse.Option]] = [\n    cmdoptions.config_settings,\n]\n\n\n# the 'dest' string values\nSUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ]\nSUPPORTED_OPTIONS_EDITABLE_REQ_DEST = [\n    str(o().dest) for o in SUPPORTED_OPTIONS_EDITABLE_REQ\n]\n\n# order of BOMS is important: codecs.BOM_UTF16_LE is a prefix of codecs.BOM_UTF32_LE\n# so data.startswith(BOM_UTF16_LE) would be true for UTF32_LE data\nBOMS: list[tuple[bytes, str]] = [\n    (codecs.BOM_UTF8, \"utf-8\"),\n    (codecs.BOM_UTF32, \"utf-32\"),\n    (codecs.BOM_UTF32_BE, \"utf-32-be\"),\n    (codecs.BOM_UTF32_LE, \"utf-32-le\"),\n    (codecs.BOM_UTF16, \"utf-16\"),\n    (codecs.BOM_UTF16_BE, \"utf-16-be\"),\n    (codecs.BOM_UTF16_LE, \"utf-16-le\"),\n]\n\nPEP263_ENCODING_RE = re.compile(rb\"coding[:=]\\s*([-\\w.]+)\")\nDEFAULT_ENCODING = \"utf-8\"\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass ParsedRequirement:\n    # TODO: replace this with slots=True when dropping Python 3.9 support.\n    __slots__ = (\n        \"requirement\",\n        \"is_editable\",\n        \"comes_from\",\n        \"constraint\",\n        \"options\",\n        \"line_source\",\n    )\n\n    requirement: str\n    is_editable: bool\n    comes_from: str\n    constraint: bool\n    options: dict[str, Any] | None\n    line_source: str | None\n\n\n@dataclass(frozen=True)\nclass ParsedLine:\n    __slots__ = (\"filename\", \"lineno\", \"args\", \"opts\", \"constraint\")\n\n    filename: str\n    lineno: int\n    args: str\n    opts: Values\n    constraint: bool\n\n    @property\n    def is_editable(self) -> bool:\n        return bool(self.opts.editables)\n\n    @property\n    def requirement(self) -> str | None:\n        if self.args:\n            return self.args\n        elif self.is_editable:\n            # We don't support multiple -e on one line\n            return self.opts.editables[0]\n        return None\n\n\ndef parse_requirements(\n    filename: str,\n    session: PipSession,\n    finder: PackageFinder | None = None,\n    options: optparse.Values | None = None,\n    constraint: bool = False,\n) -> Generator[ParsedRequirement, None, None]:\n    \"\"\"Parse a requirements file and yield ParsedRequirement instances.\n\n    :param filename:    Path or url of requirements file.\n    :param session:     PipSession instance.\n    :param finder:      Instance of pip.index.PackageFinder.\n    :param options:     cli options.\n    :param constraint:  If true, parsing a constraint file rather than\n        requirements file.\n    \"\"\"\n    line_parser = get_line_parser(finder)\n    parser = RequirementsFileParser(session, line_parser)\n\n    for parsed_line in parser.parse(filename, constraint):\n        parsed_req = handle_line(\n            parsed_line, options=options, finder=finder, session=session\n        )\n        if parsed_req is not None:\n            yield parsed_req\n\n\ndef preprocess(content: str) -> ReqFileLines:\n    \"\"\"Split, filter, and join lines, and return a line iterator\n\n    :param content: the content of the requirements file\n    \"\"\"\n    lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)\n    lines_enum = join_lines(lines_enum)\n    lines_enum = ignore_comments(lines_enum)\n    lines_enum = expand_env_variables(lines_enum)\n    return lines_enum\n\n\ndef handle_requirement_line(\n    line: ParsedLine,\n    options: optparse.Values | None = None,\n) -> ParsedRequirement:\n    # preserve for the nested code path\n    line_comes_from = \"{} {} (line {})\".format(\n        \"-c\" if line.constraint else \"-r\",\n        line.filename,\n        line.lineno,\n    )\n\n    assert line.requirement is not None\n\n    # get the options that apply to requirements\n    if line.is_editable:\n        supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST\n    else:\n        supported_dest = SUPPORTED_OPTIONS_REQ_DEST\n    req_options = {}\n    for dest in supported_dest:\n        if dest in line.opts.__dict__ and line.opts.__dict__[dest]:\n            req_options[dest] = line.opts.__dict__[dest]\n\n    line_source = f\"line {line.lineno} of {line.filename}\"\n    return ParsedRequirement(\n        requirement=line.requirement,\n        is_editable=line.is_editable,\n        comes_from=line_comes_from,\n        constraint=line.constraint,\n        options=req_options,\n        line_source=line_source,\n    )\n\n\ndef handle_option_line(\n    opts: Values,\n    filename: str,\n    lineno: int,\n    finder: PackageFinder | None = None,\n    options: optparse.Values | None = None,\n    session: PipSession | None = None,\n) -> None:\n    if opts.hashes:\n        logger.warning(\n            \"%s line %s has --hash but no requirement, and will be ignored.\",\n            filename,\n            lineno,\n        )\n\n    if options:\n        # percolate options upward\n        if opts.require_hashes:\n            options.require_hashes = opts.require_hashes\n        if opts.features_enabled:\n            options.features_enabled.extend(\n                f for f in opts.features_enabled if f not in options.features_enabled\n            )\n\n    # set finder options\n    if finder:\n        find_links = finder.find_links\n        index_urls = finder.index_urls\n        no_index = finder.search_scope.no_index\n        if opts.no_index is True:\n            no_index = True\n            index_urls = []\n        if opts.index_url and not no_index:\n            index_urls = [opts.index_url]\n        if opts.extra_index_urls and not no_index:\n            index_urls.extend(opts.extra_index_urls)\n        if opts.find_links:\n            # FIXME: it would be nice to keep track of the source\n            # of the find_links: support a find-links local path\n            # relative to a requirements file.\n            value = opts.find_links[0]\n            req_dir = os.path.dirname(os.path.abspath(filename))\n            relative_to_reqs_file = os.path.join(req_dir, value)\n            if os.path.exists(relative_to_reqs_file):\n                value = relative_to_reqs_file\n            find_links.append(value)\n\n        if session:\n            # We need to update the auth urls in session\n            session.update_index_urls(index_urls)\n\n        search_scope = SearchScope(\n            find_links=find_links,\n            index_urls=index_urls,\n            no_index=no_index,\n        )\n        finder.search_scope = search_scope\n\n        # Transform --pre into --all-releases :all:\n        if opts.pre:\n            if not opts.release_control:\n                opts.release_control = ReleaseControl()\n            opts.release_control.all_releases.add(\":all:\")\n\n        if opts.release_control:\n            if not finder.release_control:\n                # First time seeing release_control, set it on finder\n                finder.set_release_control(opts.release_control)\n\n        if opts.prefer_binary:\n            finder.set_prefer_binary()\n\n        if session:\n            for host in opts.trusted_hosts or []:\n                source = f\"line {lineno} of {filename}\"\n                session.add_trusted_host(host, source=source)\n\n\ndef handle_line(\n    line: ParsedLine,\n    options: optparse.Values | None = None,\n    finder: PackageFinder | None = None,\n    session: PipSession | None = None,\n) -> ParsedRequirement | None:\n    \"\"\"Handle a single parsed requirements line; This can result in\n    creating/yielding requirements, or updating the finder.\n\n    :param line:        The parsed line to be processed.\n    :param options:     CLI options.\n    :param finder:      The finder - updated by non-requirement lines.\n    :param session:     The session - updated by non-requirement lines.\n\n    Returns a ParsedRequirement object if the line is a requirement line,\n    otherwise returns None.\n\n    For lines that contain requirements, the only options that have an effect\n    are from SUPPORTED_OPTIONS_REQ, and they are scoped to the\n    requirement. Other options from SUPPORTED_OPTIONS may be present, but are\n    ignored.\n\n    For lines that do not contain requirements, the only options that have an\n    effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may\n    be present, but are ignored. These lines may contain multiple options\n    (although our docs imply only one is supported), and all our parsed and\n    affect the finder.\n    \"\"\"\n\n    if line.requirement is not None:\n        parsed_req = handle_requirement_line(line, options)\n        return parsed_req\n    else:\n        handle_option_line(\n            line.opts,\n            line.filename,\n            line.lineno,\n            finder,\n            options,\n            session,\n        )\n        return None\n\n\nclass RequirementsFileParser:\n    def __init__(\n        self,\n        session: PipSession,\n        line_parser: LineParser,\n    ) -> None:\n        self._session = session\n        self._line_parser = line_parser\n\n    def parse(\n        self, filename: str, constraint: bool\n    ) -> Generator[ParsedLine, None, None]:\n        \"\"\"Parse a given file, yielding parsed lines.\"\"\"\n        yield from self._parse_and_recurse(\n            filename, constraint, [{os.path.abspath(filename): None}]\n        )\n\n    def _parse_and_recurse(\n        self,\n        filename: str,\n        constraint: bool,\n        parsed_files_stack: list[dict[str, str | None]],\n    ) -> Generator[ParsedLine, None, None]:\n        for line in self._parse_file(filename, constraint):\n            if line.requirement is None and (\n                line.opts.requirements or line.opts.constraints\n            ):\n                # parse a nested requirements file\n                if line.opts.requirements:\n                    req_path = line.opts.requirements[0]\n                    nested_constraint = False\n                else:\n                    req_path = line.opts.constraints[0]\n                    nested_constraint = True\n\n                # original file is over http\n                if SCHEME_RE.search(filename):\n                    # do a url join so relative paths work\n                    req_path = urllib.parse.urljoin(filename, req_path)\n                # original file and nested file are paths\n                elif not SCHEME_RE.search(req_path):\n                    # do a join so relative paths work\n                    # and then abspath so that we can identify recursive references\n                    req_path = os.path.abspath(\n                        os.path.join(\n                            os.path.dirname(filename),\n                            req_path,\n                        )\n                    )\n                parsed_files = parsed_files_stack[0]\n                if req_path in parsed_files:\n                    initial_file = parsed_files[req_path]\n                    tail = (\n                        f\" and again in {initial_file}\"\n                        if initial_file is not None\n                        else \"\"\n                    )\n                    raise RequirementsFileParseError(\n                        f\"{req_path} recursively references itself in {filename}{tail}\"\n                    )\n                # Keeping a track where was each file first included in\n                new_parsed_files = parsed_files.copy()\n                new_parsed_files[req_path] = filename\n                yield from self._parse_and_recurse(\n                    req_path, nested_constraint, [new_parsed_files, *parsed_files_stack]\n                )\n            else:\n                yield line\n\n    def _parse_file(\n        self, filename: str, constraint: bool\n    ) -> Generator[ParsedLine, None, None]:\n        _, content = get_file_content(filename, self._session, constraint=constraint)\n\n        lines_enum = preprocess(content)\n\n        for line_number, line in lines_enum:\n            try:\n                args_str, opts = self._line_parser(line)\n            except OptionParsingError as e:\n                # add offending line\n                msg = f\"Invalid requirement: {line}\\n{e.msg}\"\n                raise RequirementsFileParseError(msg)\n\n            yield ParsedLine(\n                filename,\n                line_number,\n                args_str,\n                opts,\n                constraint,\n            )\n\n\ndef get_line_parser(finder: PackageFinder | None) -> LineParser:\n    def parse_line(line: str) -> tuple[str, Values]:\n        # Build new parser for each line since it accumulates appendable\n        # options.\n        parser = build_parser()\n        defaults = parser.get_default_values()\n        defaults.index_url = None\n        if finder:\n            defaults.format_control = finder.format_control\n            defaults.release_control = finder.release_control\n\n        args_str, options_str = break_args_options(line)\n\n        try:\n            options = shlex.split(options_str)\n        except ValueError as e:\n            raise OptionParsingError(f\"Could not split options: {options_str}\") from e\n\n        opts, _ = parser.parse_args(options, defaults)\n\n        return args_str, opts\n\n    return parse_line\n\n\ndef break_args_options(line: str) -> tuple[str, str]:\n    \"\"\"Break up the line into an args and options string.  We only want to shlex\n    (and then optparse) the options, not the args.  args can contain markers\n    which are corrupted by shlex.\n    \"\"\"\n    tokens = line.split(\" \")\n    args = []\n    options = tokens[:]\n    for token in tokens:\n        if token.startswith((\"-\", \"--\")):\n            break\n        else:\n            args.append(token)\n            options.pop(0)\n    return \" \".join(args), \" \".join(options)\n\n\nclass OptionParsingError(Exception):\n    def __init__(self, msg: str) -> None:\n        self.msg = msg\n\n\ndef build_parser() -> optparse.OptionParser:\n    \"\"\"\n    Return a parser for parsing requirement lines\n    \"\"\"\n    parser = optparse.OptionParser(add_help_option=False)\n\n    option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ\n    for option_factory in option_factories:\n        option = option_factory()\n        parser.add_option(option)\n\n    # By default optparse sys.exits on parsing errors. We want to wrap\n    # that in our own exception.\n    def parser_exit(self: Any, msg: str) -> NoReturn:\n        raise OptionParsingError(msg)\n\n    # NOTE: mypy disallows assigning to a method\n    #       https://github.com/python/mypy/issues/2427\n    parser.exit = parser_exit  # type: ignore\n\n    return parser\n\n\ndef join_lines(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"Joins a line ending in '\\' with the previous line (except when following\n    comments).  The joined line takes on the index of the first line.\n    \"\"\"\n    primary_line_number = None\n    new_line: list[str] = []\n    for line_number, line in lines_enum:\n        if not line.endswith(\"\\\\\") or COMMENT_RE.match(line):\n            if COMMENT_RE.match(line):\n                # this ensures comments are always matched later\n                line = \" \" + line\n            if new_line:\n                new_line.append(line)\n                assert primary_line_number is not None\n                yield primary_line_number, \"\".join(new_line)\n                new_line = []\n            else:\n                yield line_number, line\n        else:\n            if not new_line:\n                primary_line_number = line_number\n            new_line.append(line.strip(\"\\\\\"))\n\n    # last line contains \\\n    if new_line:\n        assert primary_line_number is not None\n        yield primary_line_number, \"\".join(new_line)\n\n    # TODO: handle space after '\\'.\n\n\ndef ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"\n    Strips comments and filter empty lines.\n    \"\"\"\n    for line_number, line in lines_enum:\n        line = COMMENT_RE.sub(\"\", line)\n        line = line.strip()\n        if line:\n            yield line_number, line\n\n\ndef expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"Replace all environment variables that can be retrieved via `os.getenv`.\n\n    The only allowed format for environment variables defined in the\n    requirement file is `${MY_VARIABLE_1}` to ensure two things:\n\n    1. Strings that contain a `$` aren't accidentally (partially) expanded.\n    2. Ensure consistency across platforms for requirement files.\n\n    These points are the result of a discussion on the `github pull\n    request #3514 <https://github.com/pypa/pip/pull/3514>`_.\n\n    Valid characters in variable names follow the `POSIX standard\n    <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited\n    to uppercase letter, digits and the `_` (underscore).\n    \"\"\"\n    for line_number, line in lines_enum:\n        for env_var, var_name in ENV_VAR_RE.findall(line):\n            value = os.getenv(var_name)\n            if not value:\n                continue\n\n            line = line.replace(env_var, value)\n\n        yield line_number, line\n\n\ndef get_file_content(\n    url: str, session: PipSession, *, constraint: bool = False\n) -> tuple[str, str]:\n    \"\"\"Gets the content of a file; it may be a filename, file: URL, or\n    http: URL.  Returns (location, content).  Content is unicode.\n    Respects # -*- coding: declarations on the retrieved files.\n\n    :param url:         File path or url.\n    :param session:     PipSession instance.\n    \"\"\"\n    scheme = urllib.parse.urlsplit(url).scheme\n    # Pip has special support for file:// URLs (LocalFSAdapter).\n    if scheme in [\"http\", \"https\", \"file\"]:\n        # Delay importing heavy network modules until absolutely necessary.\n        from pip._internal.network.utils import raise_for_status\n\n        resp = session.get(url)\n        raise_for_status(resp)\n        return resp.url, resp.text\n\n    # Assume this is a bare path.\n    try:\n        with open(url, \"rb\") as f:\n            raw_content = f.read()\n    except OSError as exc:\n        kind = \"constraint\" if constraint else \"requirements\"\n        raise InstallationError(f\"Could not open {kind} file: {exc}\")\n\n    content = _decode_req_file(raw_content, url)\n\n    return url, content\n\n\ndef _decode_req_file(data: bytes, url: str) -> str:\n    for bom, encoding in BOMS:\n        if data.startswith(bom):\n            return data[len(bom) :].decode(encoding)\n\n    for line in data.split(b\"\\n\")[:2]:\n        if line[0:1] == b\"#\":\n            result = PEP263_ENCODING_RE.search(line)\n            if result is not None:\n                encoding = result.groups()[0].decode(\"ascii\")\n                return data.decode(encoding)\n\n    try:\n        return data.decode(DEFAULT_ENCODING)\n    except UnicodeDecodeError:\n        locale_encoding = locale.getpreferredencoding(False) or sys.getdefaultencoding()\n        logging.warning(\n            \"unable to decode data from %s with default encoding %s, \"\n            \"falling back to encoding from locale: %s. \"\n            \"If this is intentional you should specify the encoding with a \"\n            \"PEP-263 style comment, e.g. '# -*- coding: %s -*-'\",\n            url,\n            DEFAULT_ENCODING,\n            locale_encoding,\n            locale_encoding,\n        )\n        return data.decode(locale_encoding)\n"
  },
  {
    "path": "src/pip/_internal/req/req_install.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport logging\nimport os\nimport shutil\nimport sys\nimport uuid\nimport zipfile\nfrom collections.abc import Collection, Iterable\nfrom optparse import Values\nfrom pathlib import Path\nfrom typing import Any\n\nfrom pip._vendor.packaging.markers import Marker\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller\n\nfrom pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment\nfrom pip._internal.exceptions import InstallationError, PreviousBuildDirError\nfrom pip._internal.locations import get_scheme\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    get_default_environment,\n    get_directory_distribution,\n    get_wheel_distribution,\n)\nfrom pip._internal.metadata.base import FilesystemWheel\nfrom pip._internal.models.direct_url import DirectUrl\nfrom pip._internal.models.link import Link\nfrom pip._internal.operations.build.metadata import generate_metadata\nfrom pip._internal.operations.build.metadata_editable import generate_editable_metadata\nfrom pip._internal.operations.install.wheel import install_wheel\nfrom pip._internal.pyproject import load_pyproject_toml, make_pyproject_path\nfrom pip._internal.req.req_uninstall import UninstallPathSet\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.misc import (\n    ConfiguredBuildBackendHookCaller,\n    ask_path_exists,\n    backup_dir,\n    display_path,\n    hide_url,\n    is_installable_dir,\n    redact_auth_from_requirement,\n    redact_auth_from_url,\n)\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\nfrom pip._internal.utils.unpacking import unpack_file\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\nfrom pip._internal.vcs import vcs\n\nlogger = logging.getLogger(__name__)\n\n\nclass InstallRequirement:\n    \"\"\"\n    Represents something that may be installed later on, may have information\n    about where to fetch the relevant requirement and also contains logic for\n    installing the said requirement.\n    \"\"\"\n\n    def __init__(\n        self,\n        req: Requirement | None,\n        comes_from: str | InstallRequirement | None,\n        editable: bool = False,\n        link: Link | None = None,\n        markers: Marker | None = None,\n        isolated: bool = False,\n        *,\n        hash_options: dict[str, list[str]] | None = None,\n        config_settings: dict[str, str | list[str]] | None = None,\n        constraint: bool = False,\n        extras: Collection[str] = (),\n        user_supplied: bool = False,\n        permit_editable_wheels: bool = False,\n    ) -> None:\n        assert req is None or isinstance(req, Requirement), req\n        self.req = req\n        self.comes_from = comes_from\n        self.constraint = constraint\n        self.editable = editable\n        self.permit_editable_wheels = permit_editable_wheels\n\n        # source_dir is the local directory where the linked requirement is\n        # located, or unpacked. In case unpacking is needed, creating and\n        # populating source_dir is done by the RequirementPreparer. Note this\n        # is not necessarily the directory where pyproject.toml or setup.py is\n        # located - that one is obtained via unpacked_source_directory.\n        self.source_dir: str | None = None\n        if self.editable:\n            assert link\n            if link.is_file:\n                self.source_dir = os.path.normpath(os.path.abspath(link.file_path))\n\n        # original_link is the direct URL that was provided by the user for the\n        # requirement, either directly or via a constraints file.\n        if link is None and req and req.url:\n            # PEP 508 URL requirement\n            link = Link(req.url)\n        self.link = self.original_link = link\n\n        # When this InstallRequirement is a wheel obtained from the cache of locally\n        # built wheels, this is the source link corresponding to the cache entry, which\n        # was used to download and build the cached wheel.\n        self.cached_wheel_source_link: Link | None = None\n\n        # Information about the location of the artifact that was downloaded . This\n        # property is guaranteed to be set in resolver results.\n        self.download_info: DirectUrl | None = None\n\n        # Path to any downloaded or already-existing package.\n        self.local_file_path: str | None = None\n        if self.link and self.link.is_file:\n            self.local_file_path = self.link.file_path\n\n        if extras:\n            self.extras = extras\n        elif req:\n            self.extras = req.extras\n        else:\n            self.extras = set()\n        if markers is None and req:\n            markers = req.marker\n        self.markers = markers\n\n        # This holds the Distribution object if this requirement is already installed.\n        self.satisfied_by: BaseDistribution | None = None\n        # Whether the installation process should try to uninstall an existing\n        # distribution before installing this requirement.\n        self.should_reinstall = False\n        # Temporary build location\n        self._temp_build_dir: TempDirectory | None = None\n        # Set to True after successful installation\n        self.install_succeeded: bool | None = None\n        # Supplied options\n        self.hash_options = hash_options if hash_options else {}\n        self.config_settings = config_settings\n        # Set to True after successful preparation of this requirement\n        self.prepared = False\n        # User supplied requirement are explicitly requested for installation\n        # by the user via CLI arguments or requirements files, as opposed to,\n        # e.g. dependencies, extras or constraints.\n        self.user_supplied = user_supplied\n\n        self.isolated = isolated\n        self.build_env: BuildEnvironment = NoOpBuildEnvironment()\n\n        # For PEP 517, the directory where we request the project metadata\n        # gets stored. We need this to pass to build_wheel, so the backend\n        # can ensure that the wheel matches the metadata (see the PEP for\n        # details).\n        self.metadata_directory: str | None = None\n\n        # The cached metadata distribution that this requirement represents.\n        # See get_dist / set_dist.\n        self._distribution: BaseDistribution | None = None\n\n        # The static build requirements (from pyproject.toml)\n        self.pyproject_requires: list[str] | None = None\n\n        # Build requirements that we will check are available\n        self.requirements_to_check: list[str] = []\n\n        # The PEP 517 backend we should use to build the project\n        self.pep517_backend: BuildBackendHookCaller | None = None\n\n        # This requirement needs more preparation before it can be built\n        self.needs_more_preparation = False\n\n        # This requirement needs to be unpacked before it can be installed.\n        self._archive_source: Path | None = None\n\n    def __str__(self) -> str:\n        if self.req:\n            s = redact_auth_from_requirement(self.req)\n            if self.link:\n                s += f\" from {redact_auth_from_url(self.link.url)}\"\n        elif self.link:\n            s = redact_auth_from_url(self.link.url)\n        else:\n            s = \"<InstallRequirement>\"\n        if self.satisfied_by is not None:\n            if self.satisfied_by.location is not None:\n                location = display_path(self.satisfied_by.location)\n            else:\n                location = \"<memory>\"\n            s += f\" in {location}\"\n        if self.comes_from:\n            if isinstance(self.comes_from, str):\n                comes_from: str | None = self.comes_from\n            else:\n                comes_from = self.comes_from.from_path()\n            if comes_from:\n                s += f\" (from {comes_from})\"\n        return s\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__} object: \"\n            f\"{str(self)} editable={self.editable!r}>\"\n        )\n\n    def format_debug(self) -> str:\n        \"\"\"An un-tested helper for getting state, for debugging.\"\"\"\n        attributes = vars(self)\n        names = sorted(attributes)\n\n        state = (f\"{attr}={attributes[attr]!r}\" for attr in sorted(names))\n        return \"<{name} object: {{{state}}}>\".format(\n            name=self.__class__.__name__,\n            state=\", \".join(state),\n        )\n\n    # Things that are valid for all kinds of requirements?\n    @property\n    def name(self) -> str | None:\n        if self.req is None:\n            return None\n        return self.req.name\n\n    @functools.cached_property\n    def supports_pyproject_editable(self) -> bool:\n        assert self.pep517_backend\n        with self.build_env:\n            runner = runner_with_spinner_message(\n                \"Checking if build backend supports build_editable\"\n            )\n            with self.pep517_backend.subprocess_runner(runner):\n                return \"build_editable\" in self.pep517_backend._supported_features()\n\n    @property\n    def specifier(self) -> SpecifierSet:\n        assert self.req is not None\n        return self.req.specifier\n\n    @property\n    def is_direct(self) -> bool:\n        \"\"\"Whether this requirement was specified as a direct URL.\"\"\"\n        return self.original_link is not None\n\n    @property\n    def is_pinned(self) -> bool:\n        \"\"\"Return whether I am pinned to an exact version.\n\n        For example, some-package==1.2 is pinned; some-package>1.2 is not.\n        \"\"\"\n        assert self.req is not None\n        specifiers = self.req.specifier\n        return len(specifiers) == 1 and next(iter(specifiers)).operator in {\"==\", \"===\"}\n\n    def match_markers(self, extras_requested: Iterable[str] | None = None) -> bool:\n        if not extras_requested:\n            # Provide an extra to safely evaluate the markers\n            # without matching any extra\n            extras_requested = (\"\",)\n        if self.markers is not None:\n            return any(\n                self.markers.evaluate({\"extra\": extra}) for extra in extras_requested\n            )\n        else:\n            return True\n\n    @property\n    def has_hash_options(self) -> bool:\n        \"\"\"Return whether any known-good hashes are specified as options.\n\n        These activate --require-hashes mode; hashes specified as part of a\n        URL do not.\n\n        \"\"\"\n        return bool(self.hash_options)\n\n    def hashes(self, trust_internet: bool = True) -> Hashes:\n        \"\"\"Return a hash-comparer that considers my option- and URL-based\n        hashes to be known-good.\n\n        Hashes in URLs--ones embedded in the requirements file, not ones\n        downloaded from an index server--are almost peers with ones from\n        flags. They satisfy --require-hashes (whether it was implicitly or\n        explicitly activated) but do not activate it. md5 and sha224 are not\n        allowed in flags, which should nudge people toward good algos. We\n        always OR all hashes together, even ones from URLs.\n\n        :param trust_internet: Whether to trust URL-based (#md5=...) hashes\n            downloaded from the internet, as by populate_link()\n\n        \"\"\"\n        good_hashes = self.hash_options.copy()\n        if trust_internet:\n            link = self.link\n        elif self.is_direct and self.user_supplied:\n            link = self.original_link\n        else:\n            link = None\n        if link and link.hash:\n            assert link.hash_name is not None\n            good_hashes.setdefault(link.hash_name, []).append(link.hash)\n        return Hashes(good_hashes)\n\n    def from_path(self) -> str | None:\n        \"\"\"Format a nice indicator to show where this \"comes from\" \"\"\"\n        if self.req is None:\n            return None\n        s = str(self.req)\n        if self.comes_from:\n            comes_from: str | None\n            if isinstance(self.comes_from, str):\n                comes_from = self.comes_from\n            else:\n                comes_from = self.comes_from.from_path()\n            if comes_from:\n                s += \"->\" + comes_from\n        return s\n\n    def ensure_build_location(\n        self, build_dir: str, autodelete: bool, parallel_builds: bool\n    ) -> str:\n        assert build_dir is not None\n        if self._temp_build_dir is not None:\n            assert self._temp_build_dir.path\n            return self._temp_build_dir.path\n        if self.req is None:\n            # Some systems have /tmp as a symlink which confuses custom\n            # builds (such as numpy). Thus, we ensure that the real path\n            # is returned.\n            self._temp_build_dir = TempDirectory(\n                kind=tempdir_kinds.REQ_BUILD, globally_managed=True\n            )\n\n            return self._temp_build_dir.path\n\n        # This is the only remaining place where we manually determine the path\n        # for the temporary directory. It is only needed for editables where\n        # it is the value of the --src option.\n\n        # When parallel builds are enabled, add a UUID to the build directory\n        # name so multiple builds do not interfere with each other.\n        dir_name: str = canonicalize_name(self.req.name)\n        if parallel_builds:\n            dir_name = f\"{dir_name}_{uuid.uuid4().hex}\"\n\n        # FIXME: Is there a better place to create the build_dir? (hg and bzr\n        # need this)\n        if not os.path.exists(build_dir):\n            logger.debug(\"Creating directory %s\", build_dir)\n            os.makedirs(build_dir)\n        actual_build_dir = os.path.join(build_dir, dir_name)\n        # `None` indicates that we respect the globally-configured deletion\n        # settings, which is what we actually want when auto-deleting.\n        delete_arg = None if autodelete else False\n        return TempDirectory(\n            path=actual_build_dir,\n            delete=delete_arg,\n            kind=tempdir_kinds.REQ_BUILD,\n            globally_managed=True,\n        ).path\n\n    def _set_requirement(self) -> None:\n        \"\"\"Set requirement after generating metadata.\"\"\"\n        assert self.req is None\n        assert self.metadata is not None\n        assert self.source_dir is not None\n\n        # Construct a Requirement object from the generated metadata\n        if isinstance(parse_version(self.metadata[\"Version\"]), Version):\n            op = \"==\"\n        else:\n            op = \"===\"\n\n        self.req = get_requirement(\n            \"\".join(\n                [\n                    self.metadata[\"Name\"],\n                    op,\n                    self.metadata[\"Version\"],\n                ]\n            )\n        )\n\n    def warn_on_mismatching_name(self) -> None:\n        assert self.req is not None\n        metadata_name = canonicalize_name(self.metadata[\"Name\"])\n        if canonicalize_name(self.req.name) == metadata_name:\n            # Everything is fine.\n            return\n\n        # If we're here, there's a mismatch. Log a warning about it.\n        logger.warning(\n            \"Generating metadata for package %s \"\n            \"produced metadata for project name %s. Fix your \"\n            \"#egg=%s fragments.\",\n            self.name,\n            metadata_name,\n            self.name,\n        )\n        self.req = get_requirement(metadata_name)\n\n    def check_if_exists(self, use_user_site: bool) -> None:\n        \"\"\"Find an installed distribution that satisfies or conflicts\n        with this requirement, and set self.satisfied_by or\n        self.should_reinstall appropriately.\n        \"\"\"\n        if self.req is None:\n            return\n        existing_dist = get_default_environment().get_distribution(self.req.name)\n        if not existing_dist:\n            return\n\n        version_compatible = self.req.specifier.contains(\n            existing_dist.version,\n            prereleases=True,\n        )\n        if not version_compatible:\n            self.satisfied_by = None\n            if use_user_site:\n                if existing_dist.in_usersite:\n                    self.should_reinstall = True\n                elif running_under_virtualenv() and existing_dist.in_site_packages:\n                    raise InstallationError(\n                        f\"Will not install to the user site because it will \"\n                        f\"lack sys.path precedence to {existing_dist.raw_name} \"\n                        f\"in {existing_dist.location}\"\n                    )\n            else:\n                self.should_reinstall = True\n        else:\n            if self.editable:\n                self.should_reinstall = True\n                # when installing editables, nothing pre-existing should ever\n                # satisfy\n                self.satisfied_by = None\n            else:\n                self.satisfied_by = existing_dist\n\n    # Things valid for wheels\n    @property\n    def is_wheel(self) -> bool:\n        if not self.link:\n            return False\n        return self.link.is_wheel\n\n    @property\n    def is_wheel_from_cache(self) -> bool:\n        # When True, it means that this InstallRequirement is a local wheel file in the\n        # cache of locally built wheels.\n        return self.cached_wheel_source_link is not None\n\n    # Things valid for sdists\n    @property\n    def unpacked_source_directory(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        return os.path.join(\n            self.source_dir, self.link and self.link.subdirectory_fragment or \"\"\n        )\n\n    @property\n    def setup_py_path(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        setup_py = os.path.join(self.unpacked_source_directory, \"setup.py\")\n\n        return setup_py\n\n    @property\n    def pyproject_toml_path(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        return make_pyproject_path(self.unpacked_source_directory)\n\n    def load_pyproject_toml(self) -> None:\n        \"\"\"Load the pyproject.toml file.\n\n        After calling this routine, all of the attributes related to PEP 517\n        processing for this requirement have been set.\n        \"\"\"\n        pyproject_toml_data = load_pyproject_toml(\n            self.pyproject_toml_path, self.setup_py_path, str(self)\n        )\n        assert pyproject_toml_data\n        requires, backend, check, backend_path = pyproject_toml_data\n        self.requirements_to_check = check\n        self.pyproject_requires = requires\n        self.pep517_backend = ConfiguredBuildBackendHookCaller(\n            self,\n            self.unpacked_source_directory,\n            backend,\n            backend_path=backend_path,\n        )\n\n    def editable_sanity_check(self) -> None:\n        \"\"\"Check that an editable requirement if valid for use with PEP 517/518.\n\n        This verifies that an editable has a build backend that supports PEP 660.\n        \"\"\"\n        if self.editable and not self.supports_pyproject_editable:\n            raise InstallationError(\n                f\"Project {self} uses a build backend \"\n                f\"that is missing the 'build_editable' hook, so \"\n                f\"it cannot be installed in editable mode. \"\n                f\"Consider using a build backend that supports PEP 660.\"\n            )\n\n    def prepare_metadata(self) -> None:\n        \"\"\"Ensure that project metadata is available.\n\n        Under PEP 517 and PEP 660, call the backend hook to prepare the metadata.\n        Under legacy processing, call setup.py egg-info.\n        \"\"\"\n        assert self.source_dir, f\"No source dir for {self}\"\n        details = self.name or f\"from {self.link}\"\n\n        assert self.pep517_backend is not None\n        if (\n            self.editable\n            and self.permit_editable_wheels\n            and self.supports_pyproject_editable\n        ):\n            self.metadata_directory = generate_editable_metadata(\n                build_env=self.build_env,\n                backend=self.pep517_backend,\n                details=details,\n            )\n        else:\n            self.metadata_directory = generate_metadata(\n                build_env=self.build_env,\n                backend=self.pep517_backend,\n                details=details,\n            )\n\n        # Act on the newly generated metadata, based on the name and version.\n        if not self.name:\n            self._set_requirement()\n        else:\n            self.warn_on_mismatching_name()\n\n        self.assert_source_matches_version()\n\n    @property\n    def metadata(self) -> Any:\n        if not hasattr(self, \"_metadata\"):\n            self._metadata = self.get_dist().metadata\n\n        return self._metadata\n\n    def set_dist(self, distribution: BaseDistribution) -> None:\n        self._distribution = distribution\n\n    def get_dist(self) -> BaseDistribution:\n        if self._distribution is not None:\n            return self._distribution\n        elif self.metadata_directory:\n            return get_directory_distribution(self.metadata_directory)\n        elif self.local_file_path and self.is_wheel:\n            assert self.req is not None\n            return get_wheel_distribution(\n                FilesystemWheel(self.local_file_path),\n                canonicalize_name(self.req.name),\n            )\n        raise AssertionError(\n            f\"InstallRequirement {self} has no metadata directory and no wheel: \"\n            f\"can't make a distribution.\"\n        )\n\n    def assert_source_matches_version(self) -> None:\n        assert self.source_dir, f\"No source dir for {self}\"\n        version = self.metadata[\"version\"]\n        if self.req and self.req.specifier and version not in self.req.specifier:\n            logger.warning(\n                \"Requested %s, but installing version %s\",\n                self,\n                version,\n            )\n        else:\n            logger.debug(\n                \"Source in %s has version %s, which satisfies requirement %s\",\n                display_path(self.source_dir),\n                version,\n                self,\n            )\n\n    # For both source distributions and editables\n    def ensure_has_source_dir(\n        self,\n        parent_dir: str,\n        autodelete: bool = False,\n        parallel_builds: bool = False,\n    ) -> None:\n        \"\"\"Ensure that a source_dir is set.\n\n        This will create a temporary build dir if the name of the requirement\n        isn't known yet.\n\n        :param parent_dir: The ideal pip parent_dir for the source_dir.\n            Generally src_dir for editables and build_dir for sdists.\n        :return: self.source_dir\n        \"\"\"\n        if self.source_dir is None:\n            self.source_dir = self.ensure_build_location(\n                parent_dir,\n                autodelete=autodelete,\n                parallel_builds=parallel_builds,\n            )\n\n    def needs_unpacked_archive(self, archive_source: Path) -> None:\n        assert self._archive_source is None\n        self._archive_source = archive_source\n\n    def ensure_pristine_source_checkout(self) -> None:\n        \"\"\"Ensure the source directory has not yet been built in.\"\"\"\n        assert self.source_dir is not None\n        if self._archive_source is not None:\n            unpack_file(str(self._archive_source), self.source_dir)\n        elif is_installable_dir(self.source_dir):\n            # If a checkout exists, it's unwise to keep going.\n            # version inconsistencies are logged later, but do not fail\n            # the installation.\n            raise PreviousBuildDirError(\n                f\"pip can't proceed with requirements '{self}' due to a \"\n                f\"pre-existing build directory ({self.source_dir}). This is likely \"\n                \"due to a previous installation that failed . pip is \"\n                \"being responsible and not assuming it can delete this. \"\n                \"Please delete it and try again.\"\n            )\n\n    # For editable installations\n    def update_editable(self) -> None:\n        if not self.link:\n            logger.debug(\n                \"Cannot update repository at %s; repository location is unknown\",\n                self.source_dir,\n            )\n            return\n        assert self.editable\n        assert self.source_dir\n        if self.link.scheme == \"file\":\n            # Static paths don't get updated\n            return\n        vcs_backend = vcs.get_backend_for_scheme(self.link.scheme)\n        # Editable requirements are validated in Requirement constructors.\n        # So here, if it's neither a path nor a valid VCS URL, it's a bug.\n        assert vcs_backend, f\"Unsupported VCS URL {self.link.url}\"\n        hidden_url = hide_url(self.link.url)\n        vcs_backend.obtain(self.source_dir, url=hidden_url, verbosity=0)\n\n    # Top-level Actions\n    def uninstall(\n        self, auto_confirm: bool = False, verbose: bool = False\n    ) -> UninstallPathSet | None:\n        \"\"\"\n        Uninstall the distribution currently satisfying this requirement.\n\n        Prompts before removing or modifying files unless\n        ``auto_confirm`` is True.\n\n        Refuses to delete or modify files outside of ``sys.prefix`` -\n        thus uninstallation within a virtual environment can only\n        modify that virtual environment, even if the virtualenv is\n        linked to global site-packages.\n\n        \"\"\"\n        assert self.req\n        dist = get_default_environment().get_distribution(self.req.name)\n        if not dist:\n            logger.warning(\"Skipping %s as it is not installed.\", self.name)\n            return None\n        logger.info(\"Found existing installation: %s\", dist)\n\n        uninstalled_pathset = UninstallPathSet.from_dist(dist)\n        uninstalled_pathset.remove(auto_confirm, verbose)\n        return uninstalled_pathset\n\n    def _get_archive_name(self, path: str, parentdir: str, rootdir: str) -> str:\n        def _clean_zip_name(name: str, prefix: str) -> str:\n            assert name.startswith(\n                prefix + os.path.sep\n            ), f\"name {name!r} doesn't start with prefix {prefix!r}\"\n            name = name[len(prefix) + 1 :]\n            name = name.replace(os.path.sep, \"/\")\n            return name\n\n        assert self.req is not None\n        path = os.path.join(parentdir, path)\n        name = _clean_zip_name(path, rootdir)\n        return self.req.name + \"/\" + name\n\n    def archive(self, build_dir: str | None) -> None:\n        \"\"\"Saves archive to provided build_dir.\n\n        Used for saving downloaded VCS requirements as part of `pip download`.\n        \"\"\"\n        assert self.source_dir\n        if build_dir is None:\n            return\n\n        create_archive = True\n        archive_name = \"{}-{}.zip\".format(self.name, self.metadata[\"version\"])\n        archive_path = os.path.join(build_dir, archive_name)\n\n        if os.path.exists(archive_path):\n            response = ask_path_exists(\n                f\"The file {display_path(archive_path)} exists. (i)gnore, (w)ipe, \"\n                \"(b)ackup, (a)bort \",\n                (\"i\", \"w\", \"b\", \"a\"),\n            )\n            if response == \"i\":\n                create_archive = False\n            elif response == \"w\":\n                logger.warning(\"Deleting %s\", display_path(archive_path))\n                os.remove(archive_path)\n            elif response == \"b\":\n                dest_file = backup_dir(archive_path)\n                logger.warning(\n                    \"Backing up %s to %s\",\n                    display_path(archive_path),\n                    display_path(dest_file),\n                )\n                shutil.move(archive_path, dest_file)\n            elif response == \"a\":\n                sys.exit(-1)\n\n        if not create_archive:\n            return\n\n        zip_output = zipfile.ZipFile(\n            archive_path,\n            \"w\",\n            zipfile.ZIP_DEFLATED,\n            allowZip64=True,\n        )\n        with zip_output:\n            dir = os.path.normcase(os.path.abspath(self.unpacked_source_directory))\n            for dirpath, dirnames, filenames in os.walk(dir):\n                for dirname in dirnames:\n                    dir_arcname = self._get_archive_name(\n                        dirname,\n                        parentdir=dirpath,\n                        rootdir=dir,\n                    )\n                    zipdir = zipfile.ZipInfo(dir_arcname + \"/\")\n                    zipdir.external_attr = 0x1ED << 16  # 0o755\n                    zip_output.writestr(zipdir, \"\")\n                for filename in filenames:\n                    file_arcname = self._get_archive_name(\n                        filename,\n                        parentdir=dirpath,\n                        rootdir=dir,\n                    )\n                    filename = os.path.join(dirpath, filename)\n                    zip_output.write(filename, file_arcname)\n\n        logger.info(\"Saved %s\", display_path(archive_path))\n\n    def install(\n        self,\n        root: str | None = None,\n        home: str | None = None,\n        prefix: str | None = None,\n        warn_script_location: bool = True,\n        use_user_site: bool = False,\n        pycompile: bool = True,\n    ) -> None:\n        assert self.req is not None\n        scheme = get_scheme(\n            self.req.name,\n            user=use_user_site,\n            home=home,\n            root=root,\n            isolated=self.isolated,\n            prefix=prefix,\n        )\n\n        assert self.is_wheel\n        assert self.local_file_path\n\n        install_wheel(\n            self.req.name,\n            self.local_file_path,\n            scheme=scheme,\n            req_description=str(self.req),\n            pycompile=pycompile,\n            warn_script_location=warn_script_location,\n            direct_url=self.download_info if self.is_direct else None,\n            requested=self.user_supplied,\n        )\n        self.install_succeeded = True\n\n\ndef check_invalid_constraint_type(req: InstallRequirement) -> str:\n    # Check for unsupported forms\n    problem = \"\"\n    if not req.name:\n        problem = \"Unnamed requirements are not allowed as constraints\"\n    elif req.editable:\n        problem = \"Editable requirements are not allowed as constraints\"\n    elif req.extras:\n        problem = \"Constraints cannot have extras\"\n\n    if problem:\n        deprecated(\n            reason=(\n                \"Constraints are only allowed to take the form of a package \"\n                \"name and a version specifier. Other forms were originally \"\n                \"permitted as an accident of the implementation, but were \"\n                \"undocumented. The new implementation of the resolver no \"\n                \"longer supports these forms.\"\n            ),\n            replacement=\"replacing the constraint with a requirement\",\n            # No plan yet for when the new resolver becomes default\n            gone_in=None,\n            issue=8210,\n        )\n\n    return problem\n\n\ndef _has_option(options: Values, reqs: list[InstallRequirement], option: str) -> bool:\n    if getattr(options, option, None):\n        return True\n    for req in reqs:\n        if getattr(req, option, None):\n            return True\n    return False\n"
  },
  {
    "path": "src/pip/_internal/req/req_set.py",
    "content": "import logging\nfrom collections import OrderedDict\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.req.req_install import InstallRequirement\n\nlogger = logging.getLogger(__name__)\n\n\nclass RequirementSet:\n    def __init__(self, check_supported_wheels: bool = True) -> None:\n        \"\"\"Create a RequirementSet.\"\"\"\n\n        self.requirements: dict[str, InstallRequirement] = OrderedDict()\n        self.check_supported_wheels = check_supported_wheels\n\n        self.unnamed_requirements: list[InstallRequirement] = []\n\n    def __str__(self) -> str:\n        requirements = sorted(\n            (req for req in self.requirements.values() if not req.comes_from),\n            key=lambda req: canonicalize_name(req.name or \"\"),\n        )\n        return \" \".join(str(req.req) for req in requirements)\n\n    def __repr__(self) -> str:\n        requirements = sorted(\n            self.requirements.values(),\n            key=lambda req: canonicalize_name(req.name or \"\"),\n        )\n\n        format_string = \"<{classname} object; {count} requirement(s): {reqs}>\"\n        return format_string.format(\n            classname=self.__class__.__name__,\n            count=len(requirements),\n            reqs=\", \".join(str(req.req) for req in requirements),\n        )\n\n    def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:\n        assert not install_req.name\n        self.unnamed_requirements.append(install_req)\n\n    def add_named_requirement(self, install_req: InstallRequirement) -> None:\n        assert install_req.name\n\n        project_name = canonicalize_name(install_req.name)\n        self.requirements[project_name] = install_req\n\n    def has_requirement(self, name: str) -> bool:\n        project_name = canonicalize_name(name)\n\n        return (\n            project_name in self.requirements\n            and not self.requirements[project_name].constraint\n        )\n\n    def get_requirement(self, name: str) -> InstallRequirement:\n        project_name = canonicalize_name(name)\n\n        if project_name in self.requirements:\n            return self.requirements[project_name]\n\n        raise KeyError(f\"No project with the name {name!r}\")\n\n    @property\n    def all_requirements(self) -> list[InstallRequirement]:\n        return self.unnamed_requirements + list(self.requirements.values())\n\n    @property\n    def requirements_to_install(self) -> list[InstallRequirement]:\n        \"\"\"Return the list of requirements that need to be installed.\n\n        TODO remove this property together with the legacy resolver, since the new\n             resolver only returns requirements that need to be installed.\n        \"\"\"\n        return [\n            install_req\n            for install_req in self.all_requirements\n            if not install_req.constraint and not install_req.satisfied_by\n        ]\n"
  },
  {
    "path": "src/pip/_internal/req/req_uninstall.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport os\nimport sys\nimport sysconfig\nfrom collections.abc import Generator, Iterable\nfrom importlib.util import cache_from_source\nfrom typing import Any, Callable\n\nfrom pip._internal.exceptions import LegacyDistutilsInstall, UninstallMissingRecord\nfrom pip._internal.locations import get_bin_prefix, get_bin_user\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.egg_link import egg_link_path_from_location\nfrom pip._internal.utils.logging import getLogger, indent_log\nfrom pip._internal.utils.misc import ask, normalize_path, renames, rmtree\nfrom pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nlogger = getLogger(__name__)\n\n\ndef _script_names(\n    bin_dir: str, script_name: str, is_gui: bool\n) -> Generator[str, None, None]:\n    \"\"\"Create the fully qualified name of the files created by\n    {console,gui}_scripts for the given ``dist``.\n    Returns the list of file names\n    \"\"\"\n    exe_name = os.path.join(bin_dir, script_name)\n    yield exe_name\n    if not WINDOWS:\n        return\n    yield f\"{exe_name}.exe\"\n    yield f\"{exe_name}.exe.manifest\"\n    if is_gui:\n        yield f\"{exe_name}-script.pyw\"\n    else:\n        yield f\"{exe_name}-script.py\"\n\n\ndef _unique(\n    fn: Callable[..., Generator[Any, None, None]],\n) -> Callable[..., Generator[Any, None, None]]:\n    @functools.wraps(fn)\n    def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:\n        seen: set[Any] = set()\n        for item in fn(*args, **kw):\n            if item not in seen:\n                seen.add(item)\n                yield item\n\n    return unique\n\n\n@_unique\ndef uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:\n    \"\"\"\n    Yield all the uninstallation paths for dist based on RECORD-without-.py[co]\n\n    Yield paths to all the files in RECORD. For each .py file in RECORD, add\n    the .pyc and .pyo in the same directory.\n\n    UninstallPathSet.add() takes care of the __pycache__ .py[co].\n\n    If RECORD is not found, raises an error,\n    with possible information from the INSTALLER file.\n\n    https://packaging.python.org/specifications/recording-installed-packages/\n    \"\"\"\n    location = dist.location\n    assert location is not None, \"not installed\"\n\n    entries = dist.iter_declared_entries()\n    if entries is None:\n        raise UninstallMissingRecord(distribution=dist)\n\n    for entry in entries:\n        path = os.path.join(location, entry)\n        yield path\n        if path.endswith(\".py\"):\n            dn, fn = os.path.split(path)\n            base = fn[:-3]\n            path = os.path.join(dn, base + \".pyc\")\n            yield path\n            path = os.path.join(dn, base + \".pyo\")\n            yield path\n\n\ndef compact(paths: Iterable[str]) -> set[str]:\n    \"\"\"Compact a path set to contain the minimal number of paths\n    necessary to contain all paths in the set. If /a/path/ and\n    /a/path/to/a/file.txt are both in the set, leave only the\n    shorter path.\"\"\"\n\n    sep = os.path.sep\n    short_paths: set[str] = set()\n    for path in sorted(paths, key=len):\n        should_skip = any(\n            path.startswith(shortpath.rstrip(\"*\"))\n            and path[len(shortpath.rstrip(\"*\").rstrip(sep))] == sep\n            for shortpath in short_paths\n        )\n        if not should_skip:\n            short_paths.add(path)\n    return short_paths\n\n\ndef compress_for_rename(paths: Iterable[str]) -> set[str]:\n    \"\"\"Returns a set containing the paths that need to be renamed.\n\n    This set may include directories when the original sequence of paths\n    included every file on disk.\n    \"\"\"\n    case_map = {os.path.normcase(p): p for p in paths}\n    remaining = set(case_map)\n    unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)\n    wildcards: set[str] = set()\n\n    def norm_join(*a: str) -> str:\n        return os.path.normcase(os.path.join(*a))\n\n    for root in unchecked:\n        if any(os.path.normcase(root).startswith(w) for w in wildcards):\n            # This directory has already been handled.\n            continue\n\n        all_files: set[str] = set()\n        all_subdirs: set[str] = set()\n        for dirname, subdirs, files in os.walk(root):\n            all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)\n            all_files.update(norm_join(root, dirname, f) for f in files)\n        # If all the files we found are in our remaining set of files to\n        # remove, then remove them from the latter set and add a wildcard\n        # for the directory.\n        if not (all_files - remaining):\n            remaining.difference_update(all_files)\n            wildcards.add(root + os.sep)\n\n    return set(map(case_map.__getitem__, remaining)) | wildcards\n\n\ndef compress_for_output_listing(paths: Iterable[str]) -> tuple[set[str], set[str]]:\n    \"\"\"Returns a tuple of 2 sets of which paths to display to user\n\n    The first set contains paths that would be deleted. Files of a package\n    are not added and the top-level directory of the package has a '*' added\n    at the end - to signify that all it's contents are removed.\n\n    The second set contains files that would have been skipped in the above\n    folders.\n    \"\"\"\n\n    will_remove = set(paths)\n    will_skip = set()\n\n    # Determine folders and files\n    folders = set()\n    files = set()\n    for path in will_remove:\n        if path.endswith(\".pyc\"):\n            continue\n        if path.endswith(\"__init__.py\") or \".dist-info\" in path:\n            folders.add(os.path.dirname(path))\n        files.add(path)\n\n    _normcased_files = set(map(os.path.normcase, files))\n\n    folders = compact(folders)\n\n    # This walks the tree using os.walk to not miss extra folders\n    # that might get added.\n    for folder in folders:\n        for dirpath, _, dirfiles in os.walk(folder):\n            for fname in dirfiles:\n                if fname.endswith(\".pyc\"):\n                    continue\n\n                file_ = os.path.join(dirpath, fname)\n                if (\n                    os.path.isfile(file_)\n                    and os.path.normcase(file_) not in _normcased_files\n                ):\n                    # We are skipping this file. Add it to the set.\n                    will_skip.add(file_)\n\n    will_remove = files | {os.path.join(folder, \"*\") for folder in folders}\n\n    return will_remove, will_skip\n\n\nclass StashedUninstallPathSet:\n    \"\"\"A set of file rename operations to stash files while\n    tentatively uninstalling them.\"\"\"\n\n    def __init__(self) -> None:\n        # Mapping from source file root to [Adjacent]TempDirectory\n        # for files under that directory.\n        self._save_dirs: dict[str, TempDirectory] = {}\n        # (old path, new path) tuples for each move that may need\n        # to be undone.\n        self._moves: list[tuple[str, str]] = []\n\n    def _get_directory_stash(self, path: str) -> str:\n        \"\"\"Stashes a directory.\n\n        Directories are stashed adjacent to their original location if\n        possible, or else moved/copied into the user's temp dir.\"\"\"\n\n        try:\n            save_dir: TempDirectory = AdjacentTempDirectory(path)\n        except OSError:\n            save_dir = TempDirectory(kind=\"uninstall\")\n        self._save_dirs[os.path.normcase(path)] = save_dir\n\n        return save_dir.path\n\n    def _get_file_stash(self, path: str) -> str:\n        \"\"\"Stashes a file.\n\n        If no root has been provided, one will be created for the directory\n        in the user's temp directory.\"\"\"\n        path = os.path.normcase(path)\n        head, old_head = os.path.dirname(path), None\n        save_dir = None\n\n        while head != old_head:\n            try:\n                save_dir = self._save_dirs[head]\n                break\n            except KeyError:\n                pass\n            head, old_head = os.path.dirname(head), head\n        else:\n            # Did not find any suitable root\n            head = os.path.dirname(path)\n            save_dir = TempDirectory(kind=\"uninstall\")\n            self._save_dirs[head] = save_dir\n\n        relpath = os.path.relpath(path, head)\n        if relpath and relpath != os.path.curdir:\n            return os.path.join(save_dir.path, relpath)\n        return save_dir.path\n\n    def stash(self, path: str) -> str:\n        \"\"\"Stashes the directory or file and returns its new location.\n        Handle symlinks as files to avoid modifying the symlink targets.\n        \"\"\"\n        path_is_dir = os.path.isdir(path) and not os.path.islink(path)\n        if path_is_dir:\n            new_path = self._get_directory_stash(path)\n        else:\n            new_path = self._get_file_stash(path)\n\n        self._moves.append((path, new_path))\n        if path_is_dir and os.path.isdir(new_path):\n            # If we're moving a directory, we need to\n            # remove the destination first or else it will be\n            # moved to inside the existing directory.\n            # We just created new_path ourselves, so it will\n            # be removable.\n            os.rmdir(new_path)\n        renames(path, new_path)\n        return new_path\n\n    def commit(self) -> None:\n        \"\"\"Commits the uninstall by removing stashed files.\"\"\"\n        for save_dir in self._save_dirs.values():\n            save_dir.cleanup()\n        self._moves = []\n        self._save_dirs = {}\n\n    def rollback(self) -> None:\n        \"\"\"Undoes the uninstall by moving stashed files back.\"\"\"\n        for p in self._moves:\n            logger.info(\"Moving to %s\\n from %s\", *p)\n\n        for new_path, path in self._moves:\n            try:\n                logger.debug(\"Replacing %s from %s\", new_path, path)\n                if os.path.isfile(new_path) or os.path.islink(new_path):\n                    os.unlink(new_path)\n                elif os.path.isdir(new_path):\n                    rmtree(new_path)\n                renames(path, new_path)\n            except OSError as ex:\n                logger.error(\"Failed to restore %s\", new_path)\n                logger.debug(\"Exception: %s\", ex)\n\n        self.commit()\n\n    @property\n    def can_rollback(self) -> bool:\n        return bool(self._moves)\n\n\nclass UninstallPathSet:\n    \"\"\"A set of file paths to be removed in the uninstallation of a\n    requirement.\"\"\"\n\n    def __init__(self, dist: BaseDistribution) -> None:\n        self._paths: set[str] = set()\n        self._refuse: set[str] = set()\n        self._pth: dict[str, UninstallPthEntries] = {}\n        self._dist = dist\n        self._moved_paths = StashedUninstallPathSet()\n        # Create local cache of normalize_path results. Creating an UninstallPathSet\n        # can result in hundreds/thousands of redundant calls to normalize_path with\n        # the same args, which hurts performance.\n        self._normalize_path_cached = functools.lru_cache(normalize_path)\n\n    def _permitted(self, path: str) -> bool:\n        \"\"\"\n        Return True if the given path is one we are permitted to\n        remove/modify, False otherwise.\n\n        \"\"\"\n        # aka is_local, but caching normalized sys.prefix\n        if not running_under_virtualenv():\n            return True\n        return path.startswith(self._normalize_path_cached(sys.prefix))\n\n    def add(self, path: str) -> None:\n        head, tail = os.path.split(path)\n\n        # we normalize the head to resolve parent directory symlinks, but not\n        # the tail, since we only want to uninstall symlinks, not their targets\n        path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail))\n\n        if not os.path.exists(path):\n            return\n        if self._permitted(path):\n            self._paths.add(path)\n        else:\n            self._refuse.add(path)\n\n        # __pycache__ files can show up after 'installed-files.txt' is created,\n        # due to imports\n        if os.path.splitext(path)[1] == \".py\":\n            self.add(cache_from_source(path))\n\n    def add_pth(self, pth_file: str, entry: str) -> None:\n        pth_file = self._normalize_path_cached(pth_file)\n        if self._permitted(pth_file):\n            if pth_file not in self._pth:\n                self._pth[pth_file] = UninstallPthEntries(pth_file)\n            self._pth[pth_file].add(entry)\n        else:\n            self._refuse.add(pth_file)\n\n    def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:\n        \"\"\"Remove paths in ``self._paths`` with confirmation (unless\n        ``auto_confirm`` is True).\"\"\"\n\n        if not self._paths:\n            logger.info(\n                \"Can't uninstall '%s'. No files were found to uninstall.\",\n                self._dist.raw_name,\n            )\n            return\n\n        dist_name_version = f\"{self._dist.raw_name}-{self._dist.raw_version}\"\n        logger.info(\"Uninstalling %s:\", dist_name_version)\n\n        with indent_log():\n            if auto_confirm or self._allowed_to_proceed(verbose):\n                moved = self._moved_paths\n\n                for_rename = compress_for_rename(self._paths)\n\n                for path in sorted(compact(for_rename)):\n                    moved.stash(path)\n                    logger.verbose(\"Removing file or directory %s\", path)\n\n                for pth in self._pth.values():\n                    pth.remove()\n\n                logger.info(\"Successfully uninstalled %s\", dist_name_version)\n\n    def _allowed_to_proceed(self, verbose: bool) -> bool:\n        \"\"\"Display which files would be deleted and prompt for confirmation\"\"\"\n\n        def _display(msg: str, paths: Iterable[str]) -> None:\n            if not paths:\n                return\n\n            logger.info(msg)\n            with indent_log():\n                for path in sorted(compact(paths)):\n                    logger.info(path)\n\n        if not verbose:\n            will_remove, will_skip = compress_for_output_listing(self._paths)\n        else:\n            # In verbose mode, display all the files that are going to be\n            # deleted.\n            will_remove = set(self._paths)\n            will_skip = set()\n\n        _display(\"Would remove:\", will_remove)\n        _display(\"Would not remove (might be manually added):\", will_skip)\n        _display(\"Would not remove (outside of prefix):\", self._refuse)\n        if verbose:\n            _display(\"Will actually move:\", compress_for_rename(self._paths))\n\n        return ask(\"Proceed (Y/n)? \", (\"y\", \"n\", \"\")) != \"n\"\n\n    def rollback(self) -> None:\n        \"\"\"Rollback the changes previously made by remove().\"\"\"\n        if not self._moved_paths.can_rollback:\n            logger.error(\n                \"Can't roll back %s; was not uninstalled\",\n                self._dist.raw_name,\n            )\n            return\n        logger.info(\"Rolling back uninstall of %s\", self._dist.raw_name)\n        self._moved_paths.rollback()\n        for pth in self._pth.values():\n            pth.rollback()\n\n    def commit(self) -> None:\n        \"\"\"Remove temporary save dir: rollback will no longer be possible.\"\"\"\n        self._moved_paths.commit()\n\n    @classmethod\n    def from_dist(cls, dist: BaseDistribution) -> UninstallPathSet:\n        dist_location = dist.location\n        info_location = dist.info_location\n        if dist_location is None:\n            logger.info(\n                \"Not uninstalling %s since it is not installed\",\n                dist.canonical_name,\n            )\n            return cls(dist)\n\n        normalized_dist_location = normalize_path(dist_location)\n        if not dist.local:\n            logger.info(\n                \"Not uninstalling %s at %s, outside environment %s\",\n                dist.canonical_name,\n                normalized_dist_location,\n                sys.prefix,\n            )\n            return cls(dist)\n\n        if normalized_dist_location in {\n            p\n            for p in {sysconfig.get_path(\"stdlib\"), sysconfig.get_path(\"platstdlib\")}\n            if p\n        }:\n            logger.info(\n                \"Not uninstalling %s at %s, as it is in the standard library.\",\n                dist.canonical_name,\n                normalized_dist_location,\n            )\n            return cls(dist)\n\n        paths_to_remove = cls(dist)\n        develop_egg_link = egg_link_path_from_location(dist.raw_name)\n\n        # Distribution is installed with metadata in a \"flat\" .egg-info\n        # directory. This means it is not a modern .dist-info installation, an\n        # egg, or legacy editable.\n        setuptools_flat_installation = (\n            dist.installed_with_setuptools_egg_info\n            and info_location is not None\n            and os.path.exists(info_location)\n            # If dist is editable and the location points to a ``.egg-info``,\n            # we are in fact in the legacy editable case.\n            and not info_location.endswith(f\"{dist.setuptools_filename}.egg-info\")\n        )\n\n        # Uninstall cases order do matter as in the case of 2 installs of the\n        # same package, pip needs to uninstall the currently detected version\n        if setuptools_flat_installation:\n            if info_location is not None:\n                paths_to_remove.add(info_location)\n            installed_files = dist.iter_declared_entries()\n            if installed_files is not None:\n                for installed_file in installed_files:\n                    paths_to_remove.add(os.path.join(dist_location, installed_file))\n            # FIXME: need a test for this elif block\n            # occurs with --single-version-externally-managed/--record outside\n            # of pip\n            elif dist.is_file(\"top_level.txt\"):\n                try:\n                    namespace_packages = dist.read_text(\"namespace_packages.txt\")\n                except FileNotFoundError:\n                    namespaces = []\n                else:\n                    namespaces = namespace_packages.splitlines(keepends=False)\n                for top_level_pkg in [\n                    p\n                    for p in dist.read_text(\"top_level.txt\").splitlines()\n                    if p and p not in namespaces\n                ]:\n                    path = os.path.join(dist_location, top_level_pkg)\n                    paths_to_remove.add(path)\n                    paths_to_remove.add(f\"{path}.py\")\n                    paths_to_remove.add(f\"{path}.pyc\")\n                    paths_to_remove.add(f\"{path}.pyo\")\n\n        elif dist.installed_by_distutils:\n            raise LegacyDistutilsInstall(distribution=dist)\n\n        elif dist.installed_as_egg:\n            # package installed by easy_install\n            # We cannot match on dist.egg_name because it can slightly vary\n            # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg\n            # XXX We use normalized_dist_location because dist_location my contain\n            # a trailing / if the distribution is a zipped egg\n            # (which is not a directory).\n            paths_to_remove.add(normalized_dist_location)\n            easy_install_egg = os.path.split(normalized_dist_location)[1]\n            easy_install_pth = os.path.join(\n                os.path.dirname(normalized_dist_location),\n                \"easy-install.pth\",\n            )\n            paths_to_remove.add_pth(easy_install_pth, \"./\" + easy_install_egg)\n\n        elif dist.installed_with_dist_info:\n            for path in uninstallation_paths(dist):\n                paths_to_remove.add(path)\n\n        elif develop_egg_link:\n            # PEP 660 modern editable is handled in the ``.dist-info`` case\n            # above, so this only covers the setuptools-style editable.\n            with open(develop_egg_link) as fh:\n                link_pointer = os.path.normcase(fh.readline().strip())\n                normalized_link_pointer = paths_to_remove._normalize_path_cached(\n                    link_pointer\n                )\n            assert os.path.samefile(\n                normalized_link_pointer, normalized_dist_location\n            ), (\n                f\"Egg-link {develop_egg_link} (to {link_pointer}) does not match \"\n                f\"installed location of {dist.raw_name} (at {dist_location})\"\n            )\n            paths_to_remove.add(develop_egg_link)\n            easy_install_pth = os.path.join(\n                os.path.dirname(develop_egg_link), \"easy-install.pth\"\n            )\n            paths_to_remove.add_pth(easy_install_pth, dist_location)\n\n        else:\n            logger.debug(\n                \"Not sure how to uninstall: %s - Check: %s\",\n                dist,\n                dist_location,\n            )\n\n        if dist.in_usersite:\n            bin_dir = get_bin_user()\n        else:\n            bin_dir = get_bin_prefix()\n\n        # find distutils scripts= scripts\n        try:\n            for script in dist.iter_distutils_script_names():\n                paths_to_remove.add(os.path.join(bin_dir, script))\n                if WINDOWS:\n                    paths_to_remove.add(os.path.join(bin_dir, f\"{script}.bat\"))\n        except (FileNotFoundError, NotADirectoryError):\n            pass\n\n        # find console_scripts and gui_scripts\n        def iter_scripts_to_remove(\n            dist: BaseDistribution,\n            bin_dir: str,\n        ) -> Generator[str, None, None]:\n            for entry_point in dist.iter_entry_points():\n                if entry_point.group == \"console_scripts\":\n                    yield from _script_names(bin_dir, entry_point.name, False)\n                elif entry_point.group == \"gui_scripts\":\n                    yield from _script_names(bin_dir, entry_point.name, True)\n\n        for s in iter_scripts_to_remove(dist, bin_dir):\n            paths_to_remove.add(s)\n\n        return paths_to_remove\n\n\nclass UninstallPthEntries:\n    def __init__(self, pth_file: str) -> None:\n        self.file = pth_file\n        self.entries: set[str] = set()\n        self._saved_lines: list[bytes] | None = None\n\n    def add(self, entry: str) -> None:\n        entry = os.path.normcase(entry)\n        # On Windows, os.path.normcase converts the entry to use\n        # backslashes.  This is correct for entries that describe absolute\n        # paths outside of site-packages, but all the others use forward\n        # slashes.\n        # os.path.splitdrive is used instead of os.path.isabs because isabs\n        # treats non-absolute paths with drive letter markings like c:foo\\bar\n        # as absolute paths. It also does not recognize UNC paths if they don't\n        # have more than \"\\\\sever\\share\". Valid examples: \"\\\\server\\share\\\" or\n        # \"\\\\server\\share\\folder\".\n        if WINDOWS and not os.path.splitdrive(entry)[0]:\n            entry = entry.replace(\"\\\\\", \"/\")\n        self.entries.add(entry)\n\n    def remove(self) -> None:\n        logger.verbose(\"Removing pth entries from %s:\", self.file)\n\n        # If the file doesn't exist, log a warning and return\n        if not os.path.isfile(self.file):\n            logger.warning(\"Cannot remove entries from nonexistent file %s\", self.file)\n            return\n        with open(self.file, \"rb\") as fh:\n            # windows uses '\\r\\n' with py3k, but uses '\\n' with py2.x\n            lines = fh.readlines()\n            self._saved_lines = lines\n        if any(b\"\\r\\n\" in line for line in lines):\n            endline = \"\\r\\n\"\n        else:\n            endline = \"\\n\"\n        # handle missing trailing newline\n        if lines and not lines[-1].endswith(endline.encode(\"utf-8\")):\n            lines[-1] = lines[-1] + endline.encode(\"utf-8\")\n        for entry in self.entries:\n            try:\n                logger.verbose(\"Removing entry: %s\", entry)\n                lines.remove((entry + endline).encode(\"utf-8\"))\n            except ValueError:\n                pass\n        with open(self.file, \"wb\") as fh:\n            fh.writelines(lines)\n\n    def rollback(self) -> bool:\n        if self._saved_lines is None:\n            logger.error(\"Cannot roll back changes to %s, none were made\", self.file)\n            return False\n        logger.debug(\"Rolling %s back to previous state\", self.file)\n        with open(self.file, \"wb\") as fh:\n            fh.writelines(self._saved_lines)\n        return True\n"
  },
  {
    "path": "src/pip/_internal/resolution/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/resolution/base.py",
    "content": "from typing import Callable, Optional\n\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.req.req_set import RequirementSet\n\nInstallRequirementProvider = Callable[\n    [str, Optional[InstallRequirement]], InstallRequirement\n]\n\n\nclass BaseResolver:\n    def resolve(\n        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        raise NotImplementedError()\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> list[InstallRequirement]:\n        raise NotImplementedError()\n"
  },
  {
    "path": "src/pip/_internal/resolution/legacy/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/resolution/legacy/resolver.py",
    "content": "\"\"\"Dependency Resolution\n\nThe dependency resolution in pip is performed as follows:\n\nfor top-level requirements:\n    a. only one spec allowed per project, regardless of conflicts or not.\n       otherwise a \"double requirement\" exception is raised\n    b. they override sub-dependency requirements.\nfor sub-dependencies\n    a. \"first found, wins\" (where the order is breadth first)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport sys\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom itertools import chain\nfrom typing import Optional\n\nfrom pip._vendor.packaging import specifiers\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.exceptions import (\n    BestVersionAlreadyInstalled,\n    DistributionNotFound,\n    HashError,\n    HashErrors,\n    InstallationError,\n    NoneMetadataError,\n    UnsupportedPythonVersion,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    check_invalid_constraint_type,\n)\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.base import BaseResolver, InstallRequirementProvider\nfrom pip._internal.utils import compatibility_tags\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.direct_url_helpers import direct_url_from_link\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import normalize_version_info\nfrom pip._internal.utils.packaging import check_requires_python\n\nlogger = logging.getLogger(__name__)\n\nDiscoveredDependencies = defaultdict[Optional[str], list[InstallRequirement]]\n\n\ndef _check_dist_requires_python(\n    dist: BaseDistribution,\n    version_info: tuple[int, int, int],\n    ignore_requires_python: bool = False,\n) -> None:\n    \"\"\"\n    Check whether the given Python version is compatible with a distribution's\n    \"Requires-Python\" value.\n\n    :param version_info: A 3-tuple of ints representing the Python\n        major-minor-micro version to check.\n    :param ignore_requires_python: Whether to ignore the \"Requires-Python\"\n        value if the given Python version isn't compatible.\n\n    :raises UnsupportedPythonVersion: When the given Python version isn't\n        compatible.\n    \"\"\"\n    # This idiosyncratically converts the SpecifierSet to str and let\n    # check_requires_python then parse it again into SpecifierSet. But this\n    # is the legacy resolver so I'm just not going to bother refactoring.\n    try:\n        requires_python = str(dist.requires_python)\n    except FileNotFoundError as e:\n        raise NoneMetadataError(dist, str(e))\n    try:\n        is_compatible = check_requires_python(\n            requires_python,\n            version_info=version_info,\n        )\n    except specifiers.InvalidSpecifier as exc:\n        logger.warning(\n            \"Package %r has an invalid Requires-Python: %s\", dist.raw_name, exc\n        )\n        return\n\n    if is_compatible:\n        return\n\n    version = \".\".join(map(str, version_info))\n    if ignore_requires_python:\n        logger.debug(\n            \"Ignoring failed Requires-Python check for package %r: %s not in %r\",\n            dist.raw_name,\n            version,\n            requires_python,\n        )\n        return\n\n    raise UnsupportedPythonVersion(\n        f\"Package {dist.raw_name!r} requires a different Python: \"\n        f\"{version} not in {requires_python!r}\"\n    )\n\n\nclass Resolver(BaseResolver):\n    \"\"\"Resolves which packages need to be installed/uninstalled to perform \\\n    the requested operation without breaking the requirements of any package.\n    \"\"\"\n\n    _allowed_strategies = {\"eager\", \"only-if-needed\", \"to-satisfy-only\"}\n\n    def __init__(\n        self,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        wheel_cache: WheelCache | None,\n        make_install_req: InstallRequirementProvider,\n        use_user_site: bool,\n        ignore_dependencies: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        force_reinstall: bool,\n        upgrade_strategy: str,\n        py_version_info: tuple[int, ...] | None = None,\n    ) -> None:\n        super().__init__()\n        assert upgrade_strategy in self._allowed_strategies\n\n        if py_version_info is None:\n            py_version_info = sys.version_info[:3]\n        else:\n            py_version_info = normalize_version_info(py_version_info)\n\n        self._py_version_info = py_version_info\n\n        self.preparer = preparer\n        self.finder = finder\n        self.wheel_cache = wheel_cache\n\n        self.upgrade_strategy = upgrade_strategy\n        self.force_reinstall = force_reinstall\n        self.ignore_dependencies = ignore_dependencies\n        self.ignore_installed = ignore_installed\n        self.ignore_requires_python = ignore_requires_python\n        self.use_user_site = use_user_site\n        self._make_install_req = make_install_req\n\n        self._discovered_dependencies: DiscoveredDependencies = defaultdict(list)\n\n    def resolve(\n        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        \"\"\"Resolve what operations need to be done\n\n        As a side-effect of this method, the packages (and their dependencies)\n        are downloaded, unpacked and prepared for installation. This\n        preparation is done by ``pip.operations.prepare``.\n\n        Once PyPI has static dependency metadata available, it would be\n        possible to move the preparation to become a step separated from\n        dependency resolution.\n        \"\"\"\n        requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels)\n        for req in root_reqs:\n            if req.constraint:\n                check_invalid_constraint_type(req)\n            self._add_requirement_to_set(requirement_set, req)\n\n        # Actually prepare the files, and collect any exceptions. Most hash\n        # exceptions cannot be checked ahead of time, because\n        # _populate_link() needs to be called before we can make decisions\n        # based on link type.\n        discovered_reqs: list[InstallRequirement] = []\n        hash_errors = HashErrors()\n        for req in chain(requirement_set.all_requirements, discovered_reqs):\n            try:\n                discovered_reqs.extend(self._resolve_one(requirement_set, req))\n            except HashError as exc:\n                exc.req = req\n                hash_errors.append(exc)\n\n        if hash_errors:\n            raise hash_errors\n\n        return requirement_set\n\n    def _add_requirement_to_set(\n        self,\n        requirement_set: RequirementSet,\n        install_req: InstallRequirement,\n        parent_req_name: str | None = None,\n        extras_requested: Iterable[str] | None = None,\n    ) -> tuple[list[InstallRequirement], InstallRequirement | None]:\n        \"\"\"Add install_req as a requirement to install.\n\n        :param parent_req_name: The name of the requirement that needed this\n            added. The name is used because when multiple unnamed requirements\n            resolve to the same name, we could otherwise end up with dependency\n            links that point outside the Requirements set. parent_req must\n            already be added. Note that None implies that this is a user\n            supplied requirement, vs an inferred one.\n        :param extras_requested: an iterable of extras used to evaluate the\n            environment markers.\n        :return: Additional requirements to scan. That is either [] if\n            the requirement is not applicable, or [install_req] if the\n            requirement is applicable and has just been added.\n        \"\"\"\n        # If the markers do not match, ignore this requirement.\n        if not install_req.match_markers(extras_requested):\n            logger.info(\n                \"Ignoring %s: markers '%s' don't match your environment\",\n                install_req.name,\n                install_req.markers,\n            )\n            return [], None\n\n        # If the wheel is not supported, raise an error.\n        # Should check this after filtering out based on environment markers to\n        # allow specifying different wheels based on the environment/OS, in a\n        # single requirements file.\n        if install_req.link and install_req.link.is_wheel:\n            wheel = Wheel(install_req.link.filename)\n            tags = compatibility_tags.get_supported()\n            if requirement_set.check_supported_wheels and not wheel.supported(tags):\n                raise InstallationError(\n                    f\"{wheel.filename} is not a supported wheel on this platform.\"\n                )\n\n        # This next bit is really a sanity check.\n        assert (\n            not install_req.user_supplied or parent_req_name is None\n        ), \"a user supplied req shouldn't have a parent\"\n\n        # Unnamed requirements are scanned again and the requirement won't be\n        # added as a dependency until after scanning.\n        if not install_req.name:\n            requirement_set.add_unnamed_requirement(install_req)\n            return [install_req], None\n\n        try:\n            existing_req: InstallRequirement | None = requirement_set.get_requirement(\n                install_req.name\n            )\n        except KeyError:\n            existing_req = None\n\n        has_conflicting_requirement = (\n            parent_req_name is None\n            and existing_req\n            and not existing_req.constraint\n            and existing_req.extras == install_req.extras\n            and existing_req.req\n            and install_req.req\n            and existing_req.req.specifier != install_req.req.specifier\n        )\n        if has_conflicting_requirement:\n            raise InstallationError(\n                f\"Double requirement given: {install_req} \"\n                f\"(already in {existing_req}, name={install_req.name!r})\"\n            )\n\n        # When no existing requirement exists, add the requirement as a\n        # dependency and it will be scanned again after.\n        if not existing_req:\n            requirement_set.add_named_requirement(install_req)\n            # We'd want to rescan this requirement later\n            return [install_req], install_req\n\n        # Assume there's no need to scan, and that we've already\n        # encountered this for scanning.\n        if install_req.constraint or not existing_req.constraint:\n            return [], existing_req\n\n        does_not_satisfy_constraint = install_req.link and not (\n            existing_req.link and install_req.link.path == existing_req.link.path\n        )\n        if does_not_satisfy_constraint:\n            raise InstallationError(\n                f\"Could not satisfy constraints for '{install_req.name}': \"\n                \"installation from path or url cannot be \"\n                \"constrained to a version\"\n            )\n        # If we're now installing a constraint, mark the existing\n        # object for real installation.\n        existing_req.constraint = False\n        # If we're now installing a user supplied requirement,\n        # mark the existing object as such.\n        if install_req.user_supplied:\n            existing_req.user_supplied = True\n        existing_req.extras = tuple(\n            sorted(set(existing_req.extras) | set(install_req.extras))\n        )\n        logger.debug(\n            \"Setting %s extras to: %s\",\n            existing_req,\n            existing_req.extras,\n        )\n        # Return the existing requirement for addition to the parent and\n        # scanning again.\n        return [existing_req], existing_req\n\n    def _is_upgrade_allowed(self, req: InstallRequirement) -> bool:\n        if self.upgrade_strategy == \"to-satisfy-only\":\n            return False\n        elif self.upgrade_strategy == \"eager\":\n            return True\n        else:\n            assert self.upgrade_strategy == \"only-if-needed\"\n            return req.user_supplied or req.constraint\n\n    def _set_req_to_reinstall(self, req: InstallRequirement) -> None:\n        \"\"\"\n        Set a requirement to be installed.\n        \"\"\"\n        # Don't uninstall the conflict if doing a user install and the\n        # conflict is not a user install.\n        assert req.satisfied_by is not None\n        if not self.use_user_site or req.satisfied_by.in_usersite:\n            req.should_reinstall = True\n        req.satisfied_by = None\n\n    def _check_skip_installed(self, req_to_install: InstallRequirement) -> str | None:\n        \"\"\"Check if req_to_install should be skipped.\n\n        This will check if the req is installed, and whether we should upgrade\n        or reinstall it, taking into account all the relevant user options.\n\n        After calling this req_to_install will only have satisfied_by set to\n        None if the req_to_install is to be upgraded/reinstalled etc. Any\n        other value will be a dist recording the current thing installed that\n        satisfies the requirement.\n\n        Note that for vcs urls and the like we can't assess skipping in this\n        routine - we simply identify that we need to pull the thing down,\n        then later on it is pulled down and introspected to assess upgrade/\n        reinstalls etc.\n\n        :return: A text reason for why it was skipped, or None.\n        \"\"\"\n        if self.ignore_installed:\n            return None\n\n        req_to_install.check_if_exists(self.use_user_site)\n        if not req_to_install.satisfied_by:\n            return None\n\n        if self.force_reinstall:\n            self._set_req_to_reinstall(req_to_install)\n            return None\n\n        if not self._is_upgrade_allowed(req_to_install):\n            if self.upgrade_strategy == \"only-if-needed\":\n                return \"already satisfied, skipping upgrade\"\n            return \"already satisfied\"\n\n        # Check for the possibility of an upgrade.  For link-based\n        # requirements we have to pull the tree down and inspect to assess\n        # the version #, so it's handled way down.\n        if not req_to_install.link:\n            try:\n                self.finder.find_requirement(req_to_install, upgrade=True)\n            except BestVersionAlreadyInstalled:\n                # Then the best version is installed.\n                return \"already up-to-date\"\n            except DistributionNotFound:\n                # No distribution found, so we squash the error.  It will\n                # be raised later when we re-try later to do the install.\n                # Why don't we just raise here?\n                pass\n\n        self._set_req_to_reinstall(req_to_install)\n        return None\n\n    def _find_requirement_link(self, req: InstallRequirement) -> Link | None:\n        upgrade = self._is_upgrade_allowed(req)\n        best_candidate = self.finder.find_requirement(req, upgrade)\n        if not best_candidate:\n            return None\n\n        # Log a warning per PEP 592 if necessary before returning.\n        link = best_candidate.link\n        if link.is_yanked:\n            reason = link.yanked_reason or \"<none given>\"\n            msg = (\n                # Mark this as a unicode string to prevent\n                # \"UnicodeEncodeError: 'ascii' codec can't encode character\"\n                # in Python 2 when the reason contains non-ascii characters.\n                \"The candidate selected for download or install is a \"\n                f\"yanked version: {best_candidate}\\n\"\n                f\"Reason for being yanked: {reason}\"\n            )\n            logger.warning(msg)\n\n        return link\n\n    def _populate_link(self, req: InstallRequirement) -> None:\n        \"\"\"Ensure that if a link can be found for this, that it is found.\n\n        Note that req.link may still be None - if the requirement is already\n        installed and not needed to be upgraded based on the return value of\n        _is_upgrade_allowed().\n\n        If preparer.require_hashes is True, don't use the wheel cache, because\n        cached wheels, always built locally, have different hashes than the\n        files downloaded from the index server and thus throw false hash\n        mismatches. Furthermore, cached wheels at present have nondeterministic\n        contents due to file modification times.\n        \"\"\"\n        if req.link is None:\n            req.link = self._find_requirement_link(req)\n\n        if self.wheel_cache is None or self.preparer.require_hashes:\n            return\n\n        assert req.link is not None, \"_find_requirement_link unexpectedly returned None\"\n        cache_entry = self.wheel_cache.get_cache_entry(\n            link=req.link,\n            package_name=req.name,\n            supported_tags=get_supported(),\n        )\n        if cache_entry is not None:\n            logger.debug(\"Using cached wheel link: %s\", cache_entry.link)\n            if req.link is req.original_link and cache_entry.persistent:\n                req.cached_wheel_source_link = req.link\n            if cache_entry.origin is not None:\n                req.download_info = cache_entry.origin\n            else:\n                # Legacy cache entry that does not have origin.json.\n                # download_info may miss the archive_info.hashes field.\n                req.download_info = direct_url_from_link(\n                    req.link, link_is_in_wheel_cache=cache_entry.persistent\n                )\n            req.link = cache_entry.link\n\n    def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution:\n        \"\"\"Takes a InstallRequirement and returns a single AbstractDist \\\n        representing a prepared variant of the same.\n        \"\"\"\n        if req.editable:\n            return self.preparer.prepare_editable_requirement(req)\n\n        # satisfied_by is only evaluated by calling _check_skip_installed,\n        # so it must be None here.\n        assert req.satisfied_by is None\n        skip_reason = self._check_skip_installed(req)\n\n        if req.satisfied_by:\n            return self.preparer.prepare_installed_requirement(req, skip_reason)\n\n        # We eagerly populate the link, since that's our \"legacy\" behavior.\n        self._populate_link(req)\n        dist = self.preparer.prepare_linked_requirement(req)\n\n        # NOTE\n        # The following portion is for determining if a certain package is\n        # going to be re-installed/upgraded or not and reporting to the user.\n        # This should probably get cleaned up in a future refactor.\n\n        # req.req is only avail after unpack for URL\n        # pkgs repeat check_if_exists to uninstall-on-upgrade\n        # (#14)\n        if not self.ignore_installed:\n            req.check_if_exists(self.use_user_site)\n\n        if req.satisfied_by:\n            should_modify = (\n                self.upgrade_strategy != \"to-satisfy-only\"\n                or self.force_reinstall\n                or self.ignore_installed\n                or req.link.scheme == \"file\"\n            )\n            if should_modify:\n                self._set_req_to_reinstall(req)\n            else:\n                logger.info(\n                    \"Requirement already satisfied (use --upgrade to upgrade): %s\",\n                    req,\n                )\n        return dist\n\n    def _resolve_one(\n        self,\n        requirement_set: RequirementSet,\n        req_to_install: InstallRequirement,\n    ) -> list[InstallRequirement]:\n        \"\"\"Prepare a single requirements file.\n\n        :return: A list of additional InstallRequirements to also install.\n        \"\"\"\n        # Tell user what we are doing for this requirement:\n        # obtain (editable), skipping, processing (local url), collecting\n        # (remote url or package name)\n        if req_to_install.constraint or req_to_install.prepared:\n            return []\n\n        req_to_install.prepared = True\n\n        # Parse and return dependencies\n        dist = self._get_dist_for(req_to_install)\n        # This will raise UnsupportedPythonVersion if the given Python\n        # version isn't compatible with the distribution's Requires-Python.\n        _check_dist_requires_python(\n            dist,\n            version_info=self._py_version_info,\n            ignore_requires_python=self.ignore_requires_python,\n        )\n\n        more_reqs: list[InstallRequirement] = []\n\n        def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None:\n            # This idiosyncratically converts the Requirement to str and let\n            # make_install_req then parse it again into Requirement. But this is\n            # the legacy resolver so I'm just not going to bother refactoring.\n            sub_install_req = self._make_install_req(str(subreq), req_to_install)\n            parent_req_name = req_to_install.name\n            to_scan_again, add_to_parent = self._add_requirement_to_set(\n                requirement_set,\n                sub_install_req,\n                parent_req_name=parent_req_name,\n                extras_requested=extras_requested,\n            )\n            if parent_req_name and add_to_parent:\n                self._discovered_dependencies[parent_req_name].append(add_to_parent)\n            more_reqs.extend(to_scan_again)\n\n        with indent_log():\n            # We add req_to_install before its dependencies, so that we\n            # can refer to it when adding dependencies.\n            assert req_to_install.name is not None\n            if not requirement_set.has_requirement(req_to_install.name):\n                # 'unnamed' requirements will get added here\n                # 'unnamed' requirements can only come from being directly\n                # provided by the user.\n                assert req_to_install.user_supplied\n                self._add_requirement_to_set(\n                    requirement_set, req_to_install, parent_req_name=None\n                )\n\n            if not self.ignore_dependencies:\n                if req_to_install.extras:\n                    logger.debug(\n                        \"Installing extra requirements: %r\",\n                        \",\".join(req_to_install.extras),\n                    )\n                missing_requested = sorted(\n                    set(req_to_install.extras) - set(dist.iter_provided_extras())\n                )\n                for missing in missing_requested:\n                    logger.warning(\n                        \"%s %s does not provide the extra '%s'\",\n                        dist.raw_name,\n                        dist.version,\n                        missing,\n                    )\n\n                available_requested = sorted(\n                    set(dist.iter_provided_extras()) & set(req_to_install.extras)\n                )\n                for subreq in dist.iter_dependencies(available_requested):\n                    add_req(subreq, extras_requested=available_requested)\n\n        return more_reqs\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> list[InstallRequirement]:\n        \"\"\"Create the installation order.\n\n        The installation order is topological - requirements are installed\n        before the requiring thing. We break cycles at an arbitrary point,\n        and make no other guarantees.\n        \"\"\"\n        # The current implementation, which we may change at any point\n        # installs the user specified things in the order given, except when\n        # dependencies must come earlier to achieve topological order.\n        order = []\n        ordered_reqs: set[InstallRequirement] = set()\n\n        def schedule(req: InstallRequirement) -> None:\n            if req.satisfied_by or req in ordered_reqs:\n                return\n            if req.constraint:\n                return\n            ordered_reqs.add(req)\n            for dep in self._discovered_dependencies[req.name]:\n                schedule(dep)\n            order.append(req)\n\n        for install_req in req_set.requirements.values():\n            schedule(install_req)\n        return order\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/base.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.models.link import Link, links_equivalent\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.hashes import Hashes\n\nCandidateLookup = tuple[Optional[\"Candidate\"], Optional[InstallRequirement]]\n\n\ndef format_name(project: NormalizedName, extras: frozenset[NormalizedName]) -> str:\n    if not extras:\n        return project\n    extras_expr = \",\".join(sorted(extras))\n    return f\"{project}[{extras_expr}]\"\n\n\n@dataclass(frozen=True)\nclass Constraint:\n    specifier: SpecifierSet\n    hashes: Hashes\n    links: frozenset[Link]\n\n    @classmethod\n    def empty(cls) -> Constraint:\n        return Constraint(SpecifierSet(), Hashes(), frozenset())\n\n    @classmethod\n    def from_ireq(cls, ireq: InstallRequirement) -> Constraint:\n        links = frozenset([ireq.link]) if ireq.link else frozenset()\n        return Constraint(ireq.specifier, ireq.hashes(trust_internet=False), links)\n\n    def __bool__(self) -> bool:\n        return bool(self.specifier) or bool(self.hashes) or bool(self.links)\n\n    def __and__(self, other: InstallRequirement) -> Constraint:\n        if not isinstance(other, InstallRequirement):\n            return NotImplemented\n        specifier = self.specifier & other.specifier\n        hashes = self.hashes & other.hashes(trust_internet=False)\n        links = self.links\n        if other.link:\n            links = links.union([other.link])\n        return Constraint(specifier, hashes, links)\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        # Reject if there are any mismatched URL constraints on this package.\n        if self.links and not all(_match_link(link, candidate) for link in self.links):\n            return False\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        return self.specifier.contains(candidate.version, prereleases=True)\n\n\nclass Requirement:\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The \"project name\" of a requirement.\n\n        This is different from ``name`` if this requirement contains extras,\n        in which case ``name`` would contain the ``[...]`` part, while this\n        refers to the name of the project.\n        \"\"\"\n        raise NotImplementedError(\"Subclass should override\")\n\n    @property\n    def name(self) -> str:\n        \"\"\"The name identifying this requirement in the resolver.\n\n        This is different from ``project_name`` if this requirement contains\n        extras, where ``project_name`` would not contain the ``[...]`` part.\n        \"\"\"\n        raise NotImplementedError(\"Subclass should override\")\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        return False\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        raise NotImplementedError(\"Subclass should override\")\n\n    def format_for_error(self) -> str:\n        raise NotImplementedError(\"Subclass should override\")\n\n\ndef _match_link(link: Link, candidate: Candidate) -> bool:\n    if candidate.source_link:\n        return links_equivalent(link, candidate.source_link)\n    return False\n\n\nclass Candidate:\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The \"project name\" of the candidate.\n\n        This is different from ``name`` if this candidate contains extras,\n        in which case ``name`` would contain the ``[...]`` part, while this\n        refers to the name of the project.\n        \"\"\"\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def name(self) -> str:\n        \"\"\"The name identifying this candidate in the resolver.\n\n        This is different from ``project_name`` if this candidate contains\n        extras, where ``project_name`` would not contain the ``[...]`` part.\n        \"\"\"\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def version(self) -> Version:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def is_installed(self) -> bool:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def is_editable(self) -> bool:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def source_link(self) -> Link | None:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def get_install_requirement(self) -> InstallRequirement | None:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def format_for_error(self) -> str:\n        raise NotImplementedError(\"Subclass should override\")\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/candidates.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport sys\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING, Any, Union, cast\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.exceptions import (\n    FailedToPrepareCandidate,\n    HashError,\n    InstallationSubprocessError,\n    InvalidInstalledPackage,\n    MetadataInconsistent,\n    MetadataInvalid,\n)\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.models.link import Link, links_equivalent\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n)\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.direct_url_helpers import direct_url_from_link\nfrom pip._internal.utils.misc import normalize_version_info\n\nfrom .base import Candidate, Requirement, format_name\n\nif TYPE_CHECKING:\n    from .factory import Factory\n\nlogger = logging.getLogger(__name__)\n\nBaseCandidate = Union[\n    \"AlreadyInstalledCandidate\",\n    \"EditableCandidate\",\n    \"LinkCandidate\",\n]\n\n# Avoid conflicting with the PyPI package \"Python\".\nREQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, \"<Python from Requires-Python>\")\n\n\ndef as_base_candidate(candidate: Candidate) -> BaseCandidate | None:\n    \"\"\"The runtime version of BaseCandidate.\"\"\"\n    base_candidate_classes = (\n        AlreadyInstalledCandidate,\n        EditableCandidate,\n        LinkCandidate,\n    )\n    if isinstance(candidate, base_candidate_classes):\n        return candidate\n    return None\n\n\ndef make_install_req_from_link(\n    link: Link, template: InstallRequirement\n) -> InstallRequirement:\n    assert not template.editable, \"template is editable\"\n    if template.req:\n        line = str(template.req)\n    else:\n        line = link.url\n    ireq = install_req_from_line(\n        line,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        hash_options=template.hash_options,\n        config_settings=template.config_settings,\n    )\n    ireq.original_link = template.original_link\n    ireq.link = link\n    ireq.extras = template.extras\n    return ireq\n\n\ndef make_install_req_from_editable(\n    link: Link, template: InstallRequirement\n) -> InstallRequirement:\n    assert template.editable, \"template not editable\"\n    if template.name:\n        req_string = f\"{template.name} @ {link.url}\"\n    else:\n        req_string = link.url\n    ireq = install_req_from_editable(\n        req_string,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        permit_editable_wheels=template.permit_editable_wheels,\n        hash_options=template.hash_options,\n        config_settings=template.config_settings,\n    )\n    ireq.extras = template.extras\n    return ireq\n\n\ndef _make_install_req_from_dist(\n    dist: BaseDistribution, template: InstallRequirement\n) -> InstallRequirement:\n    if template.req:\n        line = str(template.req)\n    elif template.link:\n        line = f\"{dist.canonical_name} @ {template.link.url}\"\n    else:\n        line = f\"{dist.canonical_name}=={dist.version}\"\n    ireq = install_req_from_line(\n        line,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        hash_options=template.hash_options,\n        config_settings=template.config_settings,\n    )\n    ireq.satisfied_by = dist\n    return ireq\n\n\nclass _InstallRequirementBackedCandidate(Candidate):\n    \"\"\"A candidate backed by an ``InstallRequirement``.\n\n    This represents a package request with the target not being already\n    in the environment, and needs to be fetched and installed. The backing\n    ``InstallRequirement`` is responsible for most of the leg work; this\n    class exposes appropriate information to the resolver.\n\n    :param link: The link passed to the ``InstallRequirement``. The backing\n        ``InstallRequirement`` will use this link to fetch the distribution.\n    :param source_link: The link this candidate \"originates\" from. This is\n        different from ``link`` when the link is found in the wheel cache.\n        ``link`` would point to the wheel cache, while this points to the\n        found remote link (e.g. from pypi.org).\n    \"\"\"\n\n    dist: BaseDistribution\n    is_installed = False\n\n    def __init__(\n        self,\n        link: Link,\n        source_link: Link,\n        ireq: InstallRequirement,\n        factory: Factory,\n        name: NormalizedName | None = None,\n        version: Version | None = None,\n    ) -> None:\n        self._link = link\n        self._source_link = source_link\n        self._factory = factory\n        self._ireq = ireq\n        self._name = name\n        self._version = version\n        self.dist = self._prepare()\n        self._hash: int | None = None\n\n    def __str__(self) -> str:\n        return f\"{self.name} {self.version}\"\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({str(self._link)!r})\"\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n\n        self._hash = hash((self.__class__, self._link))\n        return self._hash\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, self.__class__):\n            return links_equivalent(self._link, other._link)\n        return False\n\n    @property\n    def source_link(self) -> Link | None:\n        return self._source_link\n\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The normalised name of the project the candidate refers to\"\"\"\n        if self._name is None:\n            self._name = self.dist.canonical_name\n        return self._name\n\n    @property\n    def name(self) -> str:\n        return self.project_name\n\n    @property\n    def version(self) -> Version:\n        if self._version is None:\n            self._version = self.dist.version\n        return self._version\n\n    def format_for_error(self) -> str:\n        return (\n            f\"{self.name} {self.version} \"\n            f\"(from {self._link.file_path if self._link.is_file else self._link})\"\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def _check_metadata_consistency(self, dist: BaseDistribution) -> None:\n        \"\"\"Check for consistency of project name and version of dist.\"\"\"\n        if self._name is not None and self._name != dist.canonical_name:\n            raise MetadataInconsistent(\n                self._ireq,\n                \"name\",\n                self._name,\n                dist.canonical_name,\n            )\n        if self._version is not None and self._version != dist.version:\n            raise MetadataInconsistent(\n                self._ireq,\n                \"version\",\n                str(self._version),\n                str(dist.version),\n            )\n        # check dependencies are valid\n        # TODO performance: this means we iterate the dependencies at least twice,\n        # we may want to cache parsed Requires-Dist\n        try:\n            list(dist.iter_dependencies(list(dist.iter_provided_extras())))\n        except InvalidRequirement as e:\n            raise MetadataInvalid(self._ireq, str(e))\n\n    def _prepare(self) -> BaseDistribution:\n        try:\n            dist = self._prepare_distribution()\n        except HashError as e:\n            # Provide HashError the underlying ireq that caused it. This\n            # provides context for the resulting error message to show the\n            # offending line to the user.\n            e.req = self._ireq\n            raise\n        except InstallationSubprocessError as exc:\n            if isinstance(self._ireq.comes_from, InstallRequirement):\n                request_chain = self._ireq.comes_from.from_path()\n            else:\n                request_chain = self._ireq.comes_from\n\n            if request_chain is None:\n                request_chain = \"directly requested\"\n\n            raise FailedToPrepareCandidate(\n                package_name=self._ireq.name or str(self._link),\n                requirement_chain=request_chain,\n                failed_step=exc.command_description,\n            )\n\n        self._check_metadata_consistency(dist)\n        return dist\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:\n        # Emit the Requires-Python requirement first to fail fast on\n        # unsupported candidates and avoid pointless downloads/preparation.\n        yield self._factory.make_requires_python_requirement(self.dist.requires_python)\n        requires = self.dist.iter_dependencies() if with_requires else ()\n        for r in requires:\n            yield from self._factory.make_requirements_from_spec(str(r), self._ireq)\n\n    def get_install_requirement(self) -> InstallRequirement | None:\n        return self._ireq\n\n\nclass LinkCandidate(_InstallRequirementBackedCandidate):\n    is_editable = False\n\n    def __init__(\n        self,\n        link: Link,\n        template: InstallRequirement,\n        factory: Factory,\n        name: NormalizedName | None = None,\n        version: Version | None = None,\n    ) -> None:\n        source_link = link\n        cache_entry = factory.get_wheel_cache_entry(source_link, name)\n        if cache_entry is not None:\n            logger.debug(\"Using cached wheel link: %s\", cache_entry.link)\n            link = cache_entry.link\n        ireq = make_install_req_from_link(link, template)\n        assert ireq.link == link\n        if ireq.link.is_wheel and not ireq.link.is_file:\n            wheel = Wheel(ireq.link.filename)\n            wheel_name = wheel.name\n            assert name == wheel_name, f\"{name!r} != {wheel_name!r} for wheel\"\n            # Version may not be present for PEP 508 direct URLs\n            if version is not None:\n                wheel_version = Version(wheel.version)\n                assert (\n                    version == wheel_version\n                ), f\"{version!r} != {wheel_version!r} for wheel {name}\"\n\n        if cache_entry is not None:\n            assert ireq.link.is_wheel\n            assert ireq.link.is_file\n            if cache_entry.persistent and template.link is template.original_link:\n                ireq.cached_wheel_source_link = source_link\n            if cache_entry.origin is not None:\n                ireq.download_info = cache_entry.origin\n            else:\n                # Legacy cache entry that does not have origin.json.\n                # download_info may miss the archive_info.hashes field.\n                ireq.download_info = direct_url_from_link(\n                    source_link, link_is_in_wheel_cache=cache_entry.persistent\n                )\n\n        super().__init__(\n            link=link,\n            source_link=source_link,\n            ireq=ireq,\n            factory=factory,\n            name=name,\n            version=version,\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        preparer = self._factory.preparer\n        return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)\n\n\nclass EditableCandidate(_InstallRequirementBackedCandidate):\n    is_editable = True\n\n    def __init__(\n        self,\n        link: Link,\n        template: InstallRequirement,\n        factory: Factory,\n        name: NormalizedName | None = None,\n        version: Version | None = None,\n    ) -> None:\n        super().__init__(\n            link=link,\n            source_link=link,\n            ireq=make_install_req_from_editable(link, template),\n            factory=factory,\n            name=name,\n            version=version,\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        return self._factory.preparer.prepare_editable_requirement(self._ireq)\n\n\nclass AlreadyInstalledCandidate(Candidate):\n    is_installed = True\n    source_link = None\n\n    def __init__(\n        self,\n        dist: BaseDistribution,\n        template: InstallRequirement,\n        factory: Factory,\n    ) -> None:\n        self.dist = dist\n        self._ireq = _make_install_req_from_dist(dist, template)\n        self._factory = factory\n        self._version = None\n\n        # This is just logging some messages, so we can do it eagerly.\n        # The returned dist would be exactly the same as self.dist because we\n        # set satisfied_by in _make_install_req_from_dist.\n        # TODO: Supply reason based on force_reinstall and upgrade_strategy.\n        skip_reason = \"already satisfied\"\n        factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)\n\n    def __str__(self) -> str:\n        return str(self.dist)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self.dist!r})\"\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, AlreadyInstalledCandidate):\n            return NotImplemented\n        return self.name == other.name and self.version == other.version\n\n    def __hash__(self) -> int:\n        return hash((self.name, self.version))\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self.dist.canonical_name\n\n    @property\n    def name(self) -> str:\n        return self.project_name\n\n    @property\n    def version(self) -> Version:\n        if self._version is None:\n            self._version = self.dist.version\n        return self._version\n\n    @property\n    def is_editable(self) -> bool:\n        return self.dist.editable\n\n    def format_for_error(self) -> str:\n        return f\"{self.name} {self.version} (Installed)\"\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:\n        if not with_requires:\n            return\n\n        try:\n            for r in self.dist.iter_dependencies():\n                yield from self._factory.make_requirements_from_spec(str(r), self._ireq)\n        except InvalidRequirement as exc:\n            raise InvalidInstalledPackage(dist=self.dist, invalid_exc=exc) from None\n\n    def get_install_requirement(self) -> InstallRequirement | None:\n        return None\n\n\nclass ExtrasCandidate(Candidate):\n    \"\"\"A candidate that has 'extras', indicating additional dependencies.\n\n    Requirements can be for a project with dependencies, something like\n    foo[extra].  The extras don't affect the project/version being installed\n    directly, but indicate that we need additional dependencies. We model that\n    by having an artificial ExtrasCandidate that wraps the \"base\" candidate.\n\n    The ExtrasCandidate differs from the base in the following ways:\n\n    1. It has a unique name, of the form foo[extra]. This causes the resolver\n       to treat it as a separate node in the dependency graph.\n    2. When we're getting the candidate's dependencies,\n       a) We specify that we want the extra dependencies as well.\n       b) We add a dependency on the base candidate.\n          See below for why this is needed.\n    3. We return None for the underlying InstallRequirement, as the base\n       candidate will provide it, and we don't want to end up with duplicates.\n\n    The dependency on the base candidate is needed so that the resolver can't\n    decide that it should recommend foo[extra1] version 1.0 and foo[extra2]\n    version 2.0. Having those candidates depend on foo=1.0 and foo=2.0\n    respectively forces the resolver to recognise that this is a conflict.\n    \"\"\"\n\n    def __init__(\n        self,\n        base: BaseCandidate,\n        extras: frozenset[str],\n        *,\n        comes_from: InstallRequirement | None = None,\n    ) -> None:\n        \"\"\"\n        :param comes_from: the InstallRequirement that led to this candidate if it\n            differs from the base's InstallRequirement. This will often be the\n            case in the sense that this candidate's requirement has the extras\n            while the base's does not. Unlike the InstallRequirement backed\n            candidates, this requirement is used solely for reporting purposes,\n            it does not do any leg work.\n        \"\"\"\n        self.base = base\n        self.extras = frozenset(canonicalize_name(e) for e in extras)\n        self._comes_from = comes_from if comes_from is not None else self.base._ireq\n\n    def __str__(self) -> str:\n        name, rest = str(self.base).split(\" \", 1)\n        return \"{}[{}] {}\".format(name, \",\".join(self.extras), rest)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}(base={self.base!r}, extras={self.extras!r})\"\n\n    def __hash__(self) -> int:\n        return hash((self.base, self.extras))\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, self.__class__):\n            return self.base == other.base and self.extras == other.extras\n        return False\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self.base.project_name\n\n    @property\n    def name(self) -> str:\n        \"\"\"The normalised name of the project the candidate refers to\"\"\"\n        return format_name(self.base.project_name, self.extras)\n\n    @property\n    def version(self) -> Version:\n        return self.base.version\n\n    def format_for_error(self) -> str:\n        return \"{} [{}]\".format(\n            self.base.format_for_error(), \", \".join(sorted(self.extras))\n        )\n\n    @property\n    def is_installed(self) -> bool:\n        return self.base.is_installed\n\n    @property\n    def is_editable(self) -> bool:\n        return self.base.is_editable\n\n    @property\n    def source_link(self) -> Link | None:\n        return self.base.source_link\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:\n        factory = self.base._factory\n\n        # Add a dependency on the exact base\n        # (See note 2b in the class docstring)\n        yield factory.make_requirement_from_candidate(self.base)\n        if not with_requires:\n            return\n\n        # The user may have specified extras that the candidate doesn't\n        # support. We ignore any unsupported extras here.\n        valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras())\n        invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras())\n        for extra in sorted(invalid_extras):\n            logger.warning(\n                \"%s %s does not provide the extra '%s'\",\n                self.base.name,\n                self.version,\n                extra,\n            )\n\n        for r in self.base.dist.iter_dependencies(valid_extras):\n            yield from factory.make_requirements_from_spec(\n                str(r),\n                self._comes_from,\n                valid_extras,\n            )\n\n    def get_install_requirement(self) -> InstallRequirement | None:\n        # We don't return anything here, because we always\n        # depend on the base candidate, and we'll get the\n        # install requirement from that.\n        return None\n\n\nclass RequiresPythonCandidate(Candidate):\n    is_installed = False\n    source_link = None\n\n    def __init__(self, py_version_info: tuple[int, ...] | None) -> None:\n        if py_version_info is not None:\n            version_info = normalize_version_info(py_version_info)\n        else:\n            version_info = sys.version_info[:3]\n        self._version = Version(\".\".join(str(c) for c in version_info))\n\n    # We don't need to implement __eq__() and __ne__() since there is always\n    # only one RequiresPythonCandidate in a resolution, i.e. the host Python.\n    # The built-in object.__eq__() and object.__ne__() do exactly what we want.\n\n    def __str__(self) -> str:\n        return f\"Python {self._version}\"\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self._version!r})\"\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return REQUIRES_PYTHON_IDENTIFIER\n\n    @property\n    def name(self) -> str:\n        return REQUIRES_PYTHON_IDENTIFIER\n\n    @property\n    def version(self) -> Version:\n        return self._version\n\n    def format_for_error(self) -> str:\n        return f\"Python {self.version}\"\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:\n        return ()\n\n    def get_install_requirement(self) -> InstallRequirement | None:\n        return None\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/factory.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport functools\nimport logging\nfrom collections.abc import Iterable, Iterator, Mapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    NamedTuple,\n    Protocol,\n    TypeVar,\n    cast,\n)\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import InvalidVersion, Version\nfrom pip._vendor.resolvelib import ResolutionImpossible\n\nfrom pip._internal.cache import CacheEntry, WheelCache\nfrom pip._internal.exceptions import (\n    DistributionNotFound,\n    InstallationError,\n    InvalidInstalledPackage,\n    MetadataInconsistent,\n    MetadataInvalid,\n    UnsupportedPythonVersion,\n    UnsupportedWheel,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution, get_default_environment\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import (\n    install_req_drop_extras,\n    install_req_from_link_and_ireq,\n)\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    check_invalid_constraint_type,\n)\nfrom pip._internal.resolution.base import InstallRequirementProvider\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import Candidate, Constraint, Requirement\nfrom .candidates import (\n    AlreadyInstalledCandidate,\n    BaseCandidate,\n    EditableCandidate,\n    ExtrasCandidate,\n    LinkCandidate,\n    RequiresPythonCandidate,\n    as_base_candidate,\n)\nfrom .found_candidates import FoundCandidates, IndexCandidateInfo\nfrom .requirements import (\n    ExplicitRequirement,\n    RequiresPythonRequirement,\n    SpecifierRequirement,\n    SpecifierWithoutExtrasRequirement,\n    UnsatisfiableRequirement,\n)\n\nif TYPE_CHECKING:\n\n    class ConflictCause(Protocol):\n        requirement: RequiresPythonRequirement\n        parent: Candidate\n\n\nlogger = logging.getLogger(__name__)\n\nC = TypeVar(\"C\")\nCache = dict[Link, C]\n\n\nclass CollectedRootRequirements(NamedTuple):\n    requirements: list[Requirement]\n    constraints: dict[str, Constraint]\n    user_requested: dict[str, int]\n\n\nclass Factory:\n    def __init__(\n        self,\n        finder: PackageFinder,\n        preparer: RequirementPreparer,\n        make_install_req: InstallRequirementProvider,\n        wheel_cache: WheelCache | None,\n        use_user_site: bool,\n        force_reinstall: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        py_version_info: tuple[int, ...] | None = None,\n    ) -> None:\n        self._finder = finder\n        self.preparer = preparer\n        self._wheel_cache = wheel_cache\n        self._python_candidate = RequiresPythonCandidate(py_version_info)\n        self._make_install_req_from_spec = make_install_req\n        self._use_user_site = use_user_site\n        self._force_reinstall = force_reinstall\n        self._ignore_requires_python = ignore_requires_python\n\n        self._build_failures: Cache[InstallationError] = {}\n        self._link_candidate_cache: Cache[LinkCandidate] = {}\n        self._editable_candidate_cache: Cache[EditableCandidate] = {}\n        self._installed_candidate_cache: dict[str, AlreadyInstalledCandidate] = {}\n        self._extras_candidate_cache: dict[\n            tuple[int, frozenset[NormalizedName]], ExtrasCandidate\n        ] = {}\n        self._supported_tags_cache = get_supported()\n\n        if not ignore_installed:\n            env = get_default_environment()\n            self._installed_dists = {\n                dist.canonical_name: dist\n                for dist in env.iter_installed_distributions(local_only=False)\n            }\n        else:\n            self._installed_dists = {}\n\n    @property\n    def force_reinstall(self) -> bool:\n        return self._force_reinstall\n\n    def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None:\n        if not link.is_wheel:\n            return\n        wheel = Wheel(link.filename)\n        if wheel.supported(self._finder.target_python.get_unsorted_tags()):\n            return\n        msg = f\"{link.filename} is not a supported wheel on this platform.\"\n        raise UnsupportedWheel(msg)\n\n    def _make_extras_candidate(\n        self,\n        base: BaseCandidate,\n        extras: frozenset[str],\n        *,\n        comes_from: InstallRequirement | None = None,\n    ) -> ExtrasCandidate:\n        cache_key = (id(base), frozenset(canonicalize_name(e) for e in extras))\n        try:\n            candidate = self._extras_candidate_cache[cache_key]\n        except KeyError:\n            candidate = ExtrasCandidate(base, extras, comes_from=comes_from)\n            self._extras_candidate_cache[cache_key] = candidate\n        return candidate\n\n    def _make_candidate_from_dist(\n        self,\n        dist: BaseDistribution,\n        extras: frozenset[str],\n        template: InstallRequirement,\n    ) -> Candidate:\n        try:\n            base = self._installed_candidate_cache[dist.canonical_name]\n        except KeyError:\n            base = AlreadyInstalledCandidate(dist, template, factory=self)\n            self._installed_candidate_cache[dist.canonical_name] = base\n        if not extras:\n            return base\n        return self._make_extras_candidate(base, extras, comes_from=template)\n\n    def _make_candidate_from_link(\n        self,\n        link: Link,\n        extras: frozenset[str],\n        template: InstallRequirement,\n        name: NormalizedName | None,\n        version: Version | None,\n    ) -> Candidate | None:\n        base: BaseCandidate | None = self._make_base_candidate_from_link(\n            link, template, name, version\n        )\n        if not extras or base is None:\n            return base\n        return self._make_extras_candidate(base, extras, comes_from=template)\n\n    def _make_base_candidate_from_link(\n        self,\n        link: Link,\n        template: InstallRequirement,\n        name: NormalizedName | None,\n        version: Version | None,\n    ) -> BaseCandidate | None:\n        # TODO: Check already installed candidate, and use it if the link and\n        # editable flag match.\n\n        if link in self._build_failures:\n            # We already tried this candidate before, and it does not build.\n            # Don't bother trying again.\n            return None\n\n        if template.editable:\n            if link not in self._editable_candidate_cache:\n                try:\n                    self._editable_candidate_cache[link] = EditableCandidate(\n                        link,\n                        template,\n                        factory=self,\n                        name=name,\n                        version=version,\n                    )\n                except (MetadataInconsistent, MetadataInvalid) as e:\n                    logger.info(\n                        \"Discarding [blue underline]%s[/]: [yellow]%s[reset]\",\n                        link,\n                        e,\n                        extra={\"markup\": True},\n                    )\n                    self._build_failures[link] = e\n                    return None\n\n            return self._editable_candidate_cache[link]\n        else:\n            if link not in self._link_candidate_cache:\n                try:\n                    self._link_candidate_cache[link] = LinkCandidate(\n                        link,\n                        template,\n                        factory=self,\n                        name=name,\n                        version=version,\n                    )\n                except MetadataInconsistent as e:\n                    logger.info(\n                        \"Discarding [blue underline]%s[/]: [yellow]%s[reset]\",\n                        link,\n                        e,\n                        extra={\"markup\": True},\n                    )\n                    self._build_failures[link] = e\n                    return None\n            return self._link_candidate_cache[link]\n\n    def _iter_found_candidates(\n        self,\n        ireqs: Sequence[InstallRequirement],\n        specifier: SpecifierSet,\n        hashes: Hashes,\n        prefers_installed: bool,\n        incompatible_ids: set[int],\n    ) -> Iterable[Candidate]:\n        if not ireqs:\n            return ()\n\n        # The InstallRequirement implementation requires us to give it a\n        # \"template\". Here we just choose the first requirement to represent\n        # all of them.\n        # Hopefully the Project model can correct this mismatch in the future.\n        template = ireqs[0]\n        assert template.req, \"Candidates found on index must be PEP 508\"\n        name = canonicalize_name(template.req.name)\n\n        extras: frozenset[str] = frozenset()\n        for ireq in ireqs:\n            assert ireq.req, \"Candidates found on index must be PEP 508\"\n            specifier &= ireq.req.specifier\n            hashes &= ireq.hashes(trust_internet=False)\n            extras |= frozenset(ireq.extras)\n\n        def _get_installed_candidate() -> Candidate | None:\n            \"\"\"Get the candidate for the currently-installed version.\"\"\"\n            # If --force-reinstall is set, we want the version from the index\n            # instead, so we \"pretend\" there is nothing installed.\n            if self._force_reinstall:\n                return None\n            try:\n                installed_dist = self._installed_dists[name]\n            except KeyError:\n                return None\n\n            try:\n                # Don't use the installed distribution if its version\n                # does not fit the current dependency graph.\n                if not specifier.contains(installed_dist.version, prereleases=True):\n                    return None\n            except InvalidVersion as e:\n                raise InvalidInstalledPackage(dist=installed_dist, invalid_exc=e)\n\n            candidate = self._make_candidate_from_dist(\n                dist=installed_dist,\n                extras=extras,\n                template=template,\n            )\n            # The candidate is a known incompatibility. Don't use it.\n            if id(candidate) in incompatible_ids:\n                return None\n            return candidate\n\n        def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:\n            result = self._finder.find_best_candidate(\n                project_name=name,\n                specifier=specifier,\n                hashes=hashes,\n            )\n            icans = result.applicable_candidates\n\n            # PEP 592: Yanked releases are ignored unless the specifier\n            # explicitly pins a version (via '==' or '===') that can be\n            # solely satisfied by a yanked release.\n            all_yanked = all(ican.link.is_yanked for ican in icans)\n\n            def is_pinned(specifier: SpecifierSet) -> bool:\n                for sp in specifier:\n                    if sp.operator == \"===\":\n                        return True\n                    if sp.operator != \"==\":\n                        continue\n                    if sp.version.endswith(\".*\"):\n                        continue\n                    return True\n                return False\n\n            pinned = is_pinned(specifier)\n\n            # PackageFinder returns earlier versions first, so we reverse.\n            for ican in reversed(icans):\n                if not (all_yanked and pinned) and ican.link.is_yanked:\n                    continue\n                func = functools.partial(\n                    self._make_candidate_from_link,\n                    link=ican.link,\n                    extras=extras,\n                    template=template,\n                    name=name,\n                    version=ican.version,\n                )\n                yield ican.version, func\n\n        return FoundCandidates(\n            iter_index_candidate_infos,\n            _get_installed_candidate(),\n            prefers_installed,\n            incompatible_ids,\n        )\n\n    def _iter_explicit_candidates_from_base(\n        self,\n        base_requirements: Iterable[Requirement],\n        extras: frozenset[str],\n    ) -> Iterator[Candidate]:\n        \"\"\"Produce explicit candidates from the base given an extra-ed package.\n\n        :param base_requirements: Requirements known to the resolver. The\n            requirements are guaranteed to not have extras.\n        :param extras: The extras to inject into the explicit requirements'\n            candidates.\n        \"\"\"\n        for req in base_requirements:\n            lookup_cand, _ = req.get_candidate_lookup()\n            if lookup_cand is None:  # Not explicit.\n                continue\n            # We've stripped extras from the identifier, and should always\n            # get a BaseCandidate here, unless there's a bug elsewhere.\n            base_cand = as_base_candidate(lookup_cand)\n            assert base_cand is not None, \"no extras here\"\n            yield self._make_extras_candidate(base_cand, extras)\n\n    def _iter_candidates_from_constraints(\n        self,\n        identifier: str,\n        constraint: Constraint,\n        template: InstallRequirement,\n    ) -> Iterator[Candidate]:\n        \"\"\"Produce explicit candidates from constraints.\n\n        This creates \"fake\" InstallRequirement objects that are basically clones\n        of what \"should\" be the template, but with original_link set to link.\n        \"\"\"\n        for link in constraint.links:\n            self._fail_if_link_is_unsupported_wheel(link)\n            candidate = self._make_base_candidate_from_link(\n                link,\n                template=install_req_from_link_and_ireq(link, template),\n                name=canonicalize_name(identifier),\n                version=None,\n            )\n            if candidate:\n                yield candidate\n\n    def find_candidates(\n        self,\n        identifier: str,\n        requirements: Mapping[str, Iterable[Requirement]],\n        incompatibilities: Mapping[str, Iterator[Candidate]],\n        constraint: Constraint,\n        prefers_installed: bool,\n        is_satisfied_by: Callable[[Requirement, Candidate], bool],\n    ) -> Iterable[Candidate]:\n        # Collect basic lookup information from the requirements.\n        explicit_candidates: set[Candidate] = set()\n        ireqs: list[InstallRequirement] = []\n        for req in requirements[identifier]:\n            cand, ireq = req.get_candidate_lookup()\n            if cand is not None:\n                explicit_candidates.add(cand)\n            if ireq is not None:\n                ireqs.append(ireq)\n\n        # If the current identifier contains extras, add requires and explicit\n        # candidates from entries from extra-less identifier.\n        with contextlib.suppress(InvalidRequirement):\n            parsed_requirement = get_requirement(identifier)\n            if parsed_requirement.name != identifier:\n                explicit_candidates.update(\n                    self._iter_explicit_candidates_from_base(\n                        requirements.get(parsed_requirement.name, ()),\n                        frozenset(parsed_requirement.extras),\n                    ),\n                )\n                for req in requirements.get(parsed_requirement.name, []):\n                    _, ireq = req.get_candidate_lookup()\n                    if ireq is not None:\n                        ireqs.append(ireq)\n\n        # Add explicit candidates from constraints. We only do this if there are\n        # known ireqs, which represent requirements not already explicit. If\n        # there are no ireqs, we're constraining already-explicit requirements,\n        # which is handled later when we return the explicit candidates.\n        if ireqs:\n            try:\n                explicit_candidates.update(\n                    self._iter_candidates_from_constraints(\n                        identifier,\n                        constraint,\n                        template=ireqs[0],\n                    ),\n                )\n            except UnsupportedWheel:\n                # If we're constrained to install a wheel incompatible with the\n                # target architecture, no candidates will ever be valid.\n                return ()\n\n        # Since we cache all the candidates, incompatibility identification\n        # can be made quicker by comparing only the id() values.\n        incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}\n\n        # If none of the requirements want an explicit candidate, we can ask\n        # the finder for candidates.\n        if not explicit_candidates:\n            return self._iter_found_candidates(\n                ireqs,\n                constraint.specifier,\n                constraint.hashes,\n                prefers_installed,\n                incompat_ids,\n            )\n\n        return (\n            c\n            for c in explicit_candidates\n            if id(c) not in incompat_ids\n            and constraint.is_satisfied_by(c)\n            and all(is_satisfied_by(req, c) for req in requirements[identifier])\n        )\n\n    def _make_requirements_from_install_req(\n        self, ireq: InstallRequirement, requested_extras: Iterable[str]\n    ) -> Iterator[Requirement]:\n        \"\"\"\n        Returns requirement objects associated with the given InstallRequirement. In\n        most cases this will be a single object but the following special cases exist:\n            - the InstallRequirement has markers that do not apply -> result is empty\n            - the InstallRequirement has both a constraint (or link) and extras\n                -> result is split in two requirement objects: one with the constraint\n                (or link) and one with the extra. This allows centralized constraint\n                handling for the base, resulting in fewer candidate rejections.\n        \"\"\"\n        if not ireq.match_markers(requested_extras):\n            logger.info(\n                \"Ignoring %s: markers '%s' don't match your environment\",\n                ireq.name,\n                ireq.markers,\n            )\n        elif not ireq.link:\n            if ireq.extras and ireq.req is not None and ireq.req.specifier:\n                yield SpecifierWithoutExtrasRequirement(ireq)\n            yield SpecifierRequirement(ireq)\n        else:\n            self._fail_if_link_is_unsupported_wheel(ireq.link)\n            # Always make the link candidate for the base requirement to make it\n            # available to `find_candidates` for explicit candidate lookup for any\n            # set of extras.\n            # The extras are required separately via a second requirement.\n            cand = self._make_base_candidate_from_link(\n                ireq.link,\n                template=install_req_drop_extras(ireq) if ireq.extras else ireq,\n                name=canonicalize_name(ireq.name) if ireq.name else None,\n                version=None,\n            )\n            if cand is None:\n                # There's no way we can satisfy a URL requirement if the underlying\n                # candidate fails to build. An unnamed URL must be user-supplied, so\n                # we fail eagerly. If the URL is named, an unsatisfiable requirement\n                # can make the resolver do the right thing, either backtrack (and\n                # maybe find some other requirement that's buildable) or raise a\n                # ResolutionImpossible eventually.\n                if not ireq.name:\n                    raise self._build_failures[ireq.link]\n                yield UnsatisfiableRequirement(canonicalize_name(ireq.name))\n            else:\n                # require the base from the link\n                yield self.make_requirement_from_candidate(cand)\n                if ireq.extras:\n                    # require the extras on top of the base candidate\n                    yield self.make_requirement_from_candidate(\n                        self._make_extras_candidate(cand, frozenset(ireq.extras))\n                    )\n\n    def collect_root_requirements(\n        self, root_ireqs: list[InstallRequirement]\n    ) -> CollectedRootRequirements:\n        collected = CollectedRootRequirements([], {}, {})\n        for i, ireq in enumerate(root_ireqs):\n            if ireq.constraint:\n                # Ensure we only accept valid constraints\n                problem = check_invalid_constraint_type(ireq)\n                if problem:\n                    raise InstallationError(problem)\n                if not ireq.match_markers():\n                    continue\n                assert ireq.name, \"Constraint must be named\"\n                name = canonicalize_name(ireq.name)\n                if name in collected.constraints:\n                    collected.constraints[name] &= ireq\n                else:\n                    collected.constraints[name] = Constraint.from_ireq(ireq)\n            else:\n                reqs = list(\n                    self._make_requirements_from_install_req(\n                        ireq,\n                        requested_extras=(),\n                    )\n                )\n                if not reqs:\n                    continue\n                template = reqs[0]\n                if ireq.user_supplied and template.name not in collected.user_requested:\n                    collected.user_requested[template.name] = i\n                collected.requirements.extend(reqs)\n        # Put requirements with extras at the end of the root requires. This does not\n        # affect resolvelib's picking preference but it does affect its initial criteria\n        # population: by putting extras at the end we enable the candidate finder to\n        # present resolvelib with a smaller set of candidates to resolvelib, already\n        # taking into account any non-transient constraints on the associated base. This\n        # means resolvelib will have fewer candidates to visit and reject.\n        # Python's list sort is stable, meaning relative order is kept for objects with\n        # the same key.\n        collected.requirements.sort(key=lambda r: r.name != r.project_name)\n        return collected\n\n    def make_requirement_from_candidate(\n        self, candidate: Candidate\n    ) -> ExplicitRequirement:\n        return ExplicitRequirement(candidate)\n\n    def make_requirements_from_spec(\n        self,\n        specifier: str,\n        comes_from: InstallRequirement | None,\n        requested_extras: Iterable[str] = (),\n    ) -> Iterator[Requirement]:\n        \"\"\"\n        Returns requirement objects associated with the given specifier. In most cases\n        this will be a single object but the following special cases exist:\n            - the specifier has markers that do not apply -> result is empty\n            - the specifier has both a constraint and extras -> result is split\n                in two requirement objects: one with the constraint and one with the\n                extra. This allows centralized constraint handling for the base,\n                resulting in fewer candidate rejections.\n        \"\"\"\n        ireq = self._make_install_req_from_spec(specifier, comes_from)\n        return self._make_requirements_from_install_req(ireq, requested_extras)\n\n    def make_requires_python_requirement(\n        self,\n        specifier: SpecifierSet,\n    ) -> Requirement | None:\n        if self._ignore_requires_python:\n            return None\n        # Don't bother creating a dependency for an empty Requires-Python.\n        if not str(specifier):\n            return None\n        return RequiresPythonRequirement(specifier, self._python_candidate)\n\n    def get_wheel_cache_entry(self, link: Link, name: str | None) -> CacheEntry | None:\n        \"\"\"Look up the link in the wheel cache.\n\n        If ``preparer.require_hashes`` is True, don't use the wheel cache,\n        because cached wheels, always built locally, have different hashes\n        than the files downloaded from the index server and thus throw false\n        hash mismatches. Furthermore, cached wheels at present have\n        nondeterministic contents due to file modification times.\n        \"\"\"\n        if self._wheel_cache is None:\n            return None\n        return self._wheel_cache.get_cache_entry(\n            link=link,\n            package_name=name,\n            supported_tags=self._supported_tags_cache,\n        )\n\n    def get_dist_to_uninstall(self, candidate: Candidate) -> BaseDistribution | None:\n        # TODO: Are there more cases this needs to return True? Editable?\n        dist = self._installed_dists.get(candidate.project_name)\n        if dist is None:  # Not installed, no uninstallation required.\n            return None\n\n        # We're installing into global site. The current installation must\n        # be uninstalled, no matter it's in global or user site, because the\n        # user site installation has precedence over global.\n        if not self._use_user_site:\n            return dist\n\n        # We're installing into user site. Remove the user site installation.\n        if dist.in_usersite:\n            return dist\n\n        # We're installing into user site, but the installed incompatible\n        # package is in global site. We can't uninstall that, and would let\n        # the new user installation to \"shadow\" it. But shadowing won't work\n        # in virtual environments, so we error out.\n        if running_under_virtualenv() and dist.in_site_packages:\n            message = (\n                f\"Will not install to the user site because it will lack \"\n                f\"sys.path precedence to {dist.raw_name} in {dist.location}\"\n            )\n            raise InstallationError(message)\n        return None\n\n    def _report_requires_python_error(\n        self, causes: Sequence[ConflictCause]\n    ) -> UnsupportedPythonVersion:\n        assert causes, \"Requires-Python error reported with no cause\"\n\n        version = self._python_candidate.version\n\n        if len(causes) == 1:\n            specifier = str(causes[0].requirement.specifier)\n            message = (\n                f\"Package {causes[0].parent.name!r} requires a different \"\n                f\"Python: {version} not in {specifier!r}\"\n            )\n            return UnsupportedPythonVersion(message)\n\n        message = f\"Packages require a different Python. {version} not in:\"\n        for cause in causes:\n            package = cause.parent.format_for_error()\n            specifier = str(cause.requirement.specifier)\n            message += f\"\\n{specifier!r} (required by {package})\"\n        return UnsupportedPythonVersion(message)\n\n    def _report_single_requirement_conflict(\n        self, req: Requirement, parent: Candidate | None\n    ) -> DistributionNotFound:\n        if parent is None:\n            req_disp = str(req)\n        else:\n            req_disp = f\"{req} (from {parent.name})\"\n\n        cands = self._finder.find_all_candidates(req.project_name)\n        skipped_by_requires_python = self._finder.requires_python_skipped_reasons()\n\n        versions_set: set[Version] = set()\n        yanked_versions_set: set[Version] = set()\n        for c in cands:\n            is_yanked = c.link.is_yanked if c.link else False\n            if is_yanked:\n                yanked_versions_set.add(c.version)\n            else:\n                versions_set.add(c.version)\n\n        versions = [str(v) for v in sorted(versions_set)]\n        yanked_versions = [str(v) for v in sorted(yanked_versions_set)]\n\n        if yanked_versions:\n            # Saying \"version X is yanked\" isn't entirely accurate.\n            # https://github.com/pypa/pip/issues/11745#issuecomment-1402805842\n            logger.critical(\n                \"Ignored the following yanked versions: %s\",\n                \", \".join(yanked_versions) or \"none\",\n            )\n        if skipped_by_requires_python:\n            logger.critical(\n                \"Ignored the following versions that require a different python \"\n                \"version: %s\",\n                \"; \".join(skipped_by_requires_python) or \"none\",\n            )\n\n        # Check if only final releases are allowed for this package\n        version_type = \"version\"\n        if self._finder.release_control is not None:\n            allows_pre = self._finder.release_control.allows_prereleases(\n                canonicalize_name(req.project_name)\n            )\n            if allows_pre is False:\n                version_type = \"final version\"\n\n        logger.critical(\n            \"Could not find a %s that satisfies the requirement %s \"\n            \"(from versions: %s)\",\n            version_type,\n            req_disp,\n            \", \".join(versions) or \"none\",\n        )\n        if str(req) == \"requirements.txt\":\n            logger.info(\n                \"HINT: You are attempting to install a package literally \"\n                'named \"requirements.txt\" (which cannot exist). Consider '\n                \"using the '-r' flag to install the packages listed in \"\n                \"requirements.txt\"\n            )\n\n        return DistributionNotFound(f\"No matching distribution found for {req}\")\n\n    def _has_any_candidates(self, project_name: str) -> bool:\n        \"\"\"\n        Check if there are any candidates available for the project name.\n        \"\"\"\n        return any(\n            self.find_candidates(\n                project_name,\n                requirements={project_name: []},\n                incompatibilities={},\n                constraint=Constraint.empty(),\n                prefers_installed=True,\n                is_satisfied_by=lambda r, c: True,\n            )\n        )\n\n    def get_installation_error(\n        self,\n        e: ResolutionImpossible[Requirement, Candidate],\n        constraints: dict[str, Constraint],\n    ) -> InstallationError:\n        assert e.causes, \"Installation error reported with no cause\"\n\n        # If one of the things we can't solve is \"we need Python X.Y\",\n        # that is what we report.\n        requires_python_causes = [\n            cause\n            for cause in e.causes\n            if isinstance(cause.requirement, RequiresPythonRequirement)\n            and not cause.requirement.is_satisfied_by(self._python_candidate)\n        ]\n        if requires_python_causes:\n            # The comprehension above makes sure all Requirement instances are\n            # RequiresPythonRequirement, so let's cast for convenience.\n            return self._report_requires_python_error(\n                cast(\"Sequence[ConflictCause]\", requires_python_causes),\n            )\n\n        # Otherwise, we have a set of causes which can't all be satisfied\n        # at once.\n\n        # The simplest case is when we have *one* cause that can't be\n        # satisfied. We just report that case.\n        if len(e.causes) == 1:\n            req, parent = next(iter(e.causes))\n            if req.name not in constraints:\n                return self._report_single_requirement_conflict(req, parent)\n\n        # OK, we now have a list of requirements that can't all be\n        # satisfied at once.\n\n        # A couple of formatting helpers\n        def text_join(parts: list[str]) -> str:\n            if len(parts) == 1:\n                return parts[0]\n\n            return \", \".join(parts[:-1]) + \" and \" + parts[-1]\n\n        def describe_trigger(parent: Candidate) -> str:\n            ireq = parent.get_install_requirement()\n            if not ireq or not ireq.comes_from:\n                return f\"{parent.name}=={parent.version}\"\n            if isinstance(ireq.comes_from, InstallRequirement):\n                return str(ireq.comes_from.name)\n            return str(ireq.comes_from)\n\n        triggers = set()\n        for req, parent in e.causes:\n            if parent is None:\n                # This is a root requirement, so we can report it directly\n                trigger = req.format_for_error()\n            else:\n                trigger = describe_trigger(parent)\n            triggers.add(trigger)\n\n        if triggers:\n            info = text_join(sorted(triggers))\n        else:\n            info = \"the requested packages\"\n\n        msg = (\n            f\"Cannot install {info} because these package versions \"\n            \"have conflicting dependencies.\"\n        )\n        logger.critical(msg)\n        msg = \"\\nThe conflict is caused by:\"\n\n        relevant_constraints = set()\n        for req, parent in e.causes:\n            if req.name in constraints:\n                relevant_constraints.add(req.name)\n            msg = msg + \"\\n    \"\n            if parent:\n                msg = msg + f\"{parent.name} {parent.version} depends on \"\n            else:\n                msg = msg + \"The user requested \"\n            msg = msg + req.format_for_error()\n        for key in relevant_constraints:\n            spec = constraints[key].specifier\n            msg += f\"\\n    The user requested (constraint) {key}{spec}\"\n\n        # Check for causes that had no candidates\n        causes = set()\n        for req, _ in e.causes:\n            causes.add(req.name)\n\n        no_candidates = {c for c in causes if not self._has_any_candidates(c)}\n        if no_candidates:\n            msg = (\n                msg\n                + \"\\n\\n\"\n                + \"Additionally, some packages in these conflicts have no \"\n                + \"matching distributions available for your environment:\"\n                + \"\\n    \"\n                + \"\\n    \".join(sorted(no_candidates))\n            )\n\n        msg = (\n            msg\n            + \"\\n\\n\"\n            + \"To fix this you could try to:\\n\"\n            + \"1. loosen the range of package versions you've specified\\n\"\n            + \"2. remove package versions to allow pip to attempt to solve \"\n            + \"the dependency conflict\\n\"\n        )\n\n        logger.info(msg)\n\n        return DistributionNotFound(\n            \"ResolutionImpossible: for help visit \"\n            \"https://pip.pypa.io/en/latest/topics/dependency-resolution/\"\n            \"#dealing-with-dependency-conflicts\"\n        )\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/found_candidates.py",
    "content": "\"\"\"Utilities to lazily create and visit candidates found.\n\nCreating and visiting a candidate is a *very* costly operation. It involves\nfetching, extracting, potentially building modules from source, and verifying\ndistribution metadata. It is therefore crucial for performance to keep\neverything here lazy all the way down, so we only touch candidates that we\nabsolutely need, and not \"download the world\" when we only need one version of\nsomething.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nfrom collections.abc import Iterator, Sequence\nfrom typing import Any, Callable, Optional\n\nfrom pip._vendor.packaging.version import _BaseVersion\n\nfrom pip._internal.exceptions import MetadataInvalid\n\nfrom .base import Candidate\n\nlogger = logging.getLogger(__name__)\n\nIndexCandidateInfo = tuple[_BaseVersion, Callable[[], Optional[Candidate]]]\n\n\ndef _iter_built(infos: Iterator[IndexCandidateInfo]) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the package is not already installed. Candidates\n    from index come later in their normal ordering.\n    \"\"\"\n    versions_found: set[_BaseVersion] = set()\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        try:\n            candidate = func()\n        except MetadataInvalid as e:\n            logger.warning(\n                \"Ignoring version %s of %s since it has invalid metadata:\\n\"\n                \"%s\\n\"\n                \"Please use pip<24.1 if you need to use this version.\",\n                version,\n                e.ireq.name,\n                e,\n            )\n            # Mark version as found to avoid trying other candidates with the same\n            # version, since they most likely have invalid metadata as well.\n            versions_found.add(version)\n        else:\n            if candidate is None:\n                continue\n            yield candidate\n            versions_found.add(version)\n\n\ndef _iter_built_with_prepended(\n    installed: Candidate, infos: Iterator[IndexCandidateInfo]\n) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the resolver prefers the already-installed\n    candidate and NOT to upgrade. The installed candidate is therefore\n    always yielded first, and candidates from index come later in their\n    normal ordering, except skipped when the version is already installed.\n    \"\"\"\n    yield installed\n    versions_found: set[_BaseVersion] = {installed.version}\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        candidate = func()\n        if candidate is None:\n            continue\n        yield candidate\n        versions_found.add(version)\n\n\ndef _iter_built_with_inserted(\n    installed: Candidate, infos: Iterator[IndexCandidateInfo]\n) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the resolver prefers to upgrade an\n    already-installed package. Candidates from index are returned in their\n    normal ordering, except replaced when the version is already installed.\n\n    The implementation iterates through and yields other candidates, inserting\n    the installed candidate exactly once before we start yielding older or\n    equivalent candidates, or after all other candidates if they are all newer.\n    \"\"\"\n    versions_found: set[_BaseVersion] = set()\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        # If the installed candidate is better, yield it first.\n        if installed.version >= version:\n            yield installed\n            versions_found.add(installed.version)\n        candidate = func()\n        if candidate is None:\n            continue\n        yield candidate\n        versions_found.add(version)\n\n    # If the installed candidate is older than all other candidates.\n    if installed.version not in versions_found:\n        yield installed\n\n\nclass FoundCandidates(Sequence[Candidate]):\n    \"\"\"A lazy sequence to provide candidates to the resolver.\n\n    The intended usage is to return this from `find_matches()` so the resolver\n    can iterate through the sequence multiple times, but only access the index\n    page when remote packages are actually needed. This improve performances\n    when suitable candidates are already installed on disk.\n    \"\"\"\n\n    def __init__(\n        self,\n        get_infos: Callable[[], Iterator[IndexCandidateInfo]],\n        installed: Candidate | None,\n        prefers_installed: bool,\n        incompatible_ids: set[int],\n    ):\n        self._get_infos = get_infos\n        self._installed = installed\n        self._prefers_installed = prefers_installed\n        self._incompatible_ids = incompatible_ids\n        self._bool: bool | None = None\n\n    def __getitem__(self, index: Any) -> Any:\n        # Implemented to satisfy the ABC check. This is not needed by the\n        # resolver, and should not be used by the provider either (for\n        # performance reasons).\n        raise NotImplementedError(\"don't do this\")\n\n    def __iter__(self) -> Iterator[Candidate]:\n        infos = self._get_infos()\n        if not self._installed:\n            iterator = _iter_built(infos)\n        elif self._prefers_installed:\n            iterator = _iter_built_with_prepended(self._installed, infos)\n        else:\n            iterator = _iter_built_with_inserted(self._installed, infos)\n        return (c for c in iterator if id(c) not in self._incompatible_ids)\n\n    def __len__(self) -> int:\n        # Implemented to satisfy the ABC check. This is not needed by the\n        # resolver, and should not be used by the provider either (for\n        # performance reasons).\n        raise NotImplementedError(\"don't do this\")\n\n    def __bool__(self) -> bool:\n        if self._bool is not None:\n            return self._bool\n\n        if self._prefers_installed and self._installed:\n            self._bool = True\n            return True\n\n        self._bool = any(self)\n        return self._bool\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/provider.py",
    "content": "from __future__ import annotations\n\nimport math\nfrom collections.abc import Iterable, Iterator, Mapping, Sequence\nfrom functools import cache\nfrom typing import (\n    TYPE_CHECKING,\n    TypeVar,\n)\n\nfrom pip._vendor.resolvelib.providers import AbstractProvider\n\nfrom pip._internal.req.req_install import InstallRequirement\n\nfrom .base import Candidate, Constraint, Requirement\nfrom .candidates import REQUIRES_PYTHON_IDENTIFIER\nfrom .factory import Factory\nfrom .requirements import ExplicitRequirement\n\nif TYPE_CHECKING:\n    from pip._vendor.resolvelib.providers import Preference\n    from pip._vendor.resolvelib.resolvers import RequirementInformation\n\n    PreferenceInformation = RequirementInformation[Requirement, Candidate]\n\n    _ProviderBase = AbstractProvider[Requirement, Candidate, str]\nelse:\n    _ProviderBase = AbstractProvider\n\n# Notes on the relationship between the provider, the factory, and the\n# candidate and requirement classes.\n#\n# The provider is a direct implementation of the resolvelib class. Its role\n# is to deliver the API that resolvelib expects.\n#\n# Rather than work with completely abstract \"requirement\" and \"candidate\"\n# concepts as resolvelib does, pip has concrete classes implementing these two\n# ideas. The API of Requirement and Candidate objects are defined in the base\n# classes, but essentially map fairly directly to the equivalent provider\n# methods. In particular, `find_matches` and `is_satisfied_by` are\n# requirement methods, and `get_dependencies` is a candidate method.\n#\n# The factory is the interface to pip's internal mechanisms. It is stateless,\n# and is created by the resolver and held as a property of the provider. It is\n# responsible for creating Requirement and Candidate objects, and provides\n# services to those objects (access to pip's finder and preparer).\n\n\nD = TypeVar(\"D\")\nV = TypeVar(\"V\")\n\n\ndef _get_with_identifier(\n    mapping: Mapping[str, V],\n    identifier: str,\n    default: D,\n) -> D | V:\n    \"\"\"Get item from a package name lookup mapping with a resolver identifier.\n\n    This extra logic is needed when the target mapping is keyed by package\n    name, which cannot be directly looked up with an identifier (which may\n    contain requested extras). Additional logic is added to also look up a value\n    by \"cleaning up\" the extras from the identifier.\n    \"\"\"\n    if identifier in mapping:\n        return mapping[identifier]\n    # HACK: Theoretically we should check whether this identifier is a valid\n    # \"NAME[EXTRAS]\" format, and parse out the name part with packaging or\n    # some regular expression. But since pip's resolver only spits out three\n    # kinds of identifiers: normalized PEP 503 names, normalized names plus\n    # extras, and Requires-Python, we can cheat a bit here.\n    name, open_bracket, _ = identifier.partition(\"[\")\n    if open_bracket and name in mapping:\n        return mapping[name]\n    return default\n\n\nclass PipProvider(_ProviderBase):\n    \"\"\"Pip's provider implementation for resolvelib.\n\n    :params constraints: A mapping of constraints specified by the user. Keys\n        are canonicalized project names.\n    :params ignore_dependencies: Whether the user specified ``--no-deps``.\n    :params upgrade_strategy: The user-specified upgrade strategy.\n    :params user_requested: A set of canonicalized package names that the user\n        supplied for pip to install/upgrade.\n    \"\"\"\n\n    def __init__(\n        self,\n        factory: Factory,\n        constraints: dict[str, Constraint],\n        ignore_dependencies: bool,\n        upgrade_strategy: str,\n        user_requested: dict[str, int],\n    ) -> None:\n        self._factory = factory\n        self._constraints = constraints\n        self._ignore_dependencies = ignore_dependencies\n        self._upgrade_strategy = upgrade_strategy\n        self._user_requested = user_requested\n\n    @property\n    def constraints(self) -> dict[str, Constraint]:\n        \"\"\"Public view of user-specified constraints.\n\n        Exposes the provider's constraints mapping without encouraging\n        external callers to reach into private attributes.\n        \"\"\"\n        return self._constraints\n\n    def identify(self, requirement_or_candidate: Requirement | Candidate) -> str:\n        return requirement_or_candidate.name\n\n    def narrow_requirement_selection(\n        self,\n        identifiers: Iterable[str],\n        resolutions: Mapping[str, Candidate],\n        candidates: Mapping[str, Iterator[Candidate]],\n        information: Mapping[str, Iterator[PreferenceInformation]],\n        backtrack_causes: Sequence[PreferenceInformation],\n    ) -> Iterable[str]:\n        \"\"\"Produce a subset of identifiers that should be considered before others.\n\n        Currently pip narrows the following selection:\n            * Requires-Python, if present is always returned by itself\n            * Backtrack causes are considered next because they can be identified\n              in linear time here, whereas because get_preference() is called\n              for each identifier, it would be quadratic to check for them there.\n              Further, the current backtrack causes likely need to be resolved\n              before other requirements as a resolution can't be found while\n              there is a conflict.\n        \"\"\"\n        backtrack_identifiers = set()\n        for info in backtrack_causes:\n            backtrack_identifiers.add(info.requirement.name)\n            if info.parent is not None:\n                backtrack_identifiers.add(info.parent.name)\n\n        current_backtrack_causes = []\n        for identifier in identifiers:\n            # Requires-Python has only one candidate and the check is basically\n            # free, so we always do it first to avoid needless work if it fails.\n            # This skips calling get_preference() for all other identifiers.\n            if identifier == REQUIRES_PYTHON_IDENTIFIER:\n                return [identifier]\n\n            # Check if this identifier is a backtrack cause\n            if identifier in backtrack_identifiers:\n                current_backtrack_causes.append(identifier)\n                continue\n\n        if current_backtrack_causes:\n            return current_backtrack_causes\n\n        return identifiers\n\n    def get_preference(\n        self,\n        identifier: str,\n        resolutions: Mapping[str, Candidate],\n        candidates: Mapping[str, Iterator[Candidate]],\n        information: Mapping[str, Iterable[PreferenceInformation]],\n        backtrack_causes: Sequence[PreferenceInformation],\n    ) -> Preference:\n        \"\"\"Produce a sort key for given requirement based on preference.\n\n        The lower the return value is, the more preferred this group of\n        arguments is.\n\n        Currently pip considers the following in order:\n\n        * Any requirement that is \"direct\", e.g., points to an explicit URL.\n        * Any requirement that is \"pinned\", i.e., contains the operator ``===``\n          or ``==`` without a wildcard.\n        * Any requirement that imposes an upper version limit, i.e., contains the\n          operator ``<``, ``<=``, ``~=``, or ``==`` with a wildcard. Because\n          pip prioritizes the latest version, preferring explicit upper bounds\n          can rule out infeasible candidates sooner. This does not imply that\n          upper bounds are good practice; they can make dependency management\n          and resolution harder.\n        * Order user-specified requirements as they are specified, placing\n          other requirements afterward.\n        * Any \"non-free\" requirement, i.e., one that contains at least one\n          operator, such as ``>=`` or ``!=``.\n        * Alphabetical order for consistency (aids debuggability).\n        \"\"\"\n        try:\n            next(iter(information[identifier]))\n        except StopIteration:\n            # There is no information for this identifier, so there's no known\n            # candidates.\n            has_information = False\n        else:\n            has_information = True\n\n        if not has_information:\n            direct = False\n            ireqs: tuple[InstallRequirement | None, ...] = ()\n        else:\n            # Go through the information and for each requirement,\n            # check if it's explicit (e.g., a direct link) and get the\n            # InstallRequirement (the second element) from get_candidate_lookup()\n            directs, ireqs = zip(\n                *(\n                    (isinstance(r, ExplicitRequirement), r.get_candidate_lookup()[1])\n                    for r, _ in information[identifier]\n                )\n            )\n            direct = any(directs)\n\n        operators: list[tuple[str, str]] = [\n            (specifier.operator, specifier.version)\n            for specifier_set in (ireq.specifier for ireq in ireqs if ireq)\n            for specifier in specifier_set\n        ]\n\n        pinned = any(((op[:2] == \"==\") and (\"*\" not in ver)) for op, ver in operators)\n        upper_bounded = any(\n            ((op in (\"<\", \"<=\", \"~=\")) or (op == \"==\" and \"*\" in ver))\n            for op, ver in operators\n        )\n        unfree = bool(operators)\n        requested_order = self._user_requested.get(identifier, math.inf)\n\n        return (\n            not direct,\n            not pinned,\n            not upper_bounded,\n            requested_order,\n            not unfree,\n            identifier,\n        )\n\n    def find_matches(\n        self,\n        identifier: str,\n        requirements: Mapping[str, Iterator[Requirement]],\n        incompatibilities: Mapping[str, Iterator[Candidate]],\n    ) -> Iterable[Candidate]:\n        def _eligible_for_upgrade(identifier: str) -> bool:\n            \"\"\"Are upgrades allowed for this project?\n\n            This checks the upgrade strategy, and whether the project was one\n            that the user specified in the command line, in order to decide\n            whether we should upgrade if there's a newer version available.\n\n            (Note that we don't need access to the `--upgrade` flag, because\n            an upgrade strategy of \"to-satisfy-only\" means that `--upgrade`\n            was not specified).\n            \"\"\"\n            if self._upgrade_strategy == \"eager\":\n                return True\n            elif self._upgrade_strategy == \"only-if-needed\":\n                user_order = _get_with_identifier(\n                    self._user_requested,\n                    identifier,\n                    default=None,\n                )\n                return user_order is not None\n            return False\n\n        constraint = _get_with_identifier(\n            self._constraints,\n            identifier,\n            default=Constraint.empty(),\n        )\n        return self._factory.find_candidates(\n            identifier=identifier,\n            requirements=requirements,\n            constraint=constraint,\n            prefers_installed=(not _eligible_for_upgrade(identifier)),\n            incompatibilities=incompatibilities,\n            is_satisfied_by=self.is_satisfied_by,\n        )\n\n    @staticmethod\n    @cache\n    def is_satisfied_by(requirement: Requirement, candidate: Candidate) -> bool:\n        return requirement.is_satisfied_by(candidate)\n\n    def get_dependencies(self, candidate: Candidate) -> Iterable[Requirement]:\n        with_requires = not self._ignore_dependencies\n        # iter_dependencies() can perform nontrivial work so delay until needed.\n        return (r for r in candidate.iter_dependencies(with_requires) if r is not None)\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/reporter.py",
    "content": "from __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Mapping\nfrom logging import getLogger\nfrom typing import Any\n\nfrom pip._vendor.resolvelib.reporters import BaseReporter\n\nfrom .base import Candidate, Constraint, Requirement\n\nlogger = getLogger(__name__)\n\n\nclass PipReporter(BaseReporter[Requirement, Candidate, str]):\n    def __init__(self, constraints: Mapping[str, Constraint] | None = None) -> None:\n        self.reject_count_by_package: defaultdict[str, int] = defaultdict(int)\n        self._constraints = constraints or {}\n\n        self._messages_at_reject_count = {\n            1: (\n                \"pip is looking at multiple versions of {package_name} to \"\n                \"determine which version is compatible with other \"\n                \"requirements. This could take a while.\"\n            ),\n            8: (\n                \"pip is still looking at multiple versions of {package_name} to \"\n                \"determine which version is compatible with other \"\n                \"requirements. This could take a while.\"\n            ),\n            13: (\n                \"This is taking longer than usual. You might need to provide \"\n                \"the dependency resolver with stricter constraints to reduce \"\n                \"runtime. See https://pip.pypa.io/warnings/backtracking for \"\n                \"guidance. If you want to abort this run, press Ctrl + C.\"\n            ),\n        }\n\n    def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:\n        \"\"\"Report a candidate being rejected.\n\n        Logs both the rejection count message (if applicable) and details about\n        the requirements and constraints that caused the rejection.\n        \"\"\"\n        self.reject_count_by_package[candidate.name] += 1\n\n        count = self.reject_count_by_package[candidate.name]\n        if count in self._messages_at_reject_count:\n            message = self._messages_at_reject_count[count]\n            logger.info(\"INFO: %s\", message.format(package_name=candidate.name))\n\n        msg = \"Will try a different candidate, due to conflict:\"\n        for req_info in criterion.information:\n            req, parent = req_info.requirement, req_info.parent\n            msg += \"\\n    \"\n            if parent:\n                msg += f\"{parent.name} {parent.version} depends on \"\n            else:\n                msg += \"The user requested \"\n            msg += req.format_for_error()\n\n        # Add any relevant constraints\n        if self._constraints:\n            name = candidate.name\n            constraint = self._constraints.get(name)\n            if constraint and constraint.specifier:\n                constraint_text = f\"{name}{constraint.specifier}\"\n                msg += f\"\\n    The user requested (constraint) {constraint_text}\"\n\n        logger.debug(msg)\n\n\nclass PipDebuggingReporter(BaseReporter[Requirement, Candidate, str]):\n    \"\"\"A reporter that does an info log for every event it sees.\"\"\"\n\n    def starting(self) -> None:\n        logger.info(\"Reporter.starting()\")\n\n    def starting_round(self, index: int) -> None:\n        logger.info(\"Reporter.starting_round(%r)\", index)\n\n    def ending_round(self, index: int, state: Any) -> None:\n        logger.info(\"Reporter.ending_round(%r, state)\", index)\n        logger.debug(\"Reporter.ending_round(%r, %r)\", index, state)\n\n    def ending(self, state: Any) -> None:\n        logger.info(\"Reporter.ending(%r)\", state)\n\n    def adding_requirement(\n        self, requirement: Requirement, parent: Candidate | None\n    ) -> None:\n        logger.info(\"Reporter.adding_requirement(%r, %r)\", requirement, parent)\n\n    def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:\n        logger.info(\"Reporter.rejecting_candidate(%r, %r)\", criterion, candidate)\n\n    def pinning(self, candidate: Candidate) -> None:\n        logger.info(\"Reporter.pinning(%r)\", candidate)\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/requirements.py",
    "content": "from __future__ import annotations\n\nfrom typing import Any\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.req.constructors import install_req_drop_extras\nfrom pip._internal.req.req_install import InstallRequirement\n\nfrom .base import Candidate, CandidateLookup, Requirement, format_name\n\n\nclass ExplicitRequirement(Requirement):\n    def __init__(self, candidate: Candidate) -> None:\n        self.candidate = candidate\n\n    def __str__(self) -> str:\n        return str(self.candidate)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self.candidate!r})\"\n\n    def __hash__(self) -> int:\n        return hash(self.candidate)\n\n    def __eq__(self, other: Any) -> bool:\n        if not isinstance(other, ExplicitRequirement):\n            return False\n        return self.candidate == other.candidate\n\n    @property\n    def project_name(self) -> NormalizedName:\n        # No need to canonicalize - the candidate did this\n        return self.candidate.project_name\n\n    @property\n    def name(self) -> str:\n        # No need to canonicalize - the candidate did this\n        return self.candidate.name\n\n    def format_for_error(self) -> str:\n        return self.candidate.format_for_error()\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return self.candidate, None\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        return candidate == self.candidate\n\n\nclass SpecifierRequirement(Requirement):\n    def __init__(self, ireq: InstallRequirement) -> None:\n        assert ireq.link is None, \"This is a link, not a specifier\"\n        self._ireq = ireq\n        self._equal_cache: str | None = None\n        self._hash: int | None = None\n        self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras)\n\n    @property\n    def _equal(self) -> str:\n        if self._equal_cache is not None:\n            return self._equal_cache\n\n        self._equal_cache = str(self._ireq)\n        return self._equal_cache\n\n    def __str__(self) -> str:\n        return str(self._ireq.req)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({str(self._ireq.req)!r})\"\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, SpecifierRequirement):\n            return NotImplemented\n        return self._equal == other._equal\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n\n        self._hash = hash(self._equal)\n        return self._hash\n\n    @property\n    def project_name(self) -> NormalizedName:\n        assert self._ireq.req, \"Specifier-backed ireq is always PEP 508\"\n        return canonicalize_name(self._ireq.req.name)\n\n    @property\n    def name(self) -> str:\n        return format_name(self.project_name, self._extras)\n\n    def format_for_error(self) -> str:\n        # Convert comma-separated specifiers into \"A, B, ..., F and G\"\n        # This makes the specifier a bit more \"human readable\", without\n        # risking a change in meaning. (Hopefully! Not all edge cases have\n        # been checked)\n        parts = [s.strip() for s in str(self).split(\",\")]\n        if len(parts) == 0:\n            return \"\"\n        elif len(parts) == 1:\n            return parts[0]\n\n        return \", \".join(parts[:-1]) + \" and \" + parts[-1]\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return None, self._ireq\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        assert candidate.name == self.name, (\n            f\"Internal issue: Candidate is not for this requirement \"\n            f\"{candidate.name} vs {self.name}\"\n        )\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        assert self._ireq.req, \"Specifier-backed ireq is always PEP 508\"\n        spec = self._ireq.req.specifier\n        return spec.contains(candidate.version, prereleases=True)\n\n\nclass SpecifierWithoutExtrasRequirement(SpecifierRequirement):\n    \"\"\"\n    Requirement backed by an install requirement on a base package.\n    Trims extras from its install requirement if there are any.\n    \"\"\"\n\n    def __init__(self, ireq: InstallRequirement) -> None:\n        assert ireq.link is None, \"This is a link, not a specifier\"\n        self._ireq = install_req_drop_extras(ireq)\n        self._equal_cache: str | None = None\n        self._hash: int | None = None\n        self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras)\n\n    @property\n    def _equal(self) -> str:\n        if self._equal_cache is not None:\n            return self._equal_cache\n\n        self._equal_cache = str(self._ireq)\n        return self._equal_cache\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, SpecifierWithoutExtrasRequirement):\n            return NotImplemented\n        return self._equal == other._equal\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n\n        self._hash = hash(self._equal)\n        return self._hash\n\n\nclass RequiresPythonRequirement(Requirement):\n    \"\"\"A requirement representing Requires-Python metadata.\"\"\"\n\n    def __init__(self, specifier: SpecifierSet, match: Candidate) -> None:\n        self.specifier = specifier\n        self._specifier_string = str(specifier)  # for faster __eq__\n        self._hash: int | None = None\n        self._candidate = match\n\n        # Pre-compute candidate lookup to avoid repeated specifier checks\n        if specifier.contains(match.version, prereleases=True):\n            self._candidate_lookup: CandidateLookup = (match, None)\n        else:\n            self._candidate_lookup = (None, None)\n\n    def __str__(self) -> str:\n        return f\"Python {self.specifier}\"\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({str(self.specifier)!r})\"\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n\n        self._hash = hash((self._specifier_string, self._candidate))\n        return self._hash\n\n    def __eq__(self, other: Any) -> bool:\n        if not isinstance(other, RequiresPythonRequirement):\n            return False\n        return (\n            self._specifier_string == other._specifier_string\n            and self._candidate == other._candidate\n        )\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self._candidate.project_name\n\n    @property\n    def name(self) -> str:\n        return self._candidate.name\n\n    def format_for_error(self) -> str:\n        return str(self)\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return self._candidate_lookup\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        assert candidate.name == self._candidate.name, \"Not Python candidate\"\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        return self.specifier.contains(candidate.version, prereleases=True)\n\n\nclass UnsatisfiableRequirement(Requirement):\n    \"\"\"A requirement that cannot be satisfied.\"\"\"\n\n    def __init__(self, name: NormalizedName) -> None:\n        self._name = name\n\n    def __str__(self) -> str:\n        return f\"{self._name} (unavailable)\"\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({str(self._name)!r})\"\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, UnsatisfiableRequirement):\n            return NotImplemented\n        return self._name == other._name\n\n    def __hash__(self) -> int:\n        return hash(self._name)\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self._name\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    def format_for_error(self) -> str:\n        return str(self)\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return None, None\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        return False\n"
  },
  {
    "path": "src/pip/_internal/resolution/resolvelib/resolver.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport functools\nimport logging\nimport os\nfrom typing import TYPE_CHECKING, cast\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.resolvelib import BaseReporter, ResolutionImpossible, ResolutionTooDeep\nfrom pip._vendor.resolvelib import Resolver as RLResolver\nfrom pip._vendor.resolvelib.structs import DirectedGraph\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.exceptions import ResolutionTooDeepError\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import install_req_extend_extras\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.base import BaseResolver, InstallRequirementProvider\nfrom pip._internal.resolution.resolvelib.provider import PipProvider\nfrom pip._internal.resolution.resolvelib.reporter import (\n    PipDebuggingReporter,\n    PipReporter,\n)\nfrom pip._internal.utils.packaging import get_requirement\n\nfrom .base import Candidate, Requirement\nfrom .factory import Factory\n\nif TYPE_CHECKING:\n    from pip._vendor.resolvelib.resolvers import Result as RLResult\n\n    Result = RLResult[Requirement, Candidate, str]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Resolver(BaseResolver):\n    _allowed_strategies = {\"eager\", \"only-if-needed\", \"to-satisfy-only\"}\n\n    def __init__(\n        self,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        wheel_cache: WheelCache | None,\n        make_install_req: InstallRequirementProvider,\n        use_user_site: bool,\n        ignore_dependencies: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        force_reinstall: bool,\n        upgrade_strategy: str,\n        py_version_info: tuple[int, ...] | None = None,\n    ):\n        super().__init__()\n        assert upgrade_strategy in self._allowed_strategies\n\n        self.factory = Factory(\n            finder=finder,\n            preparer=preparer,\n            make_install_req=make_install_req,\n            wheel_cache=wheel_cache,\n            use_user_site=use_user_site,\n            force_reinstall=force_reinstall,\n            ignore_installed=ignore_installed,\n            ignore_requires_python=ignore_requires_python,\n            py_version_info=py_version_info,\n        )\n        self.ignore_dependencies = ignore_dependencies\n        self.upgrade_strategy = upgrade_strategy\n        self._result: Result | None = None\n\n    def resolve(\n        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        collected = self.factory.collect_root_requirements(root_reqs)\n        provider = PipProvider(\n            factory=self.factory,\n            constraints=collected.constraints,\n            ignore_dependencies=self.ignore_dependencies,\n            upgrade_strategy=self.upgrade_strategy,\n            user_requested=collected.user_requested,\n        )\n        if \"PIP_RESOLVER_DEBUG\" in os.environ:\n            reporter: BaseReporter[Requirement, Candidate, str] = PipDebuggingReporter()\n        else:\n            reporter = PipReporter(constraints=provider.constraints)\n\n        resolver: RLResolver[Requirement, Candidate, str] = RLResolver(\n            provider,\n            reporter,\n        )\n\n        try:\n            limit_how_complex_resolution_can_be = 200000\n            result = self._result = resolver.resolve(\n                collected.requirements, max_rounds=limit_how_complex_resolution_can_be\n            )\n\n        except ResolutionImpossible as e:\n            error = self.factory.get_installation_error(\n                cast(\"ResolutionImpossible[Requirement, Candidate]\", e),\n                collected.constraints,\n            )\n            raise error from e\n        except ResolutionTooDeep:\n            raise ResolutionTooDeepError from None\n\n        req_set = RequirementSet(check_supported_wheels=check_supported_wheels)\n        # process candidates with extras last to ensure their base equivalent is\n        # already in the req_set if appropriate.\n        # Python's sort is stable so using a binary key function keeps relative order\n        # within both subsets.\n        for candidate in sorted(\n            result.mapping.values(), key=lambda c: c.name != c.project_name\n        ):\n            ireq = candidate.get_install_requirement()\n            if ireq is None:\n                if candidate.name != candidate.project_name:\n                    # extend existing req's extras\n                    with contextlib.suppress(KeyError):\n                        req = req_set.get_requirement(candidate.project_name)\n                        req_set.add_named_requirement(\n                            install_req_extend_extras(\n                                req, get_requirement(candidate.name).extras\n                            )\n                        )\n                continue\n\n            # Check if there is already an installation under the same name,\n            # and set a flag for later stages to uninstall it, if needed.\n            installed_dist = self.factory.get_dist_to_uninstall(candidate)\n            if installed_dist is None:\n                # There is no existing installation -- nothing to uninstall.\n                ireq.should_reinstall = False\n            elif self.factory.force_reinstall:\n                # The --force-reinstall flag is set -- reinstall.\n                ireq.should_reinstall = True\n            elif installed_dist.version != candidate.version:\n                # The installation is different in version -- reinstall.\n                ireq.should_reinstall = True\n            elif candidate.is_editable or installed_dist.editable:\n                # The incoming distribution is editable, or different in\n                # editable-ness to installation -- reinstall.\n                ireq.should_reinstall = True\n            elif candidate.source_link and candidate.source_link.is_file:\n                # The incoming distribution is under file://\n                if candidate.source_link.is_wheel:\n                    # is a local wheel -- do nothing.\n                    logger.info(\n                        \"%s is already installed with the same version as the \"\n                        \"provided wheel. Use --force-reinstall to force an \"\n                        \"installation of the wheel.\",\n                        ireq.name,\n                    )\n                    continue\n\n                # is a local sdist or path -- reinstall\n                ireq.should_reinstall = True\n            else:\n                continue\n\n            link = candidate.source_link\n            if link and link.is_yanked:\n                # The reason can contain non-ASCII characters, Unicode\n                # is required for Python 2.\n                msg = (\n                    \"The candidate selected for download or install is a \"\n                    \"yanked version: {name!r} candidate (version {version} \"\n                    \"at {link})\\nReason for being yanked: {reason}\"\n                ).format(\n                    name=candidate.name,\n                    version=candidate.version,\n                    link=link,\n                    reason=link.yanked_reason or \"<none given>\",\n                )\n                logger.warning(msg)\n\n            req_set.add_named_requirement(ireq)\n\n        return req_set\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> list[InstallRequirement]:\n        \"\"\"Get order for installation of requirements in RequirementSet.\n\n        The returned list contains a requirement before another that depends on\n        it. This helps ensure that the environment is kept consistent as they\n        get installed one-by-one.\n\n        The current implementation creates a topological ordering of the\n        dependency graph, giving more weight to packages with less\n        or no dependencies, while breaking any cycles in the graph at\n        arbitrary points. We make no guarantees about where the cycle\n        would be broken, other than it *would* be broken.\n        \"\"\"\n        assert self._result is not None, \"must call resolve() first\"\n\n        if not req_set.requirements:\n            # Nothing is left to install, so we do not need an order.\n            return []\n\n        graph = self._result.graph\n        weights = get_topological_weights(graph, set(req_set.requirements.keys()))\n\n        sorted_items = sorted(\n            req_set.requirements.items(),\n            key=functools.partial(_req_set_item_sorter, weights=weights),\n            reverse=True,\n        )\n        return [ireq for _, ireq in sorted_items]\n\n\ndef get_topological_weights(\n    graph: DirectedGraph[str | None], requirement_keys: set[str]\n) -> dict[str | None, int]:\n    \"\"\"Assign weights to each node based on how \"deep\" they are.\n\n    This implementation may change at any point in the future without prior\n    notice.\n\n    We first simplify the dependency graph by pruning any leaves and giving them\n    the highest weight: a package without any dependencies should be installed\n    first. This is done again and again in the same way, giving ever less weight\n    to the newly found leaves. The loop stops when no leaves are left: all\n    remaining packages have at least one dependency left in the graph.\n\n    Then we continue with the remaining graph, by taking the length for the\n    longest path to any node from root, ignoring any paths that contain a single\n    node twice (i.e. cycles). This is done through a depth-first search through\n    the graph, while keeping track of the path to the node.\n\n    Cycles in the graph result would result in node being revisited while also\n    being on its own path. In this case, take no action. This helps ensure we\n    don't get stuck in a cycle.\n\n    When assigning weight, the longer path (i.e. larger length) is preferred.\n\n    We are only interested in the weights of packages that are in the\n    requirement_keys.\n    \"\"\"\n    path: set[str | None] = set()\n    weights: dict[str | None, list[int]] = {}\n\n    def visit(node: str | None) -> None:\n        if node in path:\n            # We hit a cycle, so we'll break it here.\n            return\n\n        # The walk is exponential and for pathologically connected graphs (which\n        # are the ones most likely to contain cycles in the first place) it can\n        # take until the heat-death of the universe. To counter this we limit\n        # the number of attempts to visit (i.e. traverse through) any given\n        # node. We choose a value here which gives decent enough coverage for\n        # fairly well behaved graphs, and still limits the walk complexity to be\n        # linear in nature.\n        cur_weights = weights.get(node, [])\n        if len(cur_weights) >= 5:\n            return\n\n        # Time to visit the children!\n        path.add(node)\n        for child in graph.iter_children(node):\n            visit(child)\n        path.remove(node)\n\n        if node not in requirement_keys:\n            return\n\n        cur_weights.append(len(path))\n        weights[node] = cur_weights\n\n    # Simplify the graph, pruning leaves that have no dependencies. This is\n    # needed for large graphs (say over 200 packages) because the `visit`\n    # function is slower for large/densely connected graphs, taking minutes.\n    # See https://github.com/pypa/pip/issues/10557\n    # We repeat the pruning step until we have no more leaves to remove.\n    while True:\n        leaves = set()\n        for key in graph:\n            if key is None:\n                continue\n            for _child in graph.iter_children(key):\n                # This means we have at least one child\n                break\n            else:\n                # No child.\n                leaves.add(key)\n        if not leaves:\n            # We are done simplifying.\n            break\n        # Calculate the weight for the leaves.\n        weight = len(graph) - 1\n        for leaf in leaves:\n            if leaf not in requirement_keys:\n                continue\n            weights[leaf] = [weight]\n        # Remove the leaves from the graph, making it simpler.\n        for leaf in leaves:\n            graph.remove(leaf)\n\n    # Visit the remaining graph, this will only have nodes to handle if the\n    # graph had a cycle in it, which the pruning step above could not handle.\n    # `None` is guaranteed to be the root node by resolvelib.\n    visit(None)\n\n    # Sanity check: all requirement keys should be in the weights,\n    # and no other keys should be in the weights.\n    difference = set(weights.keys()).difference(requirement_keys)\n    assert not difference, difference\n\n    # Now give back all the weights, choosing the largest ones from what we\n    # accumulated.\n    return {node: max(wgts) for (node, wgts) in weights.items()}\n\n\ndef _req_set_item_sorter(\n    item: tuple[str, InstallRequirement],\n    weights: dict[str | None, int],\n) -> tuple[int, str]:\n    \"\"\"Key function used to sort install requirements for installation.\n\n    Based on the \"weight\" mapping calculated in ``get_installation_order()``.\n    The canonical package name is returned as the second member as a tie-\n    breaker to ensure the result is predictable, which is useful in tests.\n    \"\"\"\n    name = canonicalize_name(item[0])\n    return weights[name], name\n"
  },
  {
    "path": "src/pip/_internal/self_outdated_check.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport functools\nimport hashlib\nimport json\nimport logging\nimport optparse\nimport os.path\nimport sys\nfrom dataclasses import dataclass\nfrom typing import Callable\n\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.rich.console import Group\nfrom pip._vendor.rich.markup import escape\nfrom pip._vendor.rich.text import Text\n\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.datetime import parse_iso_datetime\nfrom pip._internal.utils.entrypoints import (\n    get_best_invocation_for_this_pip,\n    get_best_invocation_for_this_python,\n)\nfrom pip._internal.utils.filesystem import (\n    adjacent_tmp_file,\n    check_path_owner,\n    copy_directory_permissions,\n    replace,\n)\nfrom pip._internal.utils.misc import (\n    ExternallyManagedEnvironment,\n    check_externally_managed,\n    ensure_dir,\n)\n\n_WEEK = datetime.timedelta(days=7)\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_statefile_name(key: str) -> str:\n    key_bytes = key.encode()\n    name = hashlib.sha224(key_bytes).hexdigest()\n    return name\n\n\nclass SelfCheckState:\n    def __init__(self, cache_dir: str) -> None:\n        self._state: dict[str, str] = {}\n        self._statefile_path = None\n\n        # Try to load the existing state\n        if cache_dir:\n            self._statefile_path = os.path.join(\n                cache_dir, \"selfcheck\", _get_statefile_name(self.key)\n            )\n            try:\n                with open(self._statefile_path, encoding=\"utf-8\") as statefile:\n                    self._state = json.load(statefile)\n            except (OSError, ValueError, KeyError):\n                # Explicitly suppressing exceptions, since we don't want to\n                # error out if the cache file is invalid.\n                pass\n\n    @property\n    def key(self) -> str:\n        return sys.prefix\n\n    def get(self, current_time: datetime.datetime) -> str | None:\n        \"\"\"Check if we have a not-outdated version loaded already.\"\"\"\n        if not self._state:\n            return None\n\n        if \"last_check\" not in self._state:\n            return None\n\n        if \"pypi_version\" not in self._state:\n            return None\n\n        # Determine if we need to refresh the state\n        last_check = parse_iso_datetime(self._state[\"last_check\"])\n        time_since_last_check = current_time - last_check\n        if time_since_last_check > _WEEK:\n            return None\n\n        return self._state[\"pypi_version\"]\n\n    def set(self, pypi_version: str, current_time: datetime.datetime) -> None:\n        # If we do not have a path to cache in, don't bother saving.\n        if not self._statefile_path:\n            return\n\n        statefile_directory = os.path.dirname(self._statefile_path)\n\n        # Check to make sure that we own the directory\n        if not check_path_owner(statefile_directory):\n            return\n\n        # Now that we've ensured the directory is owned by this user, we'll go\n        # ahead and make sure that all our directories are created.\n        ensure_dir(statefile_directory)\n\n        state = {\n            # Include the key so it's easy to tell which pip wrote the\n            # file.\n            \"key\": self.key,\n            \"last_check\": current_time.isoformat(),\n            \"pypi_version\": pypi_version,\n        }\n\n        text = json.dumps(state, sort_keys=True, separators=(\",\", \":\"))\n\n        with adjacent_tmp_file(self._statefile_path) as f:\n            f.write(text.encode())\n            copy_directory_permissions(statefile_directory, f)\n\n        try:\n            # Since we have a prefix-specific state file, we can just\n            # overwrite whatever is there, no need to check.\n            replace(f.name, self._statefile_path)\n        except OSError:\n            # Best effort.\n            pass\n\n\n@dataclass\nclass UpgradePrompt:\n    old: str\n    new: str\n\n    def __rich__(self) -> Group:\n        if WINDOWS:\n            pip_cmd = f\"{get_best_invocation_for_this_python()} -m pip\"\n        else:\n            pip_cmd = get_best_invocation_for_this_pip()\n\n        notice = \"[bold][[reset][blue]notice[reset][bold]][reset]\"\n        return Group(\n            Text(),\n            Text.from_markup(\n                f\"{notice} A new release of pip is available: \"\n                f\"[red]{self.old}[reset] -> [green]{self.new}[reset]\"\n            ),\n            Text.from_markup(\n                f\"{notice} To update, run: \"\n                f\"[green]{escape(pip_cmd)} install --upgrade pip\"\n            ),\n        )\n\n\ndef was_installed_by_pip(pkg: str) -> bool:\n    \"\"\"Checks whether pkg was installed by pip\n\n    This is used not to display the upgrade message when pip is in fact\n    installed by system package manager, such as dnf on Fedora.\n    \"\"\"\n    dist = get_default_environment().get_distribution(pkg)\n    return dist is not None and \"pip\" == dist.installer\n\n\ndef _get_current_remote_pip_version(\n    session: PipSession, options: optparse.Values\n) -> str | None:\n    # Lets use PackageFinder to see what the latest pip version is\n    link_collector = LinkCollector.create(\n        session,\n        options=options,\n        suppress_no_index=True,\n    )\n\n    # Pass allow_yanked=False so we don't suggest upgrading to a\n    # yanked version.\n    selection_prefs = SelectionPreferences(\n        allow_yanked=False,\n        release_control=ReleaseControl(only_final={\"pip\"}),\n    )\n\n    finder = PackageFinder.create(\n        link_collector=link_collector,\n        selection_prefs=selection_prefs,\n    )\n    best_candidate = finder.find_best_candidate(\"pip\").best_candidate\n    if best_candidate is None:\n        return None\n\n    return str(best_candidate.version)\n\n\ndef _self_version_check_logic(\n    *,\n    state: SelfCheckState,\n    current_time: datetime.datetime,\n    local_version: Version,\n    get_remote_version: Callable[[], str | None],\n) -> UpgradePrompt | None:\n    remote_version_str = state.get(current_time)\n    if remote_version_str is None:\n        remote_version_str = get_remote_version()\n        if remote_version_str is None:\n            logger.debug(\"No remote pip version found\")\n            return None\n        state.set(remote_version_str, current_time)\n\n    remote_version = parse_version(remote_version_str)\n    logger.debug(\"Remote version of pip: %s\", remote_version)\n    logger.debug(\"Local version of pip:  %s\", local_version)\n\n    pip_installed_by_pip = was_installed_by_pip(\"pip\")\n    logger.debug(\"Was pip installed by pip? %s\", pip_installed_by_pip)\n    if not pip_installed_by_pip:\n        return None  # Only suggest upgrade if pip is installed by pip.\n\n    local_version_is_older = (\n        local_version < remote_version\n        and local_version.base_version != remote_version.base_version\n    )\n    if local_version_is_older:\n        return UpgradePrompt(old=str(local_version), new=remote_version_str)\n\n    return None\n\n\ndef pip_self_version_check(session: PipSession, options: optparse.Values) -> None:\n    \"\"\"Check for an update for pip.\n\n    Limit the frequency of checks to once per week. State is stored either in\n    the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n    of the pip script path.\n    \"\"\"\n    installed_dist = get_default_environment().get_distribution(\"pip\")\n    if not installed_dist:\n        return\n    try:\n        check_externally_managed()\n    except ExternallyManagedEnvironment:\n        return\n\n    upgrade_prompt = _self_version_check_logic(\n        state=SelfCheckState(cache_dir=options.cache_dir),\n        current_time=datetime.datetime.now(datetime.timezone.utc),\n        local_version=installed_dist.version,\n        get_remote_version=functools.partial(\n            _get_current_remote_pip_version, session, options\n        ),\n    )\n    if upgrade_prompt is not None:\n        logger.warning(\"%s\", upgrade_prompt, extra={\"rich\": True})\n"
  },
  {
    "path": "src/pip/_internal/utils/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_internal/utils/_jaraco_text.py",
    "content": "\"\"\"Functions brought over from jaraco.text.\n\nThese functions are not supposed to be used within `pip._internal`. These are\nhelper functions brought over from `jaraco.text` to enable vendoring newer\ncopies of `pkg_resources` without having to vendor `jaraco.text` and its entire\ndependency cone; something that our vendoring setup is not currently capable of\nhandling.\n\nLicense reproduced from original source below:\n\nCopyright Jason R. Coombs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\"\"\"\n\nimport functools\nimport itertools\n\n\ndef _nonblank(str):\n    return str and not str.startswith(\"#\")\n\n\n@functools.singledispatch\ndef yield_lines(iterable):\n    r\"\"\"\n    Yield valid lines of a string or iterable.\n\n    >>> list(yield_lines(''))\n    []\n    >>> list(yield_lines(['foo', 'bar']))\n    ['foo', 'bar']\n    >>> list(yield_lines('foo\\nbar'))\n    ['foo', 'bar']\n    >>> list(yield_lines('\\nfoo\\n#bar\\nbaz #comment'))\n    ['foo', 'baz #comment']\n    >>> list(yield_lines(['foo\\nbar', 'baz', 'bing\\n\\n\\n']))\n    ['foo', 'bar', 'baz', 'bing']\n    \"\"\"\n    return itertools.chain.from_iterable(map(yield_lines, iterable))\n\n\n@yield_lines.register(str)\ndef _(text):\n    return filter(_nonblank, map(str.strip, text.splitlines()))\n\n\ndef drop_comment(line):\n    \"\"\"\n    Drop comments.\n\n    >>> drop_comment('foo # bar')\n    'foo'\n\n    A hash without a space may be in a URL.\n\n    >>> drop_comment('http://example.com/foo#bar')\n    'http://example.com/foo#bar'\n    \"\"\"\n    return line.partition(\" #\")[0]\n\n\ndef join_continuation(lines):\n    r\"\"\"\n    Join lines continued by a trailing backslash.\n\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar \\\\', 'baz']))\n    ['foobarbaz']\n\n    Not sure why, but...\n    The character preceding the backslash is also elided.\n\n    >>> list(join_continuation(['goo\\\\', 'dly']))\n    ['godly']\n\n    A terrible idea, but...\n    If no line is available to continue, suppress the lines.\n\n    >>> list(join_continuation(['foo', 'bar\\\\', 'baz\\\\']))\n    ['foo']\n    \"\"\"\n    lines = iter(lines)\n    for item in lines:\n        while item.endswith(\"\\\\\"):\n            try:\n                item = item[:-2].strip() + next(lines)\n            except StopIteration:\n                return\n        yield item\n"
  },
  {
    "path": "src/pip/_internal/utils/_log.py",
    "content": "\"\"\"Customize logging\n\nDefines custom logger class for the `logger.verbose(...)` method.\n\ninit_logging() must be called before any other modules that call logging.getLogger.\n\"\"\"\n\nimport logging\nfrom typing import Any, cast\n\n# custom log level for `--verbose` output\n# between DEBUG and INFO\nVERBOSE = 15\n\n\nclass VerboseLogger(logging.Logger):\n    \"\"\"Custom Logger, defining a verbose log-level\n\n    VERBOSE is between INFO and DEBUG.\n    \"\"\"\n\n    def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None:\n        return self.log(VERBOSE, msg, *args, **kwargs)\n\n\ndef getLogger(name: str) -> VerboseLogger:\n    \"\"\"logging.getLogger, but ensures our VerboseLogger class is returned\"\"\"\n    return cast(VerboseLogger, logging.getLogger(name))\n\n\ndef init_logging() -> None:\n    \"\"\"Register our VerboseLogger and VERBOSE log level.\n\n    Should be called before any calls to getLogger(),\n    i.e. in pip._internal.__init__\n    \"\"\"\n    logging.setLoggerClass(VerboseLogger)\n    logging.addLevelName(VERBOSE, \"VERBOSE\")\n"
  },
  {
    "path": "src/pip/_internal/utils/appdirs.py",
    "content": "\"\"\"\nThis code wraps the vendored appdirs module to so the return values are\ncompatible for the current pip code base.\n\nThe intention is to rewrite current usages gradually, keeping the tests pass,\nand eventually drop this after all usages are changed.\n\"\"\"\n\nimport os\nimport sys\n\nfrom pip._vendor import platformdirs as _appdirs\n\n\ndef user_cache_dir(appname: str) -> str:\n    return _appdirs.user_cache_dir(appname, appauthor=False)\n\n\ndef _macos_user_config_dir(appname: str, roaming: bool = True) -> str:\n    # Use ~/Application Support/pip, if the directory exists.\n    path = _appdirs.user_data_dir(appname, appauthor=False, roaming=roaming)\n    if os.path.isdir(path):\n        return path\n\n    # Use a Linux-like ~/.config/pip, by default.\n    linux_like_path = \"~/.config/\"\n    if appname:\n        linux_like_path = os.path.join(linux_like_path, appname)\n\n    return os.path.expanduser(linux_like_path)\n\n\ndef user_config_dir(appname: str, roaming: bool = True) -> str:\n    if sys.platform == \"darwin\":\n        return _macos_user_config_dir(appname, roaming)\n\n    return _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming)\n\n\n# for the discussion regarding site_config_dir locations\n# see <https://github.com/pypa/pip/issues/1733>\ndef site_config_dirs(appname: str) -> list[str]:\n    if sys.platform == \"darwin\":\n        dirval = _appdirs.site_data_dir(appname, appauthor=False, multipath=True)\n        return dirval.split(os.pathsep)\n\n    dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True)\n    if sys.platform == \"win32\":\n        return [dirval]\n\n    # Unix-y system. Look in /etc as well.\n    return dirval.split(os.pathsep) + [\"/etc\"]\n"
  },
  {
    "path": "src/pip/_internal/utils/compat.py",
    "content": "\"\"\"Stuff that differs in different Python versions and platform\ndistributions.\"\"\"\n\nimport importlib.resources\nimport logging\nimport os\nimport sys\nfrom typing import IO\n\n__all__ = [\"get_path_uid\", \"stdlib_pkgs\", \"tomllib\", \"WINDOWS\"]\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef has_tls() -> bool:\n    try:\n        import _ssl  # noqa: F401  # ignore unused\n\n        return True\n    except ImportError:\n        pass\n\n    from pip._vendor.urllib3.util import IS_PYOPENSSL\n\n    return IS_PYOPENSSL\n\n\ndef get_path_uid(path: str) -> int:\n    \"\"\"\n    Return path's uid.\n\n    Does not follow symlinks:\n        https://github.com/pypa/pip/pull/935#discussion_r5307003\n\n    Placed this function in compat due to differences on AIX and\n    Jython, that should eventually go away.\n\n    :raises OSError: When path is a symlink or can't be read.\n    \"\"\"\n    if hasattr(os, \"O_NOFOLLOW\"):\n        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)\n        file_uid = os.fstat(fd).st_uid\n        os.close(fd)\n    else:  # AIX and Jython\n        # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW\n        if not os.path.islink(path):\n            # older versions of Jython don't have `os.fstat`\n            file_uid = os.stat(path).st_uid\n        else:\n            # raise OSError for parity with os.O_NOFOLLOW above\n            raise OSError(f\"{path} is a symlink; Will not return uid for symlinks\")\n    return file_uid\n\n\n# The importlib.resources.open_text function was deprecated in 3.11 with suggested\n# replacement we use below.\nif sys.version_info < (3, 11):\n    open_text_resource = importlib.resources.open_text\nelse:\n\n    def open_text_resource(\n        package: str, resource: str, encoding: str = \"utf-8\", errors: str = \"strict\"\n    ) -> IO[str]:\n        return (importlib.resources.files(package) / resource).open(\n            \"r\", encoding=encoding, errors=errors\n        )\n\n\nif sys.version_info >= (3, 11):\n    import tomllib\nelse:\n    from pip._vendor import tomli as tomllib\n\n\n# packages in the stdlib that may have installation metadata, but should not be\n# considered 'installed'.  this theoretically could be determined based on\n# dist.location (py27:`sysconfig.get_paths()['stdlib']`,\n# py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may\n# make this ineffective, so hard-coding\nstdlib_pkgs = {\"python\", \"wsgiref\", \"argparse\"}\n\n\n# windows detection, covers cpython and ironpython\nWINDOWS = sys.platform.startswith(\"win\") or (sys.platform == \"cli\" and os.name == \"nt\")\n"
  },
  {
    "path": "src/pip/_internal/utils/compatibility_tags.py",
    "content": "\"\"\"Generate and work with PEP 425 Compatibility Tags.\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\nfrom pip._vendor.packaging.tags import (\n    PythonVersion,\n    Tag,\n    android_platforms,\n    compatible_tags,\n    cpython_tags,\n    generic_tags,\n    interpreter_name,\n    interpreter_version,\n    ios_platforms,\n    mac_platforms,\n)\n\n_apple_arch_pat = re.compile(r\"(.+)_(\\d+)_(\\d+)_(.+)\")\n\n\ndef version_info_to_nodot(version_info: tuple[int, ...]) -> str:\n    # Only use up to the first two numbers.\n    return \"\".join(map(str, version_info[:2]))\n\n\ndef _mac_platforms(arch: str) -> list[str]:\n    match = _apple_arch_pat.match(arch)\n    if match:\n        name, major, minor, actual_arch = match.groups()\n        mac_version = (int(major), int(minor))\n        arches = [\n            # Since we have always only checked that the platform starts\n            # with \"macosx\", for backwards-compatibility we extract the\n            # actual prefix provided by the user in case they provided\n            # something like \"macosxcustom_\". It may be good to remove\n            # this as undocumented or deprecate it in the future.\n            \"{}_{}\".format(name, arch[len(\"macosx_\") :])\n            for arch in mac_platforms(mac_version, actual_arch)\n        ]\n    else:\n        # arch pattern didn't match (?!)\n        arches = [arch]\n    return arches\n\n\ndef _ios_platforms(arch: str) -> list[str]:\n    match = _apple_arch_pat.match(arch)\n    if match:\n        name, major, minor, actual_multiarch = match.groups()\n        ios_version = (int(major), int(minor))\n        arches = [\n            # Since we have always only checked that the platform starts\n            # with \"ios\", for backwards-compatibility we extract the\n            # actual prefix provided by the user in case they provided\n            # something like \"ioscustom_\". It may be good to remove\n            # this as undocumented or deprecate it in the future.\n            \"{}_{}\".format(name, arch[len(\"ios_\") :])\n            for arch in ios_platforms(ios_version, actual_multiarch)\n        ]\n    else:\n        # arch pattern didn't match (?!)\n        arches = [arch]\n    return arches\n\n\ndef _android_platforms(arch: str) -> list[str]:\n    match = re.fullmatch(r\"android_(\\d+)_(.+)\", arch)\n    if match:\n        api_level, abi = match.groups()\n        return list(android_platforms(int(api_level), abi))\n    else:\n        # arch pattern didn't match (?!)\n        return [arch]\n\n\ndef _custom_manylinux_platforms(arch: str) -> list[str]:\n    arches = [arch]\n    arch_prefix, arch_sep, arch_suffix = arch.partition(\"_\")\n    if arch_prefix == \"manylinux2014\":\n        # manylinux1/manylinux2010 wheels run on most manylinux2014 systems\n        # with the exception of wheels depending on ncurses. PEP 599 states\n        # manylinux1/manylinux2010 wheels should be considered\n        # manylinux2014 wheels:\n        # https://www.python.org/dev/peps/pep-0599/#backwards-compatibility-with-manylinux2010-wheels\n        if arch_suffix in {\"i686\", \"x86_64\"}:\n            arches.append(\"manylinux2010\" + arch_sep + arch_suffix)\n            arches.append(\"manylinux1\" + arch_sep + arch_suffix)\n    elif arch_prefix == \"manylinux2010\":\n        # manylinux1 wheels run on most manylinux2010 systems with the\n        # exception of wheels depending on ncurses. PEP 571 states\n        # manylinux1 wheels should be considered manylinux2010 wheels:\n        # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels\n        arches.append(\"manylinux1\" + arch_sep + arch_suffix)\n    return arches\n\n\ndef _get_custom_platforms(arch: str) -> list[str]:\n    arch_prefix, arch_sep, arch_suffix = arch.partition(\"_\")\n    if arch.startswith(\"macosx\"):\n        arches = _mac_platforms(arch)\n    elif arch.startswith(\"ios\"):\n        arches = _ios_platforms(arch)\n    elif arch_prefix == \"android\":\n        arches = _android_platforms(arch)\n    elif arch_prefix in [\"manylinux2014\", \"manylinux2010\"]:\n        arches = _custom_manylinux_platforms(arch)\n    else:\n        arches = [arch]\n    return arches\n\n\ndef _expand_allowed_platforms(platforms: list[str] | None) -> list[str] | None:\n    if not platforms:\n        return None\n\n    seen = set()\n    result = []\n\n    for p in platforms:\n        if p in seen:\n            continue\n        additions = [c for c in _get_custom_platforms(p) if c not in seen]\n        seen.update(additions)\n        result.extend(additions)\n\n    return result\n\n\ndef _get_python_version(version: str) -> PythonVersion:\n    if len(version) > 1:\n        return int(version[0]), int(version[1:])\n    else:\n        return (int(version[0]),)\n\n\ndef _get_custom_interpreter(\n    implementation: str | None = None, version: str | None = None\n) -> str:\n    if implementation is None:\n        implementation = interpreter_name()\n    if version is None:\n        version = interpreter_version()\n    return f\"{implementation}{version}\"\n\n\ndef get_supported(\n    version: str | None = None,\n    platforms: list[str] | None = None,\n    impl: str | None = None,\n    abis: list[str] | None = None,\n) -> list[Tag]:\n    \"\"\"Return a list of supported tags for each version specified in\n    `versions`.\n\n    :param version: a string version, of the form \"33\" or \"32\",\n        or None. The version will be assumed to support our ABI.\n    :param platform: specify a list of platforms you want valid\n        tags for, or None. If None, use the local system platform.\n    :param impl: specify the exact implementation you want valid\n        tags for, or None. If None, use the local interpreter impl.\n    :param abis: specify a list of abis you want valid\n        tags for, or None. If None, use the local interpreter abi.\n    \"\"\"\n    supported: list[Tag] = []\n\n    python_version: PythonVersion | None = None\n    if version is not None:\n        python_version = _get_python_version(version)\n\n    interpreter = _get_custom_interpreter(impl, version)\n\n    platforms = _expand_allowed_platforms(platforms)\n\n    is_cpython = (impl or interpreter_name()) == \"cp\"\n    if is_cpython:\n        supported.extend(\n            cpython_tags(\n                python_version=python_version,\n                abis=abis,\n                platforms=platforms,\n            )\n        )\n    else:\n        supported.extend(\n            generic_tags(\n                interpreter=interpreter,\n                abis=abis,\n                platforms=platforms,\n            )\n        )\n    supported.extend(\n        compatible_tags(\n            python_version=python_version,\n            interpreter=interpreter,\n            platforms=platforms,\n        )\n    )\n\n    return supported\n"
  },
  {
    "path": "src/pip/_internal/utils/datetime.py",
    "content": "\"\"\"For when pip wants to check the date or time.\"\"\"\n\nimport datetime\nimport sys\n\n\ndef today_is_later_than(year: int, month: int, day: int) -> bool:\n    today = datetime.date.today()\n    given = datetime.date(year, month, day)\n\n    return today > given\n\n\ndef parse_iso_datetime(isodate: str) -> datetime.datetime:\n    \"\"\"Convert an ISO format string to a datetime.\n\n    Handles the format 2020-01-22T14:24:01Z (trailing Z)\n    which is not supported by older versions of fromisoformat.\n    \"\"\"\n    # Python 3.11+ supports Z suffix natively in fromisoformat\n    if sys.version_info >= (3, 11):\n        return datetime.datetime.fromisoformat(isodate)\n    else:\n        return datetime.datetime.fromisoformat(\n            isodate.replace(\"Z\", \"+00:00\")\n            if isodate.endswith(\"Z\") and (\"T\" in isodate or \" \" in isodate.strip())\n            else isodate\n        )\n"
  },
  {
    "path": "src/pip/_internal/utils/deprecation.py",
    "content": "\"\"\"\nA module that implements tooling to enable easy warnings about deprecations.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport warnings\nfrom typing import Any, TextIO\n\nfrom pip._vendor.packaging.version import parse\n\nfrom pip import __version__ as current_version  # NOTE: tests patch this name.\n\nDEPRECATION_MSG_PREFIX = \"DEPRECATION: \"\n\n\nclass PipDeprecationWarning(Warning):\n    pass\n\n\n_original_showwarning: Any = None\n\n\n# Warnings <-> Logging Integration\ndef _showwarning(\n    message: Warning | str,\n    category: type[Warning],\n    filename: str,\n    lineno: int,\n    file: TextIO | None = None,\n    line: str | None = None,\n) -> None:\n    if file is not None:\n        if _original_showwarning is not None:\n            _original_showwarning(message, category, filename, lineno, file, line)\n    elif issubclass(category, PipDeprecationWarning):\n        # We use a specially named logger which will handle all of the\n        # deprecation messages for pip.\n        logger = logging.getLogger(\"pip._internal.deprecations\")\n        logger.warning(message)\n    else:\n        _original_showwarning(message, category, filename, lineno, file, line)\n\n\ndef install_warning_logger() -> None:\n    # Enable our Deprecation Warnings\n    warnings.simplefilter(\"default\", PipDeprecationWarning, append=True)\n\n    global _original_showwarning\n\n    if _original_showwarning is None:\n        _original_showwarning = warnings.showwarning\n        warnings.showwarning = _showwarning\n\n\ndef deprecated(\n    *,\n    reason: str,\n    replacement: str | None,\n    gone_in: str | None,\n    feature_flag: str | None = None,\n    issue: int | None = None,\n) -> None:\n    \"\"\"Helper to deprecate existing functionality.\n\n    reason:\n        Textual reason shown to the user about why this functionality has\n        been deprecated. Should be a complete sentence.\n    replacement:\n        Textual suggestion shown to the user about what alternative\n        functionality they can use.\n    gone_in:\n        The version of pip does this functionality should get removed in.\n        Raises an error if pip's current version is greater than or equal to\n        this.\n    feature_flag:\n        Command-line flag of the form --use-feature={feature_flag} for testing\n        upcoming functionality.\n    issue:\n        Issue number on the tracker that would serve as a useful place for\n        users to find related discussion and provide feedback.\n    \"\"\"\n\n    # Determine whether or not the feature is already gone in this version.\n    is_gone = gone_in is not None and parse(current_version) >= parse(gone_in)\n\n    message_parts = [\n        (reason, f\"{DEPRECATION_MSG_PREFIX}{{}}\"),\n        (\n            gone_in,\n            (\n                \"pip {} will enforce this behaviour change.\"\n                if not is_gone\n                else \"Since pip {}, this is no longer supported.\"\n            ),\n        ),\n        (\n            replacement,\n            \"A possible replacement is {}.\",\n        ),\n        (\n            feature_flag,\n            (\n                \"You can use the flag --use-feature={} to test the upcoming behaviour.\"\n                if not is_gone\n                else None\n            ),\n        ),\n        (\n            issue,\n            \"Discussion can be found at https://github.com/pypa/pip/issues/{}\",\n        ),\n    ]\n\n    message = \" \".join(\n        format_str.format(value)\n        for value, format_str in message_parts\n        if format_str is not None and value is not None\n    )\n\n    # Raise as an error if this behaviour is deprecated.\n    if is_gone:\n        raise PipDeprecationWarning(message)\n\n    warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)\n"
  },
  {
    "path": "src/pip/_internal/utils/direct_url_helpers.py",
    "content": "from __future__ import annotations\n\nfrom pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import vcs\n\n\ndef direct_url_as_pep440_direct_reference(direct_url: DirectUrl, name: str) -> str:\n    \"\"\"Convert a DirectUrl to a pip requirement string.\"\"\"\n    direct_url.validate()  # if invalid, this is a pip bug\n    requirement = name + \" @ \"\n    fragments = []\n    if isinstance(direct_url.info, VcsInfo):\n        requirement += (\n            f\"{direct_url.info.vcs}+{direct_url.url}@{direct_url.info.commit_id}\"\n        )\n    elif isinstance(direct_url.info, ArchiveInfo):\n        requirement += direct_url.url\n        if direct_url.info.hash:\n            fragments.append(direct_url.info.hash)\n    else:\n        assert isinstance(direct_url.info, DirInfo)\n        requirement += direct_url.url\n    if direct_url.subdirectory:\n        fragments.append(\"subdirectory=\" + direct_url.subdirectory)\n    if fragments:\n        requirement += \"#\" + \"&\".join(fragments)\n    return requirement\n\n\ndef direct_url_for_editable(source_dir: str) -> DirectUrl:\n    return DirectUrl(\n        url=path_to_url(source_dir),\n        info=DirInfo(editable=True),\n    )\n\n\ndef direct_url_from_link(\n    link: Link, source_dir: str | None = None, link_is_in_wheel_cache: bool = False\n) -> DirectUrl:\n    if link.is_vcs:\n        vcs_backend = vcs.get_backend_for_scheme(link.scheme)\n        assert vcs_backend\n        url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(\n            link.url_without_fragment\n        )\n        # For VCS links, we need to find out and add commit_id.\n        if link_is_in_wheel_cache:\n            # If the requested VCS link corresponds to a cached\n            # wheel, it means the requested revision was an\n            # immutable commit hash, otherwise it would not have\n            # been cached. In that case we don't have a source_dir\n            # with the VCS checkout.\n            assert requested_revision\n            commit_id = requested_revision\n        else:\n            # If the wheel was not in cache, it means we have\n            # had to checkout from VCS to build and we have a source_dir\n            # which we can inspect to find out the commit id.\n            assert source_dir\n            commit_id = vcs_backend.get_revision(source_dir)\n        return DirectUrl(\n            url=url,\n            info=VcsInfo(\n                vcs=vcs_backend.name,\n                commit_id=commit_id,\n                requested_revision=requested_revision,\n            ),\n            subdirectory=link.subdirectory_fragment,\n        )\n    elif link.is_existing_dir():\n        return DirectUrl(\n            url=link.url_without_fragment,\n            info=DirInfo(),\n            subdirectory=link.subdirectory_fragment,\n        )\n    else:\n        hash = None\n        hash_name = link.hash_name\n        if hash_name:\n            hash = f\"{hash_name}={link.hash}\"\n        return DirectUrl(\n            url=link.url_without_fragment,\n            info=ArchiveInfo(hash=hash),\n            subdirectory=link.subdirectory_fragment,\n        )\n"
  },
  {
    "path": "src/pip/_internal/utils/egg_link.py",
    "content": "from __future__ import annotations\n\nimport os\nimport re\nimport sys\n\nfrom pip._internal.locations import site_packages, user_site\nfrom pip._internal.utils.virtualenv import (\n    running_under_virtualenv,\n    virtualenv_no_global,\n)\n\n__all__ = [\n    \"egg_link_path_from_sys_path\",\n    \"egg_link_path_from_location\",\n]\n\n\ndef _egg_link_names(raw_name: str) -> list[str]:\n    \"\"\"\n    Convert a Name metadata value to a .egg-link name, by applying\n    the same substitution as pkg_resources's safe_name function.\n    Note: we cannot use canonicalize_name because it has a different logic.\n\n    We also look for the raw name (without normalization) as setuptools 69 changed\n    the way it names .egg-link files (https://github.com/pypa/setuptools/issues/4167).\n    \"\"\"\n    return [\n        re.sub(\"[^A-Za-z0-9.]+\", \"-\", raw_name) + \".egg-link\",\n        f\"{raw_name}.egg-link\",\n    ]\n\n\ndef egg_link_path_from_sys_path(raw_name: str) -> str | None:\n    \"\"\"\n    Look for a .egg-link file for project name, by walking sys.path.\n    \"\"\"\n    egg_link_names = _egg_link_names(raw_name)\n    for path_item in sys.path:\n        for egg_link_name in egg_link_names:\n            egg_link = os.path.join(path_item, egg_link_name)\n            if os.path.isfile(egg_link):\n                return egg_link\n    return None\n\n\ndef egg_link_path_from_location(raw_name: str) -> str | None:\n    \"\"\"\n    Return the path for the .egg-link file if it exists, otherwise, None.\n\n    There's 3 scenarios:\n    1) not in a virtualenv\n       try to find in site.USER_SITE, then site_packages\n    2) in a no-global virtualenv\n       try to find in site_packages\n    3) in a yes-global virtualenv\n       try to find in site_packages, then site.USER_SITE\n       (don't look in global location)\n\n    For #1 and #3, there could be odd cases, where there's an egg-link in 2\n    locations.\n\n    This method will just return the first one found.\n    \"\"\"\n    sites: list[str] = []\n    if running_under_virtualenv():\n        sites.append(site_packages)\n        if not virtualenv_no_global() and user_site:\n            sites.append(user_site)\n    else:\n        if user_site:\n            sites.append(user_site)\n        sites.append(site_packages)\n\n    egg_link_names = _egg_link_names(raw_name)\n    for site in sites:\n        for egg_link_name in egg_link_names:\n            egglink = os.path.join(site, egg_link_name)\n            if os.path.isfile(egglink):\n                return egglink\n    return None\n"
  },
  {
    "path": "src/pip/_internal/utils/entrypoints.py",
    "content": "from __future__ import annotations\n\nimport itertools\nimport os\nimport shutil\nimport sys\n\nfrom pip._internal.cli.main import main\nfrom pip._internal.utils.compat import WINDOWS\n\n_EXECUTABLE_NAMES = [\n    \"pip\",\n    f\"pip{sys.version_info.major}\",\n    f\"pip{sys.version_info.major}.{sys.version_info.minor}\",\n]\nif WINDOWS:\n    _allowed_extensions = {\"\", \".exe\"}\n    _EXECUTABLE_NAMES = [\n        \"\".join(parts)\n        for parts in itertools.product(_EXECUTABLE_NAMES, _allowed_extensions)\n    ]\n\n\ndef _wrapper(args: list[str] | None = None) -> int:\n    \"\"\"Central wrapper for all old entrypoints.\n\n    Historically pip has had several entrypoints defined. Because of issues\n    arising from PATH, sys.path, multiple Pythons, their interactions, and most\n    of them having a pip installed, users suffer every time an entrypoint gets\n    moved.\n\n    To alleviate this pain, and provide a mechanism for warning users and\n    directing them to an appropriate place for help, we now define all of\n    our old entrypoints as wrappers for the current one.\n    \"\"\"\n    sys.stderr.write(\n        \"WARNING: pip is being invoked by an old script wrapper. This will \"\n        \"fail in a future version of pip.\\n\"\n        \"Please see https://github.com/pypa/pip/issues/5599 for advice on \"\n        \"fixing the underlying issue.\\n\"\n        \"To avoid this problem you can invoke Python with '-m pip' instead of \"\n        \"running pip directly.\\n\"\n    )\n    return main(args)\n\n\ndef get_best_invocation_for_this_pip() -> str:\n    \"\"\"Try to figure out the best way to invoke pip in the current environment.\"\"\"\n    binary_directory = \"Scripts\" if WINDOWS else \"bin\"\n    binary_prefix = os.path.join(sys.prefix, binary_directory)\n\n    # Try to use pip[X[.Y]] names, if those executables for this environment are\n    # the first on PATH with that name.\n    path_parts = os.path.normcase(os.environ.get(\"PATH\", \"\")).split(os.pathsep)\n    exe_are_in_PATH = os.path.normcase(binary_prefix) in path_parts\n    if exe_are_in_PATH:\n        for exe_name in _EXECUTABLE_NAMES:\n            found_executable = shutil.which(exe_name)\n            binary_executable = os.path.join(binary_prefix, exe_name)\n            if (\n                found_executable\n                and os.path.exists(binary_executable)\n                and os.path.samefile(\n                    found_executable,\n                    binary_executable,\n                )\n            ):\n                return exe_name\n\n    # Use the `-m` invocation, if there's no \"nice\" invocation.\n    return f\"{get_best_invocation_for_this_python()} -m pip\"\n\n\ndef get_best_invocation_for_this_python() -> str:\n    \"\"\"Try to figure out the best way to invoke the current Python.\"\"\"\n    exe = sys.executable\n    exe_name = os.path.basename(exe)\n\n    # Try to use the basename, if it's the first executable.\n    found_executable = shutil.which(exe_name)\n    # Virtual environments often symlink to their parent Python binaries, but we don't\n    # want to treat the Python binaries as equivalent when the environment's Python is\n    # not on PATH (not activated). Thus, we don't follow symlinks.\n    if found_executable and os.path.samestat(os.lstat(found_executable), os.lstat(exe)):\n        return exe_name\n\n    # Use the full executable name, because we couldn't find something simpler.\n    return exe\n"
  },
  {
    "path": "src/pip/_internal/utils/filesystem.py",
    "content": "from __future__ import annotations\n\nimport fnmatch\nimport os\nimport os.path\nimport random\nimport sys\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom tempfile import NamedTemporaryFile\nfrom typing import Any, BinaryIO, Callable, cast\n\nfrom pip._internal.utils.compat import get_path_uid\nfrom pip._internal.utils.misc import format_size\nfrom pip._internal.utils.retry import retry\n\n\ndef check_path_owner(path: str) -> bool:\n    # If we don't have a way to check the effective uid of this process, then\n    # we'll just assume that we own the directory.\n    if sys.platform == \"win32\" or not hasattr(os, \"geteuid\"):\n        return True\n\n    assert os.path.isabs(path)\n\n    previous = None\n    while path != previous:\n        if os.path.lexists(path):\n            # Check if path is writable by current user.\n            if os.geteuid() == 0:\n                # Special handling for root user in order to handle properly\n                # cases where users use sudo without -H flag.\n                try:\n                    path_uid = get_path_uid(path)\n                except OSError:\n                    return False\n                return path_uid == 0\n            else:\n                return os.access(path, os.W_OK)\n        else:\n            previous, path = path, os.path.dirname(path)\n    return False  # assume we don't own the path\n\n\n@contextmanager\ndef adjacent_tmp_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:\n    \"\"\"Return a file-like object pointing to a tmp file next to path.\n\n    The file is created securely and is ensured to be written to disk\n    after the context reaches its end.\n\n    kwargs will be passed to tempfile.NamedTemporaryFile to control\n    the way the temporary file will be opened.\n    \"\"\"\n    with NamedTemporaryFile(\n        delete=False,\n        dir=os.path.dirname(path),\n        prefix=os.path.basename(path),\n        suffix=\".tmp\",\n        **kwargs,\n    ) as f:\n        result = cast(BinaryIO, f)\n        try:\n            yield result\n        finally:\n            result.flush()\n            os.fsync(result.fileno())\n\n\nreplace = retry(stop_after_delay=1, wait=0.25)(os.replace)\n\n\n# test_writable_dir and _test_writable_dir_win are copied from Flit,\n# with the author's agreement to also place them under pip's license.\ndef test_writable_dir(path: str) -> bool:\n    \"\"\"Check if a directory is writable.\n\n    Uses os.access() on POSIX, tries creating files on Windows.\n    \"\"\"\n    # If the directory doesn't exist, find the closest parent that does.\n    while not os.path.isdir(path):\n        parent = os.path.dirname(path)\n        if parent == path:\n            break  # Should never get here, but infinite loops are bad\n        path = parent\n\n    if os.name == \"posix\":\n        return os.access(path, os.W_OK)\n\n    return _test_writable_dir_win(path)\n\n\ndef _test_writable_dir_win(path: str) -> bool:\n    # os.access doesn't work on Windows: http://bugs.python.org/issue2528\n    # and we can't use tempfile: http://bugs.python.org/issue22107\n    basename = \"accesstest_deleteme_fishfingers_custard_\"\n    alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n    for _ in range(10):\n        name = basename + \"\".join(random.choice(alphabet) for _ in range(6))\n        file = os.path.join(path, name)\n        try:\n            fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)\n        except FileExistsError:\n            pass\n        except PermissionError:\n            # This could be because there's a directory with the same name.\n            # But it's highly unlikely there's a directory called that,\n            # so we'll assume it's because the parent dir is not writable.\n            # This could as well be because the parent dir is not readable,\n            # due to non-privileged user access.\n            return False\n        else:\n            os.close(fd)\n            os.unlink(file)\n            return True\n\n    # This should never be reached\n    raise OSError(\"Unexpected condition testing for writable directory\")\n\n\ndef find_files(path: str, pattern: str) -> list[str]:\n    \"\"\"Returns a list of absolute paths of files beneath path, recursively,\n    with filenames which match the UNIX-style shell glob pattern.\"\"\"\n    result: list[str] = []\n    for root, _, files in os.walk(path):\n        matches = fnmatch.filter(files, pattern)\n        result.extend(os.path.join(root, f) for f in matches)\n    return result\n\n\ndef file_size(path: str) -> int | float:\n    # If it's a symlink, return 0.\n    if os.path.islink(path):\n        return 0\n    return os.path.getsize(path)\n\n\ndef format_file_size(path: str) -> str:\n    return format_size(file_size(path))\n\n\ndef directory_size(path: str) -> int | float:\n    size = 0.0\n    for root, _dirs, files in os.walk(path):\n        for filename in files:\n            file_path = os.path.join(root, filename)\n            size += file_size(file_path)\n    return size\n\n\ndef format_directory_size(path: str) -> str:\n    return format_size(directory_size(path))\n\n\ndef copy_directory_permissions(directory: str, target_file: BinaryIO) -> None:\n    mode = (\n        os.stat(directory).st_mode & 0o666  # select read/write permissions of directory\n        | 0o600  # set owner read/write permissions\n    )\n    # Change permissions only if there is no risk of following a symlink.\n    if os.chmod in os.supports_fd:\n        os.chmod(target_file.fileno(), mode)\n    elif os.chmod in os.supports_follow_symlinks:\n        os.chmod(target_file.name, mode, follow_symlinks=False)\n\n\ndef _subdirs_without_generic(\n    path: str, predicate: Callable[[str, list[str]], bool]\n) -> Generator[Path]:\n    \"\"\"Yields every subdirectory of +path+ that has no files matching the\n    predicate under it.\"\"\"\n\n    directories = []\n    excluded = set()\n\n    for root_str, _, filenames in os.walk(Path(path).resolve()):\n        root = Path(root_str)\n        if predicate(root_str, filenames):\n            # This directory should be excluded, so exclude it and all of its\n            # parent directories.\n            # The last item in root.parents is \".\", so we ignore it.\n            #\n            # Wrapping this in `list()` is only needed for Python 3.9.\n            excluded.update(list(root.parents)[:-1])\n            excluded.add(root)\n        directories.append(root)\n\n    for d in sorted(directories, reverse=True):\n        if d not in excluded:\n            yield d\n\n\ndef subdirs_without_files(path: str) -> Generator[Path]:\n    \"\"\"Yields every subdirectory of +path+ that has no files under it.\"\"\"\n    return _subdirs_without_generic(path, lambda root, filenames: len(filenames) > 0)\n\n\ndef subdirs_without_wheels(path: str) -> Generator[Path]:\n    \"\"\"Yields every subdirectory of +path+ that has no .whl files under it.\"\"\"\n    return _subdirs_without_generic(\n        path, lambda root, filenames: any(x.endswith(\".whl\") for x in filenames)\n    )\n"
  },
  {
    "path": "src/pip/_internal/utils/filetypes.py",
    "content": "\"\"\"Filetype information.\"\"\"\n\nfrom pip._internal.utils.misc import splitext\n\nWHEEL_EXTENSION = \".whl\"\nBZ2_EXTENSIONS: tuple[str, ...] = (\".tar.bz2\", \".tbz\")\nXZ_EXTENSIONS: tuple[str, ...] = (\n    \".tar.xz\",\n    \".txz\",\n    \".tlz\",\n    \".tar.lz\",\n    \".tar.lzma\",\n)\nZIP_EXTENSIONS: tuple[str, ...] = (\".zip\", WHEEL_EXTENSION)\nTAR_EXTENSIONS: tuple[str, ...] = (\".tar.gz\", \".tgz\", \".tar\")\nARCHIVE_EXTENSIONS = ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS\n\n\ndef is_archive_file(name: str) -> bool:\n    \"\"\"Return True if `name` is a considered as an archive file.\"\"\"\n    ext = splitext(name)[1].lower()\n    if ext in ARCHIVE_EXTENSIONS:\n        return True\n    return False\n"
  },
  {
    "path": "src/pip/_internal/utils/glibc.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\n\n\ndef glibc_version_string() -> str | None:\n    \"Returns glibc version string, or None if not using glibc.\"\n    return glibc_version_string_confstr() or glibc_version_string_ctypes()\n\n\ndef glibc_version_string_confstr() -> str | None:\n    \"Primary implementation of glibc_version_string using os.confstr.\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module:\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183\n    if sys.platform == \"win32\":\n        return None\n    try:\n        gnu_libc_version = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        if gnu_libc_version is None:\n            return None\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\":\n        _, version = gnu_libc_version.split()\n    except (AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef glibc_version_string_ctypes() -> str | None:\n    \"Fallback implementation of glibc_version_string using ctypes.\"\n\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can't proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\n# platform.libc_ver regularly returns completely nonsensical glibc\n# versions. E.g. on my computer, platform says:\n#\n#   ~$ python2.7 -c 'import platform; print(platform.libc_ver())'\n#   ('glibc', '2.7')\n#   ~$ python3.5 -c 'import platform; print(platform.libc_ver())'\n#   ('glibc', '2.9')\n#\n# But the truth is:\n#\n#   ~$ ldd --version\n#   ldd (Debian GLIBC 2.22-11) 2.22\n#\n# This is unfortunate, because it means that the linehaul data on libc\n# versions that was generated by pip 8.1.2 and earlier is useless and\n# misleading. Solution: instead of using platform, use our code that actually\n# works.\ndef libc_ver() -> tuple[str, str]:\n    \"\"\"Try to determine the glibc version\n\n    Returns a tuple of strings (lib, version) which default to empty strings\n    in case the lookup fails.\n    \"\"\"\n    glibc_version = glibc_version_string()\n    if glibc_version is None:\n        return (\"\", \"\")\n    else:\n        return (\"glibc\", glibc_version)\n"
  },
  {
    "path": "src/pip/_internal/utils/hashes.py",
    "content": "from __future__ import annotations\n\nimport hashlib\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING, BinaryIO, NoReturn\n\nfrom pip._internal.exceptions import HashMismatch, HashMissing, InstallationError\nfrom pip._internal.utils.misc import read_chunks\n\nif TYPE_CHECKING:\n    from hashlib import _Hash\n\n\n# The recommended hash algo of the moment. Change this whenever the state of\n# the art changes; it won't hurt backward compatibility.\nFAVORITE_HASH = \"sha256\"\n\n\n# Names of hashlib algorithms allowed by the --hash option and ``pip hash``\n# Currently, those are the ones at least as collision-resistant as sha256.\nSTRONG_HASHES = [\"sha256\", \"sha384\", \"sha512\"]\n\n\nclass Hashes:\n    \"\"\"A wrapper that builds multiple hashes at once and checks them against\n    known-good values\n\n    \"\"\"\n\n    def __init__(self, hashes: dict[str, list[str]] | None = None) -> None:\n        \"\"\"\n        :param hashes: A dict of algorithm names pointing to lists of allowed\n            hex digests\n        \"\"\"\n        allowed = {}\n        if hashes is not None:\n            for alg, keys in hashes.items():\n                # Make sure values are always sorted (to ease equality checks)\n                allowed[alg] = [k.lower() for k in sorted(keys)]\n        self._allowed = allowed\n\n    def __and__(self, other: Hashes) -> Hashes:\n        if not isinstance(other, Hashes):\n            return NotImplemented\n\n        # If either of the Hashes object is entirely empty (i.e. no hash\n        # specified at all), all hashes from the other object are allowed.\n        if not other:\n            return self\n        if not self:\n            return other\n\n        # Otherwise only hashes that present in both objects are allowed.\n        new = {}\n        for alg, values in other._allowed.items():\n            if alg not in self._allowed:\n                continue\n            new[alg] = [v for v in values if v in self._allowed[alg]]\n        return Hashes(new)\n\n    @property\n    def digest_count(self) -> int:\n        return sum(len(digests) for digests in self._allowed.values())\n\n    def is_hash_allowed(self, hash_name: str, hex_digest: str) -> bool:\n        \"\"\"Return whether the given hex digest is allowed.\"\"\"\n        return hex_digest in self._allowed.get(hash_name, [])\n\n    def check_against_chunks(self, chunks: Iterable[bytes]) -> None:\n        \"\"\"Check good hashes against ones built from iterable of chunks of\n        data.\n\n        Raise HashMismatch if none match.\n\n        \"\"\"\n        gots = {}\n        for hash_name in self._allowed.keys():\n            try:\n                gots[hash_name] = hashlib.new(hash_name)\n            except (ValueError, TypeError):\n                raise InstallationError(f\"Unknown hash name: {hash_name}\")\n\n        for chunk in chunks:\n            for hash in gots.values():\n                hash.update(chunk)\n\n        for hash_name, got in gots.items():\n            if got.hexdigest() in self._allowed[hash_name]:\n                return\n        self._raise(gots)\n\n    def _raise(self, gots: dict[str, _Hash]) -> NoReturn:\n        raise HashMismatch(self._allowed, gots)\n\n    def check_against_file(self, file: BinaryIO) -> None:\n        \"\"\"Check good hashes against a file-like object\n\n        Raise HashMismatch if none match.\n\n        \"\"\"\n        return self.check_against_chunks(read_chunks(file))\n\n    def check_against_path(self, path: str) -> None:\n        with open(path, \"rb\") as file:\n            return self.check_against_file(file)\n\n    def has_one_of(self, hashes: dict[str, str]) -> bool:\n        \"\"\"Return whether any of the given hashes are allowed.\"\"\"\n        for hash_name, hex_digest in hashes.items():\n            if self.is_hash_allowed(hash_name, hex_digest):\n                return True\n        return False\n\n    def __bool__(self) -> bool:\n        \"\"\"Return whether I know any known-good hashes.\"\"\"\n        return bool(self._allowed)\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Hashes):\n            return NotImplemented\n        return self._allowed == other._allowed\n\n    def __hash__(self) -> int:\n        return hash(\n            \",\".join(\n                sorted(\n                    \":\".join((alg, digest))\n                    for alg, digest_list in self._allowed.items()\n                    for digest in digest_list\n                )\n            )\n        )\n\n\nclass MissingHashes(Hashes):\n    \"\"\"A workalike for Hashes used when we're missing a hash for a requirement\n\n    It computes the actual hash of the requirement and raises a HashMissing\n    exception showing it to the user.\n\n    \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Don't offer the ``hashes`` kwarg.\"\"\"\n        # Pass our favorite hash in to generate a \"gotten hash\". With the\n        # empty list, it will never match, so an error will always raise.\n        super().__init__(hashes={FAVORITE_HASH: []})\n\n    def _raise(self, gots: dict[str, _Hash]) -> NoReturn:\n        raise HashMissing(gots[FAVORITE_HASH].hexdigest())\n"
  },
  {
    "path": "src/pip/_internal/utils/logging.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport errno\nimport logging\nimport logging.handlers\nimport os\nimport sys\nimport threading\nfrom collections.abc import Generator\nfrom dataclasses import dataclass\nfrom io import StringIO, TextIOWrapper\nfrom logging import Filter\nfrom typing import Any, ClassVar\n\nfrom pip._vendor.rich.console import (\n    Console,\n    ConsoleOptions,\n    ConsoleRenderable,\n    RenderableType,\n    RenderResult,\n    RichCast,\n)\nfrom pip._vendor.rich.highlighter import NullHighlighter\nfrom pip._vendor.rich.logging import RichHandler\nfrom pip._vendor.rich.segment import Segment\nfrom pip._vendor.rich.style import Style\n\nfrom pip._internal.utils._log import VERBOSE, getLogger\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX\nfrom pip._internal.utils.misc import StreamWrapper, ensure_dir\n\n_log_state = threading.local()\n_stdout_console = None\n_stderr_console = None\nsubprocess_logger = getLogger(\"pip.subprocessor\")\n\n\nclass BrokenStdoutLoggingError(Exception):\n    \"\"\"\n    Raised if BrokenPipeError occurs for the stdout stream while logging.\n    \"\"\"\n\n\ndef _is_broken_pipe_error(exc_class: type[BaseException], exc: BaseException) -> bool:\n    if exc_class is BrokenPipeError:\n        return True\n\n    # On Windows, a broken pipe can show up as EINVAL rather than EPIPE:\n    # https://bugs.python.org/issue19612\n    # https://bugs.python.org/issue30418\n    if not WINDOWS:\n        return False\n\n    return isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)\n\n\n@contextlib.contextmanager\ndef capture_logging() -> Generator[StringIO, None, None]:\n    \"\"\"Capture all pip logs in a buffer temporarily.\"\"\"\n    # Patching sys.std(out|err) directly is not viable as the caller\n    # may want to emit non-logging output (e.g. a rich spinner). To\n    # avoid capturing that, temporarily patch the root logging handlers\n    # to use new rich consoles that write to a StringIO.\n    handlers = {}\n    for handler in logging.getLogger().handlers:\n        if isinstance(handler, RichPipStreamHandler):\n            # Also store the handler's original console so it can be\n            # restored on context exit.\n            handlers[handler] = handler.console\n\n    fake_stream = StreamWrapper.from_stream(sys.stdout)\n    if not handlers:\n        yield fake_stream\n        return\n\n    # HACK: grab no_color attribute from a random handler console since\n    # it's a global option anyway.\n    no_color = next(iter(handlers.values())).no_color\n    fake_console = PipConsole(file=fake_stream, no_color=no_color, soft_wrap=True)\n    try:\n        for handler in handlers:\n            handler.console = fake_console\n        yield fake_stream\n    finally:\n        for handler, original_console in handlers.items():\n            handler.console = original_console\n\n\n@contextlib.contextmanager\ndef indent_log(num: int = 2) -> Generator[None, None, None]:\n    \"\"\"\n    A context manager which will cause the log output to be indented for any\n    log messages emitted inside it.\n    \"\"\"\n    # For thread-safety\n    _log_state.indentation = get_indentation()\n    _log_state.indentation += num\n    try:\n        yield\n    finally:\n        _log_state.indentation -= num\n\n\ndef get_indentation() -> int:\n    return getattr(_log_state, \"indentation\", 0)\n\n\nclass IndentingFormatter(logging.Formatter):\n    default_time_format = \"%Y-%m-%dT%H:%M:%S\"\n\n    def __init__(\n        self,\n        *args: Any,\n        add_timestamp: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"\n        A logging.Formatter that obeys the indent_log() context manager.\n\n        :param add_timestamp: A bool indicating output lines should be prefixed\n            with their record's timestamp.\n        \"\"\"\n        self.add_timestamp = add_timestamp\n        super().__init__(*args, **kwargs)\n\n    def get_message_start(self, formatted: str, levelno: int) -> str:\n        \"\"\"\n        Return the start of the formatted log message (not counting the\n        prefix to add to each line).\n        \"\"\"\n        if levelno < logging.WARNING:\n            return \"\"\n        if formatted.startswith(DEPRECATION_MSG_PREFIX):\n            # Then the message already has a prefix.  We don't want it to\n            # look like \"WARNING: DEPRECATION: ....\"\n            return \"\"\n        if levelno < logging.ERROR:\n            return \"WARNING: \"\n\n        return \"ERROR: \"\n\n    def format(self, record: logging.LogRecord) -> str:\n        \"\"\"\n        Calls the standard formatter, but will indent all of the log message\n        lines by our current indentation level.\n        \"\"\"\n        formatted = super().format(record)\n        message_start = self.get_message_start(formatted, record.levelno)\n        formatted = message_start + formatted\n\n        prefix = \"\"\n        if self.add_timestamp:\n            prefix = f\"{self.formatTime(record)} \"\n        prefix += \" \" * get_indentation()\n        formatted = \"\".join([prefix + line for line in formatted.splitlines(True)])\n        return formatted\n\n\n@dataclass\nclass IndentedRenderable:\n    renderable: RenderableType\n    indent: int\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        segments = console.render(self.renderable, options)\n        lines = Segment.split_lines(segments)\n        for line in lines:\n            yield Segment(\" \" * self.indent)\n            yield from line\n            yield Segment(\"\\n\")\n\n\nclass PipConsole(Console):\n    def on_broken_pipe(self) -> None:\n        # Reraise the original exception, rich 13.8.0+ exits by default\n        # instead, preventing our handler from firing.\n        raise BrokenPipeError() from None\n\n\ndef get_console(*, stderr: bool = False) -> Console:\n    if stderr:\n        assert _stderr_console is not None, \"stderr rich console is missing!\"\n        return _stderr_console\n    else:\n        assert _stdout_console is not None, \"stdout rich console is missing!\"\n        return _stdout_console\n\n\nclass RichPipStreamHandler(RichHandler):\n    KEYWORDS: ClassVar[list[str] | None] = []\n\n    def __init__(self, console: Console) -> None:\n        super().__init__(\n            console=console,\n            show_time=False,\n            show_level=False,\n            show_path=False,\n            highlighter=NullHighlighter(),\n        )\n\n    # Our custom override on Rich's logger, to make things work as we need them to.\n    def emit(self, record: logging.LogRecord) -> None:\n        style: Style | None = None\n\n        # If we are given a diagnostic error to present, present it with indentation.\n        if getattr(record, \"rich\", False):\n            assert isinstance(record.args, tuple)\n            (rich_renderable,) = record.args\n            assert isinstance(\n                rich_renderable, (ConsoleRenderable, RichCast, str)\n            ), f\"{rich_renderable} is not rich-console-renderable\"\n\n            renderable: RenderableType = IndentedRenderable(\n                rich_renderable, indent=get_indentation()\n            )\n        else:\n            message = self.format(record)\n            renderable = self.render_message(record, message)\n            if record.levelno is not None:\n                if record.levelno >= logging.ERROR:\n                    style = Style(color=\"red\")\n                elif record.levelno >= logging.WARNING:\n                    style = Style(color=\"yellow\")\n\n        try:\n            self.console.print(renderable, overflow=\"ignore\", crop=False, style=style)\n        except Exception:\n            self.handleError(record)\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        \"\"\"Called when logging is unable to log some output.\"\"\"\n\n        exc_class, exc = sys.exc_info()[:2]\n        # If a broken pipe occurred while calling write() or flush() on the\n        # stdout stream in logging's Handler.emit(), then raise our special\n        # exception so we can handle it in main() instead of logging the\n        # broken pipe error and continuing.\n        if (\n            exc_class\n            and exc\n            and self.console.file is sys.stdout\n            and _is_broken_pipe_error(exc_class, exc)\n        ):\n            raise BrokenStdoutLoggingError()\n\n        return super().handleError(record)\n\n\nclass BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):\n    def _open(self) -> TextIOWrapper:\n        ensure_dir(os.path.dirname(self.baseFilename))\n        return super()._open()\n\n\nclass MaxLevelFilter(Filter):\n    def __init__(self, level: int) -> None:\n        self.level = level\n\n    def filter(self, record: logging.LogRecord) -> bool:\n        return record.levelno < self.level\n\n\nclass ExcludeLoggerFilter(Filter):\n    \"\"\"\n    A logging Filter that excludes records from a logger (or its children).\n    \"\"\"\n\n    def filter(self, record: logging.LogRecord) -> bool:\n        # The base Filter class allows only records from a logger (or its\n        # children).\n        return not super().filter(record)\n\n\ndef setup_logging(verbosity: int, no_color: bool, user_log_file: str | None) -> int:\n    \"\"\"Configures and sets up all of the logging\n\n    Returns the requested logging level, as its integer value.\n    \"\"\"\n\n    # Determine the level to be logging at.\n    if verbosity >= 2:\n        level_number = logging.DEBUG\n    elif verbosity == 1:\n        level_number = VERBOSE\n    elif verbosity == -1:\n        level_number = logging.WARNING\n    elif verbosity == -2:\n        level_number = logging.ERROR\n    elif verbosity <= -3:\n        level_number = logging.CRITICAL\n    else:\n        level_number = logging.INFO\n\n    level = logging.getLevelName(level_number)\n\n    # The \"root\" logger should match the \"console\" level *unless* we also need\n    # to log to a user log file.\n    include_user_log = user_log_file is not None\n    if include_user_log:\n        additional_log_file = user_log_file\n        root_level = \"DEBUG\"\n    else:\n        additional_log_file = \"/dev/null\"\n        root_level = level\n\n    # Disable any logging besides WARNING unless we have DEBUG level logging\n    # enabled for vendored libraries.\n    vendored_log_level = \"WARNING\" if level in [\"INFO\", \"ERROR\"] else \"DEBUG\"\n\n    # Shorthands for clarity\n    handler_classes = {\n        \"stream\": \"pip._internal.utils.logging.RichPipStreamHandler\",\n        \"file\": \"pip._internal.utils.logging.BetterRotatingFileHandler\",\n    }\n    handlers = [\"console\", \"console_errors\", \"console_subprocess\"] + (\n        [\"user_log\"] if include_user_log else []\n    )\n    global _stdout_console, stderr_console\n    _stdout_console = PipConsole(file=sys.stdout, no_color=no_color, soft_wrap=True)\n    _stderr_console = PipConsole(file=sys.stderr, no_color=no_color, soft_wrap=True)\n\n    logging.config.dictConfig(\n        {\n            \"version\": 1,\n            \"disable_existing_loggers\": False,\n            \"filters\": {\n                \"exclude_warnings\": {\n                    \"()\": \"pip._internal.utils.logging.MaxLevelFilter\",\n                    \"level\": logging.WARNING,\n                },\n                \"restrict_to_subprocess\": {\n                    \"()\": \"logging.Filter\",\n                    \"name\": subprocess_logger.name,\n                },\n                \"exclude_subprocess\": {\n                    \"()\": \"pip._internal.utils.logging.ExcludeLoggerFilter\",\n                    \"name\": subprocess_logger.name,\n                },\n            },\n            \"formatters\": {\n                \"indent\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": \"%(message)s\",\n                },\n                \"indent_with_timestamp\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": \"%(message)s\",\n                    \"add_timestamp\": True,\n                },\n            },\n            \"handlers\": {\n                \"console\": {\n                    \"level\": level,\n                    \"class\": handler_classes[\"stream\"],\n                    \"console\": _stdout_console,\n                    \"filters\": [\"exclude_subprocess\", \"exclude_warnings\"],\n                    \"formatter\": \"indent\",\n                },\n                \"console_errors\": {\n                    \"level\": \"WARNING\",\n                    \"class\": handler_classes[\"stream\"],\n                    \"console\": _stderr_console,\n                    \"filters\": [\"exclude_subprocess\"],\n                    \"formatter\": \"indent\",\n                },\n                # A handler responsible for logging to the console messages\n                # from the \"subprocessor\" logger.\n                \"console_subprocess\": {\n                    \"level\": level,\n                    \"class\": handler_classes[\"stream\"],\n                    \"console\": _stderr_console,\n                    \"filters\": [\"restrict_to_subprocess\"],\n                    \"formatter\": \"indent\",\n                },\n                \"user_log\": {\n                    \"level\": \"DEBUG\",\n                    \"class\": handler_classes[\"file\"],\n                    \"filename\": additional_log_file,\n                    \"encoding\": \"utf-8\",\n                    \"delay\": True,\n                    \"formatter\": \"indent_with_timestamp\",\n                },\n            },\n            \"root\": {\n                \"level\": root_level,\n                \"handlers\": handlers,\n            },\n            \"loggers\": {\"pip._vendor\": {\"level\": vendored_log_level}},\n        }\n    )\n\n    return level_number\n"
  },
  {
    "path": "src/pip/_internal/utils/misc.py",
    "content": "from __future__ import annotations\n\nimport errno\nimport getpass\nimport hashlib\nimport logging\nimport os\nimport posixpath\nimport shutil\nimport stat\nimport sys\nimport sysconfig\nimport urllib.parse\nfrom collections.abc import Generator, Iterable, Iterator, Mapping, Sequence\nfrom dataclasses import dataclass\nfrom functools import partial\nfrom io import StringIO\nfrom itertools import filterfalse, tee, zip_longest\nfrom pathlib import Path\nfrom types import FunctionType, TracebackType\nfrom typing import (\n    Any,\n    BinaryIO,\n    Callable,\n    Optional,\n    TextIO,\n    TypeVar,\n    cast,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.pyproject_hooks import BuildBackendHookCaller\n\nfrom pip import __version__\nfrom pip._internal.exceptions import CommandError, ExternallyManagedEnvironment\nfrom pip._internal.locations import get_major_minor_version\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.retry import retry\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n__all__ = [\n    \"rmtree\",\n    \"display_path\",\n    \"backup_dir\",\n    \"ask\",\n    \"splitext\",\n    \"format_size\",\n    \"is_installable_dir\",\n    \"normalize_path\",\n    \"renames\",\n    \"get_prog\",\n    \"ensure_dir\",\n    \"remove_auth_from_url\",\n    \"check_externally_managed\",\n    \"ConfiguredBuildBackendHookCaller\",\n]\n\nlogger = logging.getLogger(__name__)\n\nT = TypeVar(\"T\")\nExcInfo = tuple[type[BaseException], BaseException, TracebackType]\nVersionInfo = tuple[int, int, int]\nNetlocTuple = tuple[str, tuple[Optional[str], Optional[str]]]\nOnExc = Callable[[FunctionType, Path, BaseException], Any]\nOnErr = Callable[[FunctionType, Path, ExcInfo], Any]\n\nFILE_CHUNK_SIZE = 1024 * 1024\n\n\ndef get_pip_version() -> str:\n    pip_pkg_dir = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n    pip_pkg_dir = os.path.abspath(pip_pkg_dir)\n\n    return f\"pip {__version__} from {pip_pkg_dir} (python {get_major_minor_version()})\"\n\n\ndef normalize_version_info(py_version_info: tuple[int, ...]) -> tuple[int, int, int]:\n    \"\"\"\n    Convert a tuple of ints representing a Python version to one of length\n    three.\n\n    :param py_version_info: a tuple of ints representing a Python version,\n        or None to specify no version. The tuple can have any length.\n\n    :return: a tuple of length three if `py_version_info` is non-None.\n        Otherwise, return `py_version_info` unchanged (i.e. None).\n    \"\"\"\n    if len(py_version_info) < 3:\n        py_version_info += (3 - len(py_version_info)) * (0,)\n    elif len(py_version_info) > 3:\n        py_version_info = py_version_info[:3]\n\n    return cast(\"VersionInfo\", py_version_info)\n\n\ndef ensure_dir(path: str) -> None:\n    \"\"\"os.path.makedirs without EEXIST.\"\"\"\n    try:\n        os.makedirs(path)\n    except OSError as e:\n        # Windows can raise spurious ENOTEMPTY errors. See #6426.\n        if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:\n            raise\n\n\ndef get_prog() -> str:\n    try:\n        prog = os.path.basename(sys.argv[0])\n        if prog in (\"__main__.py\", \"-c\"):\n            return f\"{sys.executable} -m pip\"\n        else:\n            return prog\n    except (AttributeError, TypeError, IndexError):\n        pass\n    return \"pip\"\n\n\n# Retry every half second for up to 3 seconds\n@retry(stop_after_delay=3, wait=0.5)\ndef rmtree(dir: str, ignore_errors: bool = False, onexc: OnExc | None = None) -> None:\n    if ignore_errors:\n        onexc = _onerror_ignore\n    if onexc is None:\n        onexc = _onerror_reraise\n    handler: OnErr = partial(rmtree_errorhandler, onexc=onexc)\n    if sys.version_info >= (3, 12):\n        # See https://docs.python.org/3.12/whatsnew/3.12.html#shutil.\n        shutil.rmtree(dir, onexc=handler)  # type: ignore\n    else:\n        shutil.rmtree(dir, onerror=handler)  # type: ignore\n\n\ndef _onerror_ignore(*_args: Any) -> None:\n    pass\n\n\ndef _onerror_reraise(*_args: Any) -> None:\n    raise  # noqa: PLE0704 - Bare exception used to reraise existing exception\n\n\ndef rmtree_errorhandler(\n    func: FunctionType,\n    path: Path,\n    exc_info: ExcInfo | BaseException,\n    *,\n    onexc: OnExc = _onerror_reraise,\n) -> None:\n    \"\"\"\n    `rmtree` error handler to 'force' a file remove (i.e. like `rm -f`).\n\n    * If a file is readonly then it's write flag is set and operation is\n      retried.\n\n    * `onerror` is the original callback from `rmtree(... onerror=onerror)`\n      that is chained at the end if the \"rm -f\" still fails.\n    \"\"\"\n    try:\n        st_mode = os.stat(path).st_mode\n    except OSError:\n        # it's equivalent to os.path.exists\n        return\n\n    if not st_mode & stat.S_IWRITE:\n        # convert to read/write\n        try:\n            os.chmod(path, st_mode | stat.S_IWRITE)\n        except OSError:\n            pass\n        else:\n            # use the original function to repeat the operation\n            try:\n                func(path)\n                return\n            except OSError:\n                pass\n\n    if not isinstance(exc_info, BaseException):\n        _, exc_info, _ = exc_info\n    onexc(func, path, exc_info)\n\n\ndef display_path(path: str) -> str:\n    \"\"\"Gives the display value for a given path, making it relative to cwd\n    if possible.\"\"\"\n    try:\n        relative = Path(path).relative_to(Path.cwd())\n    except ValueError:\n        # If the path isn't relative to the CWD, leave it alone\n        return path\n    return os.path.join(\".\", relative)\n\n\ndef backup_dir(dir: str, ext: str = \".bak\") -> str:\n    \"\"\"Figure out the name of a directory to back up the given dir to\n    (adding .bak, .bak2, etc)\"\"\"\n    n = 1\n    extension = ext\n    while os.path.exists(dir + extension):\n        n += 1\n        extension = ext + str(n)\n    return dir + extension\n\n\ndef ask_path_exists(message: str, options: Iterable[str]) -> str:\n    for action in os.environ.get(\"PIP_EXISTS_ACTION\", \"\").split():\n        if action in options:\n            return action\n    return ask(message, options)\n\n\ndef _check_no_input(message: str) -> None:\n    \"\"\"Raise an error if no input is allowed.\"\"\"\n    if os.environ.get(\"PIP_NO_INPUT\"):\n        raise Exception(\n            f\"No input was expected ($PIP_NO_INPUT set); question: {message}\"\n        )\n\n\ndef ask(message: str, options: Iterable[str]) -> str:\n    \"\"\"Ask the message interactively, with the given possible responses\"\"\"\n    while 1:\n        _check_no_input(message)\n        response = input(message)\n        response = response.strip().lower()\n        if response not in options:\n            print(\n                \"Your response ({!r}) was not one of the expected responses: \"\n                \"{}\".format(response, \", \".join(options))\n            )\n        else:\n            return response\n\n\ndef ask_input(message: str) -> str:\n    \"\"\"Ask for input interactively.\"\"\"\n    _check_no_input(message)\n    return input(message)\n\n\ndef ask_password(message: str) -> str:\n    \"\"\"Ask for a password interactively.\"\"\"\n    _check_no_input(message)\n    return getpass.getpass(message)\n\n\ndef strtobool(val: str) -> int:\n    \"\"\"Convert a string representation of truth to true (1) or false (0).\n\n    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if\n    'val' is anything else.\n    \"\"\"\n    val = val.lower()\n    if val in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\"):\n        return 1\n    elif val in (\"n\", \"no\", \"f\", \"false\", \"off\", \"0\"):\n        return 0\n    else:\n        raise ValueError(f\"invalid truth value {val!r}\")\n\n\ndef format_size(bytes: float) -> str:\n    if bytes > 1000 * 1000:\n        return f\"{bytes / 1000.0 / 1000:.1f} MB\"\n    elif bytes > 10 * 1000:\n        return f\"{int(bytes / 1000)} kB\"\n    elif bytes > 1000:\n        return f\"{bytes / 1000.0:.1f} kB\"\n    else:\n        return f\"{int(bytes)} bytes\"\n\n\ndef tabulate(rows: Iterable[Iterable[Any]]) -> tuple[list[str], list[int]]:\n    \"\"\"Return a list of formatted rows and a list of column sizes.\n\n    For example::\n\n    >>> tabulate([['foobar', 2000], [0xdeadbeef]])\n    (['foobar     2000', '3735928559'], [10, 4])\n    \"\"\"\n    rows = [tuple(map(str, row)) for row in rows]\n    sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue=\"\")]\n    table = [\" \".join(map(str.ljust, row, sizes)).rstrip() for row in rows]\n    return table, sizes\n\n\ndef is_installable_dir(path: str) -> bool:\n    \"\"\"Is path is a directory containing pyproject.toml or setup.py?\n\n    If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for\n    a legacy setuptools layout by identifying setup.py. We don't check for the\n    setup.cfg because using it without setup.py is only available for PEP 517\n    projects, which are already covered by the pyproject.toml check.\n    \"\"\"\n    if not os.path.isdir(path):\n        return False\n    if os.path.isfile(os.path.join(path, \"pyproject.toml\")):\n        return True\n    if os.path.isfile(os.path.join(path, \"setup.py\")):\n        return True\n    return False\n\n\ndef read_chunks(\n    file: BinaryIO, size: int = FILE_CHUNK_SIZE\n) -> Generator[bytes, None, None]:\n    \"\"\"Yield pieces of data from a file-like object until EOF.\"\"\"\n    while True:\n        chunk = file.read(size)\n        if not chunk:\n            break\n        yield chunk\n\n\ndef normalize_path(path: str, resolve_symlinks: bool = True) -> str:\n    \"\"\"\n    Convert a path to its canonical, case-normalized, absolute version.\n\n    \"\"\"\n    path = os.path.expanduser(path)\n    if resolve_symlinks:\n        path = os.path.realpath(path)\n    else:\n        path = os.path.abspath(path)\n    return os.path.normcase(path)\n\n\ndef splitext(path: str) -> tuple[str, str]:\n    \"\"\"Like os.path.splitext, but take off .tar too\"\"\"\n    base, ext = posixpath.splitext(path)\n    if base.lower().endswith(\".tar\"):\n        ext = base[-4:] + ext\n        base = base[:-4]\n    return base, ext\n\n\ndef renames(old: str, new: str) -> None:\n    \"\"\"Like os.renames(), but handles renaming across devices.\"\"\"\n    # Implementation borrowed from os.renames().\n    head, tail = os.path.split(new)\n    if head and tail and not os.path.exists(head):\n        os.makedirs(head)\n\n    shutil.move(old, new)\n\n    head, tail = os.path.split(old)\n    if head and tail:\n        try:\n            os.removedirs(head)\n        except OSError:\n            pass\n\n\ndef is_local(path: str) -> bool:\n    \"\"\"\n    Return True if path is within sys.prefix, if we're running in a virtualenv.\n\n    If we're not in a virtualenv, all paths are considered \"local.\"\n\n    Caution: this function assumes the head of path has been normalized\n    with normalize_path.\n    \"\"\"\n    if not running_under_virtualenv():\n        return True\n    return path.startswith(normalize_path(sys.prefix))\n\n\ndef write_output(msg: Any, *args: Any) -> None:\n    logger.info(msg, *args)\n\n\nclass StreamWrapper(StringIO):\n    orig_stream: TextIO\n\n    @classmethod\n    def from_stream(cls, orig_stream: TextIO) -> StreamWrapper:\n        ret = cls()\n        ret.orig_stream = orig_stream\n        return ret\n\n    # compileall.compile_dir() needs stdout.encoding to print to stdout\n    # type ignore is because TextIOBase.encoding is writeable\n    @property\n    def encoding(self) -> str:  # type: ignore\n        return self.orig_stream.encoding\n\n\n# Simulates an enum\ndef enum(*sequential: Any, **named: Any) -> type[Any]:\n    enums = dict(zip(sequential, range(len(sequential))), **named)\n    reverse = {value: key for key, value in enums.items()}\n    enums[\"reverse_mapping\"] = reverse\n    return type(\"Enum\", (), enums)\n\n\ndef build_netloc(host: str, port: int | None) -> str:\n    \"\"\"\n    Build a netloc from a host-port pair\n    \"\"\"\n    if port is None:\n        return host\n    if \":\" in host:\n        # Only wrap host with square brackets when it is IPv6\n        host = f\"[{host}]\"\n    return f\"{host}:{port}\"\n\n\ndef build_url_from_netloc(netloc: str, scheme: str = \"https\") -> str:\n    \"\"\"\n    Build a full URL from a netloc.\n    \"\"\"\n    if netloc.count(\":\") >= 2 and \"@\" not in netloc and \"[\" not in netloc:\n        # It must be a bare IPv6 address, so wrap it with brackets.\n        netloc = f\"[{netloc}]\"\n    return f\"{scheme}://{netloc}\"\n\n\ndef parse_netloc(netloc: str) -> tuple[str | None, int | None]:\n    \"\"\"\n    Return the host-port pair from a netloc.\n    \"\"\"\n    url = build_url_from_netloc(netloc)\n    parsed = urllib.parse.urlparse(url)\n    return parsed.hostname, parsed.port\n\n\ndef split_auth_from_netloc(netloc: str) -> NetlocTuple:\n    \"\"\"\n    Parse out and remove the auth information from a netloc.\n\n    Returns: (netloc, (username, password)).\n    \"\"\"\n    if \"@\" not in netloc:\n        return netloc, (None, None)\n\n    # Split from the right because that's how urllib.parse.urlsplit()\n    # behaves if more than one @ is present (which can be checked using\n    # the password attribute of urlsplit()'s return value).\n    auth, netloc = netloc.rsplit(\"@\", 1)\n    pw: str | None = None\n    if \":\" in auth:\n        # Split from the left because that's how urllib.parse.urlsplit()\n        # behaves if more than one : is present (which again can be checked\n        # using the password attribute of the return value)\n        user, pw = auth.split(\":\", 1)\n    else:\n        user, pw = auth, None\n\n    user = urllib.parse.unquote(user)\n    if pw is not None:\n        pw = urllib.parse.unquote(pw)\n\n    return netloc, (user, pw)\n\n\ndef redact_netloc(netloc: str) -> str:\n    \"\"\"\n    Replace the sensitive data in a netloc with \"****\", if it exists.\n\n    For example:\n        - \"user:pass@example.com\" returns \"user:****@example.com\"\n        - \"accesstoken@example.com\" returns \"****@example.com\"\n    \"\"\"\n    netloc, (user, password) = split_auth_from_netloc(netloc)\n    if user is None:\n        return netloc\n    if password is None:\n        user = \"****\"\n        password = \"\"\n    else:\n        user = urllib.parse.quote(user)\n        password = \":****\"\n    return f\"{user}{password}@{netloc}\"\n\n\ndef _transform_url(\n    url: str, transform_netloc: Callable[[str], tuple[Any, ...]]\n) -> tuple[str, NetlocTuple]:\n    \"\"\"Transform and replace netloc in a url.\n\n    transform_netloc is a function taking the netloc and returning a\n    tuple. The first element of this tuple is the new netloc. The\n    entire tuple is returned.\n\n    Returns a tuple containing the transformed url as item 0 and the\n    original tuple returned by transform_netloc as item 1.\n    \"\"\"\n    purl = urllib.parse.urlsplit(url)\n    netloc_tuple = transform_netloc(purl.netloc)\n    # stripped url\n    url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)\n    surl = urllib.parse.urlunsplit(url_pieces)\n    return surl, cast(\"NetlocTuple\", netloc_tuple)\n\n\ndef _get_netloc(netloc: str) -> NetlocTuple:\n    return split_auth_from_netloc(netloc)\n\n\ndef _redact_netloc(netloc: str) -> tuple[str]:\n    return (redact_netloc(netloc),)\n\n\ndef split_auth_netloc_from_url(\n    url: str,\n) -> tuple[str, str, tuple[str | None, str | None]]:\n    \"\"\"\n    Parse a url into separate netloc, auth, and url with no auth.\n\n    Returns: (url_without_auth, netloc, (username, password))\n    \"\"\"\n    url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)\n    return url_without_auth, netloc, auth\n\n\ndef remove_auth_from_url(url: str) -> str:\n    \"\"\"Return a copy of url with 'username:password@' removed.\"\"\"\n    # username/pass params are passed to subversion through flags\n    # and are not recognized in the url.\n    return _transform_url(url, _get_netloc)[0]\n\n\ndef redact_auth_from_url(url: str) -> str:\n    \"\"\"Replace the password in a given url with ****.\"\"\"\n    return _transform_url(url, _redact_netloc)[0]\n\n\ndef redact_auth_from_requirement(req: Requirement) -> str:\n    \"\"\"Replace the password in a given requirement url with ****.\"\"\"\n    if not req.url:\n        return str(req)\n    return str(req).replace(req.url, redact_auth_from_url(req.url))\n\n\n@dataclass(frozen=True)\nclass HiddenText:\n    secret: str\n    redacted: str\n\n    def __repr__(self) -> str:\n        return f\"<HiddenText {str(self)!r}>\"\n\n    def __str__(self) -> str:\n        return self.redacted\n\n    def __eq__(self, other: object) -> bool:\n        # Equality is particularly useful for testing.\n        if type(self) is type(other):\n            # The string being used for redaction doesn't also have to match,\n            # just the raw, original string.\n            return self.secret == cast(HiddenText, other).secret\n        return NotImplemented\n\n    # Disable hashing, since we have a custom __eq__ and don't need hash-ability\n    # (yet). The only required property of hashing is that objects which compare\n    # equal have the same hash value.\n    __hash__ = None  # type: ignore[assignment]\n\n\ndef hide_value(value: str) -> HiddenText:\n    return HiddenText(value, redacted=\"****\")\n\n\ndef hide_url(url: str) -> HiddenText:\n    redacted = redact_auth_from_url(url)\n    return HiddenText(url, redacted=redacted)\n\n\ndef protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:\n    \"\"\"Protection of pip.exe from modification on Windows\n\n    On Windows, any operation modifying pip should be run as:\n        python -m pip ...\n    \"\"\"\n    pip_names = [\n        \"pip\",\n        f\"pip{sys.version_info.major}\",\n        f\"pip{sys.version_info.major}.{sys.version_info.minor}\",\n    ]\n\n    # See https://github.com/pypa/pip/issues/1299 for more discussion\n    should_show_use_python_msg = (\n        modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names\n    )\n\n    if should_show_use_python_msg:\n        new_command = [sys.executable, \"-m\", \"pip\"] + sys.argv[1:]\n        raise CommandError(\n            \"To modify pip, please run the following command:\\n{}\".format(\n                \" \".join(new_command)\n            )\n        )\n\n\ndef check_externally_managed() -> None:\n    \"\"\"Check whether the current environment is externally managed.\n\n    If the ``EXTERNALLY-MANAGED`` config file is found, the current environment\n    is considered externally managed, and an ExternallyManagedEnvironment is\n    raised.\n    \"\"\"\n    if running_under_virtualenv():\n        return\n    marker = os.path.join(sysconfig.get_path(\"stdlib\"), \"EXTERNALLY-MANAGED\")\n    if not os.path.isfile(marker):\n        return\n    raise ExternallyManagedEnvironment.from_config(marker)\n\n\ndef is_console_interactive() -> bool:\n    \"\"\"Is this console interactive?\"\"\"\n    return sys.stdin is not None and sys.stdin.isatty()\n\n\ndef hash_file(path: str, blocksize: int = 1 << 20) -> tuple[Any, int]:\n    \"\"\"Return (hash, length) for path using hashlib.sha256()\"\"\"\n\n    h = hashlib.sha256()\n    length = 0\n    with open(path, \"rb\") as f:\n        for block in read_chunks(f, size=blocksize):\n            length += len(block)\n            h.update(block)\n    return h, length\n\n\ndef pairwise(iterable: Iterable[Any]) -> Iterator[tuple[Any, Any]]:\n    \"\"\"\n    Return paired elements.\n\n    For example:\n        s -> (s0, s1), (s2, s3), (s4, s5), ...\n    \"\"\"\n    iterable = iter(iterable)\n    return zip_longest(iterable, iterable)\n\n\ndef partition(\n    pred: Callable[[T], bool], iterable: Iterable[T]\n) -> tuple[Iterable[T], Iterable[T]]:\n    \"\"\"\n    Use a predicate to partition entries into false entries and true entries,\n    like\n\n        partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9\n    \"\"\"\n    t1, t2 = tee(iterable)\n    return filterfalse(pred, t1), filter(pred, t2)\n\n\nclass ConfiguredBuildBackendHookCaller(BuildBackendHookCaller):\n    def __init__(\n        self,\n        config_holder: Any,\n        source_dir: str,\n        build_backend: str,\n        backend_path: str | None = None,\n        runner: Callable[..., None] | None = None,\n        python_executable: str | None = None,\n    ):\n        super().__init__(\n            source_dir, build_backend, backend_path, runner, python_executable\n        )\n        self.config_holder = config_holder\n\n    def build_wheel(\n        self,\n        wheel_directory: str,\n        config_settings: Mapping[str, Any] | None = None,\n        metadata_directory: str | None = None,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_wheel(\n            wheel_directory, config_settings=cs, metadata_directory=metadata_directory\n        )\n\n    def build_sdist(\n        self,\n        sdist_directory: str,\n        config_settings: Mapping[str, Any] | None = None,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_sdist(sdist_directory, config_settings=cs)\n\n    def build_editable(\n        self,\n        wheel_directory: str,\n        config_settings: Mapping[str, Any] | None = None,\n        metadata_directory: str | None = None,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_editable(\n            wheel_directory, config_settings=cs, metadata_directory=metadata_directory\n        )\n\n    def get_requires_for_build_wheel(\n        self, config_settings: Mapping[str, Any] | None = None\n    ) -> Sequence[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_wheel(config_settings=cs)\n\n    def get_requires_for_build_sdist(\n        self, config_settings: Mapping[str, Any] | None = None\n    ) -> Sequence[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_sdist(config_settings=cs)\n\n    def get_requires_for_build_editable(\n        self, config_settings: Mapping[str, Any] | None = None\n    ) -> Sequence[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_editable(config_settings=cs)\n\n    def prepare_metadata_for_build_wheel(\n        self,\n        metadata_directory: str,\n        config_settings: Mapping[str, Any] | None = None,\n        _allow_fallback: bool = True,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().prepare_metadata_for_build_wheel(\n            metadata_directory=metadata_directory,\n            config_settings=cs,\n            _allow_fallback=_allow_fallback,\n        )\n\n    def prepare_metadata_for_build_editable(\n        self,\n        metadata_directory: str,\n        config_settings: Mapping[str, Any] | None = None,\n        _allow_fallback: bool = True,\n    ) -> str | None:\n        cs = self.config_holder.config_settings\n        return super().prepare_metadata_for_build_editable(\n            metadata_directory=metadata_directory,\n            config_settings=cs,\n            _allow_fallback=_allow_fallback,\n        )\n\n\ndef warn_if_run_as_root() -> None:\n    \"\"\"Output a warning for sudo users on Unix.\n\n    In a virtual environment, sudo pip still writes to virtualenv.\n    On Windows, users may run pip as Administrator without issues.\n    This warning only applies to Unix root users outside of virtualenv.\n    \"\"\"\n    if running_under_virtualenv():\n        return\n    if not hasattr(os, \"getuid\"):\n        return\n    # On Windows, there are no \"system managed\" Python packages. Installing as\n    # Administrator via pip is the correct way of updating system environments.\n    #\n    # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform\n    # checks: https://mypy.readthedocs.io/en/stable/common_issues.html\n    if sys.platform == \"win32\" or sys.platform == \"cygwin\":\n        return\n\n    if os.getuid() != 0:\n        return\n\n    logger.warning(\n        \"Running pip as the 'root' user can result in broken permissions and \"\n        \"conflicting behaviour with the system package manager, possibly \"\n        \"rendering your system unusable. \"\n        \"It is recommended to use a virtual environment instead: \"\n        \"https://pip.pypa.io/warnings/venv. \"\n        \"Use the --root-user-action option if you know what you are doing and \"\n        \"want to suppress this warning.\"\n    )\n"
  },
  {
    "path": "src/pip/_internal/utils/packaging.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport logging\n\nfrom pip._vendor.packaging import specifiers, version\nfrom pip._vendor.packaging.requirements import Requirement\n\nlogger = logging.getLogger(__name__)\n\n\n@functools.lru_cache(maxsize=32)\ndef check_requires_python(\n    requires_python: str | None, version_info: tuple[int, ...]\n) -> bool:\n    \"\"\"\n    Check if the given Python version matches a \"Requires-Python\" specifier.\n\n    :param version_info: A 3-tuple of ints representing a Python\n        major-minor-micro version to check (e.g. `sys.version_info[:3]`).\n\n    :return: `True` if the given Python version satisfies the requirement.\n        Otherwise, return `False`.\n\n    :raises InvalidSpecifier: If `requires_python` has an invalid format.\n    \"\"\"\n    if requires_python is None:\n        # The package provides no information\n        return True\n    requires_python_specifier = specifiers.SpecifierSet(requires_python)\n\n    python_version = version.parse(\".\".join(map(str, version_info)))\n    return python_version in requires_python_specifier\n\n\n@functools.lru_cache(maxsize=10000)\ndef get_requirement(req_string: str) -> Requirement:\n    \"\"\"Construct a packaging.Requirement object with caching\"\"\"\n    # Parsing requirement strings is expensive, and is also expected to happen\n    # with a low diversity of different arguments (at least relative the number\n    # constructed). This method adds a cache to requirement object creation to\n    # minimize repeated parsing of the same string to construct equivalent\n    # Requirement objects.\n    return Requirement(req_string)\n"
  },
  {
    "path": "src/pip/_internal/utils/pylock.py",
    "content": "from collections.abc import Iterable\nfrom pathlib import Path\n\nfrom pip._vendor.packaging.pylock import (\n    Package,\n    PackageArchive,\n    PackageDirectory,\n    PackageSdist,\n    PackageVcs,\n    PackageWheel,\n    Pylock,\n)\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.models.direct_url import ArchiveInfo, DirInfo, VcsInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.urls import url_to_path\n\n\ndef _pylock_package_from_install_requirement(\n    ireq: InstallRequirement, base_dir: Path\n) -> Package:\n    base_dir = base_dir.resolve()\n    dist = ireq.get_dist()\n    download_info = ireq.download_info\n    assert download_info\n    package_version = None\n    package_vcs = None\n    package_directory = None\n    package_archive = None\n    package_sdist = None\n    package_wheels = None\n    if ireq.is_direct:\n        if isinstance(download_info.info, VcsInfo):\n            package_vcs = PackageVcs(\n                type=download_info.info.vcs,\n                url=download_info.url,\n                path=None,\n                requested_revision=download_info.info.requested_revision,\n                commit_id=download_info.info.commit_id,\n                subdirectory=download_info.subdirectory,\n            )\n        elif isinstance(download_info.info, DirInfo):\n            package_directory = PackageDirectory(\n                path=(\n                    Path(url_to_path(download_info.url))\n                    .resolve()\n                    .relative_to(base_dir)\n                    .as_posix()\n                ),\n                editable=(\n                    download_info.info.editable if download_info.info.editable else None\n                ),\n                subdirectory=download_info.subdirectory,\n            )\n        elif isinstance(download_info.info, ArchiveInfo):\n            if not download_info.info.hashes:\n                raise NotImplementedError()\n            package_archive = PackageArchive(\n                url=download_info.url,\n                path=None,\n                hashes=download_info.info.hashes,\n                subdirectory=download_info.subdirectory,\n            )\n        else:\n            # should never happen\n            raise NotImplementedError()\n    else:\n        package_version = dist.version\n        if isinstance(download_info.info, ArchiveInfo):\n            if not download_info.info.hashes:\n                raise NotImplementedError()\n            link = Link(download_info.url)\n            if link.is_wheel:\n                package_wheels = [\n                    PackageWheel(\n                        name=link.filename,\n                        url=download_info.url,\n                        hashes=download_info.info.hashes,\n                    )\n                ]\n            else:\n                package_sdist = PackageSdist(\n                    name=link.filename,\n                    url=download_info.url,\n                    hashes=download_info.info.hashes,\n                )\n        else:\n            # should never happen\n            raise NotImplementedError()\n    return Package(\n        name=dist.canonical_name,\n        version=package_version,\n        vcs=package_vcs,\n        directory=package_directory,\n        archive=package_archive,\n        sdist=package_sdist,\n        wheels=package_wheels,\n    )\n\n\ndef pylock_from_install_requirements(\n    install_requirements: Iterable[InstallRequirement], base_dir: Path\n) -> Pylock:\n    return Pylock(\n        lock_version=Version(\"1.0\"),\n        created_by=\"pip\",\n        packages=sorted(\n            (\n                _pylock_package_from_install_requirement(ireq, base_dir)\n                for ireq in install_requirements\n            ),\n            key=lambda p: p.name,\n        ),\n    )\n"
  },
  {
    "path": "src/pip/_internal/utils/retry.py",
    "content": "from __future__ import annotations\n\nimport functools\nfrom time import perf_counter, sleep\nfrom typing import TYPE_CHECKING, Callable, TypeVar\n\nif TYPE_CHECKING:\n    from typing_extensions import ParamSpec\n\n    T = TypeVar(\"T\")\n    P = ParamSpec(\"P\")\n\n\ndef retry(\n    wait: float, stop_after_delay: float\n) -> Callable[[Callable[P, T]], Callable[P, T]]:\n    \"\"\"Decorator to automatically retry a function on error.\n\n    If the function raises, the function is recalled with the same arguments\n    until it returns or the time limit is reached. When the time limit is\n    surpassed, the last exception raised is reraised.\n\n    :param wait: The time to wait after an error before retrying, in seconds.\n    :param stop_after_delay: The time limit after which retries will cease,\n        in seconds.\n    \"\"\"\n\n    def wrapper(func: Callable[P, T]) -> Callable[P, T]:\n\n        @functools.wraps(func)\n        def retry_wrapped(*args: P.args, **kwargs: P.kwargs) -> T:\n            # The performance counter is monotonic on all platforms we care\n            # about and has much better resolution than time.monotonic().\n            start_time = perf_counter()\n            while True:\n                try:\n                    return func(*args, **kwargs)\n                except Exception:\n                    if perf_counter() - start_time > stop_after_delay:\n                        raise\n                    sleep(wait)\n\n        return retry_wrapped\n\n    return wrapper\n"
  },
  {
    "path": "src/pip/_internal/utils/subprocess.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport shlex\nimport subprocess\nfrom collections.abc import Iterable, Mapping\nfrom typing import Any, Callable, Literal, Union\n\nfrom pip._vendor.rich.markup import escape\n\nfrom pip._internal.cli.spinners import SpinnerInterface, open_spinner\nfrom pip._internal.exceptions import InstallationSubprocessError\nfrom pip._internal.utils.logging import VERBOSE, subprocess_logger\nfrom pip._internal.utils.misc import HiddenText\n\nCommandArgs = list[Union[str, HiddenText]]\n\n\ndef make_command(*args: str | HiddenText | CommandArgs) -> CommandArgs:\n    \"\"\"\n    Create a CommandArgs object.\n    \"\"\"\n    command_args: CommandArgs = []\n    for arg in args:\n        # Check for list instead of CommandArgs since CommandArgs is\n        # only known during type-checking.\n        if isinstance(arg, list):\n            command_args.extend(arg)\n        else:\n            # Otherwise, arg is str or HiddenText.\n            command_args.append(arg)\n\n    return command_args\n\n\ndef format_command_args(args: list[str] | CommandArgs) -> str:\n    \"\"\"\n    Format command arguments for display.\n    \"\"\"\n    # For HiddenText arguments, display the redacted form by calling str().\n    # Also, we don't apply str() to arguments that aren't HiddenText since\n    # this can trigger a UnicodeDecodeError in Python 2 if the argument\n    # has type unicode and includes a non-ascii character.  (The type\n    # checker doesn't ensure the annotations are correct in all cases.)\n    return \" \".join(\n        shlex.quote(str(arg)) if isinstance(arg, HiddenText) else shlex.quote(arg)\n        for arg in args\n    )\n\n\ndef reveal_command_args(args: list[str] | CommandArgs) -> list[str]:\n    \"\"\"\n    Return the arguments in their raw, unredacted form.\n    \"\"\"\n    return [arg.secret if isinstance(arg, HiddenText) else arg for arg in args]\n\n\ndef call_subprocess(\n    cmd: list[str] | CommandArgs,\n    show_stdout: bool = False,\n    cwd: str | None = None,\n    on_returncode: Literal[\"raise\", \"warn\", \"ignore\"] = \"raise\",\n    extra_ok_returncodes: Iterable[int] | None = None,\n    extra_environ: Mapping[str, Any] | None = None,\n    unset_environ: Iterable[str] | None = None,\n    spinner: SpinnerInterface | None = None,\n    log_failed_cmd: bool | None = True,\n    stdout_only: bool | None = False,\n    *,\n    command_desc: str,\n) -> str:\n    \"\"\"\n    Args:\n      show_stdout: if true, use INFO to log the subprocess's stderr and\n        stdout streams.  Otherwise, use DEBUG.  Defaults to False.\n      extra_ok_returncodes: an iterable of integer return codes that are\n        acceptable, in addition to 0. Defaults to None, which means [].\n      unset_environ: an iterable of environment variable names to unset\n        prior to calling subprocess.Popen().\n      log_failed_cmd: if false, failed commands are not logged, only raised.\n      stdout_only: if true, return only stdout, else return both. When true,\n        logging of both stdout and stderr occurs when the subprocess has\n        terminated, else logging occurs as subprocess output is produced.\n    \"\"\"\n    if extra_ok_returncodes is None:\n        extra_ok_returncodes = []\n    if unset_environ is None:\n        unset_environ = []\n    # Most places in pip use show_stdout=False. What this means is--\n    #\n    # - We connect the child's output (combined stderr and stdout) to a\n    #   single pipe, which we read.\n    # - We log this output to stderr at DEBUG level as it is received.\n    # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't\n    #   requested), then we show a spinner so the user can still see the\n    #   subprocess is in progress.\n    # - If the subprocess exits with an error, we log the output to stderr\n    #   at ERROR level if it hasn't already been displayed to the console\n    #   (e.g. if --verbose logging wasn't enabled).  This way we don't log\n    #   the output to the console twice.\n    #\n    # If show_stdout=True, then the above is still done, but with DEBUG\n    # replaced by INFO.\n    if show_stdout:\n        # Then log the subprocess output at INFO level.\n        log_subprocess: Callable[..., None] = subprocess_logger.info\n        used_level = logging.INFO\n    else:\n        # Then log the subprocess output using VERBOSE.  This also ensures\n        # it will be logged to the log file (aka user_log), if enabled.\n        log_subprocess = subprocess_logger.verbose\n        used_level = VERBOSE\n\n    # Whether the subprocess will be visible in the console.\n    showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level\n\n    # Only use the spinner if we're not showing the subprocess output\n    # and we have a spinner.\n    use_spinner = not showing_subprocess and spinner is not None\n\n    log_subprocess(\"Running command %s\", command_desc)\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n    for name in unset_environ:\n        env.pop(name, None)\n    try:\n        proc = subprocess.Popen(\n            # Convert HiddenText objects to the underlying str.\n            reveal_command_args(cmd),\n            stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,\n            cwd=cwd,\n            env=env,\n            errors=\"backslashreplace\",\n        )\n    except Exception as exc:\n        if log_failed_cmd:\n            subprocess_logger.critical(\n                \"Error %s while executing command %s\",\n                exc,\n                command_desc,\n            )\n        raise\n    all_output = []\n    if not stdout_only:\n        assert proc.stdout\n        assert proc.stdin\n        proc.stdin.close()\n        # In this mode, stdout and stderr are in the same pipe.\n        while True:\n            line: str = proc.stdout.readline()\n            if not line:\n                break\n            line = line.rstrip()\n            all_output.append(line + \"\\n\")\n\n            # Show the line immediately.\n            log_subprocess(line)\n            # Update the spinner.\n            if use_spinner:\n                assert spinner\n                spinner.spin()\n        try:\n            proc.wait()\n        finally:\n            if proc.stdout:\n                proc.stdout.close()\n        output = \"\".join(all_output)\n    else:\n        # In this mode, stdout and stderr are in different pipes.\n        # We must use communicate() which is the only safe way to read both.\n        out, err = proc.communicate()\n        # log line by line to preserve pip log indenting\n        for out_line in out.splitlines():\n            log_subprocess(out_line)\n        all_output.append(out)\n        for err_line in err.splitlines():\n            log_subprocess(err_line)\n        all_output.append(err)\n        output = out\n\n    proc_had_error = proc.returncode and proc.returncode not in extra_ok_returncodes\n    if use_spinner:\n        assert spinner\n        if proc_had_error:\n            spinner.finish(\"error\")\n        else:\n            spinner.finish(\"done\")\n    if proc_had_error:\n        if on_returncode == \"raise\":\n            error = InstallationSubprocessError(\n                command_description=command_desc,\n                exit_code=proc.returncode,\n                output_lines=all_output if not showing_subprocess else None,\n            )\n            if log_failed_cmd:\n                subprocess_logger.error(\"%s\", error, extra={\"rich\": True})\n                subprocess_logger.verbose(\n                    \"[bold magenta]full command[/]: [blue]%s[/]\",\n                    escape(format_command_args(cmd)),\n                    extra={\"markup\": True},\n                )\n                subprocess_logger.verbose(\n                    \"[bold magenta]cwd[/]: %s\",\n                    escape(cwd or \"[inherit]\"),\n                    extra={\"markup\": True},\n                )\n\n            raise error\n        elif on_returncode == \"warn\":\n            subprocess_logger.warning(\n                'Command \"%s\" had error code %s in %s',\n                command_desc,\n                proc.returncode,\n                cwd,\n            )\n        elif on_returncode == \"ignore\":\n            pass\n        else:\n            raise ValueError(f\"Invalid value: on_returncode={on_returncode!r}\")\n    return output\n\n\ndef runner_with_spinner_message(message: str) -> Callable[..., None]:\n    \"\"\"Provide a subprocess_runner that shows a spinner message.\n\n    Intended for use with for BuildBackendHookCaller. Thus, the runner has\n    an API that matches what's expected by BuildBackendHookCaller.subprocess_runner.\n    \"\"\"\n\n    def runner(\n        cmd: list[str],\n        cwd: str | None = None,\n        extra_environ: Mapping[str, Any] | None = None,\n    ) -> None:\n        with open_spinner(message) as spinner:\n            call_subprocess(\n                cmd,\n                command_desc=message,\n                cwd=cwd,\n                extra_environ=extra_environ,\n                spinner=spinner,\n            )\n\n    return runner\n"
  },
  {
    "path": "src/pip/_internal/utils/temp_dir.py",
    "content": "from __future__ import annotations\n\nimport errno\nimport itertools\nimport logging\nimport os.path\nimport tempfile\nimport traceback\nfrom collections.abc import Generator\nfrom contextlib import ExitStack, contextmanager\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Callable,\n    TypeVar,\n)\n\nfrom pip._internal.utils.misc import enum, rmtree\n\nlogger = logging.getLogger(__name__)\n\n_T = TypeVar(\"_T\", bound=\"TempDirectory\")\n\n\n# Kinds of temporary directories. Only needed for ones that are\n# globally-managed.\ntempdir_kinds = enum(\n    BUILD_ENV=\"build-env\",\n    EPHEM_WHEEL_CACHE=\"ephem-wheel-cache\",\n    REQ_BUILD=\"req-build\",\n)\n\n\n_tempdir_manager: ExitStack | None = None\n\n\n@contextmanager\ndef global_tempdir_manager() -> Generator[None, None, None]:\n    global _tempdir_manager\n    with ExitStack() as stack:\n        old_tempdir_manager, _tempdir_manager = _tempdir_manager, stack\n        try:\n            yield\n        finally:\n            _tempdir_manager = old_tempdir_manager\n\n\nclass TempDirectoryTypeRegistry:\n    \"\"\"Manages temp directory behavior\"\"\"\n\n    def __init__(self) -> None:\n        self._should_delete: dict[str, bool] = {}\n\n    def set_delete(self, kind: str, value: bool) -> None:\n        \"\"\"Indicate whether a TempDirectory of the given kind should be\n        auto-deleted.\n        \"\"\"\n        self._should_delete[kind] = value\n\n    def get_delete(self, kind: str) -> bool:\n        \"\"\"Get configured auto-delete flag for a given TempDirectory type,\n        default True.\n        \"\"\"\n        return self._should_delete.get(kind, True)\n\n\n_tempdir_registry: TempDirectoryTypeRegistry | None = None\n\n\n@contextmanager\ndef tempdir_registry() -> Generator[TempDirectoryTypeRegistry, None, None]:\n    \"\"\"Provides a scoped global tempdir registry that can be used to dictate\n    whether directories should be deleted.\n    \"\"\"\n    global _tempdir_registry\n    old_tempdir_registry = _tempdir_registry\n    _tempdir_registry = TempDirectoryTypeRegistry()\n    try:\n        yield _tempdir_registry\n    finally:\n        _tempdir_registry = old_tempdir_registry\n\n\nclass _Default:\n    pass\n\n\n_default = _Default()\n\n\nclass TempDirectory:\n    \"\"\"Helper class that owns and cleans up a temporary directory.\n\n    This class can be used as a context manager or as an OO representation of a\n    temporary directory.\n\n    Attributes:\n        path\n            Location to the created temporary directory\n        delete\n            Whether the directory should be deleted when exiting\n            (when used as a contextmanager)\n\n    Methods:\n        cleanup()\n            Deletes the temporary directory\n\n    When used as a context manager, if the delete attribute is True, on\n    exiting the context the temporary directory is deleted.\n    \"\"\"\n\n    def __init__(\n        self,\n        path: str | None = None,\n        delete: bool | None | _Default = _default,\n        kind: str = \"temp\",\n        globally_managed: bool = False,\n        ignore_cleanup_errors: bool = True,\n    ):\n        super().__init__()\n\n        if delete is _default:\n            if path is not None:\n                # If we were given an explicit directory, resolve delete option\n                # now.\n                delete = False\n            else:\n                # Otherwise, we wait until cleanup and see what\n                # tempdir_registry says.\n                delete = None\n\n        # The only time we specify path is in for editables where it\n        # is the value of the --src option.\n        if path is None:\n            path = self._create(kind)\n\n        self._path = path\n        self._deleted = False\n        self.delete = delete\n        self.kind = kind\n        self.ignore_cleanup_errors = ignore_cleanup_errors\n\n        if globally_managed:\n            assert _tempdir_manager is not None\n            _tempdir_manager.enter_context(self)\n\n    @property\n    def path(self) -> str:\n        assert not self._deleted, f\"Attempted to access deleted path: {self._path}\"\n        return self._path\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__} {self.path!r}>\"\n\n    def __enter__(self: _T) -> _T:\n        return self\n\n    def __exit__(self, exc: Any, value: Any, tb: Any) -> None:\n        if self.delete is not None:\n            delete = self.delete\n        elif _tempdir_registry:\n            delete = _tempdir_registry.get_delete(self.kind)\n        else:\n            delete = True\n\n        if delete:\n            self.cleanup()\n\n    def _create(self, kind: str) -> str:\n        \"\"\"Create a temporary directory and store its path in self.path\"\"\"\n        # We realpath here because some systems have their default tmpdir\n        # symlinked to another directory.  This tends to confuse build\n        # scripts, so we canonicalize the path by traversing potential\n        # symlinks here.\n        path = os.path.realpath(tempfile.mkdtemp(prefix=f\"pip-{kind}-\"))\n        logger.debug(\"Created temporary directory: %s\", path)\n        return path\n\n    def cleanup(self) -> None:\n        \"\"\"Remove the temporary directory created and reset state\"\"\"\n        self._deleted = True\n        if not os.path.exists(self._path):\n            return\n\n        errors: list[BaseException] = []\n\n        def onerror(\n            func: Callable[..., Any],\n            path: Path,\n            exc_val: BaseException,\n        ) -> None:\n            \"\"\"Log a warning for a `rmtree` error and continue\"\"\"\n            formatted_exc = \"\\n\".join(\n                traceback.format_exception_only(type(exc_val), exc_val)\n            )\n            formatted_exc = formatted_exc.rstrip()  # remove trailing new line\n            if func in (os.unlink, os.remove, os.rmdir):\n                logger.debug(\n                    \"Failed to remove a temporary file '%s' due to %s.\\n\",\n                    path,\n                    formatted_exc,\n                )\n            else:\n                logger.debug(\"%s failed with %s.\", func.__qualname__, formatted_exc)\n            errors.append(exc_val)\n\n        if self.ignore_cleanup_errors:\n            try:\n                # first try with @retry; retrying to handle ephemeral errors\n                rmtree(self._path, ignore_errors=False)\n            except OSError:\n                # last pass ignore/log all errors\n                rmtree(self._path, onexc=onerror)\n            if errors:\n                logger.warning(\n                    \"Failed to remove contents in a temporary directory '%s'.\\n\"\n                    \"You can safely remove it manually.\",\n                    self._path,\n                )\n        else:\n            rmtree(self._path)\n\n\nclass AdjacentTempDirectory(TempDirectory):\n    \"\"\"Helper class that creates a temporary directory adjacent to a real one.\n\n    Attributes:\n        original\n            The original directory to create a temp directory for.\n        path\n            After calling create() or entering, contains the full\n            path to the temporary directory.\n        delete\n            Whether the directory should be deleted when exiting\n            (when used as a contextmanager)\n\n    \"\"\"\n\n    # The characters that may be used to name the temp directory\n    # We always prepend a ~ and then rotate through these until\n    # a usable name is found.\n    # pkg_resources raises a different error for .dist-info folder\n    # with leading '-' and invalid metadata\n    LEADING_CHARS = \"-~.=%0123456789\"\n\n    def __init__(self, original: str, delete: bool | None = None) -> None:\n        self.original = original.rstrip(\"/\\\\\")\n        super().__init__(delete=delete)\n\n    @classmethod\n    def _generate_names(cls, name: str) -> Generator[str, None, None]:\n        \"\"\"Generates a series of temporary names.\n\n        The algorithm replaces the leading characters in the name\n        with ones that are valid filesystem characters, but are not\n        valid package names (for both Python and pip definitions of\n        package).\n        \"\"\"\n        for i in range(1, len(name)):\n            for candidate in itertools.combinations_with_replacement(\n                cls.LEADING_CHARS, i - 1\n            ):\n                new_name = \"~\" + \"\".join(candidate) + name[i:]\n                if new_name != name:\n                    yield new_name\n\n        # If we make it this far, we will have to make a longer name\n        for i in range(len(cls.LEADING_CHARS)):\n            for candidate in itertools.combinations_with_replacement(\n                cls.LEADING_CHARS, i\n            ):\n                new_name = \"~\" + \"\".join(candidate) + name\n                if new_name != name:\n                    yield new_name\n\n    def _create(self, kind: str) -> str:\n        root, name = os.path.split(self.original)\n        for candidate in self._generate_names(name):\n            path = os.path.join(root, candidate)\n            try:\n                os.mkdir(path)\n            except OSError as ex:\n                # Continue if the name exists already\n                if ex.errno != errno.EEXIST:\n                    raise\n            else:\n                path = os.path.realpath(path)\n                break\n        else:\n            # Final fallback on the default behavior.\n            path = os.path.realpath(tempfile.mkdtemp(prefix=f\"pip-{kind}-\"))\n\n        logger.debug(\"Created temporary directory: %s\", path)\n        return path\n"
  },
  {
    "path": "src/pip/_internal/utils/unpacking.py",
    "content": "\"\"\"Utilities related archives.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport shutil\nimport stat\nimport sys\nimport tarfile\nimport zipfile\nfrom collections.abc import Iterable\nfrom zipfile import ZipInfo\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils.filetypes import (\n    BZ2_EXTENSIONS,\n    TAR_EXTENSIONS,\n    XZ_EXTENSIONS,\n    ZIP_EXTENSIONS,\n)\nfrom pip._internal.utils.misc import ensure_dir\n\nlogger = logging.getLogger(__name__)\n\n\nSUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS\n\ntry:\n    import bz2  # noqa\n\n    SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS\nexcept ImportError:\n    logger.debug(\"bz2 module is not available\")\n\ntry:\n    # Only for Python 3.3+\n    import lzma  # noqa\n\n    SUPPORTED_EXTENSIONS += XZ_EXTENSIONS\nexcept ImportError:\n    logger.debug(\"lzma module is not available\")\n\n\ndef current_umask() -> int:\n    \"\"\"Get the current umask which involves having to set it temporarily.\"\"\"\n    mask = os.umask(0)\n    os.umask(mask)\n    return mask\n\n\ndef split_leading_dir(path: str) -> list[str]:\n    path = path.lstrip(\"/\").lstrip(\"\\\\\")\n    if \"/\" in path and (\n        (\"\\\\\" in path and path.find(\"/\") < path.find(\"\\\\\")) or \"\\\\\" not in path\n    ):\n        return path.split(\"/\", 1)\n    elif \"\\\\\" in path:\n        return path.split(\"\\\\\", 1)\n    else:\n        return [path, \"\"]\n\n\ndef has_leading_dir(paths: Iterable[str]) -> bool:\n    \"\"\"Returns true if all the paths have the same leading path name\n    (i.e., everything is in one subdirectory in an archive)\"\"\"\n    common_prefix = None\n    for path in paths:\n        prefix, rest = split_leading_dir(path)\n        if not prefix:\n            return False\n        elif common_prefix is None:\n            common_prefix = prefix\n        elif prefix != common_prefix:\n            return False\n    return True\n\n\ndef is_within_directory(directory: str, target: str) -> bool:\n    \"\"\"\n    Return true if the absolute path of target is within the directory\n    \"\"\"\n    abs_directory = os.path.abspath(directory)\n    abs_target = os.path.abspath(target)\n\n    prefix = os.path.commonpath([abs_directory, abs_target])\n    return prefix == abs_directory\n\n\ndef _get_default_mode_plus_executable() -> int:\n    return 0o777 & ~current_umask() | 0o111\n\n\ndef set_extracted_file_to_default_mode_plus_executable(path: str) -> None:\n    \"\"\"\n    Make file present at path have execute for user/group/world\n    (chmod +x) is no-op on windows per python docs\n    \"\"\"\n    os.chmod(path, _get_default_mode_plus_executable())\n\n\ndef zip_item_is_executable(info: ZipInfo) -> bool:\n    mode = info.external_attr >> 16\n    # if mode and regular file and any execute permissions for\n    # user/group/world?\n    return bool(mode and stat.S_ISREG(mode) and mode & 0o111)\n\n\ndef unzip_file(filename: str, location: str, flatten: bool = True) -> None:\n    \"\"\"\n    Unzip the file (with path `filename`) to the destination `location`.  All\n    files are written based on system defaults and umask (i.e. permissions are\n    not preserved), except that regular file members with any execute\n    permissions (user, group, or world) have \"chmod +x\" applied after being\n    written. Note that for windows, any execute changes using os.chmod are\n    no-ops per the python docs.\n    \"\"\"\n    ensure_dir(location)\n    zipfp = open(filename, \"rb\")\n    try:\n        zip = zipfile.ZipFile(zipfp, allowZip64=True)\n        leading = has_leading_dir(zip.namelist()) and flatten\n        for info in zip.infolist():\n            name = info.filename\n            fn = name\n            if leading:\n                fn = split_leading_dir(name)[1]\n            fn = os.path.join(location, fn)\n            dir = os.path.dirname(fn)\n            if not is_within_directory(location, fn):\n                message = (\n                    \"The zip file ({}) has a file ({}) trying to install \"\n                    \"outside target directory ({})\"\n                )\n                raise InstallationError(message.format(filename, fn, location))\n            if fn.endswith((\"/\", \"\\\\\")):\n                # A directory\n                ensure_dir(fn)\n            else:\n                ensure_dir(dir)\n                # Don't use read() to avoid allocating an arbitrarily large\n                # chunk of memory for the file's content\n                fp = zip.open(name)\n                try:\n                    with open(fn, \"wb\") as destfp:\n                        shutil.copyfileobj(fp, destfp)\n                finally:\n                    fp.close()\n                    if zip_item_is_executable(info):\n                        set_extracted_file_to_default_mode_plus_executable(fn)\n    finally:\n        zipfp.close()\n\n\ndef untar_file(filename: str, location: str) -> None:\n    \"\"\"\n    Untar the file (with path `filename`) to the destination `location`.\n    All files are written based on system defaults and umask (i.e. permissions\n    are not preserved), except that regular file members with any execute\n    permissions (user, group, or world) have \"chmod +x\" applied on top of the\n    default.  Note that for windows, any execute changes using os.chmod are\n    no-ops per the python docs.\n    \"\"\"\n    ensure_dir(location)\n    if filename.lower().endswith(\".gz\") or filename.lower().endswith(\".tgz\"):\n        mode = \"r:gz\"\n    elif filename.lower().endswith(BZ2_EXTENSIONS):\n        mode = \"r:bz2\"\n    elif filename.lower().endswith(XZ_EXTENSIONS):\n        mode = \"r:xz\"\n    elif filename.lower().endswith(\".tar\"):\n        mode = \"r\"\n    else:\n        logger.warning(\n            \"Cannot determine compression type for file %s\",\n            filename,\n        )\n        mode = \"r:*\"\n\n    tar = tarfile.open(filename, mode, encoding=\"utf-8\")  # type: ignore\n    try:\n        leading = has_leading_dir([member.name for member in tar.getmembers()])\n\n        # PEP 706 added `tarfile.data_filter`, and made some other changes to\n        # Python's tarfile module (see below). The features were backported to\n        # security releases.\n        try:\n            data_filter = tarfile.data_filter\n        except AttributeError:\n            _untar_without_filter(filename, location, tar, leading)\n        else:\n            default_mode_plus_executable = _get_default_mode_plus_executable()\n\n            if leading:\n                # Strip the leading directory from all files in the archive,\n                # including hardlink targets (which are relative to the\n                # unpack location).\n                for member in tar.getmembers():\n                    name_lead, name_rest = split_leading_dir(member.name)\n                    member.name = name_rest\n                    if member.islnk():\n                        lnk_lead, lnk_rest = split_leading_dir(member.linkname)\n                        if lnk_lead == name_lead:\n                            member.linkname = lnk_rest\n\n            def pip_filter(member: tarfile.TarInfo, path: str) -> tarfile.TarInfo:\n                orig_mode = member.mode\n                try:\n                    try:\n                        member = data_filter(member, location)\n                    except tarfile.LinkOutsideDestinationError:\n                        if sys.version_info[:3] in {\n                            (3, 9, 17),\n                            (3, 10, 12),\n                            (3, 11, 4),\n                        }:\n                            # The tarfile filter in specific Python versions\n                            # raises LinkOutsideDestinationError on valid input\n                            # (https://github.com/python/cpython/issues/107845)\n                            # Ignore the error there, but do use the\n                            # more lax `tar_filter`\n                            member = tarfile.tar_filter(member, location)\n                        else:\n                            raise\n                except tarfile.TarError as exc:\n                    message = \"Invalid member in the tar file {}: {}\"\n                    # Filter error messages mention the member name.\n                    # No need to add it here.\n                    raise InstallationError(\n                        message.format(\n                            filename,\n                            exc,\n                        )\n                    )\n                if member.isfile() and orig_mode & 0o111:\n                    member.mode = default_mode_plus_executable\n                else:\n                    # See PEP 706 note above.\n                    # The PEP changed this from `int` to `Optional[int]`,\n                    # where None means \"use the default\". Mypy doesn't\n                    # know this yet.\n                    member.mode = None  # type: ignore [assignment]\n                return member\n\n            tar.extractall(location, filter=pip_filter)\n\n    finally:\n        tar.close()\n\n\ndef is_symlink_target_in_tar(tar: tarfile.TarFile, tarinfo: tarfile.TarInfo) -> bool:\n    \"\"\"Check if the file pointed to by the symbolic link is in the tar archive\"\"\"\n    linkname = os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname)\n\n    linkname = os.path.normpath(linkname)\n    linkname = linkname.replace(\"\\\\\", \"/\")\n\n    try:\n        tar.getmember(linkname)\n        return True\n    except KeyError:\n        return False\n\n\ndef _untar_without_filter(\n    filename: str,\n    location: str,\n    tar: tarfile.TarFile,\n    leading: bool,\n) -> None:\n    \"\"\"Fallback for Python without tarfile.data_filter\"\"\"\n    # NOTE: This function can be removed once pip requires CPython ≥ 3.12.​\n    # PEP 706 added tarfile.data_filter, made tarfile extraction operations more secure.\n    # This feature is fully supported from CPython 3.12 onward.\n    for member in tar.getmembers():\n        fn = member.name\n        if leading:\n            fn = split_leading_dir(fn)[1]\n        path = os.path.join(location, fn)\n        if not is_within_directory(location, path):\n            message = (\n                \"The tar file ({}) has a file ({}) trying to install \"\n                \"outside target directory ({})\"\n            )\n            raise InstallationError(message.format(filename, path, location))\n        if member.isdir():\n            ensure_dir(path)\n        elif member.issym():\n            if not is_symlink_target_in_tar(tar, member):\n                message = (\n                    \"The tar file ({}) has a file ({}) trying to install \"\n                    \"outside target directory ({})\"\n                )\n                raise InstallationError(\n                    message.format(filename, member.name, member.linkname)\n                )\n            try:\n                tar._extract_member(member, path)\n            except Exception as exc:\n                # Some corrupt tar files seem to produce this\n                # (specifically bad symlinks)\n                logger.warning(\n                    \"In the tar file %s the member %s is invalid: %s\",\n                    filename,\n                    member.name,\n                    exc,\n                )\n                continue\n        else:\n            try:\n                fp = tar.extractfile(member)\n            except (KeyError, AttributeError) as exc:\n                # Some corrupt tar files seem to produce this\n                # (specifically bad symlinks)\n                logger.warning(\n                    \"In the tar file %s the member %s is invalid: %s\",\n                    filename,\n                    member.name,\n                    exc,\n                )\n                continue\n            ensure_dir(os.path.dirname(path))\n            assert fp is not None\n            with open(path, \"wb\") as destfp:\n                shutil.copyfileobj(fp, destfp)\n            fp.close()\n            # Update the timestamp (useful for cython compiled files)\n            tar.utime(member, path)\n            # member have any execute permissions for user/group/world?\n            if member.mode & 0o111:\n                set_extracted_file_to_default_mode_plus_executable(path)\n\n\ndef unpack_file(\n    filename: str,\n    location: str,\n    content_type: str | None = None,\n) -> None:\n    filename = os.path.realpath(filename)\n    if (\n        content_type == \"application/zip\"\n        or filename.lower().endswith(ZIP_EXTENSIONS)\n        or zipfile.is_zipfile(filename)\n    ):\n        unzip_file(filename, location, flatten=not filename.endswith(\".whl\"))\n    elif (\n        content_type == \"application/x-gzip\"\n        or tarfile.is_tarfile(filename)\n        or filename.lower().endswith(TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS)\n    ):\n        untar_file(filename, location)\n    else:\n        # FIXME: handle?\n        # FIXME: magic signatures?\n        logger.critical(\n            \"Cannot unpack file %s (downloaded from %s, content-type: %s); \"\n            \"cannot detect archive format\",\n            filename,\n            location,\n            content_type,\n        )\n        raise InstallationError(f\"Cannot determine archive format of {location}\")\n"
  },
  {
    "path": "src/pip/_internal/utils/urls.py",
    "content": "import os\nimport string\nimport urllib.parse\nimport urllib.request\n\nfrom .compat import WINDOWS\n\n\ndef path_to_url(path: str) -> str:\n    \"\"\"\n    Convert a path to a file: URL.  The path will be made absolute and have\n    quoted path parts.\n    \"\"\"\n    path = os.path.normpath(os.path.abspath(path))\n    url = urllib.parse.urljoin(\"file://\", urllib.request.pathname2url(path))\n    return url\n\n\ndef url_to_path(url: str) -> str:\n    \"\"\"\n    Convert a file: URL to a path.\n    \"\"\"\n    assert url.startswith(\n        \"file:\"\n    ), f\"You can only turn file: urls into filenames (not {url!r})\"\n\n    _, netloc, path, _, _ = urllib.parse.urlsplit(url)\n\n    if not netloc or netloc == \"localhost\":\n        # According to RFC 8089, same as empty authority.\n        netloc = \"\"\n    elif WINDOWS:\n        # If we have a UNC path, prepend UNC share notation.\n        netloc = \"\\\\\\\\\" + netloc\n    else:\n        raise ValueError(\n            f\"non-local file URIs are not supported on this platform: {url!r}\"\n        )\n\n    path = urllib.request.url2pathname(netloc + path)\n\n    # On Windows, urlsplit parses the path as something like \"/C:/Users/foo\".\n    # This creates issues for path-related functions like io.open(), so we try\n    # to detect and strip the leading slash.\n    if (\n        WINDOWS\n        and not netloc  # Not UNC.\n        and len(path) >= 3\n        and path[0] == \"/\"  # Leading slash to strip.\n        and path[1] in string.ascii_letters  # Drive letter.\n        and path[2:4] in (\":\", \":/\")  # Colon + end of string, or colon + absolute path.\n    ):\n        path = path[1:]\n\n    return path\n"
  },
  {
    "path": "src/pip/_internal/utils/virtualenv.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport re\nimport site\nimport sys\n\nlogger = logging.getLogger(__name__)\n_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(\n    r\"include-system-site-packages\\s*=\\s*(?P<value>true|false)\"\n)\n\n\ndef _running_under_venv() -> bool:\n    \"\"\"Checks if sys.base_prefix and sys.prefix match.\n\n    This handles PEP 405 compliant virtual environments.\n    \"\"\"\n    return sys.prefix != getattr(sys, \"base_prefix\", sys.prefix)\n\n\ndef _running_under_legacy_virtualenv() -> bool:\n    \"\"\"Checks if sys.real_prefix is set.\n\n    This handles virtual environments created with pypa's virtualenv.\n    \"\"\"\n    # pypa/virtualenv case\n    return hasattr(sys, \"real_prefix\")\n\n\ndef running_under_virtualenv() -> bool:\n    \"\"\"True if we're running inside a virtual environment, False otherwise.\"\"\"\n    return _running_under_venv() or _running_under_legacy_virtualenv()\n\n\ndef _get_pyvenv_cfg_lines() -> list[str] | None:\n    \"\"\"Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines\n\n    Returns None, if it could not read/access the file.\n    \"\"\"\n    pyvenv_cfg_file = os.path.join(sys.prefix, \"pyvenv.cfg\")\n    try:\n        # Although PEP 405 does not specify, the built-in venv module always\n        # writes with UTF-8. (pypa/pip#8717)\n        with open(pyvenv_cfg_file, encoding=\"utf-8\") as f:\n            return f.read().splitlines()  # avoids trailing newlines\n    except OSError:\n        return None\n\n\ndef _no_global_under_venv() -> bool:\n    \"\"\"Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion\n\n    PEP 405 specifies that when system site-packages are not supposed to be\n    visible from a virtual environment, `pyvenv.cfg` must contain the following\n    line:\n\n        include-system-site-packages = false\n\n    Additionally, log a warning if accessing the file fails.\n    \"\"\"\n    cfg_lines = _get_pyvenv_cfg_lines()\n    if cfg_lines is None:\n        # We're not in a \"sane\" venv, so assume there is no system\n        # site-packages access (since that's PEP 405's default state).\n        logger.warning(\n            \"Could not access 'pyvenv.cfg' despite a virtual environment \"\n            \"being active. Assuming global site-packages is not accessible \"\n            \"in this environment.\"\n        )\n        return True\n\n    for line in cfg_lines:\n        match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)\n        if match is not None and match.group(\"value\") == \"false\":\n            return True\n    return False\n\n\ndef _no_global_under_legacy_virtualenv() -> bool:\n    \"\"\"Check if \"no-global-site-packages.txt\" exists beside site.py\n\n    This mirrors logic in pypa/virtualenv for determining whether system\n    site-packages are visible in the virtual environment.\n    \"\"\"\n    site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))\n    no_global_site_packages_file = os.path.join(\n        site_mod_dir,\n        \"no-global-site-packages.txt\",\n    )\n    return os.path.exists(no_global_site_packages_file)\n\n\ndef virtualenv_no_global() -> bool:\n    \"\"\"Returns a boolean, whether running in venv with no system site-packages.\"\"\"\n    # PEP 405 compliance needs to be checked first since virtualenv >=20 would\n    # return True for both checks, but is only able to use the PEP 405 config.\n    if _running_under_venv():\n        return _no_global_under_venv()\n\n    if _running_under_legacy_virtualenv():\n        return _no_global_under_legacy_virtualenv()\n\n    return False\n"
  },
  {
    "path": "src/pip/_internal/utils/wheel.py",
    "content": "\"\"\"Support functions for working with wheel files.\"\"\"\n\nimport logging\nfrom email.message import Message\nfrom email.parser import Parser\nfrom zipfile import BadZipFile, ZipFile\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import UnsupportedWheel\n\nVERSION_COMPATIBLE = (1, 0)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_wheel(wheel_zip: ZipFile, name: str) -> tuple[str, Message]:\n    \"\"\"Extract information from the provided wheel, ensuring it meets basic\n    standards.\n\n    Returns the name of the .dist-info directory and the parsed WHEEL metadata.\n    \"\"\"\n    try:\n        info_dir = wheel_dist_info_dir(wheel_zip, name)\n        metadata = wheel_metadata(wheel_zip, info_dir)\n        version = wheel_version(metadata)\n    except UnsupportedWheel as e:\n        raise UnsupportedWheel(f\"{name} has an invalid wheel, {e}\")\n\n    check_compatibility(version, name)\n\n    return info_dir, metadata\n\n\ndef wheel_dist_info_dir(source: ZipFile, name: str) -> str:\n    \"\"\"Returns the name of the contained .dist-info directory.\n\n    Raises AssertionError or UnsupportedWheel if not found, >1 found, or\n    it doesn't match the provided name.\n    \"\"\"\n    # Zip file path separators must be /\n    subdirs = {p.split(\"/\", 1)[0] for p in source.namelist()}\n\n    info_dirs = [s for s in subdirs if s.endswith(\".dist-info\")]\n\n    if not info_dirs:\n        raise UnsupportedWheel(\".dist-info directory not found\")\n\n    if len(info_dirs) > 1:\n        raise UnsupportedWheel(\n            \"multiple .dist-info directories found: {}\".format(\", \".join(info_dirs))\n        )\n\n    info_dir = info_dirs[0]\n\n    info_dir_name = canonicalize_name(info_dir)\n    canonical_name = canonicalize_name(name)\n    if not info_dir_name.startswith(canonical_name):\n        raise UnsupportedWheel(\n            f\".dist-info directory {info_dir!r} does not start with {canonical_name!r}\"\n        )\n\n    return info_dir\n\n\ndef read_wheel_metadata_file(source: ZipFile, path: str) -> bytes:\n    try:\n        return source.read(path)\n        # BadZipFile for general corruption, KeyError for missing entry,\n        # and RuntimeError for password-protected files\n    except (BadZipFile, KeyError, RuntimeError) as e:\n        raise UnsupportedWheel(f\"could not read {path!r} file: {e!r}\")\n\n\ndef wheel_metadata(source: ZipFile, dist_info_dir: str) -> Message:\n    \"\"\"Return the WHEEL metadata of an extracted wheel, if possible.\n    Otherwise, raise UnsupportedWheel.\n    \"\"\"\n    path = f\"{dist_info_dir}/WHEEL\"\n    # Zip file path separators must be /\n    wheel_contents = read_wheel_metadata_file(source, path)\n\n    try:\n        wheel_text = wheel_contents.decode()\n    except UnicodeDecodeError as e:\n        raise UnsupportedWheel(f\"error decoding {path!r}: {e!r}\")\n\n    # FeedParser (used by Parser) does not raise any exceptions. The returned\n    # message may have .defects populated, but for backwards-compatibility we\n    # currently ignore them.\n    return Parser().parsestr(wheel_text)\n\n\ndef wheel_version(wheel_data: Message) -> tuple[int, ...]:\n    \"\"\"Given WHEEL metadata, return the parsed Wheel-Version.\n    Otherwise, raise UnsupportedWheel.\n    \"\"\"\n    version_text = wheel_data[\"Wheel-Version\"]\n    if version_text is None:\n        raise UnsupportedWheel(\"WHEEL is missing Wheel-Version\")\n\n    version = version_text.strip()\n\n    try:\n        return tuple(map(int, version.split(\".\")))\n    except ValueError:\n        raise UnsupportedWheel(f\"invalid Wheel-Version: {version!r}\")\n\n\ndef check_compatibility(version: tuple[int, ...], name: str) -> None:\n    \"\"\"Raises errors or warns if called with an incompatible Wheel-Version.\n\n    pip should refuse to install a Wheel-Version that's a major series\n    ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when\n    installing a version only minor version ahead (e.g 1.2 > 1.1).\n\n    version: a 2-tuple representing a Wheel-Version (Major, Minor)\n    name: name of wheel or package to raise exception about\n\n    :raises UnsupportedWheel: when an incompatible Wheel-Version is given\n    \"\"\"\n    if version[0] > VERSION_COMPATIBLE[0]:\n        raise UnsupportedWheel(\n            \"{}'s Wheel-Version ({}) is not compatible with this version \"\n            \"of pip\".format(name, \".\".join(map(str, version)))\n        )\n    elif version > VERSION_COMPATIBLE:\n        logger.warning(\n            \"Installing from a newer Wheel-Version (%s)\",\n            \".\".join(map(str, version)),\n        )\n"
  },
  {
    "path": "src/pip/_internal/vcs/__init__.py",
    "content": "# Expose a limited set of classes and functions so callers outside of\n# the vcs package don't need to import deeper than `pip._internal.vcs`.\n# (The test directory may still need to import from a vcs sub-package.)\n# Import all vcs modules to register each VCS in the VcsSupport object.\nimport pip._internal.vcs.bazaar\nimport pip._internal.vcs.git\nimport pip._internal.vcs.mercurial\nimport pip._internal.vcs.subversion  # noqa: F401\nfrom pip._internal.vcs.versioncontrol import (  # noqa: F401\n    RemoteNotFoundError,\n    RemoteNotValidError,\n    is_url,\n    make_vcs_requirement_url,\n    vcs,\n)\n"
  },
  {
    "path": "src/pip/_internal/vcs/bazaar.py",
    "content": "from __future__ import annotations\n\nimport logging\n\nfrom pip._internal.utils.misc import HiddenText, display_path\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RevOptions,\n    VersionControl,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Bazaar(VersionControl):\n    name = \"bzr\"\n    dirname = \".bzr\"\n    repo_name = \"branch\"\n    schemes = (\n        \"bzr+http\",\n        \"bzr+https\",\n        \"bzr+ssh\",\n        \"bzr+sftp\",\n        \"bzr+ftp\",\n        \"bzr+lp\",\n        \"bzr+file\",\n    )\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> list[str]:\n        return [\"-r\", rev]\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Checking out %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flags = [\"--quiet\"]\n        elif verbosity == 1:\n            flags = []\n        else:\n            flags = [f\"-{'v'*verbosity}\"]\n        cmd_args = make_command(\n            \"checkout\", \"--lightweight\", *flags, rev_options.to_args(), url, dest\n        )\n        self.run_command(cmd_args)\n\n    def switch(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        self.run_command(make_command(\"switch\", url), cwd=dest)\n\n    def update(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        flags = []\n\n        if verbosity <= 0:\n            flags.append(\"-q\")\n\n        output = self.run_command(\n            make_command(\"info\"), show_stdout=False, stdout_only=True, cwd=dest\n        )\n        if output.startswith(\"Standalone \"):\n            # Older versions of pip used to create standalone branches.\n            # Convert the standalone branch to a checkout by calling \"bzr bind\".\n            cmd_args = make_command(\"bind\", *flags, url)\n            self.run_command(cmd_args, cwd=dest)\n\n        cmd_args = make_command(\"update\", *flags, rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:\n        # hotfix the URL scheme after removing bzr+ from bzr+ssh:// re-add it\n        url, rev, user_pass = super().get_url_rev_and_auth(url)\n        if url.startswith(\"ssh://\"):\n            url = \"bzr+\" + url\n        return url, rev, user_pass\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        urls = cls.run_command(\n            [\"info\"], show_stdout=False, stdout_only=True, cwd=location\n        )\n        for line in urls.splitlines():\n            line = line.strip()\n            for x in (\"checkout of branch: \", \"parent branch: \"):\n                if line.startswith(x):\n                    repo = line.split(x)[1]\n                    if cls._is_local_repository(repo):\n                        return path_to_url(repo)\n                    return repo\n        raise RemoteNotFoundError\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        revision = cls.run_command(\n            [\"revno\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        return revision.splitlines()[-1]\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n\nvcs.register(Bazaar)\n"
  },
  {
    "path": "src/pip/_internal/vcs/git.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os.path\nimport pathlib\nimport re\nimport urllib.parse\nimport urllib.request\nfrom dataclasses import replace\nfrom typing import Any\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import HiddenText, display_path, hide_url\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RemoteNotValidError,\n    RevOptions,\n    VersionControl,\n    find_path_to_project_root_from_repo_root,\n    vcs,\n)\n\nurlsplit = urllib.parse.urlsplit\nurlunsplit = urllib.parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nGIT_VERSION_REGEX = re.compile(\n    r\"^git version \"  # Prefix.\n    r\"(\\d+)\"  # Major.\n    r\"\\.(\\d+)\"  # Dot, minor.\n    r\"(?:\\.(\\d+))?\"  # Optional dot, patch.\n    r\".*$\"  # Suffix, including any pre- and post-release segments we don't care about.\n)\n\nHASH_REGEX = re.compile(\"^[a-fA-F0-9]{40}$\")\n\n# SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git'\nSCP_REGEX = re.compile(\n    r\"\"\"^\n    # Optional user, e.g. 'git@'\n    (\\w+@)?\n    # Server, e.g. 'github.com'.\n    ([^/:]+):\n    # The server-side path. e.g. 'user/project.git'. Must start with an\n    # alphanumeric character so as not to be confusable with a Windows paths\n    # like 'C:/foo/bar' or 'C:\\foo\\bar'.\n    (\\w[^:]*)\n    $\"\"\",\n    re.VERBOSE,\n)\n\n\ndef looks_like_hash(sha: str) -> bool:\n    return bool(HASH_REGEX.match(sha))\n\n\nclass Git(VersionControl):\n    name = \"git\"\n    dirname = \".git\"\n    repo_name = \"clone\"\n    schemes = (\n        \"git+http\",\n        \"git+https\",\n        \"git+ssh\",\n        \"git+git\",\n        \"git+file\",\n    )\n    # Prevent the user's environment variables from interfering with pip:\n    # https://github.com/pypa/pip/issues/1130\n    unset_environ = (\"GIT_DIR\", \"GIT_WORK_TREE\")\n    default_arg_rev = \"HEAD\"\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> list[str]:\n        return [rev]\n\n    @classmethod\n    def run_command(cls, *args: Any, **kwargs: Any) -> str:\n        if os.environ.get(\"PIP_NO_INPUT\"):\n            extra_environ = kwargs.get(\"extra_environ\", {})\n            extra_environ[\"GIT_TERMINAL_PROMPT\"] = \"0\"\n            extra_environ[\"GIT_SSH_COMMAND\"] = \"ssh -oBatchMode=yes\"\n            kwargs[\"extra_environ\"] = extra_environ\n        return super().run_command(*args, **kwargs)\n\n    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:\n        _, rev_options = self.get_url_rev_options(hide_url(url))\n        if not rev_options.rev:\n            return False\n        if not self.is_commit_id_equal(dest, rev_options.rev):\n            # the current commit is different from rev,\n            # which means rev was something else than a commit hash\n            return False\n        # return False in the rare case rev is both a commit hash\n        # and a tag or a branch; we don't want to cache in that case\n        # because that branch/tag could point to something else in the future\n        is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0])\n        return not is_tag_or_branch\n\n    def get_git_version(self) -> tuple[int, ...]:\n        version = self.run_command(\n            [\"version\"],\n            command_desc=\"git version\",\n            show_stdout=False,\n            stdout_only=True,\n        )\n        match = GIT_VERSION_REGEX.match(version)\n        if not match:\n            logger.warning(\"Can't parse git version: %s\", version)\n            return ()\n        return (int(match.group(1)), int(match.group(2)))\n\n    @classmethod\n    def get_current_branch(cls, location: str) -> str | None:\n        \"\"\"\n        Return the current branch, or None if HEAD isn't at a branch\n        (e.g. detached HEAD).\n        \"\"\"\n        # git-symbolic-ref exits with empty stdout if \"HEAD\" is a detached\n        # HEAD rather than a symbolic ref.  In addition, the -q causes the\n        # command to exit with status code 1 instead of 128 in this case\n        # and to suppress the message to stderr.\n        args = [\"symbolic-ref\", \"-q\", \"HEAD\"]\n        output = cls.run_command(\n            args,\n            extra_ok_returncodes=(1,),\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        ref = output.strip()\n\n        if ref.startswith(\"refs/heads/\"):\n            return ref[len(\"refs/heads/\") :]\n\n        return None\n\n    @classmethod\n    def get_revision_sha(cls, dest: str, rev: str) -> tuple[str | None, bool]:\n        \"\"\"\n        Return (sha_or_none, is_branch), where sha_or_none is a commit hash\n        if the revision names a remote branch or tag, otherwise None.\n\n        Args:\n          dest: the repository directory.\n          rev: the revision name.\n        \"\"\"\n        # Pass rev to pre-filter the list.\n        output = cls.run_command(\n            [\"show-ref\", rev],\n            cwd=dest,\n            show_stdout=False,\n            stdout_only=True,\n            on_returncode=\"ignore\",\n        )\n        refs = {}\n        # NOTE: We do not use splitlines here since that would split on other\n        #       unicode separators, which can be maliciously used to install a\n        #       different revision.\n        for line in output.strip().split(\"\\n\"):\n            line = line.rstrip(\"\\r\")\n            if not line:\n                continue\n            try:\n                ref_sha, ref_name = line.split(\" \", maxsplit=2)\n            except ValueError:\n                # Include the offending line to simplify troubleshooting if\n                # this error ever occurs.\n                raise ValueError(f\"unexpected show-ref line: {line!r}\")\n\n            refs[ref_name] = ref_sha\n\n        branch_ref = f\"refs/remotes/origin/{rev}\"\n        tag_ref = f\"refs/tags/{rev}\"\n\n        sha = refs.get(branch_ref)\n        if sha is not None:\n            return (sha, True)\n\n        sha = refs.get(tag_ref)\n\n        return (sha, False)\n\n    @classmethod\n    def _should_fetch(cls, dest: str, rev: str) -> bool:\n        \"\"\"\n        Return true if rev is a ref or is a commit that we don't have locally.\n\n        Branches and tags are not considered in this method because they are\n        assumed to be always available locally (which is a normal outcome of\n        ``git clone`` and ``git fetch --tags``).\n        \"\"\"\n        if rev.startswith(\"refs/\"):\n            # Always fetch remote refs.\n            return True\n\n        if not looks_like_hash(rev):\n            # Git fetch would fail with abbreviated commits.\n            return False\n\n        if cls.has_commit(dest, rev):\n            # Don't fetch if we have the commit locally.\n            return False\n\n        return True\n\n    @classmethod\n    def resolve_revision(\n        cls, dest: str, url: HiddenText, rev_options: RevOptions\n    ) -> RevOptions:\n        \"\"\"\n        Resolve a revision to a new RevOptions object with the SHA1 of the\n        branch, tag, or ref if found.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        rev = rev_options.arg_rev\n        # The arg_rev property's implementation for Git ensures that the\n        # rev return value is always non-None.\n        assert rev is not None\n\n        sha, is_branch = cls.get_revision_sha(dest, rev)\n\n        if sha is not None:\n            rev_options = rev_options.make_new(sha)\n            rev_options = replace(rev_options, branch_name=(rev if is_branch else None))\n\n            return rev_options\n\n        # Do not show a warning for the common case of something that has\n        # the form of a Git commit hash.\n        if not looks_like_hash(rev):\n            logger.info(\n                \"Did not find branch or tag '%s', assuming revision or ref.\",\n                rev,\n            )\n\n        if not cls._should_fetch(dest, rev):\n            return rev_options\n\n        # fetch the requested revision\n        cls.run_command(\n            make_command(\"fetch\", \"-q\", url, rev_options.to_args()),\n            cwd=dest,\n        )\n        # Change the revision to the SHA of the ref we fetched\n        sha = cls.get_revision(dest, rev=\"FETCH_HEAD\")\n        rev_options = rev_options.make_new(sha)\n\n        return rev_options\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:\n        \"\"\"\n        Return whether the current commit hash equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        if not name:\n            # Then avoid an unnecessary subprocess call.\n            return False\n\n        return cls.get_revision(dest) == name\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\"Cloning %s%s to %s\", url, rev_display, display_path(dest))\n        if verbosity <= 0:\n            flags: tuple[str, ...] = (\"--quiet\",)\n        elif verbosity == 1:\n            flags = ()\n        else:\n            flags = (\"--verbose\", \"--progress\")\n        if self.get_git_version() >= (2, 17):\n            # Git added support for partial clone in 2.17\n            # https://git-scm.com/docs/partial-clone\n            # Speeds up cloning by functioning without a complete copy of repository\n            self.run_command(\n                make_command(\n                    \"clone\",\n                    \"--filter=blob:none\",\n                    *flags,\n                    url,\n                    dest,\n                )\n            )\n        else:\n            self.run_command(make_command(\"clone\", *flags, url, dest))\n\n        if rev_options.rev:\n            # Then a specific revision was requested.\n            rev_options = self.resolve_revision(dest, url, rev_options)\n            branch_name = getattr(rev_options, \"branch_name\", None)\n            logger.debug(\"Rev options %s, branch_name %s\", rev_options, branch_name)\n            if branch_name is None:\n                # Only do a checkout if the current commit id doesn't match\n                # the requested revision.\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    cmd_args = make_command(\n                        \"checkout\",\n                        \"-q\",\n                        rev_options.to_args(),\n                    )\n                    self.run_command(cmd_args, cwd=dest)\n            elif self.get_current_branch(dest) != branch_name:\n                # Then a specific branch was requested, and that branch\n                # is not yet checked out.\n                track_branch = f\"origin/{branch_name}\"\n                cmd_args = [\n                    \"checkout\",\n                    \"-b\",\n                    branch_name,\n                    \"--track\",\n                    track_branch,\n                ]\n                self.run_command(cmd_args, cwd=dest)\n        else:\n            sha = self.get_revision(dest)\n            rev_options = rev_options.make_new(sha)\n\n        logger.info(\"Resolved %s to commit %s\", url, rev_options.rev)\n\n        #: repo may contain submodules\n        self.update_submodules(dest, verbosity=verbosity)\n\n    def switch(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        self.run_command(\n            make_command(\"config\", \"remote.origin.url\", url),\n            cwd=dest,\n        )\n\n        extra_flags = []\n\n        if verbosity <= 0:\n            extra_flags.append(\"-q\")\n\n        cmd_args = make_command(\"checkout\", *extra_flags, rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n        self.update_submodules(dest, verbosity=verbosity)\n\n    def update(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        extra_flags = []\n\n        if verbosity <= 0:\n            extra_flags.append(\"-q\")\n\n        # First fetch changes from the default remote\n        if self.get_git_version() >= (1, 9):\n            # fetch tags in addition to everything else\n            self.run_command([\"fetch\", \"--tags\", *extra_flags], cwd=dest)\n        else:\n            self.run_command([\"fetch\", *extra_flags], cwd=dest)\n        # Then reset to wanted revision (maybe even origin/master)\n        rev_options = self.resolve_revision(dest, url, rev_options)\n        cmd_args = make_command(\n            \"reset\",\n            \"--hard\",\n            *extra_flags,\n            rev_options.to_args(),\n        )\n        self.run_command(cmd_args, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest, verbosity=verbosity)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        \"\"\"\n        Return URL of the first remote encountered.\n\n        Raises RemoteNotFoundError if the repository does not have a remote\n        url configured.\n        \"\"\"\n        # We need to pass 1 for extra_ok_returncodes since the command\n        # exits with return code 1 if there are no matching lines.\n        stdout = cls.run_command(\n            [\"config\", \"--get-regexp\", r\"remote\\..*\\.url\"],\n            extra_ok_returncodes=(1,),\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        remotes = stdout.splitlines()\n        try:\n            found_remote = remotes[0]\n        except IndexError:\n            raise RemoteNotFoundError\n\n        for remote in remotes:\n            if remote.startswith(\"remote.origin.url \"):\n                found_remote = remote\n                break\n        url = found_remote.split(\" \")[1]\n        return cls._git_remote_to_pip_url(url.strip())\n\n    @staticmethod\n    def _git_remote_to_pip_url(url: str) -> str:\n        \"\"\"\n        Convert a remote url from what git uses to what pip accepts.\n\n        There are 3 legal forms **url** may take:\n\n            1. A fully qualified url: ssh://git@example.com/foo/bar.git\n            2. A local project.git folder: /path/to/bare/repository.git\n            3. SCP shorthand for form 1: git@example.com:foo/bar.git\n\n        Form 1 is output as-is. Form 2 must be converted to URI and form 3 must\n        be converted to form 1.\n\n        See the corresponding test test_git_remote_url_to_pip() for examples of\n        sample inputs/outputs.\n        \"\"\"\n        if re.match(r\"\\w+://\", url):\n            # This is already valid. Pass it though as-is.\n            return url\n        if os.path.exists(url):\n            # A local bare remote (git clone --mirror).\n            # Needs a file:// prefix.\n            return pathlib.PurePath(url).as_uri()\n        scp_match = SCP_REGEX.match(url)\n        if scp_match:\n            # Add an ssh:// prefix and replace the ':' with a '/'.\n            return scp_match.expand(r\"ssh://\\1\\2/\\3\")\n        # Otherwise, bail out.\n        raise RemoteNotValidError(url)\n\n    @classmethod\n    def has_commit(cls, location: str, rev: str) -> bool:\n        \"\"\"\n        Check if rev is a commit that is available in the local repository.\n        \"\"\"\n        try:\n            cls.run_command(\n                [\"rev-parse\", \"-q\", \"--verify\", \"sha^\" + rev],\n                cwd=location,\n                log_failed_cmd=False,\n            )\n        except InstallationError:\n            return False\n        else:\n            return True\n\n    @classmethod\n    def get_revision(cls, location: str, rev: str | None = None) -> str:\n        if rev is None:\n            rev = \"HEAD\"\n        current_rev = cls.run_command(\n            [\"rev-parse\", rev],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        return current_rev.strip()\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> str | None:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        # find the repo root\n        git_dir = cls.run_command(\n            [\"rev-parse\", \"--git-dir\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        if not os.path.isabs(git_dir):\n            git_dir = os.path.join(location, git_dir)\n        repo_root = os.path.abspath(os.path.join(git_dir, \"..\"))\n        return find_path_to_project_root_from_repo_root(location, repo_root)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:\n        \"\"\"\n        Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.\n        That's required because although they use SSH they sometimes don't\n        work with a ssh:// scheme (e.g. GitHub). But we need a scheme for\n        parsing. Hence we remove it again afterwards and return it as a stub.\n        \"\"\"\n        # Works around an apparent Git bug\n        # (see https://article.gmane.org/gmane.comp.version-control.git/146500)\n        scheme, netloc, path, query, fragment = urlsplit(url)\n        if scheme.endswith(\"file\"):\n            initial_slashes = path[: -len(path.lstrip(\"/\"))]\n            newpath = initial_slashes + urllib.request.url2pathname(path).replace(\n                \"\\\\\", \"/\"\n            ).lstrip(\"/\")\n            after_plus = scheme.find(\"+\") + 1\n            url = scheme[:after_plus] + urlunsplit(\n                (scheme[after_plus:], netloc, newpath, query, fragment),\n            )\n\n        if \"://\" not in url:\n            assert \"file:\" not in url\n            url = url.replace(\"git+\", \"git+ssh://\")\n            url, rev, user_pass = super().get_url_rev_and_auth(url)\n            url = url.replace(\"ssh://\", \"\")\n        else:\n            url, rev, user_pass = super().get_url_rev_and_auth(url)\n\n        return url, rev, user_pass\n\n    @classmethod\n    def update_submodules(cls, location: str, verbosity: int = 0) -> None:\n        argv = [\"submodule\", \"update\", \"--init\", \"--recursive\"]\n\n        if verbosity <= 0:\n            argv.append(\"-q\")\n\n        if not os.path.exists(os.path.join(location, \".gitmodules\")):\n            return\n        cls.run_command(\n            argv,\n            cwd=location,\n        )\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> str | None:\n        loc = super().get_repository_root(location)\n        if loc:\n            return loc\n        try:\n            r = cls.run_command(\n                [\"rev-parse\", \"--show-toplevel\"],\n                cwd=location,\n                show_stdout=False,\n                stdout_only=True,\n                on_returncode=\"raise\",\n                log_failed_cmd=False,\n            )\n        except BadCommand:\n            logger.debug(\n                \"could not determine if %s is under git control \"\n                \"because git is not available\",\n                location,\n            )\n            return None\n        except InstallationError:\n            return None\n        return os.path.normpath(r.rstrip(\"\\r\\n\"))\n\n    @staticmethod\n    def should_add_vcs_url_prefix(repo_url: str) -> bool:\n        \"\"\"In either https or ssh form, requirements must be prefixed with git+.\"\"\"\n        return True\n\n\nvcs.register(Git)\n"
  },
  {
    "path": "src/pip/_internal/vcs/mercurial.py",
    "content": "from __future__ import annotations\n\nimport configparser\nimport logging\nimport os\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import HiddenText, display_path\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs.versioncontrol import (\n    RevOptions,\n    VersionControl,\n    find_path_to_project_root_from_repo_root,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Mercurial(VersionControl):\n    name = \"hg\"\n    dirname = \".hg\"\n    repo_name = \"clone\"\n    schemes = (\n        \"hg+file\",\n        \"hg+http\",\n        \"hg+https\",\n        \"hg+ssh\",\n        \"hg+static-http\",\n    )\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> list[str]:\n        return [f\"--rev={rev}\"]\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Cloning hg %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flags: tuple[str, ...] = (\"--quiet\",)\n        elif verbosity == 1:\n            flags = ()\n        elif verbosity == 2:\n            flags = (\"--verbose\",)\n        else:\n            flags = (\"--verbose\", \"--debug\")\n        self.run_command(make_command(\"clone\", \"--noupdate\", *flags, url, dest))\n        self.run_command(\n            make_command(\"update\", *flags, rev_options.to_args()),\n            cwd=dest,\n        )\n\n    def switch(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        extra_flags = []\n        repo_config = os.path.join(dest, self.dirname, \"hgrc\")\n        config = configparser.RawConfigParser()\n\n        if verbosity <= 0:\n            extra_flags.append(\"-q\")\n\n        try:\n            config.read(repo_config)\n            config.set(\"paths\", \"default\", url.secret)\n            with open(repo_config, \"w\") as config_file:\n                config.write(config_file)\n        except (OSError, configparser.NoSectionError) as exc:\n            logger.warning(\"Could not switch Mercurial repository to %s: %s\", url, exc)\n        else:\n            cmd_args = make_command(\"update\", *extra_flags, rev_options.to_args())\n            self.run_command(cmd_args, cwd=dest)\n\n    def update(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        extra_flags = []\n\n        if verbosity <= 0:\n            extra_flags.append(\"-q\")\n\n        self.run_command([\"pull\", *extra_flags], cwd=dest)\n        cmd_args = make_command(\"update\", *extra_flags, rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        url = cls.run_command(\n            [\"showconfig\", \"paths.default\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        if cls._is_local_repository(url):\n            url = path_to_url(url)\n        return url.strip()\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the repository-local changeset revision number, as an integer.\n        \"\"\"\n        current_revision = cls.run_command(\n            [\"parents\", \"--template={rev}\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        return current_revision\n\n    @classmethod\n    def get_requirement_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the changeset identification hash, as a 40-character\n        hexadecimal string\n        \"\"\"\n        current_rev_hash = cls.run_command(\n            [\"parents\", \"--template={node}\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        return current_rev_hash\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> str | None:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        # find the repo root\n        repo_root = cls.run_command(\n            [\"root\"], show_stdout=False, stdout_only=True, cwd=location\n        ).strip()\n        if not os.path.isabs(repo_root):\n            repo_root = os.path.abspath(os.path.join(location, repo_root))\n        return find_path_to_project_root_from_repo_root(location, repo_root)\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> str | None:\n        loc = super().get_repository_root(location)\n        if loc:\n            return loc\n        try:\n            r = cls.run_command(\n                [\"root\"],\n                cwd=location,\n                show_stdout=False,\n                stdout_only=True,\n                on_returncode=\"raise\",\n                log_failed_cmd=False,\n            )\n        except BadCommand:\n            logger.debug(\n                \"could not determine if %s is under hg control \"\n                \"because hg is not available\",\n                location,\n            )\n            return None\n        except InstallationError:\n            return None\n        return os.path.normpath(r.rstrip(\"\\r\\n\"))\n\n\nvcs.register(Mercurial)\n"
  },
  {
    "path": "src/pip/_internal/vcs/subversion.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport re\n\nfrom pip._internal.utils.misc import (\n    HiddenText,\n    display_path,\n    is_console_interactive,\n    is_installable_dir,\n    split_auth_from_netloc,\n)\nfrom pip._internal.utils.subprocess import CommandArgs, make_command\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RevOptions,\n    VersionControl,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n_svn_xml_url_re = re.compile('url=\"([^\"]+)\"')\n_svn_rev_re = re.compile(r'committed-rev=\"(\\d+)\"')\n_svn_info_xml_rev_re = re.compile(r'\\s*revision=\"(\\d+)\"')\n_svn_info_xml_url_re = re.compile(r\"<url>(.*)</url>\")\n\n\nclass Subversion(VersionControl):\n    name = \"svn\"\n    dirname = \".svn\"\n    repo_name = \"checkout\"\n    schemes = (\"svn+ssh\", \"svn+http\", \"svn+https\", \"svn+svn\", \"svn+file\")\n\n    @classmethod\n    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:\n        return True\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> list[str]:\n        return [\"-r\", rev]\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the maximum revision for all files under a given location\n        \"\"\"\n        # Note: taken from setuptools.command.egg_info\n        revision = 0\n\n        for base, dirs, _ in os.walk(location):\n            if cls.dirname not in dirs:\n                dirs[:] = []\n                continue  # no sense walking uncontrolled subdirs\n            dirs.remove(cls.dirname)\n            entries_fn = os.path.join(base, cls.dirname, \"entries\")\n            if not os.path.exists(entries_fn):\n                # FIXME: should we warn?\n                continue\n\n            dirurl, localrev = cls._get_svn_url_rev(base)\n\n            if base == location:\n                assert dirurl is not None\n                base = dirurl + \"/\"  # save the root url\n            elif not dirurl or not dirurl.startswith(base):\n                dirs[:] = []\n                continue  # not part of the same svn tree, skip it\n            revision = max(revision, localrev)\n        return str(revision)\n\n    @classmethod\n    def get_netloc_and_auth(\n        cls, netloc: str, scheme: str\n    ) -> tuple[str, tuple[str | None, str | None]]:\n        \"\"\"\n        This override allows the auth information to be passed to svn via the\n        --username and --password options instead of via the URL.\n        \"\"\"\n        if scheme == \"ssh\":\n            # The --username and --password options can't be used for\n            # svn+ssh URLs, so keep the auth information in the URL.\n            return super().get_netloc_and_auth(netloc, scheme)\n\n        return split_auth_from_netloc(netloc)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:\n        # hotfix the URL scheme after removing svn+ from svn+ssh:// re-add it\n        url, rev, user_pass = super().get_url_rev_and_auth(url)\n        if url.startswith(\"ssh://\"):\n            url = \"svn+\" + url\n        return url, rev, user_pass\n\n    @staticmethod\n    def make_rev_args(username: str | None, password: HiddenText | None) -> CommandArgs:\n        extra_args: CommandArgs = []\n        if username:\n            extra_args += [\"--username\", username]\n        if password:\n            extra_args += [\"--password\", password]\n\n        return extra_args\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        # In cases where the source is in a subdirectory, we have to look up in\n        # the location until we find a valid project root.\n        orig_location = location\n        while not is_installable_dir(location):\n            last_location = location\n            location = os.path.dirname(location)\n            if location == last_location:\n                # We've traversed up to the root of the filesystem without\n                # finding a Python project.\n                logger.warning(\n                    \"Could not find Python project for directory %s (tried all \"\n                    \"parent directories)\",\n                    orig_location,\n                )\n                raise RemoteNotFoundError\n\n        url, _rev = cls._get_svn_url_rev(location)\n        if url is None:\n            raise RemoteNotFoundError\n\n        return url\n\n    @classmethod\n    def _get_svn_url_rev(cls, location: str) -> tuple[str | None, int]:\n        from pip._internal.exceptions import InstallationError\n\n        entries_path = os.path.join(location, cls.dirname, \"entries\")\n        if os.path.exists(entries_path):\n            with open(entries_path) as f:\n                data = f.read()\n        else:  # subversion >= 1.7 does not have the 'entries' file\n            data = \"\"\n\n        url = None\n        if data.startswith((\"8\", \"9\", \"10\")):\n            entries = list(map(str.splitlines, data.split(\"\\n\\x0c\\n\")))\n            del entries[0][0]  # get rid of the '8'\n            url = entries[0][3]\n            revs = [int(d[9]) for d in entries if len(d) > 9 and d[9]] + [0]\n        elif data.startswith(\"<?xml\"):\n            match = _svn_xml_url_re.search(data)\n            if not match:\n                raise ValueError(f\"Badly formatted data: {data!r}\")\n            url = match.group(1)  # get repository URL\n            revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]\n        else:\n            try:\n                # subversion >= 1.7\n                # Note that using get_remote_call_options is not necessary here\n                # because `svn info` is being run against a local directory.\n                # We don't need to worry about making sure interactive mode\n                # is being used to prompt for passwords, because passwords\n                # are only potentially needed for remote server requests.\n                xml = cls.run_command(\n                    [\"info\", \"--xml\", location],\n                    show_stdout=False,\n                    stdout_only=True,\n                )\n                match = _svn_info_xml_url_re.search(xml)\n                assert match is not None\n                url = match.group(1)\n                revs = [int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)]\n            except InstallationError:\n                url, revs = None, []\n\n        if revs:\n            rev = max(revs)\n        else:\n            rev = 0\n\n        return url, rev\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n    def __init__(self, use_interactive: bool | None = None) -> None:\n        if use_interactive is None:\n            use_interactive = is_console_interactive()\n        self.use_interactive = use_interactive\n\n        # This member is used to cache the fetched version of the current\n        # ``svn`` client.\n        # Special value definitions:\n        #   None: Not evaluated yet.\n        #   Empty tuple: Could not parse version.\n        self._vcs_version: tuple[int, ...] | None = None\n\n        super().__init__()\n\n    def call_vcs_version(self) -> tuple[int, ...]:\n        \"\"\"Query the version of the currently installed Subversion client.\n\n        :return: A tuple containing the parts of the version information or\n            ``()`` if the version returned from ``svn`` could not be parsed.\n        :raises: BadCommand: If ``svn`` is not installed.\n        \"\"\"\n        # Example versions:\n        #   svn, version 1.10.3 (r1842928)\n        #      compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0\n        #   svn, version 1.7.14 (r1542130)\n        #      compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu\n        #   svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)\n        #      compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2\n        version_prefix = \"svn, version \"\n        version = self.run_command([\"--version\"], show_stdout=False, stdout_only=True)\n        if not version.startswith(version_prefix):\n            return ()\n\n        version = version[len(version_prefix) :].split()[0]\n        version_list = version.partition(\"-\")[0].split(\".\")\n        try:\n            parsed_version = tuple(map(int, version_list))\n        except ValueError:\n            return ()\n\n        return parsed_version\n\n    def get_vcs_version(self) -> tuple[int, ...]:\n        \"\"\"Return the version of the currently installed Subversion client.\n\n        If the version of the Subversion client has already been queried,\n        a cached value will be used.\n\n        :return: A tuple containing the parts of the version information or\n            ``()`` if the version returned from ``svn`` could not be parsed.\n        :raises: BadCommand: If ``svn`` is not installed.\n        \"\"\"\n        if self._vcs_version is not None:\n            # Use cached version, if available.\n            # If parsing the version failed previously (empty tuple),\n            # do not attempt to parse it again.\n            return self._vcs_version\n\n        vcs_version = self.call_vcs_version()\n        self._vcs_version = vcs_version\n        return vcs_version\n\n    def get_remote_call_options(self) -> CommandArgs:\n        \"\"\"Return options to be used on calls to Subversion that contact the server.\n\n        These options are applicable for the following ``svn`` subcommands used\n        in this class.\n\n            - checkout\n            - switch\n            - update\n\n        :return: A list of command line arguments to pass to ``svn``.\n        \"\"\"\n        if not self.use_interactive:\n            # --non-interactive switch is available since Subversion 0.14.4.\n            # Subversion < 1.8 runs in interactive mode by default.\n            return [\"--non-interactive\"]\n\n        svn_version = self.get_vcs_version()\n        # By default, Subversion >= 1.8 runs in non-interactive mode if\n        # stdin is not a TTY. Since that is how pip invokes SVN, in\n        # call_subprocess(), pip must pass --force-interactive to ensure\n        # the user can be prompted for a password, if required.\n        #   SVN added the --force-interactive option in SVN 1.8. Since\n        # e.g. RHEL/CentOS 7, which is supported until 2024, ships with\n        # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip\n        # can't safely add the option if the SVN version is < 1.8 (or unknown).\n        if svn_version >= (1, 8):\n            return [\"--force-interactive\"]\n\n        return []\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Checking out %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flags = [\"--quiet\"]\n        else:\n            flags = []\n        cmd_args = make_command(\n            \"checkout\",\n            *flags,\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            url,\n            dest,\n        )\n        self.run_command(cmd_args)\n\n    def switch(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        cmd_args = make_command(\n            \"switch\",\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            url,\n            dest,\n        )\n        self.run_command(cmd_args)\n\n    def update(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        cmd_args = make_command(\n            \"update\",\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            dest,\n        )\n        self.run_command(cmd_args)\n\n\nvcs.register(Subversion)\n"
  },
  {
    "path": "src/pip/_internal/vcs/versioncontrol.py",
    "content": "\"\"\"Handles all VCS (version control) support\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport urllib.parse\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom dataclasses import dataclass, field\nfrom typing import (\n    Any,\n    Literal,\n    Optional,\n)\n\nfrom pip._internal.cli.spinners import SpinnerInterface\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import (\n    HiddenText,\n    ask_path_exists,\n    backup_dir,\n    display_path,\n    hide_url,\n    hide_value,\n    is_installable_dir,\n    rmtree,\n)\nfrom pip._internal.utils.subprocess import (\n    CommandArgs,\n    call_subprocess,\n    format_command_args,\n    make_command,\n)\n\n__all__ = [\"vcs\"]\n\n\nlogger = logging.getLogger(__name__)\n\nAuthInfo = tuple[Optional[str], Optional[str]]\n\n\ndef is_url(name: str) -> bool:\n    \"\"\"\n    Return true if the name looks like a URL.\n    \"\"\"\n    scheme = urllib.parse.urlsplit(name).scheme\n    if not scheme:\n        return False\n    return scheme in [\"http\", \"https\", \"file\", \"ftp\"] + vcs.all_schemes\n\n\ndef make_vcs_requirement_url(\n    repo_url: str, rev: str, project_name: str, subdir: str | None = None\n) -> str:\n    \"\"\"\n    Return the URL for a VCS requirement.\n\n    Args:\n      repo_url: the remote VCS url, with any needed VCS prefix (e.g. \"git+\").\n      project_name: the (unescaped) project name.\n    \"\"\"\n    quoted_rev = urllib.parse.quote(rev, \"/\")\n    egg_project_name = project_name.replace(\"-\", \"_\")\n    req = f\"{repo_url}@{quoted_rev}#egg={egg_project_name}\"\n    if subdir:\n        req += f\"&subdirectory={subdir}\"\n\n    return req\n\n\ndef find_path_to_project_root_from_repo_root(\n    location: str, repo_root: str\n) -> str | None:\n    \"\"\"\n    Find the the Python project's root by searching up the filesystem from\n    `location`. Return the path to project root relative to `repo_root`.\n    Return None if the project root is `repo_root`, or cannot be found.\n    \"\"\"\n    # find project root.\n    orig_location = location\n    while not is_installable_dir(location):\n        last_location = location\n        location = os.path.dirname(location)\n        if location == last_location:\n            # We've traversed up to the root of the filesystem without\n            # finding a Python project.\n            logger.warning(\n                \"Could not find a Python project for directory %s (tried all \"\n                \"parent directories)\",\n                orig_location,\n            )\n            return None\n\n    if os.path.samefile(repo_root, location):\n        return None\n\n    return os.path.relpath(location, repo_root)\n\n\nclass RemoteNotFoundError(Exception):\n    pass\n\n\nclass RemoteNotValidError(Exception):\n    def __init__(self, url: str):\n        super().__init__(url)\n        self.url = url\n\n\n@dataclass(frozen=True)\nclass RevOptions:\n    \"\"\"\n    Encapsulates a VCS-specific revision to install, along with any VCS\n    install options.\n\n    Args:\n        vc_class: a VersionControl subclass.\n        rev: the name of the revision to install.\n        extra_args: a list of extra options.\n    \"\"\"\n\n    vc_class: type[VersionControl]\n    rev: str | None = None\n    extra_args: CommandArgs = field(default_factory=list)\n    branch_name: str | None = None\n\n    def __repr__(self) -> str:\n        return f\"<RevOptions {self.vc_class.name}: rev={self.rev!r}>\"\n\n    @property\n    def arg_rev(self) -> str | None:\n        if self.rev is None:\n            return self.vc_class.default_arg_rev\n\n        return self.rev\n\n    def to_args(self) -> CommandArgs:\n        \"\"\"\n        Return the VCS-specific command arguments.\n        \"\"\"\n        args: CommandArgs = []\n        rev = self.arg_rev\n        if rev is not None:\n            args += self.vc_class.get_base_rev_args(rev)\n        args += self.extra_args\n\n        return args\n\n    def to_display(self) -> str:\n        if not self.rev:\n            return \"\"\n\n        return f\" (to revision {self.rev})\"\n\n    def make_new(self, rev: str) -> RevOptions:\n        \"\"\"\n        Make a copy of the current instance, but with a new rev.\n\n        Args:\n          rev: the name of the revision for the new object.\n        \"\"\"\n        return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)\n\n\nclass VcsSupport:\n    _registry: dict[str, VersionControl] = {}\n    schemes = [\"ssh\", \"git\", \"hg\", \"bzr\", \"sftp\", \"svn\"]\n\n    def __init__(self) -> None:\n        # Register more schemes with urlparse for various version control\n        # systems\n        urllib.parse.uses_netloc.extend(self.schemes)\n        super().__init__()\n\n    def __iter__(self) -> Iterator[str]:\n        return self._registry.__iter__()\n\n    @property\n    def backends(self) -> list[VersionControl]:\n        return list(self._registry.values())\n\n    @property\n    def dirnames(self) -> list[str]:\n        return [backend.dirname for backend in self.backends]\n\n    @property\n    def all_schemes(self) -> list[str]:\n        schemes: list[str] = []\n        for backend in self.backends:\n            schemes.extend(backend.schemes)\n        return schemes\n\n    def register(self, cls: type[VersionControl]) -> None:\n        if not hasattr(cls, \"name\"):\n            logger.warning(\"Cannot register VCS %s\", cls.__name__)\n            return\n        if cls.name not in self._registry:\n            self._registry[cls.name] = cls()\n            logger.debug(\"Registered VCS backend: %s\", cls.name)\n\n    def unregister(self, name: str) -> None:\n        if name in self._registry:\n            del self._registry[name]\n\n    def get_backend_for_dir(self, location: str) -> VersionControl | None:\n        \"\"\"\n        Return a VersionControl object if a repository of that type is found\n        at the given directory.\n        \"\"\"\n        vcs_backends = {}\n        for vcs_backend in self._registry.values():\n            repo_path = vcs_backend.get_repository_root(location)\n            if not repo_path:\n                continue\n            logger.debug(\"Determine that %s uses VCS: %s\", location, vcs_backend.name)\n            vcs_backends[repo_path] = vcs_backend\n\n        if not vcs_backends:\n            return None\n\n        # Choose the VCS in the inner-most directory. Since all repository\n        # roots found here would be either `location` or one of its\n        # parents, the longest path should have the most path components,\n        # i.e. the backend representing the inner-most repository.\n        inner_most_repo_path = max(vcs_backends, key=len)\n        return vcs_backends[inner_most_repo_path]\n\n    def get_backend_for_scheme(self, scheme: str) -> VersionControl | None:\n        \"\"\"\n        Return a VersionControl object or None.\n        \"\"\"\n        for vcs_backend in self._registry.values():\n            if scheme in vcs_backend.schemes:\n                return vcs_backend\n        return None\n\n    def get_backend(self, name: str) -> VersionControl | None:\n        \"\"\"\n        Return a VersionControl object or None.\n        \"\"\"\n        name = name.lower()\n        return self._registry.get(name)\n\n\nvcs = VcsSupport()\n\n\nclass VersionControl:\n    name = \"\"\n    dirname = \"\"\n    repo_name = \"\"\n    # List of supported schemes for this Version Control\n    schemes: tuple[str, ...] = ()\n    # Iterable of environment variable names to pass to call_subprocess().\n    unset_environ: tuple[str, ...] = ()\n    default_arg_rev: str | None = None\n\n    @classmethod\n    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:\n        \"\"\"\n        Return whether the vcs prefix (e.g. \"git+\") should be added to a\n        repository's remote url when used in a requirement.\n        \"\"\"\n        return not remote_url.lower().startswith(f\"{cls.name}:\")\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> str | None:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        return None\n\n    @classmethod\n    def get_requirement_revision(cls, repo_dir: str) -> str:\n        \"\"\"\n        Return the revision string that should be used in a requirement.\n        \"\"\"\n        return cls.get_revision(repo_dir)\n\n    @classmethod\n    def get_src_requirement(cls, repo_dir: str, project_name: str) -> str:\n        \"\"\"\n        Return the requirement string to use to redownload the files\n        currently at the given repository directory.\n\n        Args:\n          project_name: the (unescaped) project name.\n\n        The return value has a form similar to the following:\n\n            {repository_url}@{revision}#egg={project_name}\n        \"\"\"\n        repo_url = cls.get_remote_url(repo_dir)\n\n        if cls.should_add_vcs_url_prefix(repo_url):\n            repo_url = f\"{cls.name}+{repo_url}\"\n\n        revision = cls.get_requirement_revision(repo_dir)\n        subdir = cls.get_subdirectory(repo_dir)\n        req = make_vcs_requirement_url(repo_url, revision, project_name, subdir=subdir)\n\n        return req\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> list[str]:\n        \"\"\"\n        Return the base revision arguments for a vcs command.\n\n        Args:\n          rev: the name of a revision to install.  Cannot be None.\n        \"\"\"\n        raise NotImplementedError\n\n    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:\n        \"\"\"\n        Return true if the commit hash checked out at dest matches\n        the revision in url.\n\n        Always return False, if the VCS does not support immutable commit\n        hashes.\n\n        This method does not check if there are local uncommitted changes\n        in dest after checkout, as pip currently has no use case for that.\n        \"\"\"\n        return False\n\n    @classmethod\n    def make_rev_options(\n        cls, rev: str | None = None, extra_args: CommandArgs | None = None\n    ) -> RevOptions:\n        \"\"\"\n        Return a RevOptions object.\n\n        Args:\n          rev: the name of a revision to install.\n          extra_args: a list of extra options.\n        \"\"\"\n        return RevOptions(cls, rev, extra_args=extra_args or [])\n\n    @classmethod\n    def _is_local_repository(cls, repo: str) -> bool:\n        \"\"\"\n        posix absolute paths start with os.path.sep,\n        win32 ones start with drive (like c:\\\\folder)\n        \"\"\"\n        drive, tail = os.path.splitdrive(repo)\n        return repo.startswith(os.path.sep) or bool(drive)\n\n    @classmethod\n    def get_netloc_and_auth(\n        cls, netloc: str, scheme: str\n    ) -> tuple[str, tuple[str | None, str | None]]:\n        \"\"\"\n        Parse the repository URL's netloc, and return the new netloc to use\n        along with auth information.\n\n        Args:\n          netloc: the original repository URL netloc.\n          scheme: the repository URL's scheme without the vcs prefix.\n\n        This is mainly for the Subversion class to override, so that auth\n        information can be provided via the --username and --password options\n        instead of through the URL.  For other subclasses like Git without\n        such an option, auth information must stay in the URL.\n\n        Returns: (netloc, (username, password)).\n        \"\"\"\n        return netloc, (None, None)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:\n        \"\"\"\n        Parse the repository URL to use, and return the URL, revision,\n        and auth info to use.\n\n        Returns: (url, rev, (username, password)).\n        \"\"\"\n        scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)\n        if \"+\" not in scheme:\n            raise ValueError(\n                f\"Sorry, {url!r} is a malformed VCS url. \"\n                \"The format is <vcs>+<protocol>://<url>, \"\n                \"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp\"\n            )\n        # Remove the vcs prefix.\n        scheme = scheme.split(\"+\", 1)[1]\n        netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)\n        rev = None\n        if \"@\" in path:\n            path, rev = path.rsplit(\"@\", 1)\n            if not rev:\n                raise InstallationError(\n                    f\"The URL {url!r} has an empty revision (after @) \"\n                    \"which is not supported. Include a revision after @ \"\n                    \"or remove @ from the URL.\"\n                )\n            rev = urllib.parse.unquote(rev)\n        url = urllib.parse.urlunsplit((scheme, netloc, path, query, \"\"))\n        return url, rev, user_pass\n\n    @staticmethod\n    def make_rev_args(username: str | None, password: HiddenText | None) -> CommandArgs:\n        \"\"\"\n        Return the RevOptions \"extra arguments\" to use in obtain().\n        \"\"\"\n        return []\n\n    def get_url_rev_options(self, url: HiddenText) -> tuple[HiddenText, RevOptions]:\n        \"\"\"\n        Return the URL and RevOptions object to use in obtain(),\n        as a tuple (url, rev_options).\n        \"\"\"\n        secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)\n        username, secret_password = user_pass\n        password: HiddenText | None = None\n        if secret_password is not None:\n            password = hide_value(secret_password)\n        extra_args = self.make_rev_args(username, password)\n        rev_options = self.make_rev_options(rev, extra_args=extra_args)\n\n        return hide_url(secret_url), rev_options\n\n    @staticmethod\n    def normalize_url(url: str) -> str:\n        \"\"\"\n        Normalize a URL for comparison by unquoting it and removing any\n        trailing slash.\n        \"\"\"\n        return urllib.parse.unquote(url).rstrip(\"/\")\n\n    @classmethod\n    def compare_urls(cls, url1: str, url2: str) -> bool:\n        \"\"\"\n        Compare two repo URLs for identity, ignoring incidental differences.\n        \"\"\"\n        return cls.normalize_url(url1) == cls.normalize_url(url2)\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        \"\"\"\n        Fetch a revision from a repository, in the case that this is the\n        first fetch from the repository.\n\n        Args:\n          dest: the directory to fetch the repository to.\n          rev_options: a RevOptions object.\n          verbosity: verbosity level.\n        \"\"\"\n        raise NotImplementedError\n\n    def switch(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        \"\"\"\n        Switch the repo at ``dest`` to point to ``URL``.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        raise NotImplementedError\n\n    def update(\n        self,\n        dest: str,\n        url: HiddenText,\n        rev_options: RevOptions,\n        verbosity: int = 0,\n    ) -> None:\n        \"\"\"\n        Update an already-existing repo to the given ``rev_options``.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:\n        \"\"\"\n        Return whether the id of the current commit equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        raise NotImplementedError\n\n    def obtain(self, dest: str, url: HiddenText, verbosity: int) -> None:\n        \"\"\"\n        Install or update in editable mode the package represented by this\n        VersionControl object.\n\n        :param dest: the repository directory in which to install or update.\n        :param url: the repository URL starting with a vcs prefix.\n        :param verbosity: verbosity level.\n        \"\"\"\n        url, rev_options = self.get_url_rev_options(url)\n\n        if not os.path.exists(dest):\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        rev_display = rev_options.to_display()\n        if self.is_repository_directory(dest):\n            existing_url = self.get_remote_url(dest)\n            if self.compare_urls(existing_url, url.secret):\n                logger.debug(\n                    \"%s in %s exists, and has correct URL (%s)\",\n                    self.repo_name.title(),\n                    display_path(dest),\n                    url,\n                )\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    logger.info(\n                        \"Updating %s %s%s\",\n                        display_path(dest),\n                        self.repo_name,\n                        rev_display,\n                    )\n                    self.update(dest, url, rev_options, verbosity=verbosity)\n                else:\n                    logger.info(\"Skipping because already up-to-date.\")\n                return\n\n            logger.warning(\n                \"%s %s in %s exists with URL %s\",\n                self.name,\n                self.repo_name,\n                display_path(dest),\n                existing_url,\n            )\n            prompt = (\"(s)witch, (i)gnore, (w)ipe, (b)ackup \", (\"s\", \"i\", \"w\", \"b\"))\n        else:\n            logger.warning(\n                \"Directory %s already exists, and is not a %s %s.\",\n                dest,\n                self.name,\n                self.repo_name,\n            )\n            # https://github.com/python/mypy/issues/1174\n            prompt = (\"(i)gnore, (w)ipe, (b)ackup \", (\"i\", \"w\", \"b\"))  # type: ignore\n\n        logger.warning(\n            \"The plan is to install the %s repository %s\",\n            self.name,\n            url,\n        )\n        response = ask_path_exists(f\"What to do?  {prompt[0]}\", prompt[1])\n\n        if response == \"a\":\n            sys.exit(-1)\n\n        if response == \"w\":\n            logger.warning(\"Deleting %s\", display_path(dest))\n            rmtree(dest)\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        if response == \"b\":\n            dest_dir = backup_dir(dest)\n            logger.warning(\"Backing up %s to %s\", display_path(dest), dest_dir)\n            shutil.move(dest, dest_dir)\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        # Do nothing if the response is \"i\".\n        if response == \"s\":\n            logger.info(\n                \"Switching %s %s to %s%s\",\n                self.repo_name,\n                display_path(dest),\n                url,\n                rev_display,\n            )\n            self.switch(dest, url, rev_options, verbosity=verbosity)\n\n    def unpack(self, location: str, url: HiddenText, verbosity: int) -> None:\n        \"\"\"\n        Clean up current location and download the url repository\n        (and vcs infos) into location\n\n        :param url: the repository URL starting with a vcs prefix.\n        :param verbosity: verbosity level.\n        \"\"\"\n        if os.path.exists(location):\n            rmtree(location)\n        self.obtain(location, url=url, verbosity=verbosity)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        \"\"\"\n        Return the url used at location\n\n        Raises RemoteNotFoundError if the repository does not have a remote\n        url configured.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the current commit id of the files at the given location.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def run_command(\n        cls,\n        cmd: list[str] | CommandArgs,\n        show_stdout: bool = True,\n        cwd: str | None = None,\n        on_returncode: Literal[\"raise\", \"warn\", \"ignore\"] = \"raise\",\n        extra_ok_returncodes: Iterable[int] | None = None,\n        command_desc: str | None = None,\n        extra_environ: Mapping[str, Any] | None = None,\n        spinner: SpinnerInterface | None = None,\n        log_failed_cmd: bool = True,\n        stdout_only: bool = False,\n    ) -> str:\n        \"\"\"\n        Run a VCS subcommand\n        This is simply a wrapper around call_subprocess that adds the VCS\n        command name, and checks that the VCS is available\n        \"\"\"\n        cmd = make_command(cls.name, *cmd)\n        if command_desc is None:\n            command_desc = format_command_args(cmd)\n        try:\n            return call_subprocess(\n                cmd,\n                show_stdout,\n                cwd,\n                on_returncode=on_returncode,\n                extra_ok_returncodes=extra_ok_returncodes,\n                command_desc=command_desc,\n                extra_environ=extra_environ,\n                unset_environ=cls.unset_environ,\n                spinner=spinner,\n                log_failed_cmd=log_failed_cmd,\n                stdout_only=stdout_only,\n            )\n        except NotADirectoryError:\n            raise BadCommand(f\"Cannot find command {cls.name!r} - invalid PATH\")\n        except FileNotFoundError:\n            # errno.ENOENT = no such file or directory\n            # In other words, the VCS executable isn't available\n            raise BadCommand(\n                f\"Cannot find command {cls.name!r} - do you have \"\n                f\"{cls.name!r} installed and in your PATH?\"\n            )\n        except PermissionError:\n            # errno.EACCES = Permission denied\n            # This error occurs, for instance, when the command is installed\n            # only for another user. So, the current user don't have\n            # permission to call the other user command.\n            raise BadCommand(\n                f\"No permission to execute {cls.name!r} - install it \"\n                f\"locally, globally (ask admin), or check your PATH. \"\n                f\"See possible solutions at \"\n                f\"https://pip.pypa.io/en/latest/reference/pip_freeze/\"\n                f\"#fixing-permission-denied.\"\n            )\n\n    @classmethod\n    def is_repository_directory(cls, path: str) -> bool:\n        \"\"\"\n        Return whether a directory path is a repository directory.\n        \"\"\"\n        logger.debug(\"Checking in %s for %s (%s)...\", path, cls.dirname, cls.name)\n        return os.path.exists(os.path.join(path, cls.dirname))\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> str | None:\n        \"\"\"\n        Return the \"root\" (top-level) directory controlled by the vcs,\n        or `None` if the directory is not in any.\n\n        It is meant to be overridden to implement smarter detection\n        mechanisms for specific vcs.\n\n        This can do more than is_repository_directory() alone. For\n        example, the Git override checks that Git is actually available.\n        \"\"\"\n        if cls.is_repository_directory(location):\n            return location\n        return None\n"
  },
  {
    "path": "src/pip/_internal/wheel_builder.py",
    "content": "\"\"\"Orchestrator for building wheels from InstallRequirements.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os.path\nimport re\nfrom collections.abc import Iterable\nfrom tempfile import TemporaryDirectory\n\nfrom pip._vendor.packaging.utils import canonicalize_name, canonicalize_version\nfrom pip._vendor.packaging.version import InvalidVersion, Version\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.exceptions import InvalidWheelFilename, UnsupportedWheel\nfrom pip._internal.metadata import FilesystemWheel, get_wheel_distribution\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.build.wheel import build_wheel_pep517\nfrom pip._internal.operations.build.wheel_editable import build_wheel_editable\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import ensure_dir, hash_file\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import vcs\n\nlogger = logging.getLogger(__name__)\n\n_egg_info_re = re.compile(r\"([a-z0-9_.]+)-([a-z0-9_.!+-]+)\", re.IGNORECASE)\n\nBuildResult = tuple[list[InstallRequirement], list[InstallRequirement]]\n\n\ndef _contains_egg_info(s: str) -> bool:\n    \"\"\"Determine whether the string looks like an egg_info.\n\n    :param s: The string to parse. E.g. foo-2.1\n    \"\"\"\n    return bool(_egg_info_re.search(s))\n\n\ndef _should_cache(\n    req: InstallRequirement,\n) -> bool | None:\n    \"\"\"\n    Return whether a built InstallRequirement can be stored in the persistent\n    wheel cache, assuming the wheel cache is available.\n    \"\"\"\n    if req.editable or not req.source_dir:\n        # never cache editable requirements\n        return False\n\n    if req.link and req.link.is_vcs:\n        # VCS checkout. Do not cache\n        # unless it points to an immutable commit hash.\n        assert not req.editable\n        assert req.source_dir\n        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)\n        assert vcs_backend\n        if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):\n            return True\n        return False\n\n    assert req.link\n    base, ext = req.link.splitext()\n    if _contains_egg_info(base):\n        return True\n\n    # Otherwise, do not cache.\n    return False\n\n\ndef _get_cache_dir(\n    req: InstallRequirement,\n    wheel_cache: WheelCache,\n) -> str:\n    \"\"\"Return the persistent or temporary cache directory where the built\n    wheel need to be stored.\n    \"\"\"\n    cache_available = bool(wheel_cache.cache_dir)\n    assert req.link\n    if cache_available and _should_cache(req):\n        cache_dir = wheel_cache.get_path_for_link(req.link)\n    else:\n        cache_dir = wheel_cache.get_ephem_path_for_link(req.link)\n    return cache_dir\n\n\ndef _verify_one(req: InstallRequirement, wheel_path: str) -> None:\n    canonical_name = canonicalize_name(req.name or \"\")\n    w = Wheel(os.path.basename(wheel_path))\n    if w.name != canonical_name:\n        raise InvalidWheelFilename(\n            f\"Wheel has unexpected file name: expected {canonical_name!r}, \"\n            f\"got {w.name!r}\",\n        )\n    dist = get_wheel_distribution(FilesystemWheel(wheel_path), canonical_name)\n    dist_verstr = str(dist.version)\n    if canonicalize_version(dist_verstr) != canonicalize_version(w.version):\n        raise InvalidWheelFilename(\n            f\"Wheel has unexpected file name: expected {dist_verstr!r}, \"\n            f\"got {w.version!r}\",\n        )\n    metadata_version_value = dist.metadata_version\n    if metadata_version_value is None:\n        raise UnsupportedWheel(\"Missing Metadata-Version\")\n    try:\n        metadata_version = Version(metadata_version_value)\n    except InvalidVersion:\n        msg = f\"Invalid Metadata-Version: {metadata_version_value}\"\n        raise UnsupportedWheel(msg)\n    if metadata_version >= Version(\"1.2\") and not isinstance(dist.version, Version):\n        raise UnsupportedWheel(\n            f\"Metadata 1.2 mandates PEP 440 version, but {dist_verstr!r} is not\"\n        )\n\n\ndef _build_one(\n    req: InstallRequirement,\n    output_dir: str,\n    verify: bool,\n    editable: bool,\n) -> str | None:\n    \"\"\"Build one wheel.\n\n    :return: The filename of the built wheel, or None if the build failed.\n    \"\"\"\n    artifact = \"editable\" if editable else \"wheel\"\n    try:\n        ensure_dir(output_dir)\n    except OSError as e:\n        logger.warning(\n            \"Building %s for %s failed: %s\",\n            artifact,\n            req.name,\n            e,\n        )\n        return None\n\n    # Install build deps into temporary directory (PEP 518)\n    with req.build_env:\n        wheel_path = _build_one_inside_env(req, output_dir, editable)\n    if wheel_path and verify:\n        try:\n            _verify_one(req, wheel_path)\n        except (InvalidWheelFilename, UnsupportedWheel) as e:\n            logger.warning(\"Built %s for %s is invalid: %s\", artifact, req.name, e)\n            return None\n    return wheel_path\n\n\ndef _build_one_inside_env(\n    req: InstallRequirement,\n    output_dir: str,\n    editable: bool,\n) -> str | None:\n    with TemporaryDirectory(dir=output_dir) as wheel_directory:\n        assert req.name\n        assert req.metadata_directory\n        assert req.pep517_backend\n        if editable:\n            wheel_path = build_wheel_editable(\n                name=req.name,\n                backend=req.pep517_backend,\n                metadata_directory=req.metadata_directory,\n                wheel_directory=wheel_directory,\n            )\n        else:\n            wheel_path = build_wheel_pep517(\n                name=req.name,\n                backend=req.pep517_backend,\n                metadata_directory=req.metadata_directory,\n                wheel_directory=wheel_directory,\n            )\n\n        if wheel_path is not None:\n            wheel_name = os.path.basename(wheel_path)\n            dest_path = os.path.join(output_dir, wheel_name)\n            try:\n                wheel_hash, length = hash_file(wheel_path)\n                # We can do a replace here because wheel_path is guaranteed to\n                # be in the same filesystem as output_dir. This will perform an\n                # atomic rename, which is necessary to avoid concurrency issues\n                # when populating the cache.\n                os.replace(wheel_path, dest_path)\n                logger.info(\n                    \"Created wheel for %s: filename=%s size=%d sha256=%s\",\n                    req.name,\n                    wheel_name,\n                    length,\n                    wheel_hash.hexdigest(),\n                )\n                logger.info(\"Stored in directory: %s\", output_dir)\n                return dest_path\n            except Exception as e:\n                logger.warning(\n                    \"Building wheel for %s failed: %s\",\n                    req.name,\n                    e,\n                )\n        return None\n\n\ndef build(\n    requirements: Iterable[InstallRequirement],\n    wheel_cache: WheelCache,\n    verify: bool,\n) -> BuildResult:\n    \"\"\"Build wheels.\n\n    :return: The list of InstallRequirement that succeeded to build and\n        the list of InstallRequirement that failed to build.\n    \"\"\"\n    if not requirements:\n        return [], []\n\n    # Build the wheels.\n    logger.info(\n        \"Building wheels for collected packages: %s\",\n        \", \".join(req.name for req in requirements),  # type: ignore\n    )\n\n    with indent_log():\n        build_successes, build_failures = [], []\n        for req in requirements:\n            assert req.name\n            cache_dir = _get_cache_dir(req, wheel_cache)\n            wheel_file = _build_one(\n                req,\n                cache_dir,\n                verify,\n                req.editable and req.permit_editable_wheels,\n            )\n            if wheel_file:\n                # Record the download origin in the cache\n                if req.download_info is not None:\n                    # download_info is guaranteed to be set because when we build an\n                    # InstallRequirement it has been through the preparer before, but\n                    # let's be cautious.\n                    wheel_cache.record_download_origin(cache_dir, req.download_info)\n                # Update the link for this.\n                req.link = Link(path_to_url(wheel_file))\n                req.local_file_path = req.link.file_path\n                assert req.link.is_wheel\n                build_successes.append(req)\n            else:\n                build_failures.append(req)\n\n    # notify success/failure\n    if build_successes:\n        logger.info(\n            \"Successfully built %s\",\n            \" \".join([req.name for req in build_successes]),  # type: ignore\n        )\n    if build_failures:\n        logger.info(\n            \"Failed to build %s\",\n            \" \".join([req.name for req in build_failures]),  # type: ignore\n        )\n    # Return a list of requirements that failed to build\n    return build_successes, build_failures\n"
  },
  {
    "path": "src/pip/_vendor/README.rst",
    "content": "================\nVendoring Policy\n================\n\n* Vendored libraries **MUST** not be modified except as required to\n  successfully vendor them.\n* Vendored libraries **MUST** be released copies of libraries available on\n  PyPI.\n* Vendored libraries **MUST** be available under a license that allows\n  them to be integrated into ``pip``, which is released under the MIT license.\n* Vendored libraries **MUST** be accompanied with LICENSE files.\n* The versions of libraries vendored in pip **MUST** be reflected in\n  ``pip/_vendor/vendor.txt``.\n* Vendored libraries **MUST** function without any build steps such as ``2to3``\n  or compilation of C code, practically this limits to single source 2.x/3.x and\n  pure Python.\n* Any modifications made to libraries **MUST** be noted in\n  ``pip/_vendor/README.rst`` and their corresponding patches **MUST** be\n  included ``tools/vendoring/patches``.\n* Vendored libraries should have corresponding ``vendored()`` entries in\n  ``pip/_vendor/__init__.py``.\n\nRationale\n=========\n\nHistorically pip has not had any dependencies except for ``setuptools`` itself,\nchoosing instead to implement any functionality it needed to prevent needing\na dependency. However, starting with pip 1.5, we began to replace code that was\nimplemented inside of pip with reusable libraries from PyPI. This brought the\ntypical benefits of reusing libraries instead of reinventing the wheel like\nhigher quality and more battle tested code, centralization of bug fixes\n(particularly security sensitive ones), and better/more features for less work.\n\nHowever, there are several issues with having dependencies in the traditional\nway (via ``install_requires``) for pip. These issues are:\n\n**Fragility**\n   When pip depends on another library to function then if for whatever reason\n   that library either isn't installed or an incompatible version is installed\n   then pip ceases to function. This is of course true for all Python\n   applications, however for every application *except* for pip the way you fix\n   it is by re-running pip. Obviously, when pip can't run, you can't use pip to\n   fix pip, so you're left having to manually resolve dependencies and\n   installing them by hand.\n\n**Making other libraries uninstallable**\n   One of pip's current dependencies is the ``requests`` library, for which pip\n   requires a fairly recent version to run.  If pip depended on ``requests`` in\n   the traditional manner, then we'd either have to maintain compatibility with\n   every ``requests`` version that has ever existed (and ever will), OR allow\n   pip to render certain versions of ``requests`` uninstallable. (The second\n   issue, although technically true for any Python application, is magnified by\n   pip's ubiquity; pip is installed by default in Python, in ``pyvenv``, and in\n   ``virtualenv``.)\n\n**Security**\n   This might seem puzzling at first glance, since vendoring has a tendency to\n   complicate updating dependencies for security updates, and that holds true\n   for pip. However, given the *other* reasons for avoiding dependencies, the\n   alternative is for pip to reinvent the wheel itself.  This is what pip did\n   historically. It forced pip to re-implement its own HTTPS verification\n   routines as a workaround for the Python standard library's lack of SSL\n   validation, which resulted in similar bugs in the validation routine in\n   ``requests`` and ``urllib3``, except that they had to be discovered and\n   fixed independently. Even though we're vendoring, reusing libraries keeps\n   pip more secure by relying on the great work of our dependencies, *and*\n   allowing for faster, easier security fixes by simply pulling in newer\n   versions of dependencies.\n\n**Bootstrapping**\n   Currently most popular methods of installing pip rely on pip's\n   self-contained nature to install pip itself. These tools work by bundling a\n   copy of pip, adding it to ``sys.path``, and then executing that copy of pip.\n   This is done instead of implementing a \"mini installer\" (to reduce\n   duplication); pip already knows how to install a Python package, and is far\n   more battle-tested than any \"mini installer\" could ever possibly be.\n\nMany downstream redistributors have policies against this kind of bundling, and\ninstead opt to patch the software they distribute to debundle it and make it\nrely on the global versions of the software that they already have packaged\n(which may have its own patches applied to it). We (the pip team) would prefer\nit if pip was *not* debundled in this manner due to the above reasons and\ninstead we would prefer it if pip would be left intact as it is now.\n\nIn the longer term, if someone has a *portable* solution to the above problems,\nother than the bundling method we currently use, that doesn't add additional\nproblems that are unreasonable then we would be happy to consider, and possibly\nswitch to said method. This solution must function correctly across all of the\nsituation that we expect pip to be used and not mandate some external mechanism\nsuch as OS packages.\n\n\nModifications\n=============\n\n* ``setuptools`` is completely stripped to only keep ``pkg_resources``.\n* ``pkg_resources`` has been modified to import its dependencies from\n  ``pip._vendor``, and to use the vendored copy of ``platformdirs``\n  rather than ``appdirs``.\n* ``packaging`` has been modified to import its dependencies from\n  ``pip._vendor``.\n* ``CacheControl`` has been modified to import its dependencies from\n  ``pip._vendor``.\n* ``requests`` has been modified to import its other dependencies from\n  ``pip._vendor`` and to *not* load ``simplejson`` (all platforms) and\n  ``pyopenssl`` (Windows).\n* ``platformdirs`` has been modified to import its submodules from ``pip._vendor.platformdirs``.\n\nAutomatic Vendoring\n===================\n\nVendoring is automated via the `vendoring <https://pypi.org/project/vendoring/>`_ tool from the content of\n``pip/_vendor/vendor.txt`` and the different patches in\n``tools/vendoring/patches``.\nLaunch it via ``vendoring sync . -v`` (requires ``vendoring>=0.2.2``).\nTool configuration is done via ``pyproject.toml``.\n\nTo update the vendored library versions, we have a session defined in ``nox``.\nThe command to upgrade everything is::\n\n    nox -s vendoring -- --upgrade-all --skip urllib3 --skip setuptools\n\nAt the time of writing (April 2025) we do not upgrade ``urllib3`` because the\nnext version is a major upgrade and will be handled as an independent PR. We also\ndo not upgrade ``setuptools``, because we only rely on ``pkg_resources``, and\ntracking every ``setuptools`` change is unnecessary for our needs.\n\n\nManaging Local Patches\n======================\n\nThe ``vendoring`` tool automatically applies our local patches, but updating,\nthe patches sometimes no longer apply cleanly. In that case, the update will\nfail. To resolve this, take the following steps:\n\n1. Revert any incomplete changes in the revendoring branch, to ensure you have\n   a clean starting point.\n2. Run the revendoring of the library with a problem again: ``nox -s vendoring\n   -- --upgrade <library_name>``.\n3. This will fail again, but you will have the original source in your working\n   directory. Review the existing patch against the source, and modify the patch\n   to reflect the new version of the source. If you ``git add`` the changes the\n   vendoring made, you can modify the source to reflect the patch file and then\n   generate a new patch with ``git diff``.\n4. Now, revert everything *except* the patch file changes. Leave the modified\n   patch file unstaged but saved in the working tree.\n5. Re-run the vendoring. This time, it should pick up the changed patch file\n   and apply it cleanly. The patch file changes will be committed along with the\n   revendoring, so the new commit should be ready to test and publish as a PR.\n\n\nDebundling\n==========\n\nAs mentioned in the rationale, we, the pip team, would prefer it if pip was not\ndebundled (other than optionally ``pip/_vendor/requests/cacert.pem``) and that\npip was left intact. However, if you insist on doing so, we have a\nsemi-supported method (that we don't test in our CI) and requires a bit of\nextra work on your end in order to solve the problems described above.\n\n1. Delete everything in ``pip/_vendor/`` **except** for\n   ``pip/_vendor/__init__.py`` and ``pip/_vendor/vendor.txt``.\n2. Generate wheels for each of pip's dependencies (and any of their\n   dependencies) using your patched copies of these libraries. These must be\n   placed somewhere on the filesystem that pip can access (``pip/_vendor`` is\n   the default assumption).\n3. Modify ``pip/_vendor/__init__.py`` so that the ``DEBUNDLED`` variable is\n   ``True``.\n4. Upon installation, the ``INSTALLER`` file in pip's own ``dist-info``\n   directory should be set to something other than ``pip``, so that pip\n   can detect that it wasn't installed using itself.\n5. *(optional)* If you've placed the wheels in a location other than\n   ``pip/_vendor/``, then modify ``pip/_vendor/__init__.py`` so that the\n   ``WHEEL_DIR`` variable points to the location you've placed them.\n6. *(optional)* Update the ``pip_self_version_check`` logic to use the\n   appropriate logic for determining the latest available version of pip and\n   prompt the user with the correct upgrade message.\n\nNote that partial debundling is **NOT** supported. You need to prepare wheels\nfor all dependencies for successful debundling.\n"
  },
  {
    "path": "src/pip/_vendor/__init__.py",
    "content": "\"\"\"\npip._vendor is for vendoring dependencies of pip to prevent needing pip to\ndepend on something external.\n\nFiles inside of pip._vendor should be considered immutable and should only be\nupdated to versions from upstream.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport glob\nimport os.path\nimport sys\n\n# Downstream redistributors which have debundled our dependencies should also\n# patch this value to be true. This will trigger the additional patching\n# to cause things like \"six\" to be available as pip.\nDEBUNDLED = False\n\n# By default, look in this directory for a bunch of .whl files which we will\n# add to the beginning of sys.path before attempting to import anything. This\n# is done to support downstream re-distributors like Debian and Fedora who\n# wish to create their own Wheels for our dependencies to aid in debundling.\nWHEEL_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\n# Define a small helper function to alias our vendored modules to the real ones\n# if the vendored ones do not exist. This idea of this was taken from\n# https://github.com/kennethreitz/requests/pull/2567.\ndef vendored(modulename):\n    vendored_name = \"{0}.{1}\".format(__name__, modulename)\n\n    try:\n        __import__(modulename, globals(), locals(), level=0)\n    except ImportError:\n        # We can just silently allow import failures to pass here. If we\n        # got to this point it means that ``import pip._vendor.whatever``\n        # failed and so did ``import whatever``. Since we're importing this\n        # upfront in an attempt to alias imports, not erroring here will\n        # just mean we get a regular import error whenever pip *actually*\n        # tries to import one of these modules to use it, which actually\n        # gives us a better error message than we would have otherwise\n        # gotten.\n        pass\n    else:\n        sys.modules[vendored_name] = sys.modules[modulename]\n        base, head = vendored_name.rsplit(\".\", 1)\n        setattr(sys.modules[base], head, sys.modules[modulename])\n\n\n# If we're operating in a debundled setup, then we want to go ahead and trigger\n# the aliasing of our vendored libraries as well as looking for wheels to add\n# to our sys.path. This will cause all of this code to be a no-op typically\n# however downstream redistributors can enable it in a consistent way across\n# all platforms.\nif DEBUNDLED:\n    # Actually look inside of WHEEL_DIR to find .whl files and add them to the\n    # front of our sys.path.\n    sys.path[:] = glob.glob(os.path.join(WHEEL_DIR, \"*.whl\")) + sys.path\n\n    # Actually alias all of our vendored dependencies.\n    vendored(\"cachecontrol\")\n    vendored(\"certifi\")\n    vendored(\"dependency-groups\")\n    vendored(\"distlib\")\n    vendored(\"distro\")\n    vendored(\"packaging\")\n    vendored(\"packaging.version\")\n    vendored(\"packaging.specifiers\")\n    vendored(\"pkg_resources\")\n    vendored(\"platformdirs\")\n    vendored(\"progress\")\n    vendored(\"pyproject_hooks\")\n    vendored(\"requests\")\n    vendored(\"requests.exceptions\")\n    vendored(\"requests.packages\")\n    vendored(\"requests.packages.urllib3\")\n    vendored(\"requests.packages.urllib3._collections\")\n    vendored(\"requests.packages.urllib3.connection\")\n    vendored(\"requests.packages.urllib3.connectionpool\")\n    vendored(\"requests.packages.urllib3.contrib\")\n    vendored(\"requests.packages.urllib3.contrib.ntlmpool\")\n    vendored(\"requests.packages.urllib3.contrib.pyopenssl\")\n    vendored(\"requests.packages.urllib3.exceptions\")\n    vendored(\"requests.packages.urllib3.fields\")\n    vendored(\"requests.packages.urllib3.filepost\")\n    vendored(\"requests.packages.urllib3.packages\")\n    vendored(\"requests.packages.urllib3.packages.ordered_dict\")\n    vendored(\"requests.packages.urllib3.packages.six\")\n    vendored(\"requests.packages.urllib3.packages.ssl_match_hostname\")\n    vendored(\"requests.packages.urllib3.packages.ssl_match_hostname.\"\n             \"_implementation\")\n    vendored(\"requests.packages.urllib3.poolmanager\")\n    vendored(\"requests.packages.urllib3.request\")\n    vendored(\"requests.packages.urllib3.response\")\n    vendored(\"requests.packages.urllib3.util\")\n    vendored(\"requests.packages.urllib3.util.connection\")\n    vendored(\"requests.packages.urllib3.util.request\")\n    vendored(\"requests.packages.urllib3.util.response\")\n    vendored(\"requests.packages.urllib3.util.retry\")\n    vendored(\"requests.packages.urllib3.util.ssl_\")\n    vendored(\"requests.packages.urllib3.util.timeout\")\n    vendored(\"requests.packages.urllib3.util.url\")\n    vendored(\"resolvelib\")\n    vendored(\"rich\")\n    vendored(\"rich.console\")\n    vendored(\"rich.highlighter\")\n    vendored(\"rich.logging\")\n    vendored(\"rich.markup\")\n    vendored(\"rich.progress\")\n    vendored(\"rich.segment\")\n    vendored(\"rich.style\")\n    vendored(\"rich.text\")\n    vendored(\"rich.traceback\")\n    if sys.version_info < (3, 11):\n        vendored(\"tomli\")\n    vendored(\"truststore\")\n    vendored(\"urllib3\")\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/LICENSE.txt",
    "content": "Copyright 2012-2021  Eric Larson\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/__init__.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"CacheControl import Interface.\n\nMake it easy to import from cachecontrol without long namespaces.\n\"\"\"\n\nimport importlib.metadata\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.controller import CacheController\nfrom pip._vendor.cachecontrol.wrapper import CacheControl\n\n__author__ = \"Eric Larson\"\n__email__ = \"eric@ionrock.org\"\n# pip patch: this won't work when vendored, so just patch it out as it's unused\n# __version__ = importlib.metadata.version(\"cachecontrol\")\n\n__all__ = [\n    \"__author__\",\n    \"__email__\",\n    \"__version__\",\n    \"CacheControlAdapter\",\n    \"CacheController\",\n    \"CacheControl\",\n]\n\nimport logging\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/_cmd.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport logging\nfrom argparse import ArgumentParser\nfrom typing import TYPE_CHECKING\n\nfrom pip._vendor import requests\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.cache import DictCache\nfrom pip._vendor.cachecontrol.controller import logger\n\nif TYPE_CHECKING:\n    from argparse import Namespace\n\n    from pip._vendor.cachecontrol.controller import CacheController\n\n\ndef setup_logging() -> None:\n    logger.setLevel(logging.DEBUG)\n    handler = logging.StreamHandler()\n    logger.addHandler(handler)\n\n\ndef get_session() -> requests.Session:\n    adapter = CacheControlAdapter(\n        DictCache(), cache_etags=True, serializer=None, heuristic=None\n    )\n    sess = requests.Session()\n    sess.mount(\"http://\", adapter)\n    sess.mount(\"https://\", adapter)\n\n    sess.cache_controller = adapter.controller  # type: ignore[attr-defined]\n    return sess\n\n\ndef get_args() -> Namespace:\n    parser = ArgumentParser()\n    parser.add_argument(\"url\", help=\"The URL to try and cache\")\n    return parser.parse_args()\n\n\ndef main() -> None:\n    args = get_args()\n    sess = get_session()\n\n    # Make a request to get a response\n    resp = sess.get(args.url)\n\n    # Turn on logging\n    setup_logging()\n\n    # try setting the cache\n    cache_controller: CacheController = (\n        sess.cache_controller  # type: ignore[attr-defined]\n    )\n    cache_controller.cache_response(resp.request, resp.raw)\n\n    # Now try to get it\n    if cache_controller.cached_request(resp.request):\n        print(\"Cached!\")\n    else:\n        print(\"Not cached :(\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/adapter.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport functools\nimport weakref\nimport zlib\nfrom typing import TYPE_CHECKING, Any, Collection, Mapping\n\nfrom pip._vendor.requests.adapters import HTTPAdapter\n\nfrom pip._vendor.cachecontrol.cache import DictCache\nfrom pip._vendor.cachecontrol.controller import PERMANENT_REDIRECT_STATUSES, CacheController\nfrom pip._vendor.cachecontrol.filewrapper import CallbackFileWrapper\n\nif TYPE_CHECKING:\n    from pip._vendor.requests import PreparedRequest, Response\n    from pip._vendor.urllib3 import HTTPResponse\n\n    from pip._vendor.cachecontrol.cache import BaseCache\n    from pip._vendor.cachecontrol.heuristics import BaseHeuristic\n    from pip._vendor.cachecontrol.serialize import Serializer\n\n\nclass CacheControlAdapter(HTTPAdapter):\n    invalidating_methods = {\"PUT\", \"PATCH\", \"DELETE\"}\n\n    def __init__(\n        self,\n        cache: BaseCache | None = None,\n        cache_etags: bool = True,\n        controller_class: type[CacheController] | None = None,\n        serializer: Serializer | None = None,\n        heuristic: BaseHeuristic | None = None,\n        cacheable_methods: Collection[str] | None = None,\n        *args: Any,\n        **kw: Any,\n    ) -> None:\n        super().__init__(*args, **kw)\n        self.cache = DictCache() if cache is None else cache\n        self.heuristic = heuristic\n        self.cacheable_methods = cacheable_methods or (\"GET\",)\n\n        controller_factory = controller_class or CacheController\n        self.controller = controller_factory(\n            self.cache, cache_etags=cache_etags, serializer=serializer\n        )\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: None | float | tuple[float, float] | tuple[float, None] = None,\n        verify: bool | str = True,\n        cert: (None | bytes | str | tuple[bytes | str, bytes | str]) = None,\n        proxies: Mapping[str, str] | None = None,\n        cacheable_methods: Collection[str] | None = None,\n    ) -> Response:\n        \"\"\"\n        Send a request. Use the request information to see if it\n        exists in the cache and cache the response if we need to and can.\n        \"\"\"\n        cacheable = cacheable_methods or self.cacheable_methods\n        if request.method in cacheable:\n            try:\n                cached_response = self.controller.cached_request(request)\n            except zlib.error:\n                cached_response = None\n            if cached_response:\n                return self.build_response(request, cached_response, from_cache=True)\n\n            # check for etags and add headers if appropriate\n            request.headers.update(self.controller.conditional_headers(request))\n\n        resp = super().send(request, stream, timeout, verify, cert, proxies)\n\n        return resp\n\n    def build_response(  # type: ignore[override]\n        self,\n        request: PreparedRequest,\n        response: HTTPResponse,\n        from_cache: bool = False,\n        cacheable_methods: Collection[str] | None = None,\n    ) -> Response:\n        \"\"\"\n        Build a response by making a request or using the cache.\n\n        This will end up calling send and returning a potentially\n        cached response\n        \"\"\"\n        cacheable = cacheable_methods or self.cacheable_methods\n        if not from_cache and request.method in cacheable:\n            # Check for any heuristics that might update headers\n            # before trying to cache.\n            if self.heuristic:\n                response = self.heuristic.apply(response)\n\n            # apply any expiration heuristics\n            if response.status == 304:\n                # We must have sent an ETag request. This could mean\n                # that we've been expired already or that we simply\n                # have an etag. In either case, we want to try and\n                # update the cache if that is the case.\n                cached_response = self.controller.update_cached_response(\n                    request, response\n                )\n\n                if cached_response is not response:\n                    from_cache = True\n\n                # We are done with the server response, read a\n                # possible response body (compliant servers will\n                # not return one, but we cannot be 100% sure) and\n                # release the connection back to the pool.\n                response.read(decode_content=False)\n                response.release_conn()\n\n                response = cached_response\n\n            # We always cache the 301 responses\n            elif int(response.status) in PERMANENT_REDIRECT_STATUSES:\n                self.controller.cache_response(request, response)\n            else:\n                # Wrap the response file with a wrapper that will cache the\n                #   response when the stream has been consumed.\n                response._fp = CallbackFileWrapper(  # type: ignore[assignment]\n                    response._fp,  # type: ignore[arg-type]\n                    functools.partial(\n                        self.controller.cache_response, request, weakref.ref(response)\n                    ),\n                )\n                if response.chunked:\n                    super_update_chunk_length = response.__class__._update_chunk_length\n\n                    def _update_chunk_length(\n                        weak_self: weakref.ReferenceType[HTTPResponse],\n                    ) -> None:\n                        self = weak_self()\n                        if self is None:\n                            return\n\n                        super_update_chunk_length(self)\n                        if self.chunk_left == 0:\n                            self._fp._close()  # type: ignore[union-attr]\n\n                    response._update_chunk_length = functools.partial(  # type: ignore[method-assign]\n                        _update_chunk_length, weakref.ref(response)\n                    )\n\n        resp: Response = super().build_response(request, response)\n\n        # See if we should invalidate the cache.\n        if request.method in self.invalidating_methods and resp.ok:\n            assert request.url is not None\n            cache_url = self.controller.cache_url(request.url)\n            self.cache.delete(cache_url)\n\n        # Give the request a from_cache attr to let people use it\n        resp.from_cache = from_cache  # type: ignore[attr-defined]\n\n        return resp\n\n    def close(self) -> None:\n        self.cache.close()\n        super().close()  # type: ignore[no-untyped-call]\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThe cache object API for implementing caches. The default is a thread\nsafe in-memory dictionary.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom threading import Lock\nfrom typing import IO, TYPE_CHECKING, MutableMapping\n\nif TYPE_CHECKING:\n    from datetime import datetime\n\n\nclass BaseCache:\n    def get(self, key: str) -> bytes | None:\n        raise NotImplementedError()\n\n    def set(\n        self, key: str, value: bytes, expires: int | datetime | None = None\n    ) -> None:\n        raise NotImplementedError()\n\n    def delete(self, key: str) -> None:\n        raise NotImplementedError()\n\n    def close(self) -> None:\n        pass\n\n\nclass DictCache(BaseCache):\n    def __init__(self, init_dict: MutableMapping[str, bytes] | None = None) -> None:\n        self.lock = Lock()\n        self.data = init_dict or {}\n\n    def get(self, key: str) -> bytes | None:\n        return self.data.get(key, None)\n\n    def set(\n        self, key: str, value: bytes, expires: int | datetime | None = None\n    ) -> None:\n        with self.lock:\n            self.data.update({key: value})\n\n    def delete(self, key: str) -> None:\n        with self.lock:\n            if key in self.data:\n                self.data.pop(key)\n\n\nclass SeparateBodyBaseCache(BaseCache):\n    \"\"\"\n    In this variant, the body is not stored mixed in with the metadata, but is\n    passed in (as a bytes-like object) in a separate call to ``set_body()``.\n\n    That is, the expected interaction pattern is::\n\n        cache.set(key, serialized_metadata)\n        cache.set_body(key)\n\n    Similarly, the body should be loaded separately via ``get_body()``.\n    \"\"\"\n\n    def set_body(self, key: str, body: bytes) -> None:\n        raise NotImplementedError()\n\n    def get_body(self, key: str) -> IO[bytes] | None:\n        \"\"\"\n        Return the body as file-like object.\n        \"\"\"\n        raise NotImplementedError()\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/caches/__init__.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom pip._vendor.cachecontrol.caches.file_cache import FileCache, SeparateBodyFileCache\nfrom pip._vendor.cachecontrol.caches.redis_cache import RedisCache\n\n__all__ = [\"FileCache\", \"SeparateBodyFileCache\", \"RedisCache\"]\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/caches/file_cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport hashlib\nimport os\nimport tempfile\nfrom textwrap import dedent\nfrom typing import IO, TYPE_CHECKING\nfrom pathlib import Path\n\nfrom pip._vendor.cachecontrol.cache import BaseCache, SeparateBodyBaseCache\nfrom pip._vendor.cachecontrol.controller import CacheController\n\nif TYPE_CHECKING:\n    from datetime import datetime\n\n    from filelock import BaseFileLock\n\n\nclass _FileCacheMixin:\n    \"\"\"Shared implementation for both FileCache variants.\"\"\"\n\n    def __init__(\n        self,\n        directory: str | Path,\n        forever: bool = False,\n        filemode: int = 0o0600,\n        dirmode: int = 0o0700,\n        lock_class: type[BaseFileLock] | None = None,\n    ) -> None:\n        try:\n            if lock_class is None:\n                from filelock import FileLock\n\n                lock_class = FileLock\n        except ImportError:\n            notice = dedent(\n                \"\"\"\n            NOTE: In order to use the FileCache you must have\n            filelock installed. You can install it via pip:\n              pip install cachecontrol[filecache]\n            \"\"\"\n            )\n            raise ImportError(notice)\n\n        self.directory = directory\n        self.forever = forever\n        self.filemode = filemode\n        self.dirmode = dirmode\n        self.lock_class = lock_class\n\n    @staticmethod\n    def encode(x: str) -> str:\n        return hashlib.sha224(x.encode()).hexdigest()\n\n    def _fn(self, name: str) -> str:\n        # NOTE: This method should not change as some may depend on it.\n        #       See: https://github.com/ionrock/cachecontrol/issues/63\n        hashed = self.encode(name)\n        parts = list(hashed[:5]) + [hashed]\n        return os.path.join(self.directory, *parts)\n\n    def get(self, key: str) -> bytes | None:\n        name = self._fn(key)\n        try:\n            with open(name, \"rb\") as fh:\n                return fh.read()\n\n        except FileNotFoundError:\n            return None\n\n    def set(\n        self, key: str, value: bytes, expires: int | datetime | None = None\n    ) -> None:\n        name = self._fn(key)\n        self._write(name, value)\n\n    def _write(self, path: str, data: bytes) -> None:\n        \"\"\"\n        Safely write the data to the given path.\n        \"\"\"\n        # Make sure the directory exists\n        dirname = os.path.dirname(path)\n        os.makedirs(dirname, self.dirmode, exist_ok=True)\n\n        with self.lock_class(path + \".lock\"):\n            # Write our actual file\n            (fd, name) = tempfile.mkstemp(dir=dirname)\n            try:\n                os.write(fd, data)\n            finally:\n                os.close(fd)\n            os.chmod(name, self.filemode)\n            os.replace(name, path)\n\n    def _delete(self, key: str, suffix: str) -> None:\n        name = self._fn(key) + suffix\n        if not self.forever:\n            try:\n                os.remove(name)\n            except FileNotFoundError:\n                pass\n\n\nclass FileCache(_FileCacheMixin, BaseCache):\n    \"\"\"\n    Traditional FileCache: body is stored in memory, so not suitable for large\n    downloads.\n    \"\"\"\n\n    def delete(self, key: str) -> None:\n        self._delete(key, \"\")\n\n\nclass SeparateBodyFileCache(_FileCacheMixin, SeparateBodyBaseCache):\n    \"\"\"\n    Memory-efficient FileCache: body is stored in a separate file, reducing\n    peak memory usage.\n    \"\"\"\n\n    def get_body(self, key: str) -> IO[bytes] | None:\n        name = self._fn(key) + \".body\"\n        try:\n            return open(name, \"rb\")\n        except FileNotFoundError:\n            return None\n\n    def set_body(self, key: str, body: bytes) -> None:\n        name = self._fn(key) + \".body\"\n        self._write(name, body)\n\n    def delete(self, key: str) -> None:\n        self._delete(key, \"\")\n        self._delete(key, \".body\")\n\n\ndef url_to_file_path(url: str, filecache: FileCache) -> str:\n    \"\"\"Return the file cache path based on the URL.\n\n    This does not ensure the file exists!\n    \"\"\"\n    key = CacheController.cache_url(url)\n    return filecache._fn(key)\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/caches/redis_cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\n\nfrom datetime import datetime, timezone\nfrom typing import TYPE_CHECKING\n\nfrom pip._vendor.cachecontrol.cache import BaseCache\n\nif TYPE_CHECKING:\n    from redis import Redis\n\n\nclass RedisCache(BaseCache):\n    def __init__(self, conn: Redis[bytes]) -> None:\n        self.conn = conn\n\n    def get(self, key: str) -> bytes | None:\n        return self.conn.get(key)\n\n    def set(\n        self, key: str, value: bytes, expires: int | datetime | None = None\n    ) -> None:\n        if not expires:\n            self.conn.set(key, value)\n        elif isinstance(expires, datetime):\n            now_utc = datetime.now(timezone.utc)\n            if expires.tzinfo is None:\n                now_utc = now_utc.replace(tzinfo=None)\n            delta = expires - now_utc\n            self.conn.setex(key, int(delta.total_seconds()), value)\n        else:\n            self.conn.setex(key, expires, value)\n\n    def delete(self, key: str) -> None:\n        self.conn.delete(key)\n\n    def clear(self) -> None:\n        \"\"\"Helper for clearing all the keys in a database. Use with\n        caution!\"\"\"\n        for key in self.conn.keys():\n            self.conn.delete(key)\n\n    def close(self) -> None:\n        \"\"\"Redis uses connection pooling, no need to close the connection.\"\"\"\n        pass\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/controller.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThe httplib2 algorithms ported for use with requests.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport calendar\nimport logging\nimport re\nimport time\nimport weakref\nfrom email.utils import parsedate_tz\nfrom typing import TYPE_CHECKING, Collection, Mapping\n\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\n\nfrom pip._vendor.cachecontrol.cache import DictCache, SeparateBodyBaseCache\nfrom pip._vendor.cachecontrol.serialize import Serializer\n\nif TYPE_CHECKING:\n    from typing import Literal\n\n    from pip._vendor.requests import PreparedRequest\n    from pip._vendor.urllib3 import HTTPResponse\n\n    from pip._vendor.cachecontrol.cache import BaseCache\n\nlogger = logging.getLogger(__name__)\n\nURI = re.compile(r\"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\")\n\nPERMANENT_REDIRECT_STATUSES = (301, 308)\n\n\ndef parse_uri(uri: str) -> tuple[str, str, str, str, str]:\n    \"\"\"Parses a URI using the regex given in Appendix B of RFC 3986.\n\n    (scheme, authority, path, query, fragment) = parse_uri(uri)\n    \"\"\"\n    match = URI.match(uri)\n    assert match is not None\n    groups = match.groups()\n    return (groups[1], groups[3], groups[4], groups[6], groups[8])\n\n\nclass CacheController:\n    \"\"\"An interface to see if request should cached or not.\"\"\"\n\n    def __init__(\n        self,\n        cache: BaseCache | None = None,\n        cache_etags: bool = True,\n        serializer: Serializer | None = None,\n        status_codes: Collection[int] | None = None,\n    ):\n        self.cache = DictCache() if cache is None else cache\n        self.cache_etags = cache_etags\n        self.serializer = serializer or Serializer()\n        self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308)\n\n    @classmethod\n    def _urlnorm(cls, uri: str) -> str:\n        \"\"\"Normalize the URL to create a safe key for the cache\"\"\"\n        (scheme, authority, path, query, fragment) = parse_uri(uri)\n        if not scheme or not authority:\n            raise Exception(\"Only absolute URIs are allowed. uri = %s\" % uri)\n\n        scheme = scheme.lower()\n        authority = authority.lower()\n\n        if not path:\n            path = \"/\"\n\n        # Could do syntax based normalization of the URI before\n        # computing the digest. See Section 6.2.2 of Std 66.\n        request_uri = query and \"?\".join([path, query]) or path\n        defrag_uri = scheme + \"://\" + authority + request_uri\n\n        return defrag_uri\n\n    @classmethod\n    def cache_url(cls, uri: str) -> str:\n        return cls._urlnorm(uri)\n\n    def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]:\n        known_directives = {\n            # https://tools.ietf.org/html/rfc7234#section-5.2\n            \"max-age\": (int, True),\n            \"max-stale\": (int, False),\n            \"min-fresh\": (int, True),\n            \"no-cache\": (None, False),\n            \"no-store\": (None, False),\n            \"no-transform\": (None, False),\n            \"only-if-cached\": (None, False),\n            \"must-revalidate\": (None, False),\n            \"public\": (None, False),\n            \"private\": (None, False),\n            \"proxy-revalidate\": (None, False),\n            \"s-maxage\": (int, True),\n        }\n\n        cc_headers = headers.get(\"cache-control\", headers.get(\"Cache-Control\", \"\"))\n\n        retval: dict[str, int | None] = {}\n\n        for cc_directive in cc_headers.split(\",\"):\n            if not cc_directive.strip():\n                continue\n\n            parts = cc_directive.split(\"=\", 1)\n            directive = parts[0].strip()\n\n            try:\n                typ, required = known_directives[directive]\n            except KeyError:\n                logger.debug(\"Ignoring unknown cache-control directive: %s\", directive)\n                continue\n\n            if not typ or not required:\n                retval[directive] = None\n            if typ:\n                try:\n                    retval[directive] = typ(parts[1].strip())\n                except IndexError:\n                    if required:\n                        logger.debug(\n                            \"Missing value for cache-control \" \"directive: %s\",\n                            directive,\n                        )\n                except ValueError:\n                    logger.debug(\n                        \"Invalid value for cache-control directive \" \"%s, must be %s\",\n                        directive,\n                        typ.__name__,\n                    )\n\n        return retval\n\n    def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None:\n        \"\"\"\n        Load a cached response, or return None if it's not available.\n        \"\"\"\n        # We do not support caching of partial content: so if the request contains a\n        # Range header then we don't want to load anything from the cache.\n        if \"Range\" in request.headers:\n            return None\n\n        cache_url = request.url\n        assert cache_url is not None\n        cache_data = self.cache.get(cache_url)\n        if cache_data is None:\n            logger.debug(\"No cache entry available\")\n            return None\n\n        if isinstance(self.cache, SeparateBodyBaseCache):\n            body_file = self.cache.get_body(cache_url)\n        else:\n            body_file = None\n\n        result = self.serializer.loads(request, cache_data, body_file)\n        if result is None:\n            logger.warning(\"Cache entry deserialization failed, entry ignored\")\n        return result\n\n    def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]:\n        \"\"\"\n        Return a cached response if it exists in the cache, otherwise\n        return False.\n        \"\"\"\n        assert request.url is not None\n        cache_url = self.cache_url(request.url)\n        logger.debug('Looking up \"%s\" in the cache', cache_url)\n        cc = self.parse_cache_control(request.headers)\n\n        # Bail out if the request insists on fresh data\n        if \"no-cache\" in cc:\n            logger.debug('Request header has \"no-cache\", cache bypassed')\n            return False\n\n        if \"max-age\" in cc and cc[\"max-age\"] == 0:\n            logger.debug('Request header has \"max_age\" as 0, cache bypassed')\n            return False\n\n        # Check whether we can load the response from the cache:\n        resp = self._load_from_cache(request)\n        if not resp:\n            return False\n\n        # If we have a cached permanent redirect, return it immediately. We\n        # don't need to test our response for other headers b/c it is\n        # intrinsically \"cacheable\" as it is Permanent.\n        #\n        # See:\n        #   https://tools.ietf.org/html/rfc7231#section-6.4.2\n        #\n        # Client can try to refresh the value by repeating the request\n        # with cache busting headers as usual (ie no-cache).\n        if int(resp.status) in PERMANENT_REDIRECT_STATUSES:\n            msg = (\n                \"Returning cached permanent redirect response \"\n                \"(ignoring date and etag information)\"\n            )\n            logger.debug(msg)\n            return resp\n\n        headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)\n        if not headers or \"date\" not in headers:\n            if \"etag\" not in headers:\n                # Without date or etag, the cached response can never be used\n                # and should be deleted.\n                logger.debug(\"Purging cached response: no date or etag\")\n                self.cache.delete(cache_url)\n            logger.debug(\"Ignoring cached response: no date\")\n            return False\n\n        now = time.time()\n        time_tuple = parsedate_tz(headers[\"date\"])\n        assert time_tuple is not None\n        date = calendar.timegm(time_tuple[:6])\n        current_age = max(0, now - date)\n        logger.debug(\"Current age based on date: %i\", current_age)\n\n        # TODO: There is an assumption that the result will be a\n        #       urllib3 response object. This may not be best since we\n        #       could probably avoid instantiating or constructing the\n        #       response until we know we need it.\n        resp_cc = self.parse_cache_control(headers)\n\n        # determine freshness\n        freshness_lifetime = 0\n\n        # Check the max-age pragma in the cache control header\n        max_age = resp_cc.get(\"max-age\")\n        if max_age is not None:\n            freshness_lifetime = max_age\n            logger.debug(\"Freshness lifetime from max-age: %i\", freshness_lifetime)\n\n        # If there isn't a max-age, check for an expires header\n        elif \"expires\" in headers:\n            expires = parsedate_tz(headers[\"expires\"])\n            if expires is not None:\n                expire_time = calendar.timegm(expires[:6]) - date\n                freshness_lifetime = max(0, expire_time)\n                logger.debug(\"Freshness lifetime from expires: %i\", freshness_lifetime)\n\n        # Determine if we are setting freshness limit in the\n        # request. Note, this overrides what was in the response.\n        max_age = cc.get(\"max-age\")\n        if max_age is not None:\n            freshness_lifetime = max_age\n            logger.debug(\n                \"Freshness lifetime from request max-age: %i\", freshness_lifetime\n            )\n\n        min_fresh = cc.get(\"min-fresh\")\n        if min_fresh is not None:\n            # adjust our current age by our min fresh\n            current_age += min_fresh\n            logger.debug(\"Adjusted current age from min-fresh: %i\", current_age)\n\n        # Return entry if it is fresh enough\n        if freshness_lifetime > current_age:\n            logger.debug('The response is \"fresh\", returning cached response')\n            logger.debug(\"%i > %i\", freshness_lifetime, current_age)\n            return resp\n\n        # we're not fresh. If we don't have an Etag, clear it out\n        if \"etag\" not in headers:\n            logger.debug('The cached response is \"stale\" with no etag, purging')\n            self.cache.delete(cache_url)\n\n        # return the original handler\n        return False\n\n    def conditional_headers(self, request: PreparedRequest) -> dict[str, str]:\n        resp = self._load_from_cache(request)\n        new_headers = {}\n\n        if resp:\n            headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)\n\n            if \"etag\" in headers:\n                new_headers[\"If-None-Match\"] = headers[\"ETag\"]\n\n            if \"last-modified\" in headers:\n                new_headers[\"If-Modified-Since\"] = headers[\"Last-Modified\"]\n\n        return new_headers\n\n    def _cache_set(\n        self,\n        cache_url: str,\n        request: PreparedRequest,\n        response: HTTPResponse,\n        body: bytes | None = None,\n        expires_time: int | None = None,\n    ) -> None:\n        \"\"\"\n        Store the data in the cache.\n        \"\"\"\n        if isinstance(self.cache, SeparateBodyBaseCache):\n            # We pass in the body separately; just put a placeholder empty\n            # string in the metadata.\n            self.cache.set(\n                cache_url,\n                self.serializer.dumps(request, response, b\"\"),\n                expires=expires_time,\n            )\n            # body is None can happen when, for example, we're only updating\n            # headers, as is the case in update_cached_response().\n            if body is not None:\n                self.cache.set_body(cache_url, body)\n        else:\n            self.cache.set(\n                cache_url,\n                self.serializer.dumps(request, response, body),\n                expires=expires_time,\n            )\n\n    def cache_response(\n        self,\n        request: PreparedRequest,\n        response_or_ref: HTTPResponse | weakref.ReferenceType[HTTPResponse],\n        body: bytes | None = None,\n        status_codes: Collection[int] | None = None,\n    ) -> None:\n        \"\"\"\n        Algorithm for caching requests.\n\n        This assumes a requests Response object.\n        \"\"\"\n        if isinstance(response_or_ref, weakref.ReferenceType):\n            response = response_or_ref()\n            if response is None:\n                # The weakref can be None only in case the user used streamed request\n                # and did not consume or close it, and holds no reference to requests.Response.\n                # In such case, we don't want to cache the response.\n                return\n        else:\n            response = response_or_ref\n\n        # From httplib2: Don't cache 206's since we aren't going to\n        #                handle byte range requests\n        cacheable_status_codes = status_codes or self.cacheable_status_codes\n        if response.status not in cacheable_status_codes:\n            logger.debug(\n                \"Status code %s not in %s\", response.status, cacheable_status_codes\n            )\n            return\n\n        response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(\n            response.headers\n        )\n\n        if \"date\" in response_headers:\n            time_tuple = parsedate_tz(response_headers[\"date\"])\n            assert time_tuple is not None\n            date = calendar.timegm(time_tuple[:6])\n        else:\n            date = 0\n\n        # If we've been given a body, our response has a Content-Length, that\n        # Content-Length is valid then we can check to see if the body we've\n        # been given matches the expected size, and if it doesn't we'll just\n        # skip trying to cache it.\n        if (\n            body is not None\n            and \"content-length\" in response_headers\n            and response_headers[\"content-length\"].isdigit()\n            and int(response_headers[\"content-length\"]) != len(body)\n        ):\n            return\n\n        cc_req = self.parse_cache_control(request.headers)\n        cc = self.parse_cache_control(response_headers)\n\n        assert request.url is not None\n        cache_url = self.cache_url(request.url)\n        logger.debug('Updating cache with response from \"%s\"', cache_url)\n\n        # Delete it from the cache if we happen to have it stored there\n        no_store = False\n        if \"no-store\" in cc:\n            no_store = True\n            logger.debug('Response header has \"no-store\"')\n        if \"no-store\" in cc_req:\n            no_store = True\n            logger.debug('Request header has \"no-store\"')\n        if no_store and self.cache.get(cache_url):\n            logger.debug('Purging existing cache entry to honor \"no-store\"')\n            self.cache.delete(cache_url)\n        if no_store:\n            return\n\n        # https://tools.ietf.org/html/rfc7234#section-4.1:\n        # A Vary header field-value of \"*\" always fails to match.\n        # Storing such a response leads to a deserialization warning\n        # during cache lookup and is not allowed to ever be served,\n        # so storing it can be avoided.\n        if \"*\" in response_headers.get(\"vary\", \"\"):\n            logger.debug('Response header has \"Vary: *\"')\n            return\n\n        # If we've been given an etag, then keep the response\n        if self.cache_etags and \"etag\" in response_headers:\n            expires_time = 0\n            if response_headers.get(\"expires\"):\n                expires = parsedate_tz(response_headers[\"expires\"])\n                if expires is not None:\n                    expires_time = calendar.timegm(expires[:6]) - date\n\n            expires_time = max(expires_time, 14 * 86400)\n\n            logger.debug(f\"etag object cached for {expires_time} seconds\")\n            logger.debug(\"Caching due to etag\")\n            self._cache_set(cache_url, request, response, body, expires_time)\n\n        # Add to the cache any permanent redirects. We do this before looking\n        # that the Date headers.\n        elif int(response.status) in PERMANENT_REDIRECT_STATUSES:\n            logger.debug(\"Caching permanent redirect\")\n            self._cache_set(cache_url, request, response, b\"\")\n\n        # Add to the cache if the response headers demand it. If there\n        # is no date header then we can't do anything about expiring\n        # the cache.\n        elif \"date\" in response_headers:\n            time_tuple = parsedate_tz(response_headers[\"date\"])\n            assert time_tuple is not None\n            date = calendar.timegm(time_tuple[:6])\n            # cache when there is a max-age > 0\n            max_age = cc.get(\"max-age\")\n            if max_age is not None and max_age > 0:\n                logger.debug(\"Caching b/c date exists and max-age > 0\")\n                expires_time = max_age\n                self._cache_set(\n                    cache_url,\n                    request,\n                    response,\n                    body,\n                    expires_time,\n                )\n\n            # If the request can expire, it means we should cache it\n            # in the meantime.\n            elif \"expires\" in response_headers:\n                if response_headers[\"expires\"]:\n                    expires = parsedate_tz(response_headers[\"expires\"])\n                    if expires is not None:\n                        expires_time = calendar.timegm(expires[:6]) - date\n                    else:\n                        expires_time = None\n\n                    logger.debug(\n                        \"Caching b/c of expires header. expires in {} seconds\".format(\n                            expires_time\n                        )\n                    )\n                    self._cache_set(\n                        cache_url,\n                        request,\n                        response,\n                        body,\n                        expires_time,\n                    )\n\n    def update_cached_response(\n        self, request: PreparedRequest, response: HTTPResponse\n    ) -> HTTPResponse:\n        \"\"\"On a 304 we will get a new set of headers that we want to\n        update our cached value with, assuming we have one.\n\n        This should only ever be called when we've sent an ETag and\n        gotten a 304 as the response.\n        \"\"\"\n        assert request.url is not None\n        cache_url = self.cache_url(request.url)\n        cached_response = self._load_from_cache(request)\n\n        if not cached_response:\n            # we didn't have a cached response\n            return response\n\n        # Lets update our headers with the headers from the new request:\n        # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1\n        #\n        # The server isn't supposed to send headers that would make\n        # the cached body invalid. But... just in case, we'll be sure\n        # to strip out ones we know that might be problematic due to\n        # typical assumptions.\n        excluded_headers = [\"content-length\"]\n\n        cached_response.headers.update(\n            {\n                k: v\n                for k, v in response.headers.items()\n                if k.lower() not in excluded_headers\n            }\n        )\n\n        # we want a 200 b/c we have content via the cache\n        cached_response.status = 200\n\n        # update our cache\n        self._cache_set(cache_url, request, cached_response)\n\n        return cached_response\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/filewrapper.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport mmap\nfrom tempfile import NamedTemporaryFile\nfrom typing import TYPE_CHECKING, Any, Callable\n\nif TYPE_CHECKING:\n    from collections.abc import Buffer\n    from http.client import HTTPResponse\n\n\nclass CallbackFileWrapper:\n    \"\"\"\n    Small wrapper around a fp object which will tee everything read into a\n    buffer, and when that file is closed it will execute a callback with the\n    contents of that buffer.\n\n    All attributes are proxied to the underlying file object.\n\n    This class uses members with a double underscore (__) leading prefix so as\n    not to accidentally shadow an attribute.\n\n    The data is stored in a temporary file until it is all available.  As long\n    as the temporary files directory is disk-based (sometimes it's a\n    memory-backed-``tmpfs`` on Linux), data will be unloaded to disk if memory\n    pressure is high.  For small files the disk usually won't be used at all,\n    it'll all be in the filesystem memory cache, so there should be no\n    performance impact.\n    \"\"\"\n\n    def __init__(\n        self, fp: HTTPResponse, callback: Callable[[Buffer], None] | None\n    ) -> None:\n        self.__buf = NamedTemporaryFile(\"rb+\", delete=True)\n        self.__fp = fp\n        self.__callback = callback\n\n    def __getattr__(self, name: str) -> Any:\n        # The vagaries of garbage collection means that self.__fp is\n        # not always set.  By using __getattribute__ and the private\n        # name[0] allows looking up the attribute value and raising an\n        # AttributeError when it doesn't exist. This stop things from\n        # infinitely recursing calls to getattr in the case where\n        # self.__fp hasn't been set.\n        #\n        # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers\n        fp = self.__getattribute__(\"_CallbackFileWrapper__fp\")\n        return getattr(fp, name)\n\n    def __is_fp_closed(self) -> bool:\n        try:\n            return self.__fp.fp is None\n\n        except AttributeError:\n            pass\n\n        try:\n            closed: bool = self.__fp.closed\n            return closed\n\n        except AttributeError:\n            pass\n\n        # We just don't cache it then.\n        # TODO: Add some logging here...\n        return False\n\n    def _close(self) -> None:\n        result: Buffer\n        if self.__callback:\n            if self.__buf.tell() == 0:\n                # Empty file:\n                result = b\"\"\n            else:\n                # Return the data without actually loading it into memory,\n                # relying on Python's buffer API and mmap(). mmap() just gives\n                # a view directly into the filesystem's memory cache, so it\n                # doesn't result in duplicate memory use.\n                self.__buf.seek(0, 0)\n                result = memoryview(\n                    mmap.mmap(self.__buf.fileno(), 0, access=mmap.ACCESS_READ)\n                )\n            self.__callback(result)\n\n        # We assign this to None here, because otherwise we can get into\n        # really tricky problems where the CPython interpreter dead locks\n        # because the callback is holding a reference to something which\n        # has a __del__ method. Setting this to None breaks the cycle\n        # and allows the garbage collector to do it's thing normally.\n        self.__callback = None\n\n        # Closing the temporary file releases memory and frees disk space.\n        # Important when caching big files.\n        self.__buf.close()\n\n    def read(self, amt: int | None = None) -> bytes:\n        data: bytes = self.__fp.read(amt)\n        if data:\n            # We may be dealing with b'', a sign that things are over:\n            # it's passed e.g. after we've already closed self.__buf.\n            self.__buf.write(data)\n        if self.__is_fp_closed():\n            self._close()\n\n        return data\n\n    def _safe_read(self, amt: int) -> bytes:\n        data: bytes = self.__fp._safe_read(amt)  # type: ignore[attr-defined]\n        if amt == 2 and data == b\"\\r\\n\":\n            # urllib executes this read to toss the CRLF at the end\n            # of the chunk.\n            return data\n\n        self.__buf.write(data)\n        if self.__is_fp_closed():\n            self._close()\n\n        return data\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/heuristics.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport calendar\nimport time\nfrom datetime import datetime, timedelta, timezone\nfrom email.utils import formatdate, parsedate, parsedate_tz\nfrom typing import TYPE_CHECKING, Any, Mapping\n\nif TYPE_CHECKING:\n    from pip._vendor.urllib3 import HTTPResponse\n\nTIME_FMT = \"%a, %d %b %Y %H:%M:%S GMT\"\n\n\ndef expire_after(delta: timedelta, date: datetime | None = None) -> datetime:\n    date = date or datetime.now(timezone.utc)\n    return date + delta\n\n\ndef datetime_to_header(dt: datetime) -> str:\n    return formatdate(calendar.timegm(dt.timetuple()))\n\n\nclass BaseHeuristic:\n    def warning(self, response: HTTPResponse) -> str | None:\n        \"\"\"\n        Return a valid 1xx warning header value describing the cache\n        adjustments.\n\n        The response is provided too allow warnings like 113\n        http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need\n        to explicitly say response is over 24 hours old.\n        \"\"\"\n        return '110 - \"Response is Stale\"'\n\n    def update_headers(self, response: HTTPResponse) -> dict[str, str]:\n        \"\"\"Update the response headers with any new headers.\n\n        NOTE: This SHOULD always include some Warning header to\n              signify that the response was cached by the client, not\n              by way of the provided headers.\n        \"\"\"\n        return {}\n\n    def apply(self, response: HTTPResponse) -> HTTPResponse:\n        updated_headers = self.update_headers(response)\n\n        if updated_headers:\n            response.headers.update(updated_headers)\n            warning_header_value = self.warning(response)\n            if warning_header_value is not None:\n                response.headers.update({\"Warning\": warning_header_value})\n\n        return response\n\n\nclass OneDayCache(BaseHeuristic):\n    \"\"\"\n    Cache the response by providing an expires 1 day in the\n    future.\n    \"\"\"\n\n    def update_headers(self, response: HTTPResponse) -> dict[str, str]:\n        headers = {}\n\n        if \"expires\" not in response.headers:\n            date = parsedate(response.headers[\"date\"])\n            expires = expire_after(\n                timedelta(days=1),\n                date=datetime(*date[:6], tzinfo=timezone.utc),  # type: ignore[index,misc]\n            )\n            headers[\"expires\"] = datetime_to_header(expires)\n            headers[\"cache-control\"] = \"public\"\n        return headers\n\n\nclass ExpiresAfter(BaseHeuristic):\n    \"\"\"\n    Cache **all** requests for a defined time period.\n    \"\"\"\n\n    def __init__(self, **kw: Any) -> None:\n        self.delta = timedelta(**kw)\n\n    def update_headers(self, response: HTTPResponse) -> dict[str, str]:\n        expires = expire_after(self.delta)\n        return {\"expires\": datetime_to_header(expires), \"cache-control\": \"public\"}\n\n    def warning(self, response: HTTPResponse) -> str | None:\n        tmpl = \"110 - Automatically cached for %s. Response might be stale\"\n        return tmpl % self.delta\n\n\nclass LastModified(BaseHeuristic):\n    \"\"\"\n    If there is no Expires header already, fall back on Last-Modified\n    using the heuristic from\n    http://tools.ietf.org/html/rfc7234#section-4.2.2\n    to calculate a reasonable value.\n\n    Firefox also does something like this per\n    https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ\n    http://lxr.mozilla.org/mozilla-release/source/netwerk/protocol/http/nsHttpResponseHead.cpp#397\n    Unlike mozilla we limit this to 24-hr.\n    \"\"\"\n\n    cacheable_by_default_statuses = {\n        200,\n        203,\n        204,\n        206,\n        300,\n        301,\n        404,\n        405,\n        410,\n        414,\n        501,\n    }\n\n    def update_headers(self, resp: HTTPResponse) -> dict[str, str]:\n        headers: Mapping[str, str] = resp.headers\n\n        if \"expires\" in headers:\n            return {}\n\n        if \"cache-control\" in headers and headers[\"cache-control\"] != \"public\":\n            return {}\n\n        if resp.status not in self.cacheable_by_default_statuses:\n            return {}\n\n        if \"date\" not in headers or \"last-modified\" not in headers:\n            return {}\n\n        time_tuple = parsedate_tz(headers[\"date\"])\n        assert time_tuple is not None\n        date = calendar.timegm(time_tuple[:6])\n        last_modified = parsedate(headers[\"last-modified\"])\n        if last_modified is None:\n            return {}\n\n        now = time.time()\n        current_age = max(0, now - date)\n        delta = date - calendar.timegm(last_modified)\n        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))\n        if freshness_lifetime <= current_age:\n            return {}\n\n        expires = date + freshness_lifetime\n        return {\"expires\": time.strftime(TIME_FMT, time.gmtime(expires))}\n\n    def warning(self, resp: HTTPResponse) -> str | None:\n        return None\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/cachecontrol/serialize.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nimport io\nfrom typing import IO, TYPE_CHECKING, Any, Mapping, cast\n\nfrom pip._vendor import msgpack\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\nfrom pip._vendor.urllib3 import HTTPResponse\n\nif TYPE_CHECKING:\n    from pip._vendor.requests import PreparedRequest\n\n\nclass Serializer:\n    serde_version = \"4\"\n\n    def dumps(\n        self,\n        request: PreparedRequest,\n        response: HTTPResponse,\n        body: bytes | None = None,\n    ) -> bytes:\n        response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(\n            response.headers\n        )\n\n        if body is None:\n            # When a body isn't passed in, we'll read the response. We\n            # also update the response with a new file handler to be\n            # sure it acts as though it was never read.\n            body = response.read(decode_content=False)\n            response._fp = io.BytesIO(body)  # type: ignore[assignment]\n            response.length_remaining = len(body)\n\n        data = {\n            \"response\": {\n                \"body\": body,  # Empty bytestring if body is stored separately\n                \"headers\": {str(k): str(v) for k, v in response.headers.items()},\n                \"status\": response.status,\n                \"version\": response.version,\n                \"reason\": str(response.reason),\n                \"decode_content\": response.decode_content,\n            }\n        }\n\n        # Construct our vary headers\n        data[\"vary\"] = {}\n        if \"vary\" in response_headers:\n            varied_headers = response_headers[\"vary\"].split(\",\")\n            for header in varied_headers:\n                header = str(header).strip()\n                header_value = request.headers.get(header, None)\n                if header_value is not None:\n                    header_value = str(header_value)\n                data[\"vary\"][header] = header_value\n\n        return b\",\".join([f\"cc={self.serde_version}\".encode(), self.serialize(data)])\n\n    def serialize(self, data: dict[str, Any]) -> bytes:\n        return cast(bytes, msgpack.dumps(data, use_bin_type=True))\n\n    def loads(\n        self,\n        request: PreparedRequest,\n        data: bytes,\n        body_file: IO[bytes] | None = None,\n    ) -> HTTPResponse | None:\n        # Short circuit if we've been given an empty set of data\n        if not data:\n            return None\n\n        # Previous versions of this library supported other serialization\n        # formats, but these have all been removed.\n        if not data.startswith(f\"cc={self.serde_version},\".encode()):\n            return None\n\n        data = data[5:]\n        return self._loads_v4(request, data, body_file)\n\n    def prepare_response(\n        self,\n        request: PreparedRequest,\n        cached: Mapping[str, Any],\n        body_file: IO[bytes] | None = None,\n    ) -> HTTPResponse | None:\n        \"\"\"Verify our vary headers match and construct a real urllib3\n        HTTPResponse object.\n        \"\"\"\n        # Special case the '*' Vary value as it means we cannot actually\n        # determine if the cached response is suitable for this request.\n        # This case is also handled in the controller code when creating\n        # a cache entry, but is left here for backwards compatibility.\n        if \"*\" in cached.get(\"vary\", {}):\n            return None\n\n        # Ensure that the Vary headers for the cached response match our\n        # request\n        for header, value in cached.get(\"vary\", {}).items():\n            if request.headers.get(header, None) != value:\n                return None\n\n        body_raw = cached[\"response\"].pop(\"body\")\n\n        headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(\n            data=cached[\"response\"][\"headers\"]\n        )\n        if headers.get(\"transfer-encoding\", \"\") == \"chunked\":\n            headers.pop(\"transfer-encoding\")\n\n        cached[\"response\"][\"headers\"] = headers\n\n        try:\n            body: IO[bytes]\n            if body_file is None:\n                body = io.BytesIO(body_raw)\n            else:\n                body = body_file\n        except TypeError:\n            # This can happen if cachecontrol serialized to v1 format (pickle)\n            # using Python 2. A Python 2 str(byte string) will be unpickled as\n            # a Python 3 str (unicode string), which will cause the above to\n            # fail with:\n            #\n            #     TypeError: 'str' does not support the buffer interface\n            body = io.BytesIO(body_raw.encode(\"utf8\"))\n\n        # Discard any `strict` parameter serialized by older version of cachecontrol.\n        cached[\"response\"].pop(\"strict\", None)\n\n        return HTTPResponse(body=body, preload_content=False, **cached[\"response\"])\n\n    def _loads_v4(\n        self,\n        request: PreparedRequest,\n        data: bytes,\n        body_file: IO[bytes] | None = None,\n    ) -> HTTPResponse | None:\n        try:\n            cached = msgpack.loads(data, raw=False)\n        except ValueError:\n            return None\n\n        return self.prepare_response(request, cached, body_file)\n"
  },
  {
    "path": "src/pip/_vendor/cachecontrol/wrapper.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Collection\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.cache import DictCache\n\nif TYPE_CHECKING:\n    from pip._vendor import requests\n\n    from pip._vendor.cachecontrol.cache import BaseCache\n    from pip._vendor.cachecontrol.controller import CacheController\n    from pip._vendor.cachecontrol.heuristics import BaseHeuristic\n    from pip._vendor.cachecontrol.serialize import Serializer\n\n\ndef CacheControl(\n    sess: requests.Session,\n    cache: BaseCache | None = None,\n    cache_etags: bool = True,\n    serializer: Serializer | None = None,\n    heuristic: BaseHeuristic | None = None,\n    controller_class: type[CacheController] | None = None,\n    adapter_class: type[CacheControlAdapter] | None = None,\n    cacheable_methods: Collection[str] | None = None,\n) -> requests.Session:\n    cache = DictCache() if cache is None else cache\n    adapter_class = adapter_class or CacheControlAdapter\n    adapter = adapter_class(\n        cache,\n        cache_etags=cache_etags,\n        serializer=serializer,\n        heuristic=heuristic,\n        controller_class=controller_class,\n        cacheable_methods=cacheable_methods,\n    )\n    sess.mount(\"http://\", adapter)\n    sess.mount(\"https://\", adapter)\n\n    return sess\n"
  },
  {
    "path": "src/pip/_vendor/certifi/LICENSE",
    "content": "This package contains a modified version of ca-bundle.crt:\n\nca-bundle.crt -- Bundle of CA Root Certificates\n\nThis is a bundle of X.509 certificates of public Certificate Authorities\n(CA). These were automatically extracted from Mozilla's root certificates\nfile (certdata.txt).  This file can be found in the mozilla source tree:\nhttps://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt\nIt contains the certificates in PEM format and therefore\ncan be directly used with curl / libcurl / php_curl, or with\nan Apache+mod_ssl webserver for SSL client authentication.\nJust configure this file as the SSLCACertificateFile.#\n\n***** BEGIN LICENSE BLOCK *****\nThis Source Code Form is subject to the terms of the Mozilla Public License,\nv. 2.0. If a copy of the MPL was not distributed with this file, You can obtain\none at http://mozilla.org/MPL/2.0/.\n\n***** END LICENSE BLOCK *****\n@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $\n"
  },
  {
    "path": "src/pip/_vendor/certifi/__init__.py",
    "content": "from .core import contents, where\n\n__all__ = [\"contents\", \"where\"]\n__version__ = \"2026.01.04\"\n"
  },
  {
    "path": "src/pip/_vendor/certifi/__main__.py",
    "content": "import argparse\n\nfrom pip._vendor.certifi import contents, where\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-c\", \"--contents\", action=\"store_true\")\nargs = parser.parse_args()\n\nif args.contents:\n    print(contents())\nelse:\n    print(where())\n"
  },
  {
    "path": "src/pip/_vendor/certifi/cacert.pem",
    "content": "\n# Issuer: CN=QuoVadis Root CA 2 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 2 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 2\"\n# Serial: 1289\n# MD5 Fingerprint: 5e:39:7b:dd:f8:ba:ec:82:e9:ac:62:ba:0c:54:00:2b\n# SHA1 Fingerprint: ca:3a:fb:cf:12:40:36:4b:44:b2:16:20:88:80:48:39:19:93:7c:f7\n# SHA256 Fingerprint: 85:a0:dd:7d:d7:20:ad:b7:ff:05:f8:3d:54:2b:20:9d:c7:ff:45:28:f7:d6:77:b1:83:89:fe:a5:e5:c4:9e:86\n-----BEGIN CERTIFICATE-----\nMIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x\nGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv\nb3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV\nBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W\nYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa\nGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg\nFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J\nWpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB\nrrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp\n+ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1\nksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i\nUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz\nPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og\n/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH\noycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI\nyV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud\nEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2\nA8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL\nMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT\nElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f\nBluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn\ng/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl\nfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K\nWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha\nB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc\nhLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR\nTUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD\nmbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z\nohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y\n4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza\n8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 3\"\n# Serial: 1478\n# MD5 Fingerprint: 31:85:3c:62:94:97:63:b9:aa:fd:89:4e:af:6f:e0:cf\n# SHA1 Fingerprint: 1f:49:14:f7:d8:74:95:1d:dd:ae:02:c0:be:fd:3a:2d:82:75:51:85\n# SHA256 Fingerprint: 18:f1:fc:7f:20:5d:f8:ad:dd:eb:7f:e0:07:dd:57:e3:af:37:5a:9c:4d:8d:73:54:6b:f4:f1:fe:d1:e1:8d:35\n-----BEGIN CERTIFICATE-----\nMIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x\nGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv\nb3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV\nBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W\nYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM\nV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB\n4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr\nH556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd\n8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv\nvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT\nmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe\nbtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc\nT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt\nWAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ\nc6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A\n4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD\nVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG\nCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0\naXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0\naWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu\ndC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw\nczALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G\nA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC\nTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg\nUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0\n7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem\nd1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd\n+LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B\n4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN\nt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x\nDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57\nk8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s\nzHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j\nWy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT\nmJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK\n4SVhM7JZG+Ju1zdXtg2pEto=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root CA\"\n# Serial: 17154717934120587862167794914071425081\n# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72\n# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43\n# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c\n-----BEGIN CERTIFICATE-----\nMIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv\nb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG\nEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl\ncnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi\nMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c\nJpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP\nmDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+\nwRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4\nVYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/\nAUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB\nAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun\npyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC\ndWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf\nfwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm\nNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx\nH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe\n+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root CA\"\n# Serial: 10944719598952040374951832963794454346\n# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e\n# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36\n# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61\n-----BEGIN CERTIFICATE-----\nMIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\nQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\nMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\nb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\nCSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\nnh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\nT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\ngdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\nBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\nTLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\nDQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\nhMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\nPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\nYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\nCAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert High Assurance EV Root CA\"\n# Serial: 3553400076410547919724730734378100087\n# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a\n# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25\n# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf\n-----BEGIN CERTIFICATE-----\nMIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\nZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\nMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\nLmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\nRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\nPNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\nxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\nIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\nhzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\nEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\nFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\nnzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\neM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\nhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\nYzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\nvEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n+OkuE6N36B9K\n-----END CERTIFICATE-----\n\n# Issuer: CN=SwissSign Gold CA - G2 O=SwissSign AG\n# Subject: CN=SwissSign Gold CA - G2 O=SwissSign AG\n# Label: \"SwissSign Gold CA - G2\"\n# Serial: 13492815561806991280\n# MD5 Fingerprint: 24:77:d9:a8:91:d1:3b:fa:88:2d:c2:ff:f8:cd:33:93\n# SHA1 Fingerprint: d8:c5:38:8a:b7:30:1b:1b:6e:d4:7a:e6:45:25:3a:6f:9f:1a:27:61\n# SHA256 Fingerprint: 62:dd:0b:e9:b9:f5:0a:16:3e:a0:f8:e7:5c:05:3b:1e:ca:57:ea:55:c8:68:8f:64:7c:68:81:f2:c8:35:7b:95\n-----BEGIN CERTIFICATE-----\nMIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV\nBAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln\nbiBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF\nMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT\nd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC\nCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8\n76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+\nbbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c\n6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE\nemA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd\nMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt\nMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y\nMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y\nFGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi\naG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM\ngI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB\nqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7\nlqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn\n8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov\nL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6\n45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO\nUYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5\nO1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC\nbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv\nGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a\n77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC\nhdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3\n92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp\nLd6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w\nZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt\nQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureTrust CA O=SecureTrust Corporation\n# Subject: CN=SecureTrust CA O=SecureTrust Corporation\n# Label: \"SecureTrust CA\"\n# Serial: 17199774589125277788362757014266862032\n# MD5 Fingerprint: dc:32:c3:a7:6d:25:57:c7:68:09:9d:ea:2d:a9:a2:d1\n# SHA1 Fingerprint: 87:82:c6:c3:04:35:3b:cf:d2:96:92:d2:59:3e:7d:44:d9:34:ff:11\n# SHA256 Fingerprint: f1:c1:b5:0a:e5:a2:0d:d8:03:0e:c9:f6:bc:24:82:3d:d3:67:b5:25:57:59:b4:e7:1b:61:fc:e9:f7:37:5d:73\n-----BEGIN CERTIFICATE-----\nMIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI\nMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x\nFzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz\nMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv\ncnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz\nZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO\n0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao\nwW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj\n7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS\n8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT\nBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB\n/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg\nJYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC\nNxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3\n6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/\n3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm\nD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS\nCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR\n3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Secure Global CA O=SecureTrust Corporation\n# Subject: CN=Secure Global CA O=SecureTrust Corporation\n# Label: \"Secure Global CA\"\n# Serial: 9751836167731051554232119481456978597\n# MD5 Fingerprint: cf:f4:27:0d:d4:ed:dc:65:16:49:6d:3d:da:bf:6e:de\n# SHA1 Fingerprint: 3a:44:73:5a:e5:81:90:1f:24:86:61:46:1e:3b:9c:c4:5f:f5:3a:1b\n# SHA256 Fingerprint: 42:00:f5:04:3a:c8:59:0e:bb:52:7d:20:9e:d1:50:30:29:fb:cb:d4:1c:a1:b5:06:ec:27:f1:5a:de:7d:ac:69\n-----BEGIN CERTIFICATE-----\nMIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK\nMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x\nGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx\nMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg\nQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG\nSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ\niQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa\n/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ\njnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI\nHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7\nsFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w\ngZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw\nKaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG\nAQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L\nURYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO\nH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm\nI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY\niNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc\nf8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO Certification Authority O=COMODO CA Limited\n# Label: \"COMODO Certification Authority\"\n# Serial: 104350513648249232941998508985834464573\n# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75\n# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b\n# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66\n-----BEGIN CERTIFICATE-----\nMIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB\ngTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\nA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV\nBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw\nMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl\nYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P\nRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0\naG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3\nUcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI\n2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8\nQ5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp\n+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+\nDT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O\nnKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW\n/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g\nPKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u\nQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY\nSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv\nIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/\nRxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4\nzJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd\nBA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB\nZQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited\n# Label: \"COMODO ECC Certification Authority\"\n# Serial: 41578283867086692638256921589707938090\n# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23\n# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11\n# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7\n-----BEGIN CERTIFICATE-----\nMIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL\nMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\nBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT\nIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw\nMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy\nZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N\nT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv\nbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR\nFtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J\ncfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW\nBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/\nBAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm\nfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv\nGDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certigna O=Dhimyotis\n# Subject: CN=Certigna O=Dhimyotis\n# Label: \"Certigna\"\n# Serial: 18364802974209362175\n# MD5 Fingerprint: ab:57:a6:5b:7d:42:82:19:b5:d8:58:26:28:5e:fd:ff\n# SHA1 Fingerprint: b1:2e:13:63:45:86:a4:6f:1a:b2:60:68:37:58:2d:c4:ac:fd:94:97\n# SHA256 Fingerprint: e3:b6:a2:db:2e:d7:ce:48:84:2f:7a:c5:32:41:c7:b7:1d:54:14:4b:fb:40:c1:1f:3f:1d:0b:42:f5:ee:a1:2d\n-----BEGIN CERTIFICATE-----\nMIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV\nBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X\nDTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ\nBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3\nDQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4\nQCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny\ngQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw\nzBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q\n130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2\nJsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw\nDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw\nZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT\nAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj\nAQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG\n9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h\nbV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc\nfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu\nHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w\nt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw\nWyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg==\n-----END CERTIFICATE-----\n\n# Issuer: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority\n# Subject: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority\n# Label: \"ePKI Root Certification Authority\"\n# Serial: 28956088682735189655030529057352760477\n# MD5 Fingerprint: 1b:2e:00:ca:26:06:90:3d:ad:fe:6f:15:68:d3:6b:b3\n# SHA1 Fingerprint: 67:65:0d:f1:7e:8e:7e:5b:82:40:a4:f4:56:4b:cf:e2:3d:69:c6:f0\n# SHA256 Fingerprint: c0:a6:f4:dc:63:a2:4b:fd:cf:54:ef:2a:6a:08:2a:0a:72:de:35:80:3e:2f:f5:ff:52:7a:e5:d8:72:06:df:d5\n-----BEGIN CERTIFICATE-----\nMIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe\nMQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0\nZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe\nFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw\nIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL\nSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF\nAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH\nSyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh\nijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X\nDZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1\nTBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ\nfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA\nsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU\nWH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS\nnT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH\ndmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip\nNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC\nAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF\nMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH\nClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB\nuvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl\nPwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP\nJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/\ngpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2\nj6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6\n5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB\no2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS\n/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z\nGp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE\nW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D\nhNQ+IIX3Sj0rnP0qCglN6oH4EZw=\n-----END CERTIFICATE-----\n\n# Issuer: O=certSIGN OU=certSIGN ROOT CA\n# Subject: O=certSIGN OU=certSIGN ROOT CA\n# Label: \"certSIGN ROOT CA\"\n# Serial: 35210227249154\n# MD5 Fingerprint: 18:98:c0:d6:e9:3a:fc:f9:b0:f5:0c:f7:4b:01:44:17\n# SHA1 Fingerprint: fa:b7:ee:36:97:26:62:fb:2d:b0:2a:f6:bf:03:fd:e8:7c:4b:2f:9b\n# SHA256 Fingerprint: ea:a9:62:c4:fa:4a:6b:af:eb:e4:15:19:6d:35:1c:cd:88:8d:4f:53:f3:fa:8a:e6:d7:c4:66:a9:4e:60:42:bb\n-----BEGIN CERTIFICATE-----\nMIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT\nAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD\nQTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP\nMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC\nASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do\n0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ\nUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d\nRdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ\nOA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv\nJoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C\nAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O\nBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ\nLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY\nMnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ\n44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I\nJd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw\ni/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN\n9u6wWk5JRFRYX0KD\n-----END CERTIFICATE-----\n\n# Issuer: CN=NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny O=NetLock Kft. OU=Tan\\xfas\\xedtv\\xe1nykiad\\xf3k (Certification Services)\n# Subject: CN=NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny O=NetLock Kft. OU=Tan\\xfas\\xedtv\\xe1nykiad\\xf3k (Certification Services)\n# Label: \"NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny\"\n# Serial: 80544274841616\n# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88\n# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91\n# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98\n-----BEGIN CERTIFICATE-----\nMIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG\nEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3\nMDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl\ncnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR\ndGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB\npzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM\nb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm\naWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz\nIEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\nMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT\nlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz\nAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5\nVA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG\nILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2\nBJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG\nAQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M\nU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh\nbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C\n+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC\nbLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F\nuLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2\nXjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.\n# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.\n# Label: \"Microsec e-Szigno Root CA 2009\"\n# Serial: 14014712776195784473\n# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1\n# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e\n# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78\n-----BEGIN CERTIFICATE-----\nMIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD\nVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0\nZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G\nCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y\nOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx\nFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp\nZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o\ndTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP\nkd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc\ncbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U\nfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7\nN4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC\nxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1\n+rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G\nA1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM\nPcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG\nSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h\nmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk\nddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775\ntyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c\n2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t\nHMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3\n# Label: \"GlobalSign Root CA - R3\"\n# Serial: 4835703278459759426209954\n# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28\n# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad\n# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b\n-----BEGIN CERTIFICATE-----\nMIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G\nA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp\nZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4\nMTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG\nA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8\nRgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT\ngHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm\nKPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd\nQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ\nXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw\nDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o\nLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU\nRUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp\njjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK\n6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX\nmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs\nMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH\nWD9f\n-----END CERTIFICATE-----\n\n# Issuer: CN=Izenpe.com O=IZENPE S.A.\n# Subject: CN=Izenpe.com O=IZENPE S.A.\n# Label: \"Izenpe.com\"\n# Serial: 917563065490389241595536686991402621\n# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73\n# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19\n# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f\n-----BEGIN CERTIFICATE-----\nMIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4\nMQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6\nZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD\nVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j\nb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq\nscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO\nxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H\nLmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX\nuaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD\nyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+\nJrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q\nrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN\nBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L\nhij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB\nQFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+\nHMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu\nZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg\nQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB\nBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx\nMCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA\nA4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb\nlaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56\nawmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo\nJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw\nLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT\nVyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk\nLhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb\nUjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/\nQnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+\nnaM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls\nQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.\n# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.\n# Label: \"Go Daddy Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01\n# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b\n# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da\n-----BEGIN CERTIFICATE-----\nMIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\nEUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\nZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\nNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\nEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\nAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\nE6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\nDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\nGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\ntDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\nAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\nFDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\nWWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\ngIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\nLPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n4uJEvlz36hz1\n-----END CERTIFICATE-----\n\n# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Label: \"Starfield Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96\n# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e\n# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5\n-----BEGIN CERTIFICATE-----\nMIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\nHFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\nZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\nMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\nb25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\naG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\nY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\nggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\nnLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\nHOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\nHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\ndloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\nHZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\nBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\nCSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\nsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\npL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\nmMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n-----END CERTIFICATE-----\n\n# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Label: \"Starfield Services Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2\n# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f\n# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5\n-----BEGIN CERTIFICATE-----\nMIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\nHFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs\nZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5\nMDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD\nVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy\nZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy\ndmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p\nOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2\n8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K\nTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe\nhRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk\n6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw\nDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q\nAdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI\nbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB\nve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z\nqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd\niEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn\n0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN\nsSi6\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Network CA\"\n# Serial: 279744\n# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78\n# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e\n# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e\n-----BEGIN CERTIFICATE-----\nMIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM\nMSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D\nZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU\ncnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3\nWjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg\nUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw\nIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B\nAQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH\nUV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM\nTXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU\nBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM\nkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x\nAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV\nHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y\nsHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL\nI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8\nJ9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY\nVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI\n03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA\n# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA\n# Label: \"TWCA Root Certification Authority\"\n# Serial: 1\n# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79\n# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48\n# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44\n-----BEGIN CERTIFICATE-----\nMIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES\nMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU\nV0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz\nWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO\nLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm\naWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\nAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE\nAcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH\nK3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX\nRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z\nrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx\n3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq\nhkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC\nMErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls\nXebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D\nlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn\naspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ\nYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==\n-----END CERTIFICATE-----\n\n# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2\n# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2\n# Label: \"Security Communication RootCA2\"\n# Serial: 0\n# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43\n# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74\n# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6\n-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl\nMCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe\nU2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX\nDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy\ndXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj\nYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV\nOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr\nzbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM\nVAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ\nhNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO\nojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw\nawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs\nOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\nDQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF\ncoJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc\nokgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8\nt/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy\n1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/\nSjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03\n-----END CERTIFICATE-----\n\n# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967\n# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967\n# Label: \"Actalis Authentication Root CA\"\n# Serial: 6271844772424770508\n# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6\n# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac\n# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66\n-----BEGIN CERTIFICATE-----\nMIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE\nBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w\nMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290\nIENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC\nSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1\nODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv\nUTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX\n4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9\nKK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/\ngCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb\nrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ\n51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F\nbe8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe\nKF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F\nv6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn\nfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7\njPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz\nezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt\nifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL\ne3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70\njsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz\nWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V\nSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j\npwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX\nX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok\nfcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R\nK4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU\nZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU\nLysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT\nLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327\n# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327\n# Label: \"Buypass Class 2 Root CA\"\n# Serial: 2\n# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29\n# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99\n# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48\n-----BEGIN CERTIFICATE-----\nMIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd\nMBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg\nQ2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow\nTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw\nHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB\nBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr\n6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV\nL4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91\n1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx\nMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ\nQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB\narcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr\nUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi\nFRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS\nP/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN\n9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP\nAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz\nuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h\n9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s\nA20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t\nOluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo\n+fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7\nKcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2\nDISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us\nH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ\nI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7\n5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h\n3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz\nY11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327\n# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327\n# Label: \"Buypass Class 3 Root CA\"\n# Serial: 2\n# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec\n# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57\n# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d\n-----BEGIN CERTIFICATE-----\nMIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd\nMBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg\nQ2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow\nTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw\nHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB\nBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y\nZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E\nN3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9\ntznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX\n0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c\n/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X\nKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY\nzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS\nO1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D\n34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP\nK9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3\nAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv\nTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj\nQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV\ncSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS\nIGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2\nHJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa\nO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv\n033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u\ndmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE\nkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41\n3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD\nu79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq\n4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Label: \"T-TeleSec GlobalRoot Class 3\"\n# Serial: 1\n# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef\n# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1\n# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd\n-----BEGIN CERTIFICATE-----\nMIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx\nKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd\nBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl\nYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1\nOTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy\naXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50\nZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G\nCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN\n8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/\nRLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4\nhqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5\nZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM\nEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1\nA/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy\nWL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ\n1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30\n6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT\n91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml\ne9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p\nTpPDpFQUWw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH\n# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH\n# Label: \"D-TRUST Root Class 3 CA 2 2009\"\n# Serial: 623603\n# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f\n# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0\n# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1\n-----BEGIN CERTIFICATE-----\nMIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF\nMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD\nbGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha\nME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM\nHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB\nBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03\nUAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42\ntSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R\nySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM\nlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp\n/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G\nA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G\nA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj\ndG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy\nMENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl\ncmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js\nL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL\nBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni\nacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0\no3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K\nzCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8\nPIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y\nJohw1+qRzT65ysCQblrGXnRl11z+o+I=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH\n# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH\n# Label: \"D-TRUST Root Class 3 CA 2 EV 2009\"\n# Serial: 623604\n# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6\n# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83\n# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81\n-----BEGIN CERTIFICATE-----\nMIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF\nMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD\nbGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw\nNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV\nBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn\nljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0\n3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z\nqQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR\np75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8\nHgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw\nggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea\nHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw\nOi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh\nc3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E\nRT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt\ndHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku\nY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp\n3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05\nnsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF\nCSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na\nxpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX\nKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1\n-----END CERTIFICATE-----\n\n# Issuer: CN=CA Disig Root R2 O=Disig a.s.\n# Subject: CN=CA Disig Root R2 O=Disig a.s.\n# Label: \"CA Disig Root R2\"\n# Serial: 10572350602393338211\n# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03\n# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71\n# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03\n-----BEGIN CERTIFICATE-----\nMIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV\nBAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu\nMRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy\nMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx\nEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw\nggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe\nNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH\nPWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I\nx2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe\nQTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR\nyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO\nQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912\nH9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ\nQfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD\ni/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs\nnLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1\nrqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud\nDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI\nhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM\ntCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf\nGopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb\nlvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka\n+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal\nTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i\nnSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3\ngzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr\nG5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os\nzMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x\nL4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL\n-----END CERTIFICATE-----\n\n# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV\n# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV\n# Label: \"ACCVRAIZ1\"\n# Serial: 6828503384748696800\n# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02\n# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17\n# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13\n-----BEGIN CERTIFICATE-----\nMIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE\nAwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw\nCQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ\nBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND\nVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb\nqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY\nHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo\nG2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA\nlHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr\nIA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/\n0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH\nk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47\n4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO\nm3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa\ncXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl\nuUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI\nKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls\nZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG\nAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2\nVuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT\nVfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG\nCCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA\ncgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA\nQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA\n7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA\ncgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA\nQwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA\nczAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu\naHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt\naW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud\nDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF\nBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp\nD70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU\nJyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m\nAM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD\nvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms\ntn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH\n7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h\nI6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA\nh1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF\nd3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H\npPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7\n-----END CERTIFICATE-----\n\n# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA\n# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA\n# Label: \"TWCA Global Root CA\"\n# Serial: 3262\n# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96\n# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65\n# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b\n-----BEGIN CERTIFICATE-----\nMIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx\nEjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT\nVFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5\nNTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT\nB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF\n10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz\n0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh\nMBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH\nzIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc\n46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2\nyKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi\nlaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP\noA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA\nBDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE\nqYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm\n4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB\n/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL\n1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn\nLhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF\nH6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo\nRI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+\nnile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh\n15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW\n6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW\nnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j\nwa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz\naGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy\nKwbQBM0=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TeliaSonera Root CA v1 O=TeliaSonera\n# Subject: CN=TeliaSonera Root CA v1 O=TeliaSonera\n# Label: \"TeliaSonera Root CA v1\"\n# Serial: 199041966741090107964904287217786801558\n# MD5 Fingerprint: 37:41:49:1b:18:56:9a:26:f5:ad:c2:66:fb:40:a5:4c\n# SHA1 Fingerprint: 43:13:bb:96:f1:d5:86:9b:c1:4e:6a:92:f6:cf:f6:34:69:87:82:37\n# SHA256 Fingerprint: dd:69:36:fe:21:f8:f0:77:c1:23:a1:a5:21:c1:22:24:f7:22:55:b7:3e:03:a7:26:06:93:e8:a2:4b:0f:a3:89\n-----BEGIN CERTIFICATE-----\nMIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw\nNzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv\nb3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD\nVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F\nVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1\n7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X\nZ75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+\n/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs\n81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm\ndtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe\nOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu\nsDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4\npgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs\nslESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ\narMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD\nVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG\n9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl\ndxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx\n0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj\nTQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed\nY2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7\nQ4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI\nOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7\nvVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW\nt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn\nHL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx\nSK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Label: \"T-TeleSec GlobalRoot Class 2\"\n# Serial: 1\n# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a\n# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9\n# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52\n-----BEGIN CERTIFICATE-----\nMIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx\nKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd\nBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl\nYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1\nOTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy\naXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50\nZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G\nCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd\nAqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC\nFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi\n1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq\njnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ\nwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/\nWSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy\nNsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC\nuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw\nIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6\ng1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN\n9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP\nBSeOE6Fuwg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Atos TrustedRoot 2011 O=Atos\n# Subject: CN=Atos TrustedRoot 2011 O=Atos\n# Label: \"Atos TrustedRoot 2011\"\n# Serial: 6643877497813316402\n# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56\n# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21\n# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74\n-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE\nAwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG\nEwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM\nFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC\nREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp\nNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM\nVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+\nSZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ\n4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L\ncp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi\neowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV\nHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG\nA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3\nDQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j\nvZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP\nDpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc\nmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D\nlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv\nKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 1 G3\"\n# Serial: 687049649626669250736271037606554624078720034195\n# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab\n# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67\n# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00\nMjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV\nwedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe\nrNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341\n68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh\n4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp\nUhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o\nabw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc\n3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G\nKubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt\nhfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO\nTk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt\nzCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD\nggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC\nMTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2\ncDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN\nqXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5\nYCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv\nb2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2\n8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k\nNSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj\nZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp\nq1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt\nnh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 2 G3\"\n# Serial: 390156079458959257446133169266079962026824725800\n# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06\n# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36\n# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00\nMjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf\nqq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW\nn4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym\nc5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+\nO7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1\no9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j\nIaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq\nIcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz\n8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh\nvNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l\n7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG\ncC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD\nggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66\nAarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC\nroijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga\nW/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n\nlv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE\n+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV\ncsaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd\ndbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg\nKCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM\nHVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4\nWSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 3 G3\"\n# Serial: 268090761170461462463995952157327242137089239581\n# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7\n# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d\n# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00\nMjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR\n/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu\nFoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR\nU7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c\nra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR\nFHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k\nA9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw\neyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl\nsSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp\nVzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q\nA4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+\nydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD\nggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px\nKGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI\nFUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv\noxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg\nu/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP\n0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf\n3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl\n8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+\nDhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN\nPlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/\nywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root G2\"\n# Serial: 15385348160840213938643033620894905419\n# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d\n# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f\n# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85\n-----BEGIN CERTIFICATE-----\nMIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv\nb3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG\nEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl\ncnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi\nMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA\nn61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc\nbiJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp\nEgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA\nbx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu\nYjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB\nAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW\nBBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI\nQW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I\n0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni\nlmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9\nB5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv\nON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo\nIhNzbM8m9Yop5w==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root G3\"\n# Serial: 15459312981008553731928384953135426796\n# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb\n# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89\n# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2\n-----BEGIN CERTIFICATE-----\nMIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw\nCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu\nZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg\nRzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV\nUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu\nY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq\nhkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf\nZn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q\nRSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/\nBAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD\nAwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY\nJjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv\n6pZjamVFkpUBtA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root G2\"\n# Serial: 4293743540046975378534879503202253541\n# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44\n# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4\n# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f\n-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\nMjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT\nMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\nb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI\n2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx\n1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ\nq2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz\ntCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ\nvIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP\nBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV\n5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY\n1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4\nNeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG\nFdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91\n8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe\npLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl\nMrY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root G3\"\n# Serial: 7089244469030293291760083333884364146\n# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca\n# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e\n# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0\n-----BEGIN CERTIFICATE-----\nMIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw\nCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu\nZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe\nFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw\nEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x\nIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF\nK4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG\nfp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO\nZ9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd\nBgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx\nAK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/\noAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8\nsycX\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Trusted Root G4\"\n# Serial: 7451500558977370777930084869016614236\n# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49\n# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4\n# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88\n-----BEGIN CERTIFICATE-----\nMIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg\nRzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV\nUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu\nY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y\nithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If\nxp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV\nySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO\nDCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ\njdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/\nCNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi\nEhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM\nfRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY\nuKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK\nchYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t\n9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nhjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD\nggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2\nSV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd\n+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc\nfFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa\nsjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N\ncCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N\n0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie\n4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI\nr/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1\n/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm\ngKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited\n# Label: \"COMODO RSA Certification Authority\"\n# Serial: 101909084537582093308941363524873193117\n# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18\n# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4\n# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34\n-----BEGIN CERTIFICATE-----\nMIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\nhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\nA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\nBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\nMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\nEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\nQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\ndGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\n6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X\npz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC\n9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV\n/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf\nZd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z\n+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w\nqP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah\nSL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC\nu9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf\nFobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq\ncrxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E\nFgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB\n/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl\nwFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM\n4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV\n2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna\nFxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ\nCuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK\nboHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke\njkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL\nS0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb\nQOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl\n0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB\nNVOFBkpdn627G190\n-----END CERTIFICATE-----\n\n# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network\n# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network\n# Label: \"USERTrust RSA Certification Authority\"\n# Serial: 2645093764781058787591871645665788717\n# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5\n# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e\n# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2\n-----BEGIN CERTIFICATE-----\nMIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\niDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\ncnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\nBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\nMjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\nBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\naGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy\ndGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B\n3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY\ntJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/\nFp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2\nVN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT\n79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6\nc0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT\nYo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l\nc6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee\nUB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE\nHg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd\nBgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G\nA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF\nUp/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO\nVWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3\nATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs\n8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR\niQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze\nSf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ\nXHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/\nqS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB\nVXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB\nL6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG\njjxDah2nGN59PRbxYvnKkKj9\n-----END CERTIFICATE-----\n\n# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network\n# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network\n# Label: \"USERTrust ECC Certification Authority\"\n# Serial: 123013823720199481456569720443997572134\n# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1\n# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0\n# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a\n-----BEGIN CERTIFICATE-----\nMIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl\neSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT\nJVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx\nMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT\nCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg\nVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm\naWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo\nI+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng\no4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G\nA1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD\nVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB\nzzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW\nRNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5\n# Label: \"GlobalSign ECC Root CA - R5\"\n# Serial: 32785792099990507226680698011560947931244\n# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08\n# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa\n# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24\n-----BEGIN CERTIFICATE-----\nMIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk\nMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH\nbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX\nDTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD\nQSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc\n8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke\nhOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD\nVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI\nKoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg\n515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO\nxwy8p2Fp8fc74SrL+SvzZpA3\n-----END CERTIFICATE-----\n\n# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust\n# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust\n# Label: \"IdenTrust Commercial Root CA 1\"\n# Serial: 13298821034946342390520003877796839426\n# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7\n# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25\n# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu\nVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw\nMTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw\nJQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT\n3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU\n+ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp\nS0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1\nbVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi\nT0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL\nvYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK\nVsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK\ndHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT\nc+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv\nl7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N\niGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB\n/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD\nggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH\n6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt\nLRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93\nnAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3\n+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK\nW2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT\nAwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq\nl1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG\n4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ\nmUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A\n7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H\n-----END CERTIFICATE-----\n\n# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust\n# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust\n# Label: \"IdenTrust Public Sector Root CA 1\"\n# Serial: 13298821034946342390521976156843933698\n# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba\n# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd\n# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f\n-----BEGIN CERTIFICATE-----\nMIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu\nVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN\nMzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0\nMSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7\nekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy\nRBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS\nbdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF\n/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R\n3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw\nEUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy\n9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V\nGxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ\n2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV\nWaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD\nW/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/\nBAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN\nAQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj\nt2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV\nDRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9\nTaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G\nlwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW\nmhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df\nWN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5\n+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ\ntshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA\nGaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv\n8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c\n-----END CERTIFICATE-----\n\n# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority\n# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority\n# Label: \"CFCA EV ROOT\"\n# Serial: 407555286\n# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30\n# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83\n# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd\n-----BEGIN CERTIFICATE-----\nMIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD\nTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y\naXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx\nMjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j\naWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP\nT1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03\nsQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL\nTIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5\n/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp\n7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz\nEpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt\nhxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP\na931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot\naK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg\nTnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV\nPKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv\ncWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL\ntbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd\nBgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB\nACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT\nej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL\njOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS\nESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy\nP5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19\nxIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d\nCi77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN\n5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe\n/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z\nAAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ\n5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed\n# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed\n# Label: \"OISTE WISeKey Global Root GB CA\"\n# Serial: 157768595616588414422159278966750757568\n# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d\n# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed\n# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6\n-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt\nMQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg\nRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i\nYWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x\nCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG\nb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh\nbCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3\nHEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx\nWuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX\n1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk\nu7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P\n99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r\nM2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw\nAwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB\nBAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh\ncViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5\ngSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO\nZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf\naPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic\nNc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.\n# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.\n# Label: \"SZAFIR ROOT CA2\"\n# Serial: 357043034767186914217277344587386743377558296292\n# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99\n# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de\n# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe\n-----BEGIN CERTIFICATE-----\nMIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL\nBQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6\nZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw\nNzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L\ncmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg\nUk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN\nQLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT\n3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw\n3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6\n3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5\nBSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN\nXGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD\nAgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF\nAAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw\n8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG\nnXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP\noky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy\nd05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg\nLvWpCz/UXeHPhJ/iGcJfitYgHuNztw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Network CA 2\"\n# Serial: 44979900017204383099463764357512596969\n# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2\n# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92\n# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04\n-----BEGIN CERTIFICATE-----\nMIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB\ngDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu\nQS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG\nA1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz\nOTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ\nVW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp\nZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3\nb3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA\nDGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn\n0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB\nOJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE\nfktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E\nSv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m\no130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i\nsx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW\nOZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez\nTv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS\nadgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n\n3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD\nAQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC\nAQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ\nF/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf\nCVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29\nXN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm\ndjWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/\nWjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb\nAoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq\nP/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko\nb7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj\nXALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P\n5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi\nDrW5viSP\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Label: \"Hellenic Academic and Research Institutions RootCA 2015\"\n# Serial: 0\n# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce\n# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6\n# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36\n-----BEGIN CERTIFICATE-----\nMIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix\nDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k\nIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT\nN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v\ndENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG\nA1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh\nZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx\nQDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1\ndGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC\nAQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA\n4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0\nAoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10\n4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C\nojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV\n9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD\ngfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6\nY5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq\nNhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko\nLfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc\nBw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV\nHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd\nctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I\nXtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI\nM4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot\n9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V\nZ5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea\nj8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh\nX9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ\nl033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf\nbzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4\npcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK\ne7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0\nvm9qp/UsQu0yrbYhnr68\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Label: \"Hellenic Academic and Research Institutions ECC RootCA 2015\"\n# Serial: 0\n# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef\n# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66\n# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33\n-----BEGIN CERTIFICATE-----\nMIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN\nBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl\nc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl\nbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv\nb3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ\nBgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj\nYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5\nMUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0\ndXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg\nQehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa\njq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC\nMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi\nC4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep\nlSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof\nTUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR\n-----END CERTIFICATE-----\n\n# Issuer: CN=ISRG Root X1 O=Internet Security Research Group\n# Subject: CN=ISRG Root X1 O=Internet Security Research Group\n# Label: \"ISRG Root X1\"\n# Serial: 172886928669790476064670243504169061120\n# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e\n# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8\n# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6\n-----BEGIN CERTIFICATE-----\nMIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\nWhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\nZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\nh77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\nA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\nT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\nB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\nB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\nKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\nOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\njh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\nqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\nrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\nhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\nubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\nNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\nORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\nTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\njNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\noyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\nmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\nemyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n-----END CERTIFICATE-----\n\n# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM\n# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM\n# Label: \"AC RAIZ FNMT-RCM\"\n# Serial: 485876308206448804701554682760554759\n# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d\n# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20\n# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa\n-----BEGIN CERTIFICATE-----\nMIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx\nCzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ\nWiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ\nBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG\nTk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/\nyBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf\nBBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz\nWHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF\ntBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z\n374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC\nIfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL\nmbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7\nwk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS\nMKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2\nZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet\nUqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw\nAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H\nYJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3\nLmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD\nnFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1\nRXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM\nLVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf\n77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N\nJpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm\nfZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp\n6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp\n1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B\n9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok\nRqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv\nuu8wd+RU4riEmViAqhOLUTpPSPaLtrM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 1 O=Amazon\n# Subject: CN=Amazon Root CA 1 O=Amazon\n# Label: \"Amazon Root CA 1\"\n# Serial: 143266978916655856878034712317230054538369994\n# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6\n# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16\n# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e\n-----BEGIN CERTIFICATE-----\nMIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\nADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\nb24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\nb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\nca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\nIFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\nVOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\njgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\nA4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\nU5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\nN+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\no/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\nrqXRfboQnoZsG4q5WTP468SQvvG5\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 2 O=Amazon\n# Subject: CN=Amazon Root CA 2 O=Amazon\n# Label: \"Amazon Root CA 2\"\n# Serial: 143266982885963551818349160658925006970653239\n# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66\n# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a\n# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4\n-----BEGIN CERTIFICATE-----\nMIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF\nADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\nb24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\nb3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK\ngXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ\nW0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg\n1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K\n8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r\n2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me\nz/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR\n8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj\nmUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz\n7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6\n+XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI\n0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB\nAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm\nUjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2\nLIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY\n+gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS\nk5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl\n7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm\nbtmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl\nurR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+\nfUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63\nn749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE\n76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H\n9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT\n4PsJYGw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 3 O=Amazon\n# Subject: CN=Amazon Root CA 3 O=Amazon\n# Label: \"Amazon Root CA 3\"\n# Serial: 143266986699090766294700635381230934788665930\n# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87\n# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e\n# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4\n-----BEGIN CERTIFICATE-----\nMIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5\nMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\nUm9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG\nA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg\nQ0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl\nui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr\nttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr\nBqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM\nYyRIHN8wfdVoOw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 4 O=Amazon\n# Subject: CN=Amazon Root CA 4 O=Amazon\n# Label: \"Amazon Root CA 4\"\n# Serial: 143266989758080763974105200630763877849284878\n# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd\n# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be\n# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92\n-----BEGIN CERTIFICATE-----\nMIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5\nMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\nUm9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG\nA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg\nQ0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi\n9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk\nM6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB\n/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB\nMAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw\nCkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW\n1KyLa2tJElMzrdfkviT8tQp21KW8EA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM\n# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM\n# Label: \"TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1\"\n# Serial: 1\n# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49\n# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca\n# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16\n-----BEGIN CERTIFICATE-----\nMIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx\nGDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp\nbXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w\nKwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0\nBgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy\ndW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG\nEwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll\nIEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU\nQUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT\nTTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg\nLSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7\na9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr\nLqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr\nN3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X\nYacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/\niSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f\nAJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH\nV8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\nBQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh\nAHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf\nIPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4\nlzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c\n8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf\nlo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.\n# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.\n# Label: \"GDCA TrustAUTH R5 ROOT\"\n# Serial: 9009899650740120186\n# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4\n# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4\n# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93\n-----BEGIN CERTIFICATE-----\nMIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE\nBhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ\nIENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0\nMTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV\nBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w\nHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF\nAAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj\nDp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj\nTnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u\nKU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj\nqcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm\nMUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12\nZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP\nzgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk\nL30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC\njGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA\nHQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC\nAwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB\n/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg\np8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm\nDRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5\nCOmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry\nL3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf\nJWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg\nIHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io\n2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV\n09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ\nXR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq\nT8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe\nMTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation\n# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation\n# Label: \"SSL.com Root Certification Authority RSA\"\n# Serial: 8875640296558310041\n# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29\n# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb\n# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69\n-----BEGIN CERTIFICATE-----\nMIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE\nBhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK\nDA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz\nOTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv\ndXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv\nbSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN\nAQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R\nxFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX\nqhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC\nC52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3\n6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh\n/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF\nYD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E\nJNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc\nUS4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8\nZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm\n+Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi\nM+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV\nHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G\nA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV\ncpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc\nHadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs\nPgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/\nq5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0\ncuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr\na6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I\nH37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y\nK9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu\nnLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf\noYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY\nIc2wBlX7Jz9TkHCpBB5XJ7k=\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation\n# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation\n# Label: \"SSL.com Root Certification Authority ECC\"\n# Serial: 8495723813297216424\n# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e\n# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a\n# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65\n-----BEGIN CERTIFICATE-----\nMIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC\nVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T\nU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0\naW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz\nWjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0\nb24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS\nb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI\n7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg\nCemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud\nEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD\nVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T\nkdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+\ngA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation\n# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation\n# Label: \"SSL.com EV Root Certification Authority RSA R2\"\n# Serial: 6248227494352943350\n# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95\n# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a\n# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c\n-----BEGIN CERTIFICATE-----\nMIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV\nBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE\nCgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy\ndGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy\nMDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G\nA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD\nDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq\nM0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf\nOePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa\n4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9\nHSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR\naZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA\nb9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ\nGp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV\nPWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO\npgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu\nUDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY\nMBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV\nHSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4\n9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW\ns47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5\nSm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg\ncLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM\n79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz\n/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt\nll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm\nKf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK\nQbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ\nw/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi\nS9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07\nmKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation\n# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation\n# Label: \"SSL.com EV Root Certification Authority ECC\"\n# Serial: 3182246526754555285\n# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90\n# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d\n# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8\n-----BEGIN CERTIFICATE-----\nMIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC\nVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T\nU0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx\nNTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv\ndXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv\nbSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49\nAgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA\nVIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku\nWnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP\nMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX\n5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ\nytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg\nh5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6\n# Label: \"GlobalSign Root CA - R6\"\n# Serial: 1417766617973444989252670301619537\n# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae\n# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1\n# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69\n-----BEGIN CERTIFICATE-----\nMIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg\nMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh\nbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx\nMjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET\nMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI\nxutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k\nZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD\naNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw\nLnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw\n1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX\nk7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2\nSXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h\nbguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n\nWUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY\nrZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce\nMgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD\nAQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu\nbAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN\nnsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt\nIxg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61\n55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj\nvUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf\ncDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz\noHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp\nnOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs\npA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v\nJJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R\n8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4\n5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed\n# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed\n# Label: \"OISTE WISeKey Global Root GC CA\"\n# Serial: 44084345621038548146064804565436152554\n# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23\n# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31\n# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d\n-----BEGIN CERTIFICATE-----\nMIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw\nCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91\nbmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg\nUm9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ\nBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu\nZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS\nb290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni\neUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W\np2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T\nrYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV\n57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg\nMgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9\n-----END CERTIFICATE-----\n\n# Issuer: CN=UCA Global G2 Root O=UniTrust\n# Subject: CN=UCA Global G2 Root O=UniTrust\n# Label: \"UCA Global G2 Root\"\n# Serial: 124779693093741543919145257850076631279\n# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8\n# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a\n# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c\n-----BEGIN CERTIFICATE-----\nMIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9\nMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH\nbG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x\nCzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds\nb2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr\nb3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9\nkmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm\nVHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R\nVogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc\nC/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj\ntm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY\nD0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv\nj5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl\nNaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6\niIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP\nO6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/\nBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV\nZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj\nL3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5\n1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl\n1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU\nb3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV\nPtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj\ny88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb\nEGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg\nDMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI\n+Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy\nYiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX\nUB+K+wb1whnw0A==\n-----END CERTIFICATE-----\n\n# Issuer: CN=UCA Extended Validation Root O=UniTrust\n# Subject: CN=UCA Extended Validation Root O=UniTrust\n# Label: \"UCA Extended Validation Root\"\n# Serial: 106100277556486529736699587978573607008\n# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2\n# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a\n# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24\n-----BEGIN CERTIFICATE-----\nMIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH\nMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF\neHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx\nMDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV\nBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog\nD4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS\nsPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop\nO2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk\nsHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi\nc0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj\nVMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz\nKuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/\nTuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G\nsx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs\n1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD\nfwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T\nAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN\nl8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR\nap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ\nVBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5\nc6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp\n4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s\nt2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj\n2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO\nvpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C\nxR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx\ncmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM\nfjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036\n# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036\n# Label: \"Certigna Root CA\"\n# Serial: 269714418870597844693661054334862075617\n# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77\n# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43\n# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68\n-----BEGIN CERTIFICATE-----\nMIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw\nWjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw\nMiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x\nMzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD\nVQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX\nBgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw\nggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO\nty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M\nCiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu\nI9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm\nTLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh\nC59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf\nePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz\nIoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT\nCo/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k\nJWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5\nhwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB\nGjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\nFBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of\n1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov\nL3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo\ndHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr\naHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq\nhkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L\n6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG\nHVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6\n0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB\nlA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi\no2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1\ngPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v\nfaci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63\nNwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh\njWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw\n3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI\n# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI\n# Label: \"emSign Root CA - G1\"\n# Serial: 235931866688319308814040\n# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac\n# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c\n# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67\n-----BEGIN CERTIFICATE-----\nMIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD\nVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU\nZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH\nMTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO\nMRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv\nZ2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz\nf2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO\n8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq\nd7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM\ntTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt\nOd9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB\no0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD\nAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x\nPaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM\nwiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d\nGNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH\n6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby\nRQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx\niN66zB+Afko=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI\n# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI\n# Label: \"emSign ECC Root CA - G3\"\n# Serial: 287880440101571086945156\n# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40\n# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1\n# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b\n-----BEGIN CERTIFICATE-----\nMIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG\nEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo\nbm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g\nRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ\nTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s\nb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw\ndjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0\nWXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS\nfvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB\nzhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq\nhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB\nCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD\n+JbNR6iC8hZVdyR+EhCVBCyj\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI\n# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI\n# Label: \"emSign Root CA - C1\"\n# Serial: 825510296613316004955058\n# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68\n# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01\n# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f\n-----BEGIN CERTIFICATE-----\nMIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG\nA1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg\nSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw\nMFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln\nbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v\ndCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ\nBczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ\nHdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH\n3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH\nGPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c\nxSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1\naylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq\nTbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\nBQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87\n/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4\nkqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG\nYQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT\n+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo\nWXzhriKi4gp6D/piq1JM4fHfyr6DDUI=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI\n# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI\n# Label: \"emSign ECC Root CA - C3\"\n# Serial: 582948710642506000014504\n# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5\n# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66\n# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3\n-----BEGIN CERTIFICATE-----\nMIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG\nEwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx\nIDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw\nMFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln\nbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND\nIFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci\nMK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti\nsIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O\nBBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB\nAf8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c\n3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J\n0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post\n# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post\n# Label: \"Hongkong Post Root CA 3\"\n# Serial: 46170865288971385588281144162979347873371282084\n# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0\n# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02\n# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6\n-----BEGIN CERTIFICATE-----\nMIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL\nBQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ\nSG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n\na29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5\nNDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT\nCUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u\nZ2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO\ndem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI\nVoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV\n9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY\n2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY\nvLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt\nbNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb\nx39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+\nl2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK\nTE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj\nHno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP\nBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e\ni9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw\nDQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG\n7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk\nMpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr\ngZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk\nGMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS\n3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm\nOzj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+\nl6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c\nJfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP\nL5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa\nLJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG\nmpv0\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation\n# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation\n# Label: \"Microsoft ECC Root Certificate Authority 2017\"\n# Serial: 136839042543790627607696632466672567020\n# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67\n# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5\n# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02\n-----BEGIN CERTIFICATE-----\nMIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw\nCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD\nVQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw\nMTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV\nUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy\nb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq\nhkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR\nogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb\nhGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E\nBTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3\nFQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV\nL8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB\niudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation\n# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation\n# Label: \"Microsoft RSA Root Certificate Authority 2017\"\n# Serial: 40975477897264996090493496164228220339\n# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47\n# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74\n# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0\n-----BEGIN CERTIFICATE-----\nMIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl\nMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw\nNAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5\nIDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG\nEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N\naWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ\nNt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0\nZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1\nHLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm\ngGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ\njEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc\naDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG\nYaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6\nW6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K\nUGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH\n+FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q\nW5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/\nBAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC\nNxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC\nLgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC\ngMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6\ntZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh\nSnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2\nTaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3\npvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR\nxpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp\nGWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9\ndOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN\nAHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB\nRA+GsCyRxj3qrg+E\n-----END CERTIFICATE-----\n\n# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd.\n# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd.\n# Label: \"e-Szigno Root CA 2017\"\n# Serial: 411379200276854331539784714\n# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98\n# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1\n# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99\n-----BEGIN CERTIFICATE-----\nMIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV\nBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk\nLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv\nb3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ\nBgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg\nTHRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v\nIFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv\nxie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H\nWyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G\nA1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB\neAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo\njbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ\n+efcMQ==\n-----END CERTIFICATE-----\n\n# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2\n# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2\n# Label: \"certSIGN Root CA G2\"\n# Serial: 313609486401300475190\n# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7\n# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32\n# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05\n-----BEGIN CERTIFICATE-----\nMIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV\nBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g\nUk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ\nBgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ\nR04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF\ndRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw\nvlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ\nuIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp\nn+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs\ncpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW\nxPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P\nrCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF\nDsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx\nDTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy\nLcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C\neWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB\n/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ\nd8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq\nkX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC\nb6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl\nqiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0\nOJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c\nNywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk\nltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO\npwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj\n03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk\nPuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE\n1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX\nQRBdJ3NghVdJIgc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global Certification Authority\"\n# Serial: 1846098327275375458322922162\n# MD5 Fingerprint: f8:1c:18:2d:2f:ba:5f:6d:a1:6c:bc:c7:ab:91:c7:0e\n# SHA1 Fingerprint: 2f:8f:36:4f:e1:58:97:44:21:59:87:a5:2a:9a:d0:69:95:26:7f:b5\n# SHA256 Fingerprint: 97:55:20:15:f5:dd:fc:3c:87:88:c0:06:94:45:55:40:88:94:45:00:84:f1:00:86:70:86:bc:1a:2b:b5:8d:c8\n-----BEGIN CERTIFICATE-----\nMIIF2jCCA8KgAwIBAgIMBfcOhtpJ80Y1LrqyMA0GCSqGSIb3DQEBCwUAMIGIMQsw\nCQYDVQQGEwJVUzERMA8GA1UECAwISWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28x\nITAfBgNVBAoMGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1\nc3R3YXZlIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNzA4MjMx\nOTM0MTJaFw00MjA4MjMxOTM0MTJaMIGIMQswCQYDVQQGEwJVUzERMA8GA1UECAwI\nSWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28xITAfBgNVBAoMGFRydXN0d2F2ZSBI\nb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1c3R3YXZlIEdsb2JhbCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB\nALldUShLPDeS0YLOvR29zd24q88KPuFd5dyqCblXAj7mY2Hf8g+CY66j96xz0Xzn\nswuvCAAJWX/NKSqIk4cXGIDtiLK0thAfLdZfVaITXdHG6wZWiYj+rDKd/VzDBcdu\n7oaJuogDnXIhhpCujwOl3J+IKMujkkkP7NAP4m1ET4BqstTnoApTAbqOl5F2brz8\n1Ws25kCI1nsvXwXoLG0R8+eyvpJETNKXpP7ScoFDB5zpET71ixpZfR9oWN0EACyW\n80OzfpgZdNmcc9kYvkHHNHnZ9GLCQ7mzJ7Aiy/k9UscwR7PJPrhq4ufogXBeQotP\nJqX+OsIgbrv4Fo7NDKm0G2x2EOFYeUY+VM6AqFcJNykbmROPDMjWLBz7BegIlT1l\nRtzuzWniTY+HKE40Cz7PFNm73bZQmq131BnW2hqIyE4bJ3XYsgjxroMwuREOzYfw\nhI0Vcnyh78zyiGG69Gm7DIwLdVcEuE4qFC49DxweMqZiNu5m4iK4BUBjECLzMx10\ncoos9TkpoNPnG4CELcU9402x/RpvumUHO1jsQkUm+9jaJXLE9gCxInm943xZYkqc\nBW89zubWR2OZxiRvchLIrH+QtAuRcOi35hYQcRfO3gZPSEF9NUqjifLJS3tBEW1n\ntwiYTOURGa5CgNz7kAXU+FDKvuStx8KU1xad5hePrzb7AgMBAAGjQjBAMA8GA1Ud\nEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJngGWcNYtt2s9o9uFvo/ULSMQ6HMA4GA1Ud\nDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAmHNw4rDT7TnsTGDZqRKGFx6W\n0OhUKDtkLSGm+J1WE2pIPU/HPinbbViDVD2HfSMF1OQc3Og4ZYbFdada2zUFvXfe\nuyk3QAUHw5RSn8pk3fEbK9xGChACMf1KaA0HZJDmHvUqoai7PF35owgLEQzxPy0Q\nlG/+4jSHg9bP5Rs1bdID4bANqKCqRieCNqcVtgimQlRXtpla4gt5kNdXElE1GYhB\naCXUNxeEFfsBctyV3lImIJgm4nb1J2/6ADtKYdkNy1GTKv0WBpanI5ojSP5RvbbE\nsLFUzt5sQa0WZ37b/TjNuThOssFgy50X31ieemKyJo90lZvkWx3SD92YHJtZuSPT\nMaCm/zjdzyBP6VhWOmfD0faZmZ26NraAL4hHT4a/RDqA5Dccprrql5gR0IRiR2Qe\nqu5AvzSxnI9O4fKSTx+O856X3vOmeWqJcU9LJxdI/uz0UA9PSX3MReO9ekDFQdxh\nVicGaeVyQYHTtgGJoC86cnn+OjC/QezHYj6RS8fZMXZC+fc8Y+wmjHMMfRod6qh8\nh6jCJ3zhM0EPz8/8AKAigJ5Kp28AsEFFtyLKaEjFQqKu3R3y4G5OBVixwJAWKqQ9\nEEC+j2Jjg6mcgn0tAumDMHzLJ8n9HmYAsC7TIS+OMxZsmO0QqAfWzJPP29FpHOTK\nyeC2nOnOcXHebD8WpHk=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global ECC P256 Certification Authority\"\n# Serial: 4151900041497450638097112925\n# MD5 Fingerprint: 5b:44:e3:8d:5d:36:86:26:e8:0d:05:d2:59:a7:83:54\n# SHA1 Fingerprint: b4:90:82:dd:45:0c:be:8b:5b:b1:66:d3:e2:a4:08:26:cd:ed:42:cf\n# SHA256 Fingerprint: 94:5b:bc:82:5e:a5:54:f4:89:d1:fd:51:a7:3d:df:2e:a6:24:ac:70:19:a0:52:05:22:5c:22:a7:8c:cf:a8:b4\n-----BEGIN CERTIFICATE-----\nMIICYDCCAgegAwIBAgIMDWpfCD8oXD5Rld9dMAoGCCqGSM49BAMCMIGRMQswCQYD\nVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf\nBgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3\nYXZlIEdsb2JhbCBFQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x\nNzA4MjMxOTM1MTBaFw00MjA4MjMxOTM1MTBaMIGRMQswCQYDVQQGEwJVUzERMA8G\nA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0\nd2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF\nQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqG\nSM49AwEHA0IABH77bOYj43MyCMpg5lOcunSNGLB4kFKA3TjASh3RqMyTpJcGOMoN\nFWLGjgEqZZ2q3zSRLoHB5DOSMcT9CTqmP62jQzBBMA8GA1UdEwEB/wQFMAMBAf8w\nDwYDVR0PAQH/BAUDAwcGADAdBgNVHQ4EFgQUo0EGrJBt0UrrdaVKEJmzsaGLSvcw\nCgYIKoZIzj0EAwIDRwAwRAIgB+ZU2g6gWrKuEZ+Hxbb/ad4lvvigtwjzRM4q3wgh\nDDcCIC0mA6AFvWvR9lz4ZcyGbbOcNEhjhAnFjXca4syc4XR7\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global ECC P384 Certification Authority\"\n# Serial: 2704997926503831671788816187\n# MD5 Fingerprint: ea:cf:60:c4:3b:b9:15:29:40:a1:97:ed:78:27:93:d6\n# SHA1 Fingerprint: e7:f3:a3:c8:cf:6f:c3:04:2e:6d:0e:67:32:c5:9e:68:95:0d:5e:d2\n# SHA256 Fingerprint: 55:90:38:59:c8:c0:c3:eb:b8:75:9e:ce:4e:25:57:22:5f:f5:75:8b:bd:38:eb:d4:82:76:60:1e:1b:d5:80:97\n-----BEGIN CERTIFICATE-----\nMIICnTCCAiSgAwIBAgIMCL2Fl2yZJ6SAaEc7MAoGCCqGSM49BAMDMIGRMQswCQYD\nVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf\nBgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3\nYXZlIEdsb2JhbCBFQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x\nNzA4MjMxOTM2NDNaFw00MjA4MjMxOTM2NDNaMIGRMQswCQYDVQQGEwJVUzERMA8G\nA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0\nd2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF\nQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABGvaDXU1CDFHBa5FmVXxERMuSvgQMSOjfoPTfygIOiYaOs+Xgh+AtycJ\nj9GOMMQKmw6sWASr9zZ9lCOkmwqKi6vr/TklZvFe/oyujUF5nQlgziip04pt89ZF\n1PKYhDhloKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0G\nA1UdDgQWBBRVqYSJ0sEyvRjLbKYHTsjnnb6CkDAKBggqhkjOPQQDAwNnADBkAjA3\nAZKXRRJ+oPM+rRk6ct30UJMDEr5E0k9BpIycnR+j9sKS50gU/k6bpZFXrsY3crsC\nMGclCrEMXu6pY5Jv5ZAL/mYiykf9ijH3g/56vxC+GCsej/YpHpRZ744hN8tRmKVu\nSw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.\n# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.\n# Label: \"NAVER Global Root Certification Authority\"\n# Serial: 9013692873798656336226253319739695165984492813\n# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b\n# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1\n# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65\n-----BEGIN CERTIFICATE-----\nMIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM\nBQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG\nT1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0\naW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx\nCzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD\nb3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB\ndXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA\niQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH\n38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE\nHoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz\nkVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP\nszuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq\nvC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf\nnZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG\nYQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo\n0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a\nCJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K\nAQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I\n36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB\nAf8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN\nqo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj\ncu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm\n+LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL\nhr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe\nlHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7\np/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8\npiKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR\nLBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX\n5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO\ndh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul\n9XXeifdy\n-----END CERTIFICATE-----\n\n# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres\n# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres\n# Label: \"AC RAIZ FNMT-RCM SERVIDORES SEGUROS\"\n# Serial: 131542671362353147877283741781055151509\n# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb\n# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a\n# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb\n-----BEGIN CERTIFICATE-----\nMIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw\nCQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw\nFgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S\nQ00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5\nMzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL\nDAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS\nQUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH\nsbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK\nUm8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD\nVR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu\nSuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC\nMQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy\nv+c=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa\n# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa\n# Label: \"GlobalSign Root R46\"\n# Serial: 1552617688466950547958867513931858518042577\n# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef\n# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90\n# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9\n-----BEGIN CERTIFICATE-----\nMIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA\nMEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD\nVQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy\nMDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt\nc2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ\nOaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG\nvGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud\n316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo\n0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE\ny132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF\nzXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE\n+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN\nI/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs\nx2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa\nByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC\n4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV\nHQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4\n7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg\nJuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti\n2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk\npnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF\nFRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt\nrWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk\nZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5\nu+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP\n4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6\nN3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3\nvouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa\n# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa\n# Label: \"GlobalSign Root E46\"\n# Serial: 1552617690338932563915843282459653771421763\n# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f\n# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84\n# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58\n-----BEGIN CERTIFICATE-----\nMIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx\nCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD\nExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw\nMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex\nHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA\nIgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq\nR+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd\nyXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud\nDgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ\n7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8\n+RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A=\n-----END CERTIFICATE-----\n\n# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz\n# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz\n# Label: \"ANF Secure Server Root CA\"\n# Serial: 996390341000653745\n# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96\n# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74\n# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99\n-----BEGIN CERTIFICATE-----\nMIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV\nBAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk\nYWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV\nBAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN\nMzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF\nUzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD\nVQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v\ndCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj\ncqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q\nyGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH\n2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX\nH1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL\nzc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR\np1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz\nW7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/\nSiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn\nLNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3\nn5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B\nu8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj\no1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO\nBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\nAgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L\n9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej\nrw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK\npFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0\nvPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq\nOknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ\n/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9\n2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI\n+PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2\nMjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo\ntt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Label: \"Certum EC-384 CA\"\n# Serial: 160250656287871593594747141429395092468\n# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1\n# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed\n# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6\n-----BEGIN CERTIFICATE-----\nMIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw\nCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw\nJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT\nEENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0\nWjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT\nLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX\nBgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE\nKI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm\nFy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8\nEF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J\nUG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn\nnvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Root CA\"\n# Serial: 40870380103424195783807378461123655149\n# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29\n# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5\n# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd\n-----BEGIN CERTIFICATE-----\nMIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6\nMQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu\nMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV\nBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw\nMzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg\nU3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo\nb3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ\nn0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q\np1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq\nNwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF\n8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3\nHAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa\nmqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi\n7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF\nytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P\nqafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ\nv3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6\nTsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1\nvALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD\nggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4\nWxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo\nzMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR\n5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ\nGfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf\n5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq\n0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D\nP78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM\nqJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP\n0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf\nE2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb\n-----END CERTIFICATE-----\n\n# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique\n# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique\n# Label: \"TunTrust Root CA\"\n# Serial: 108534058042236574382096126452369648152337120275\n# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4\n# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb\n# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41\n-----BEGIN CERTIFICATE-----\nMIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL\nBQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg\nQ2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv\nb3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG\nEwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u\nIEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ\nn56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd\n2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF\nVwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ\nGoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF\nli/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU\nr8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2\neY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb\nMlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg\njwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB\n7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW\n5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE\nITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0\n90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z\nxiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu\nQEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4\nFstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH\n22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP\nxOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn\ndFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5\nXc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b\nnV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ\nCvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH\nu/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj\nd9qDRIueVSjAi1jTkD5OGwDxFa2DK5o=\n-----END CERTIFICATE-----\n\n# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Label: \"HARICA TLS RSA Root CA 2021\"\n# Serial: 76817823531813593706434026085292783742\n# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91\n# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d\n# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d\n-----BEGIN CERTIFICATE-----\nMIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs\nMQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl\nc2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg\nUm9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL\nMAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl\nYXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv\nb3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l\nmwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE\n4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv\na9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M\npbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw\nKh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b\nLW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY\nAuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB\nAGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq\nE613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr\nW2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ\nCoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE\nAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU\nX15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3\nf5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja\nH6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP\nJzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P\nzzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt\njBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0\n/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT\nBGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79\naPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW\nxw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU\n63ZTGI0RmLo=\n-----END CERTIFICATE-----\n\n# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Label: \"HARICA TLS ECC Root CA 2021\"\n# Serial: 137515985548005187474074462014555733966\n# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0\n# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48\n# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01\n-----BEGIN CERTIFICATE-----\nMIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw\nCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh\ncmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v\ndCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG\nA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj\naCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg\nQ0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7\nKKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y\nSTHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw\nAwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD\nAgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw\nSaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN\nnxS2PFOiTAZpffpskcYqSUXm7LcT4Tps\n-----END CERTIFICATE-----\n\n# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Label: \"Autoridad de Certificacion Firmaprofesional CIF A62634068\"\n# Serial: 1977337328857672817\n# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3\n# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe\n# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a\n-----BEGIN CERTIFICATE-----\nMIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE\nBhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h\ncHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1\nMDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg\nQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9\nthDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM\ncas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG\nL9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i\nNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h\nX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b\nm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy\nZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja\nEbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T\nKI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF\n6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh\nOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc\ntHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd\nIAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j\nb20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC\nAG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw\nADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m\niWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF\nSa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ\nhfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P\nVf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE\nEAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV\n1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t\nCsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR\n5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw\nf9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9\nivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK\nGbqEZycPvEJdvSRUDewdcAZfpLz6IHxV\n-----END CERTIFICATE-----\n\n# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.\n# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.\n# Label: \"vTrus ECC Root CA\"\n# Serial: 630369271402956006249506845124680065938238527194\n# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85\n# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1\n# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3\n-----BEGIN CERTIFICATE-----\nMIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw\nRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY\nBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz\nMTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u\nLEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF\nK4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0\nv/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd\ne4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD\nVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw\nV53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA\nAjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG\nGJTO\n-----END CERTIFICATE-----\n\n# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd.\n# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd.\n# Label: \"vTrus Root CA\"\n# Serial: 387574501246983434957692974888460947164905180485\n# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc\n# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7\n# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87\n-----BEGIN CERTIFICATE-----\nMIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL\nBQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x\nFjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx\nMDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s\nTHRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD\nggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc\nIrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU\nAyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+\nGrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9\n8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH\nflqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt\nJ8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim\n0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN\npGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ\nUqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW\nOXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB\nAAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E\nBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet\n8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd\nnxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j\nbhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM\nKar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv\nTDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS\nS8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr\nI8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9\nb91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB\nUvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P\nTi07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven\nsBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s=\n-----END CERTIFICATE-----\n\n# Issuer: CN=ISRG Root X2 O=Internet Security Research Group\n# Subject: CN=ISRG Root X2 O=Internet Security Research Group\n# Label: \"ISRG Root X2\"\n# Serial: 87493402998870891108772069816698636114\n# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5\n# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af\n# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70\n-----BEGIN CERTIFICATE-----\nMIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\nCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\nR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\nMDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\nZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\nEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\nItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\nAQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\nzj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\ntL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n/q4AaOeMSQ+2b1tbFfLn\n-----END CERTIFICATE-----\n\n# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.\n# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.\n# Label: \"HiPKI Root CA - G1\"\n# Serial: 60966262342023497858655262305426234976\n# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3\n# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60\n# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc\n-----BEGIN CERTIFICATE-----\nMIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP\nMQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0\nZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa\nFw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3\nYSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw\nqNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv\nVcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6\nlZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz\nQs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ\nKILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK\nFgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj\nHluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr\ny+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ\n/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM\na/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6\nfsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV\nHQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG\nSIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi\n7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc\nSE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza\nZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc\nXzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg\niLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho\nL5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF\nNe85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr\nkkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+\nvhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU\nYDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4\n# Label: \"GlobalSign ECC Root CA - R4\"\n# Serial: 159662223612894884239637590694\n# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc\n# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28\n# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2\n-----BEGIN CERTIFICATE-----\nMIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD\nVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh\nbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw\nMTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g\nUjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT\nBgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx\nuYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV\nHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/\n+wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147\nbmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R1 O=Google Trust Services LLC\n# Subject: CN=GTS Root R1 O=Google Trust Services LLC\n# Label: \"GTS Root R1\"\n# Serial: 159662320309726417404178440727\n# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40\n# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a\n# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf\n-----BEGIN CERTIFICATE-----\nMIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw\nCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\nMBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw\nMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp\nY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA\nA4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo\n27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w\nCl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw\nTcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl\nqAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH\nszVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8\nY/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk\nMiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92\nwO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p\naDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN\nVjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID\nAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E\nFgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb\nC5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe\nQkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy\nh6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4\n7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J\nZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef\nMgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/\nZ6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT\n6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ\n0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm\n2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb\nbP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R2 O=Google Trust Services LLC\n# Subject: CN=GTS Root R2 O=Google Trust Services LLC\n# Label: \"GTS Root R2\"\n# Serial: 159662449406622349769042896298\n# MD5 Fingerprint: 1e:39:c0:53:e6:1e:29:82:0b:ca:52:55:36:5d:57:dc\n# SHA1 Fingerprint: 9a:44:49:76:32:db:de:fa:d0:bc:fb:5a:7b:17:bd:9e:56:09:24:94\n# SHA256 Fingerprint: 8d:25:cd:97:22:9d:bf:70:35:6b:da:4e:b3:cc:73:40:31:e2:4c:f0:0f:af:cf:d3:2d:c7:6e:b5:84:1c:7e:a8\n-----BEGIN CERTIFICATE-----\nMIIFVzCCAz+gAwIBAgINAgPlrsWNBCUaqxElqjANBgkqhkiG9w0BAQwFADBHMQsw\nCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\nMBIGA1UEAxMLR1RTIFJvb3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw\nMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp\nY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUA\nA4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTukk3LvCvpt\nnfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY\n6Dlo7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAu\nMC6C/Pq8tBcKSOWIm8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7k\nRXuJVfeKH2JShBKzwkCX44ofR5GmdFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWg\nf9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbuak7MkogwTZq9TwtImoS1mKPV\n+3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscszcTJGr61K8Yzo\ndDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW\nIr9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKa\nG73VululycslaVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCq\ngc7dGtxRcw1PcOnlthYhGXmy5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwID\nAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E\nFgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEMBQADggIBAB/Kzt3H\nvqGf2SdMC9wXmBFqiN495nFWcrKeGk6c1SuYJF2ba3uwM4IJvd8lRuqYnrYb/oM8\n0mJhwQTtzuDFycgTE1XnqGOtjHsB/ncw4c5omwX4Eu55MaBBRTUoCnGkJE+M3DyC\nB19m3H0Q/gxhswWV7uGugQ+o+MePTagjAiZrHYNSVc61LwDKgEDg4XSsYPWHgJ2u\nNmSRXbBoGOqKYcl3qJfEycel/FVL8/B/uWU9J2jQzGv6U53hkRrJXRqWbTKH7QMg\nyALOWr7Z6v2yTcQvG99fevX4i8buMTolUVVnjWQye+mew4K6Ki3pHrTgSAai/Gev\nHyICc/sgCq+dVEuhzf9gR7A/Xe8bVr2XIZYtCtFenTgCR2y59PYjJbigapordwj6\nxLEokCZYCDzifqrXPW+6MYgKBesntaFJ7qBFVHvmJ2WZICGoo7z7GJa7Um8M7YNR\nTOlZ4iBgxcJlkoKM8xAfDoqXvneCbT+PHV28SSe9zE8P4c52hgQjxcCMElv924Sg\nJPFI/2R80L5cFtHvma3AH/vLrrw4IgYmZNralw4/KBVEqE8AyvCazM90arQ+POuV\n7LXTWtiBmelDGDfrs7vRWGJB82bSj6p4lVQgw1oudCvV0b4YacCs1aTPObpRhANl\n6WLAYv7YTVWW4tAR+kg0Eeye7QUd5MjWHYbL\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R3 O=Google Trust Services LLC\n# Subject: CN=GTS Root R3 O=Google Trust Services LLC\n# Label: \"GTS Root R3\"\n# Serial: 159662495401136852707857743206\n# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73\n# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46\n# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48\n-----BEGIN CERTIFICATE-----\nMIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD\nVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG\nA1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw\nWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz\nIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G\njOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2\n4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7\nVKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm\nZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R4 O=Google Trust Services LLC\n# Subject: CN=GTS Root R4 O=Google Trust Services LLC\n# Label: \"GTS Root R4\"\n# Serial: 159662532700760215368942768210\n# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8\n# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47\n# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d\n-----BEGIN CERTIFICATE-----\nMIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD\nVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG\nA1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw\nWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz\nIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi\nQHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR\nHYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D\n9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8\np/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD\n-----END CERTIFICATE-----\n\n# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj\n# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj\n# Label: \"Telia Root CA v2\"\n# Serial: 7288924052977061235122729490515358\n# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48\n# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd\n# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c\n-----BEGIN CERTIFICATE-----\nMIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx\nCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE\nAwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1\nNTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ\nMBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP\nADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq\nAMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9\nvVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9\nlRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD\nn3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT\n7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o\n6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC\nTEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6\nWT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R\nDolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI\npEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj\nYzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy\nrOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw\nAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ\n8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi\n0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM\nA8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS\nSRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K\nTTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF\n6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er\n3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt\nTy3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT\nVmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW\nysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA\nrBPuUBQemMc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH\n# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH\n# Label: \"D-TRUST BR Root CA 1 2020\"\n# Serial: 165870826978392376648679885835942448534\n# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed\n# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67\n# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44\n-----BEGIN CERTIFICATE-----\nMIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw\nCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS\nVVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5\nNDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG\nA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS\nzuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0\nQVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/\nVbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g\nPKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf\nY2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l\ndC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1\nc3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO\nPQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW\nwKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV\ndWNbFJWcHwHP2NVypw87\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH\n# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH\n# Label: \"D-TRUST EV Root CA 1 2020\"\n# Serial: 126288379621884218666039612629459926992\n# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e\n# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07\n# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db\n-----BEGIN CERTIFICATE-----\nMIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw\nCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS\nVVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5\nNTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG\nA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC\n/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD\nwpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3\nOqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g\nPKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf\nY2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l\ndC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1\nc3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO\nPQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA\ny/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb\ngfM0agPnIjhQW+0ZT0MW\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.\n# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.\n# Label: \"DigiCert TLS ECC P384 Root G5\"\n# Serial: 13129116028163249804115411775095713523\n# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed\n# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee\n# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05\n-----BEGIN CERTIFICATE-----\nMIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw\nCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp\nZ2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2\nMDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ\nbmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG\nByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS\n7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp\n0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS\nB4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49\nBAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ\nLgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4\nDXZDjC5Ty3zfDBeWUA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.\n# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.\n# Label: \"DigiCert TLS RSA4096 Root G5\"\n# Serial: 11930366277458970227240571539258396554\n# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1\n# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35\n# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75\n-----BEGIN CERTIFICATE-----\nMIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN\nMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT\nHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN\nNDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs\nIEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+\najWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0\n2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp\nwgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM\npG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD\nnU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po\nsMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx\nZre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd\nLvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX\nKyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe\nXoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL\ntgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv\nTiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN\nAQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw\nGXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H\nPNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF\nO4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ\nREtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik\nAdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv\n/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+\np6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw\nMUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF\nqUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK\novfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certainly Root R1 O=Certainly\n# Subject: CN=Certainly Root R1 O=Certainly\n# Label: \"Certainly Root R1\"\n# Serial: 188833316161142517227353805653483829216\n# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12\n# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af\n# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0\n-----BEGIN CERTIFICATE-----\nMIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw\nPTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy\ndGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0\nYWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2\n1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT\nvqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed\naFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0\n1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5\nr3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5\ncBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ\nwHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ\n6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA\n2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH\nWyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR\neiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB\n/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u\nd0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr\nPbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d\n8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi\n1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd\nrRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di\ntaY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7\nlcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj\nyTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn\nKx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy\nyCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n\nwXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6\nOV+KmalBWQewLK8=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certainly Root E1 O=Certainly\n# Subject: CN=Certainly Root E1 O=Certainly\n# Label: \"Certainly Root E1\"\n# Serial: 8168531406727139161245376702891150584\n# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9\n# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b\n# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2\n-----BEGIN CERTIFICATE-----\nMIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw\nCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu\nbHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ\nBgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s\neSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK\n+IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2\nQNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4\nhevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm\nut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG\nBtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR\n-----END CERTIFICATE-----\n\n# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.\n# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.\n# Label: \"Security Communication ECC RootCA1\"\n# Serial: 15446673492073852651\n# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86\n# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41\n# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11\n-----BEGIN CERTIFICATE-----\nMIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT\nAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD\nVQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx\nNjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT\nHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5\nIENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl\ndB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK\nULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu\n9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O\nbe0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k=\n-----END CERTIFICATE-----\n\n# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY\n# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY\n# Label: \"BJCA Global Root CA1\"\n# Serial: 113562791157148395269083148143378328608\n# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90\n# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a\n# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae\n-----BEGIN CERTIFICATE-----\nMIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU\nMQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI\nT1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz\nMTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF\nSUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh\nbCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z\nxRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ\nspDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5\n58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR\nat7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll\n5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq\nnMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK\nV0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/\npj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO\nz2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn\njSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+\nWGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF\n7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE\nAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4\nYRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli\nawLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u\n+2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88\nX7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN\nSoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo\nP2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI\n+pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz\nznfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9\neVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2\nYqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy\nr/6zcCwupvI=\n-----END CERTIFICATE-----\n\n# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY\n# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY\n# Label: \"BJCA Global Root CA2\"\n# Serial: 58605626836079930195615843123109055211\n# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c\n# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6\n# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82\n-----BEGIN CERTIFICATE-----\nMIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw\nCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ\nVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy\nMVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ\nTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS\nb290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B\nIgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+\n+kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK\nsVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD\nAgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA\n94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B\n43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited\n# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited\n# Label: \"Sectigo Public Server Authentication Root E46\"\n# Serial: 88989738453351742415770396670917916916\n# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01\n# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a\n# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83\n-----BEGIN CERTIFICATE-----\nMIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw\nCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T\nZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN\nMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG\nA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT\nZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA\nIgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC\nWvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+\n6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B\nAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa\nqCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q\n4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited\n# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited\n# Label: \"Sectigo Public Server Authentication Root R46\"\n# Serial: 156256931880233212765902055439220583700\n# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5\n# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38\n# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06\n-----BEGIN CERTIFICATE-----\nMIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf\nMQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD\nEy1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw\nHhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY\nMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp\nYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa\nef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz\nSDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf\niOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X\nME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3\nIuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS\nVYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE\nSJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu\n+Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt\n8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L\nHaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt\nzwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P\nAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c\nmTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ\nYKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52\ngDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA\nFv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB\nJYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX\nDhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui\nTdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5\ndHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65\nLvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp\n0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY\nQqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation\n# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation\n# Label: \"SSL.com TLS RSA Root CA 2022\"\n# Serial: 148535279242832292258835760425842727825\n# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da\n# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca\n# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed\n-----BEGIN CERTIFICATE-----\nMIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO\nMQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD\nDBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX\nDTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw\nb3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC\nAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP\nL3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY\nt6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins\nS657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3\nPnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO\nL9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3\nR2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w\ndr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS\n+YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS\nd66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG\nAtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f\ngTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j\nBBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z\nNbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt\nhEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM\nQtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf\nR4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ\nDPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW\nP4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy\nlrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq\nbLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w\nAgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q\nr5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji\nMho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU\n98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation\n# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation\n# Label: \"SSL.com TLS ECC Root CA 2022\"\n# Serial: 26605119622390491762507526719404364228\n# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5\n# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39\n# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43\n-----BEGIN CERTIFICATE-----\nMIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw\nCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT\nU0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2\nMDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh\ndGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG\nByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm\nacCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN\nSeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME\nGDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW\nuCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp\n15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN\nb0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos\n# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos\n# Label: \"Atos TrustedRoot Root CA ECC TLS 2021\"\n# Serial: 81873346711060652204712539181482831616\n# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8\n# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd\n# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8\n-----BEGIN CERTIFICATE-----\nMIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w\nLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w\nCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0\nMTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF\nQ0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI\nzj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X\ntXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4\nAjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2\nKCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD\naAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu\nCCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo\n9H1/IISpQuQo\n-----END CERTIFICATE-----\n\n# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos\n# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos\n# Label: \"Atos TrustedRoot Root CA RSA TLS 2021\"\n# Serial: 111436099570196163832749341232207667876\n# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2\n# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48\n# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f\n-----BEGIN CERTIFICATE-----\nMIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM\nMS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx\nMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00\nMTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD\nQSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN\nBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z\n4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv\nYe+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ\nkmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs\nGY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln\nnkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh\n3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD\n0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy\ngeBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8\nANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB\nc6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI\npw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU\ndEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB\nDAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS\n4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs\no0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ\nqM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw\nxfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM\nrr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4\nAXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR\n0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY\no7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5\ndDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE\noji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc.\n# Subject: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc.\n# Label: \"TrustAsia Global Root CA G3\"\n# Serial: 576386314500428537169965010905813481816650257167\n# MD5 Fingerprint: 30:42:1b:b7:bb:81:75:35:e4:16:4f:53:d2:94:de:04\n# SHA1 Fingerprint: 63:cf:b6:c1:27:2b:56:e4:88:8e:1c:23:9a:b6:2e:81:47:24:c3:c7\n# SHA256 Fingerprint: e0:d3:22:6a:eb:11:63:c2:e4:8f:f9:be:3b:50:b4:c6:43:1b:e7:bb:1e:ac:c5:c3:6b:5d:5e:c5:09:03:9a:08\n-----BEGIN CERTIFICATE-----\nMIIFpTCCA42gAwIBAgIUZPYOZXdhaqs7tOqFhLuxibhxkw8wDQYJKoZIhvcNAQEM\nBQAwWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dp\nZXMsIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHMzAe\nFw0yMTA1MjAwMjEwMTlaFw00NjA1MTkwMjEwMTlaMFoxCzAJBgNVBAYTAkNOMSUw\nIwYDVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtU\ncnVzdEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzMwggIiMA0GCSqGSIb3DQEBAQUAA4IC\nDwAwggIKAoICAQDAMYJhkuSUGwoqZdC+BqmHO1ES6nBBruL7dOoKjbmzTNyPtxNS\nT1QY4SxzlZHFZjtqz6xjbYdT8PfxObegQ2OwxANdV6nnRM7EoYNl9lA+sX4WuDqK\nAtCWHwDNBSHvBm3dIZwZQ0WhxeiAysKtQGIXBsaqvPPW5vxQfmZCHzyLpnl5hkA1\nnyDvP+uLRx+PjsXUjrYsyUQE49RDdT/VP68czH5GX6zfZBCK70bwkPAPLfSIC7Ep\nqq+FqklYqL9joDiR5rPmd2jE+SoZhLsO4fWvieylL1AgdB4SQXMeJNnKziyhWTXA\nyB1GJ2Faj/lN03J5Zh6fFZAhLf3ti1ZwA0pJPn9pMRJpxx5cynoTi+jm9WAPzJMs\nhH/x/Gr8m0ed262IPfN2dTPXS6TIi/n1Q1hPy8gDVI+lhXgEGvNz8teHHUGf59gX\nzhqcD0r83ERoVGjiQTz+LISGNzzNPy+i2+f3VANfWdP3kXjHi3dqFuVJhZBFcnAv\nkV34PmVACxmZySYgWmjBNb9Pp1Hx2BErW+Canig7CjoKH8GB5S7wprlppYiU5msT\nf9FkPz2ccEblooV7WIQn3MSAPmeamseaMQ4w7OYXQJXZRe0Blqq/DPNL0WP3E1jA\nuPP6Z92bfW1K/zJMtSU7/xxnD4UiWQWRkUF3gdCFTIcQcf+eQxuulXUtgQIDAQAB\no2MwYTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEDk5PIj7zjKsK5Xf/Ih\nMBY027ySMB0GA1UdDgQWBBRA5OTyI+84yrCuV3/yITAWNNu8kjAOBgNVHQ8BAf8E\nBAMCAQYwDQYJKoZIhvcNAQEMBQADggIBACY7UeFNOPMyGLS0XuFlXsSUT9SnYaP4\nwM8zAQLpw6o1D/GUE3d3NZ4tVlFEbuHGLige/9rsR82XRBf34EzC4Xx8MnpmyFq2\nXFNFV1pF1AWZLy4jVe5jaN/TG3inEpQGAHUNcoTpLrxaatXeL1nHo+zSh2bbt1S1\nJKv0Q3jbSwTEb93mPmY+KfJLaHEih6D4sTNjduMNhXJEIlU/HHzp/LgV6FL6qj6j\nITk1dImmasI5+njPtqzn59ZW/yOSLlALqbUHM/Q4X6RJpstlcHboCoWASzY9M/eV\nVHUl2qzEc4Jl6VL1XP04lQJqaTDFHApXB64ipCz5xUG3uOyfT0gA+QEEVcys+TIx\nxHWVBqB/0Y0n3bOppHKH/lmLmnp0Ft0WpWIp6zqW3IunaFnT63eROfjXy9mPX1on\nAX1daBli2MjN9LdyR75bl87yraKZk62Uy5P2EgmVtqvXO9A/EcswFi55gORngS1d\n7XB4tmBZrOFdRWOPyN9yaFvqHbgB8X7754qz41SgOAngPN5C8sLtLpvzHzW2Ntjj\ngKGLzZlkD8Kqq7HK9W+eQ42EVJmzbsASZthwEPEGNTNDqJwuuhQxzhB/HIbjj9LV\n+Hfsm6vxL2PZQl/gZ4FkkfGXL/xuJvYz+NO1+MRiqzFRJQJ6+N1rZdVtTTDIZbpo\nFGWsJwt0ivKH\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc.\n# Subject: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc.\n# Label: \"TrustAsia Global Root CA G4\"\n# Serial: 451799571007117016466790293371524403291602933463\n# MD5 Fingerprint: 54:dd:b2:d7:5f:d8:3e:ed:7c:e0:0b:2e:cc:ed:eb:eb\n# SHA1 Fingerprint: 57:73:a5:61:5d:80:b2:e6:ac:38:82:fc:68:07:31:ac:9f:b5:92:5a\n# SHA256 Fingerprint: be:4b:56:cb:50:56:c0:13:6a:52:6d:f4:44:50:8d:aa:36:a0:b5:4f:42:e4:ac:38:f7:2a:f4:70:e4:79:65:4c\n-----BEGIN CERTIFICATE-----\nMIICVTCCAdygAwIBAgIUTyNkuI6XY57GU4HBdk7LKnQV1tcwCgYIKoZIzj0EAwMw\nWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs\nIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHNDAeFw0y\nMTA1MjAwMjEwMjJaFw00NjA1MTkwMjEwMjJaMFoxCzAJBgNVBAYTAkNOMSUwIwYD\nVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtUcnVz\ndEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATx\ns8045CVD5d4ZCbuBeaIVXxVjAd7Cq92zphtnS4CDr5nLrBfbK5bKfFJV4hrhPVbw\nLxYI+hW8m7tH5j/uqOFMjPXTNvk4XatwmkcN4oFBButJ+bAp3TPsUKV/eSm4IJij\nYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUpbtKl86zK3+kMd6Xg1mD\npm9xy94wHQYDVR0OBBYEFKW7SpfOsyt/pDHel4NZg6ZvccveMA4GA1UdDwEB/wQE\nAwIBBjAKBggqhkjOPQQDAwNnADBkAjBe8usGzEkxn0AAbbd+NvBNEU/zy4k6LHiR\nUKNbwMp1JvK/kF0LgoxgKJ/GcJpo5PECMFxYDlZ2z1jD1xCMuo6u47xkdUfFVZDj\n/bpV6wfEU6s3qe4hsiFbYI89MvHVI5TWWA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH\n# Subject: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH\n# Label: \"Telekom Security TLS ECC Root 2020\"\n# Serial: 72082518505882327255703894282316633856\n# MD5 Fingerprint: c1:ab:fe:6a:10:2c:03:8d:bc:1c:22:32:c0:85:a7:fd\n# SHA1 Fingerprint: c0:f8:96:c5:a9:3b:01:06:21:07:da:18:42:48:bc:e9:9d:88:d5:ec\n# SHA256 Fingerprint: 57:8a:f4:de:d0:85:3f:4e:59:98:db:4a:ea:f9:cb:ea:8d:94:5f:60:b6:20:a3:8d:1a:3c:13:b2:bc:7b:a8:e1\n-----BEGIN CERTIFICATE-----\nMIICQjCCAcmgAwIBAgIQNjqWjMlcsljN0AFdxeVXADAKBggqhkjOPQQDAzBjMQsw\nCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0eSBH\nbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBFQ0MgUm9vdCAyMDIw\nMB4XDTIwMDgyNTA3NDgyMFoXDTQ1MDgyNTIzNTk1OVowYzELMAkGA1UEBhMCREUx\nJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkGA1UE\nAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgRUNDIFJvb3QgMjAyMDB2MBAGByqGSM49\nAgEGBSuBBAAiA2IABM6//leov9Wq9xCazbzREaK9Z0LMkOsVGJDZos0MKiXrPk/O\ntdKPD/M12kOLAoC+b1EkHQ9rK8qfwm9QMuU3ILYg/4gND21Ju9sGpIeQkpT0CdDP\nf8iAC8GXs7s1J8nCG6NCMEAwHQYDVR0OBBYEFONyzG6VmUex5rNhTNHLq+O6zd6f\nMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA\nMGQCMHVSi7ekEE+uShCLsoRbQuHmKjYC2qBuGT8lv9pZMo7k+5Dck2TOrbRBR2Di\nz6fLHgIwN0GMZt9Ba9aDAEH9L1r3ULRn0SyocddDypwnJJGDSA3PzfdUga/sf+Rn\n27iQ7t0l\n-----END CERTIFICATE-----\n\n# Issuer: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH\n# Subject: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH\n# Label: \"Telekom Security TLS RSA Root 2023\"\n# Serial: 44676229530606711399881795178081572759\n# MD5 Fingerprint: bf:5b:eb:54:40:cd:48:71:c4:20:8d:7d:de:0a:42:f2\n# SHA1 Fingerprint: 54:d3:ac:b3:bd:57:56:f6:85:9d:ce:e5:c3:21:e2:d4:ad:83:d0:93\n# SHA256 Fingerprint: ef:c6:5c:ad:bb:59:ad:b6:ef:e8:4d:a2:23:11:b3:56:24:b7:1b:3b:1e:a0:da:8b:66:55:17:4e:c8:97:86:46\n-----BEGIN CERTIFICATE-----\nMIIFszCCA5ugAwIBAgIQIZxULej27HF3+k7ow3BXlzANBgkqhkiG9w0BAQwFADBj\nMQswCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0\neSBHbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBSU0EgUm9vdCAy\nMDIzMB4XDTIzMDMyODEyMTY0NVoXDTQ4MDMyNzIzNTk1OVowYzELMAkGA1UEBhMC\nREUxJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkG\nA1UEAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgUlNBIFJvb3QgMjAyMzCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAO01oYGA88tKaVvC+1GDrib94W7zgRJ9\ncUD/h3VCKSHtgVIs3xLBGYSJwb3FKNXVS2xE1kzbB5ZKVXrKNoIENqil/Cf2SfHV\ncp6R+SPWcHu79ZvB7JPPGeplfohwoHP89v+1VmLhc2o0mD6CuKyVU/QBoCcHcqMA\nU6DksquDOFczJZSfvkgdmOGjup5czQRxUX11eKvzWarE4GC+j4NSuHUaQTXtvPM6\nY+mpFEXX5lLRbtLevOP1Czvm4MS9Q2QTps70mDdsipWol8hHD/BeEIvnHRz+sTug\nBTNoBUGCwQMrAcjnj02r6LX2zWtEtefdi+zqJbQAIldNsLGyMcEWzv/9FIS3R/qy\n8XDe24tsNlikfLMR0cN3f1+2JeANxdKz+bi4d9s3cXFH42AYTyS2dTd4uaNir73J\nco4vzLuu2+QVUhkHM/tqty1LkCiCc/4YizWN26cEar7qwU02OxY2kTLvtkCJkUPg\n8qKrBC7m8kwOFjQgrIfBLX7JZkcXFBGk8/ehJImr2BrIoVyxo/eMbcgByU/J7MT8\nrFEz0ciD0cmfHdRHNCk+y7AO+oMLKFjlKdw/fKifybYKu6boRhYPluV75Gp6SG12\nmAWl3G0eQh5C2hrgUve1g8Aae3g1LDj1H/1Joy7SWWO/gLCMk3PLNaaZlSJhZQNg\n+y+TS/qanIA7AgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtqeX\ngj10hZv3PJ+TmpV5dVKMbUcwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS2\np5eCPXSFm/c8n5OalXl1UoxtRzANBgkqhkiG9w0BAQwFAAOCAgEAqMxhpr51nhVQ\npGv7qHBFfLp+sVr8WyP6Cnf4mHGCDG3gXkaqk/QeoMPhk9tLrbKmXauw1GLLXrtm\n9S3ul0A8Yute1hTWjOKWi0FpkzXmuZlrYrShF2Y0pmtjxrlO8iLpWA1WQdH6DErw\nM807u20hOq6OcrXDSvvpfeWxm4bu4uB9tPcy/SKE8YXJN3nptT+/XOR0so8RYgDd\nGGah2XsjX/GO1WfoVNpbOms2b/mBsTNHM3dA+VKq3dSDz4V4mZqTuXNnQkYRIer+\nCqkbGmVps4+uFrb2S1ayLfmlyOw7YqPta9BO1UAJpB+Y1zqlklkg5LB9zVtzaL1t\nxKITDmcZuI1CfmwMmm6gJC3VRRvcxAIU/oVbZZfKTpBQCHpCNfnqwmbU+AGuHrS+\nw6jv/naaoqYfRvaE7fzbzsQCzndILIyy7MMAo+wsVRjBfhnu4S/yrYObnqsZ38aK\nL4x35bcF7DvB7L6Gs4a8wPfc5+pbrrLMtTWGS9DiP7bY+A4A7l3j941Y/8+LN+lj\nX273CXE2whJdV/LItM3z7gLfEdxquVeEHVlNjM7IDiPCtyaaEBRx/pOyiriA8A4Q\nntOoUAw3gi/q4Iqd4Sw5/7W0cwDk90imc6y/st53BIe0o82bNSQ3+pCTE4FCxpgm\ndTdmQRCsu/WU48IxK63nI1bMNSWSs1A=\n-----END CERTIFICATE-----\n\n# Issuer: CN=FIRMAPROFESIONAL CA ROOT-A WEB O=Firmaprofesional SA\n# Subject: CN=FIRMAPROFESIONAL CA ROOT-A WEB O=Firmaprofesional SA\n# Label: \"FIRMAPROFESIONAL CA ROOT-A WEB\"\n# Serial: 65916896770016886708751106294915943533\n# MD5 Fingerprint: 82:b2:ad:45:00:82:b0:66:63:f8:5f:c3:67:4e:ce:a3\n# SHA1 Fingerprint: a8:31:11:74:a6:14:15:0d:ca:77:dd:0e:e4:0c:5d:58:fc:a0:72:a5\n# SHA256 Fingerprint: be:f2:56:da:f2:6e:9c:69:bd:ec:16:02:35:97:98:f3:ca:f7:18:21:a0:3e:01:82:57:c5:3c:65:61:7f:3d:4a\n-----BEGIN CERTIFICATE-----\nMIICejCCAgCgAwIBAgIQMZch7a+JQn81QYehZ1ZMbTAKBggqhkjOPQQDAzBuMQsw\nCQYDVQQGEwJFUzEcMBoGA1UECgwTRmlybWFwcm9mZXNpb25hbCBTQTEYMBYGA1UE\nYQwPVkFURVMtQTYyNjM0MDY4MScwJQYDVQQDDB5GSVJNQVBST0ZFU0lPTkFMIENB\nIFJPT1QtQSBXRUIwHhcNMjIwNDA2MDkwMTM2WhcNNDcwMzMxMDkwMTM2WjBuMQsw\nCQYDVQQGEwJFUzEcMBoGA1UECgwTRmlybWFwcm9mZXNpb25hbCBTQTEYMBYGA1UE\nYQwPVkFURVMtQTYyNjM0MDY4MScwJQYDVQQDDB5GSVJNQVBST0ZFU0lPTkFMIENB\nIFJPT1QtQSBXRUIwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARHU+osEaR3xyrq89Zf\ne9MEkVz6iMYiuYMQYneEMy3pA4jU4DP37XcsSmDq5G+tbbT4TIqk5B/K6k84Si6C\ncyvHZpsKjECcfIr28jlgst7L7Ljkb+qbXbdTkBgyVcUgt5SjYzBhMA8GA1UdEwEB\n/wQFMAMBAf8wHwYDVR0jBBgwFoAUk+FDY1w8ndYn81LsF7Kpryz3dvgwHQYDVR0O\nBBYEFJPhQ2NcPJ3WJ/NS7Beyqa8s93b4MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjO\nPQQDAwNoADBlAjAdfKR7w4l1M+E7qUW/Runpod3JIha3RxEL2Jq68cgLcFBTApFw\nhVmpHqTm6iMxoAACMQD94vizrxa5HnPEluPBMBnYfubDl94cT7iJLzPrSA8Z94dG\nXSaQpYXFuXqUPoeovQA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA\n# Subject: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA\n# Label: \"TWCA CYBER Root CA\"\n# Serial: 85076849864375384482682434040119489222\n# MD5 Fingerprint: 0b:33:a0:97:52:95:d4:a9:fd:bb:db:6e:a3:55:5b:51\n# SHA1 Fingerprint: f6:b1:1c:1a:83:38:e9:7b:db:b3:a8:c8:33:24:e0:2d:9c:7f:26:66\n# SHA256 Fingerprint: 3f:63:bb:28:14:be:17:4e:c8:b6:43:9c:f0:8d:6d:56:f0:b7:c4:05:88:3a:56:48:a3:34:42:4d:6b:3e:c5:58\n-----BEGIN CERTIFICATE-----\nMIIFjTCCA3WgAwIBAgIQQAE0jMIAAAAAAAAAATzyxjANBgkqhkiG9w0BAQwFADBQ\nMQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FOLUNBMRAwDgYDVQQLEwdSb290\nIENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3QgQ0EwHhcNMjIxMTIyMDY1NDI5\nWhcNNDcxMTIyMTU1OTU5WjBQMQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FO\nLUNBMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3Qg\nQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDG+Moe2Qkgfh1sTs6P\n40czRJzHyWmqOlt47nDSkvgEs1JSHWdyKKHfi12VCv7qze33Kc7wb3+szT3vsxxF\navcokPFhV8UMxKNQXd7UtcsZyoC5dc4pztKFIuwCY8xEMCDa6pFbVuYdHNWdZsc/\n34bKS1PE2Y2yHer43CdTo0fhYcx9tbD47nORxc5zb87uEB8aBs/pJ2DFTxnk684i\nJkXXYJndzk834H/nY62wuFm40AZoNWDTNq5xQwTxaWV4fPMf88oon1oglWa0zbfu\nj3ikRRjpJi+NmykosaS3Om251Bw4ckVYsV7r8Cibt4LK/c/WMw+f+5eesRycnupf\nXtuq3VTpMCEobY5583WSjCb+3MX2w7DfRFlDo7YDKPYIMKoNM+HvnKkHIuNZW0CP\n2oi3aQiotyMuRAlZN1vH4xfyIutuOVLF3lSnmMlLIJXcRolftBL5hSmO68gnFSDA\nS9TMfAxsNAwmmyYxpjyn9tnQS6Jk/zuZQXLB4HCX8SS7K8R0IrGsayIyJNN4KsDA\noS/xUgXJP+92ZuJF2A09rZXIx4kmyA+upwMu+8Ff+iDhcK2wZSA3M2Cw1a/XDBzC\nkHDXShi8fgGwsOsVHkQGzaRP6AzRwyAQ4VRlnrZR0Bp2a0JaWHY06rc3Ga4udfmW\n5cFZ95RXKSWNOkyrTZpB0F8mAwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYD\nVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBSdhWEUfMFib5do5E83QOGt4A1WNzAd\nBgNVHQ4EFgQUnYVhFHzBYm+XaORPN0DhreANVjcwDQYJKoZIhvcNAQEMBQADggIB\nAGSPesRiDrWIzLjHhg6hShbNcAu3p4ULs3a2D6f/CIsLJc+o1IN1KriWiLb73y0t\ntGlTITVX1olNc79pj3CjYcya2x6a4CD4bLubIp1dhDGaLIrdaqHXKGnK/nZVekZn\n68xDiBaiA9a5F/gZbG0jAn/xX9AKKSM70aoK7akXJlQKTcKlTfjF/biBzysseKNn\nTKkHmvPfXvt89YnNdJdhEGoHK4Fa0o635yDRIG4kqIQnoVesqlVYL9zZyvpoBJ7t\nRCT5dEA7IzOrg1oYJkK2bVS1FmAwbLGg+LhBoF1JSdJlBTrq/p1hvIbZv97Tujqx\nf36SNI7JAG7cmL3c7IAFrQI932XtCwP39xaEBDG6k5TY8hL4iuO/Qq+n1M0RFxbI\nQh0UqEL20kCGoE8jypZFVmAGzbdVAaYBlGX+bgUJurSkquLvWL69J1bY73NxW0Qz\n8ppy6rBePm6pUlvscG21h483XjyMnM7k8M4MZ0HMzvaAq07MTFb1wWFZk7Q+ptq4\nNxKfKjLji7gh7MMrZQzvIt6IKTtM1/r+t+FHvpw+PoP7UV31aPcuIYXcv/Fa4nzX\nxeSDwWrruoBa3lwtcHb4yOWHh8qgnaHlIhInD0Q9HWzq1MKLL295q39QpsQZp6F6\nt5b5wR9iWqJDB0BeJsas7a5wFsWqynKKTbDPAYsDP27X\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureSign Root CA12 O=Cybertrust Japan Co., Ltd.\n# Subject: CN=SecureSign Root CA12 O=Cybertrust Japan Co., Ltd.\n# Label: \"SecureSign Root CA12\"\n# Serial: 587887345431707215246142177076162061960426065942\n# MD5 Fingerprint: c6:89:ca:64:42:9b:62:08:49:0b:1e:7f:e9:07:3d:e8\n# SHA1 Fingerprint: 7a:22:1e:3d:de:1b:06:ac:9e:c8:47:70:16:8e:3c:e5:f7:6b:06:f4\n# SHA256 Fingerprint: 3f:03:4b:b5:70:4d:44:b2:d0:85:45:a0:20:57:de:93:eb:f3:90:5f:ce:72:1a:cb:c7:30:c0:6d:da:ee:90:4e\n-----BEGIN CERTIFICATE-----\nMIIDcjCCAlqgAwIBAgIUZvnHwa/swlG07VOX5uaCwysckBYwDQYJKoZIhvcNAQEL\nBQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u\nLCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExMjAeFw0yMDA0MDgw\nNTM2NDZaFw00MDA0MDgwNTM2NDZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD\neWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS\nb290IENBMTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6OcE3emhF\nKxS06+QT61d1I02PJC0W6K6OyX2kVzsqdiUzg2zqMoqUm048luT9Ub+ZyZN+v/mt\np7JIKwccJ/VMvHASd6SFVLX9kHrko+RRWAPNEHl57muTH2SOa2SroxPjcf59q5zd\nJ1M3s6oYwlkm7Fsf0uZlfO+TvdhYXAvA42VvPMfKWeP+bl+sg779XSVOKik71gur\nFzJ4pOE+lEa+Ym6b3kaosRbnhW70CEBFEaCeVESE99g2zvVQR9wsMJvuwPWW0v4J\nhscGWa5Pro4RmHvzC1KqYiaqId+OJTN5lxZJjfU+1UefNzFJM3IFTQy2VYzxV4+K\nh9GtxRESOaCtAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD\nAgEGMB0GA1UdDgQWBBRXNPN0zwRL1SXm8UC2LEzZLemgrTANBgkqhkiG9w0BAQsF\nAAOCAQEAPrvbFxbS8hQBICw4g0utvsqFepq2m2um4fylOqyttCg6r9cBg0krY6Ld\nmmQOmFxv3Y67ilQiLUoT865AQ9tPkbeGGuwAtEGBpE/6aouIs3YIcipJQMPTw4WJ\nmBClnW8Zt7vPemVV2zfrPIpyMpcemik+rY3moxtt9XUa5rBouVui7mlHJzWhhpmA\n8zNL4WukJsPvdFlseqJkth5Ew1DgDzk9qTPxpfPSvWKErI4cqc1avTc7bgoitPQV\n55FYxTpE05Uo2cBl6XLK0A+9H7MV2anjpEcJnuDLN/v9vZfVvhgaaaI5gdka9at/\nyOPiZwud9AzqVN/Ssq+xIvEg37xEHA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd.\n# Subject: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd.\n# Label: \"SecureSign Root CA14\"\n# Serial: 575790784512929437950770173562378038616896959179\n# MD5 Fingerprint: 71:0d:72:fa:92:19:65:5e:89:04:ac:16:33:f0:bc:d5\n# SHA1 Fingerprint: dd:50:c0:f7:79:b3:64:2e:74:a2:b8:9d:9f:d3:40:dd:bb:f0:f2:4f\n# SHA256 Fingerprint: 4b:00:9c:10:34:49:4f:9a:b5:6b:ba:3b:a1:d6:27:31:fc:4d:20:d8:95:5a:dc:ec:10:a9:25:60:72:61:e3:38\n-----BEGIN CERTIFICATE-----\nMIIFcjCCA1qgAwIBAgIUZNtaDCBO6Ncpd8hQJ6JaJ90t8sswDQYJKoZIhvcNAQEM\nBQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u\nLCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNDAeFw0yMDA0MDgw\nNzA2MTlaFw00NTA0MDgwNzA2MTlaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD\neWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS\nb290IENBMTQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDF0nqh1oq/\nFjHQmNE6lPxauG4iwWL3pwon71D2LrGeaBLwbCRjOfHw3xDG3rdSINVSW0KZnvOg\nvlIfX8xnbacuUKLBl422+JX1sLrcneC+y9/3OPJH9aaakpUqYllQC6KxNedlsmGy\n6pJxaeQp8E+BgQQ8sqVb1MWoWWd7VRxJq3qdwudzTe/NCcLEVxLbAQ4jeQkHO6Lo\n/IrPj8BGJJw4J+CDnRugv3gVEOuGTgpa/d/aLIJ+7sr2KeH6caH3iGicnPCNvg9J\nkdjqOvn90Ghx2+m1K06Ckm9mH+Dw3EzsytHqunQG+bOEkJTRX45zGRBdAuVwpcAQ\n0BB8b8VYSbSwbprafZX1zNoCr7gsfXmPvkPx+SgojQlD+Ajda8iLLCSxjVIHvXib\ny8posqTdDEx5YMaZ0ZPxMBoH064iwurO8YQJzOAUbn8/ftKChazcqRZOhaBgy/ac\n18izju3Gm5h1DVXoX+WViwKkrkMpKBGk5hIwAUt1ax5mnXkvpXYvHUC0bcl9eQjs\n0Wq2XSqypWa9a4X0dFbD9ed1Uigspf9mR6XU/v6eVL9lfgHWMI+lNpyiUBzuOIAB\nSMbHdPTGrMNASRZhdCyvjG817XsYAFs2PJxQDcqSMxDxJklt33UkN4Ii1+iW/RVL\nApY+B3KVfqs9TC7XyvDf4Fg/LS8EmjijAQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD\nAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUBpOjCl4oaTeqYR3r6/wtbyPk\n86AwDQYJKoZIhvcNAQEMBQADggIBAJaAcgkGfpzMkwQWu6A6jZJOtxEaCnFxEM0E\nrX+lRVAQZk5KQaID2RFPeje5S+LGjzJmdSX7684/AykmjbgWHfYfM25I5uj4V7Ib\ned87hwriZLoAymzvftAj63iP/2SbNDefNWWipAA9EiOWWF3KY4fGoweITedpdopT\nzfFP7ELyk+OZpDc8h7hi2/DsHzc/N19DzFGdtfCXwreFamgLRB7lUe6TzktuhsHS\nDCRZNhqfLJGP4xjblJUK7ZGqDpncllPjYYPGFrojutzdfhrGe0K22VoF3Jpf1d+4\n2kd92jjbrDnVHmtsKheMYc2xbXIBw8MgAGJoFjHVdqqGuw6qnsb58Nn4DSEC5MUo\nFlkRudlpcyqSeLiSV5sI8jrlL5WwWLdrIBRtFO8KvH7YVdiI2i/6GaX7i+B/OfVy\nK4XELKzvGUWSTLNhB9xNH27SgRNcmvMSZ4PPmz+Ln52kuaiWA3rF7iDeM9ovnhp6\ndB7h7sxaOgTdsxoEqBRjrLdHEoOabPXm6RUVkRqEGQ6UROcSjiVbgGcZ3GOTEAtl\nLor6CZpO2oYofaphNdgOpygau1LgePhsumywbrmHXumZNTfxPWQrqaA0k89jL9WB\n365jJ6UeTo3cKXhZ+PmhIIynJkBugnLNeLLIjzwec+fBH7/PzqUqm9tEZDKgu39c\nJRNItX+S\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd.\n# Subject: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd.\n# Label: \"SecureSign Root CA15\"\n# Serial: 126083514594751269499665114766174399806381178503\n# MD5 Fingerprint: 13:30:fc:c4:62:a6:a9:de:b5:c1:68:af:b5:d2:31:47\n# SHA1 Fingerprint: cb:ba:83:c8:c1:5a:5d:f1:f9:73:6f:ca:d7:ef:28:13:06:4a:07:7d\n# SHA256 Fingerprint: e7:78:f0:f0:95:fe:84:37:29:cd:1a:00:82:17:9e:53:14:a9:c2:91:44:28:05:e1:fb:1d:8f:b6:b8:88:6c:3a\n-----BEGIN CERTIFICATE-----\nMIICIzCCAamgAwIBAgIUFhXHw9hJp75pDIqI7fBw+d23PocwCgYIKoZIzj0EAwMw\nUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28uLCBM\ndGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNTAeFw0yMDA0MDgwODMy\nNTZaFw00NTA0MDgwODMyNTZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpDeWJl\ncnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBSb290\nIENBMTUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQLUHSNZDKZmbPSYAi4Io5GdCx4\nwCtELW1fHcmuS1Iggz24FG1Th2CeX2yF2wYUleDHKP+dX+Sq8bOLbe1PL0vJSpSR\nZHX+AezB2Ot6lHhWGENfa4HL9rzatAy2KZMIaY+jQjBAMA8GA1UdEwEB/wQFMAMB\nAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTrQciu/NWeUUj1vYv0hyCTQSvT\n9DAKBggqhkjOPQQDAwNoADBlAjEA2S6Jfl5OpBEHvVnCB96rMjhTKkZEBhd6zlHp\n4P9mLQlO4E/0BdGF9jVg3PVys0Z9AjBEmEYagoUeYWmJSwdLZrWeqrqgHkHZAXQ6\nbkU6iYAZezKYVWOr62Nuk22rGwlgMU4=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH\n# Subject: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH\n# Label: \"D-TRUST BR Root CA 2 2023\"\n# Serial: 153168538924886464690566649552453098598\n# MD5 Fingerprint: e1:09:ed:d3:60:d4:56:1b:47:1f:b7:0c:5f:1b:5f:85\n# SHA1 Fingerprint: 2d:b0:70:ee:71:94:af:69:68:17:db:79:ce:58:9f:a0:6b:96:f7:87\n# SHA256 Fingerprint: 05:52:e6:f8:3f:df:65:e8:fa:96:70:e6:66:df:28:a4:e2:13:40:b5:10:cb:e5:25:66:f9:7c:4f:b9:4b:2b:d1\n-----BEGIN CERTIFICATE-----\nMIIFqTCCA5GgAwIBAgIQczswBEhb2U14LnNLyaHcZjANBgkqhkiG9w0BAQ0FADBI\nMQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE\nLVRSVVNUIEJSIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA4NTYzMVoXDTM4MDUw\nOTA4NTYzMFowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi\nMCAGA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN\nAQEBBQADggIPADCCAgoCggIBAK7/CVmRgApKaOYkP7in5Mg6CjoWzckjYaCTcfKr\ni3OPoGdlYNJUa2NRb0kz4HIHE304zQaSBylSa053bATTlfrdTIzZXcFhfUvnKLNE\ngXtRr90zsWh81k5M/itoucpmacTsXld/9w3HnDY25QdgrMBM6ghs7wZ8T1soegj8\nk12b9py0i4a6Ibn08OhZWiihNIQaJZG2tY/vsvmA+vk9PBFy2OMvhnbFeSzBqZCT\nRphny4NqoFAjpzv2gTng7fC5v2Xx2Mt6++9zA84A9H3X4F07ZrjcjrqDy4d2A/wl\n2ecjbwb9Z/Pg/4S8R7+1FhhGaRTMBffb00msa8yr5LULQyReS2tNZ9/WtT5PeB+U\ncSTq3nD88ZP+npNa5JRal1QMNXtfbO4AHyTsA7oC9Xb0n9Sa7YUsOCIvx9gvdhFP\n/Wxc6PWOJ4d/GUohR5AdeY0cW/jPSoXk7bNbjb7EZChdQcRurDhaTyN0dKkSw/bS\nuREVMweR2Ds3OmMwBtHFIjYoYiMQ4EbMl6zWK11kJNXuHA7e+whadSr2Y23OC0K+\n0bpwHJwh5Q8xaRfX/Aq03u2AnMuStIv13lmiWAmlY0cL4UEyNEHZmrHZqLAbWt4N\nDfTisl01gLmB1IRpkQLLddCNxbU9CZEJjxShFHR5PtbJFR2kWVki3PaKRT08EtY+\nXTIvAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUZ5Dw1t61\nGNVGKX5cq/ieCLxklRAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG\nOGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfYnJfcm9vdF9jYV8y\nXzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQA097N3U9swFrktpSHxQCF16+tI\nFoE9c+CeJyrrd6kTpGoKWloUMz1oH4Guaf2Mn2VsNELZLdB/eBaxOqwjMa1ef67n\nriv6uvw8l5VAk1/DLQOj7aRvU9f6QA4w9QAgLABMjDu0ox+2v5Eyq6+SmNMW5tTR\nVFxDWy6u71cqqLRvpO8NVhTaIasgdp4D/Ca4nj8+AybmTNudX0KEPUUDAxxZiMrc\nLmEkWqTqJwtzEr5SswrPMhfiHocaFpVIbVrg0M8JkiZmkdijYQ6qgYF/6FKC0ULn\n4B0Y+qSFNueG4A3rvNTJ1jxD8V1Jbn6Bm2m1iWKPiFLY1/4nwSPFyysCu7Ff/vtD\nhQNGvl3GyiEm/9cCnnRK3PgTFbGBVzbLZVzRHTF36SXDw7IyN9XxmAnkbWOACKsG\nkoHU6XCPpz+y7YaMgmo1yEJagtFSGkUPFaUA8JR7ZSdXOUPPfH/mvTWze/EZTN46\nls/pdu4D58JDUjxqgejBWoC9EV2Ta/vH5mQ/u2kc6d0li690yVRAysuTEwrt+2aS\nEcr1wPrYg1UDfNPFIkZ1cGt5SAYqgpq/5usWDiJFAbzdNpQ0qTUmiteXue4Icr80\nknCDgKs4qllo3UCkGJCy89UDyibK79XH4I9TjvAA46jtn/mtd+ArY0+ew+43u3gJ\nhJ65bvspmZDogNOfJA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc.\n# Subject: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc.\n# Label: \"TrustAsia TLS ECC Root CA\"\n# Serial: 310892014698942880364840003424242768478804666567\n# MD5 Fingerprint: 09:48:04:77:d2:fc:65:93:71:66:b1:11:95:4f:06:8c\n# SHA1 Fingerprint: b5:ec:39:f3:a1:66:37:ae:c3:05:94:57:e2:be:11:be:b7:a1:7f:36\n# SHA256 Fingerprint: c0:07:6b:9e:f0:53:1f:b1:a6:56:d6:7c:4e:be:97:cd:5d:ba:a4:1e:f4:45:98:ac:c2:48:98:78:c9:2d:87:11\n-----BEGIN CERTIFICATE-----\nMIICMTCCAbegAwIBAgIUNnThTXxlE8msg1UloD5Sfi9QaMcwCgYIKoZIzj0EAwMw\nWDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs\nIEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgRUNDIFJvb3QgQ0EwHhcNMjQw\nNTE1MDU0MTU2WhcNNDQwNTE1MDU0MTU1WjBYMQswCQYDVQQGEwJDTjElMCMGA1UE\nChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1c3RB\nc2lhIFRMUyBFQ0MgUm9vdCBDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLh/pVs/\nAT598IhtrimY4ZtcU5nb9wj/1WrgjstEpvDBjL1P1M7UiFPoXlfXTr4sP/MSpwDp\nguMqWzJ8S5sUKZ74LYO1644xST0mYekdcouJtgq7nDM1D9rs3qlKH8kzsaNCMEAw\nDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQULIVTu7FDzTLqnqOH/qKYqKaT6RAw\nDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMFRH18MtYYZI9HlaVQ01\nL18N9mdsd0AaRuf4aFtOJx24mH1/k78ITcTaRTChD15KeAIxAKORh/IRM4PDwYqR\nOkwrULG9IpRdNYlzg8WbGf60oenUoWa2AaU2+dhoYSi3dOGiMQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc.\n# Subject: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc.\n# Label: \"TrustAsia TLS RSA Root CA\"\n# Serial: 160405846464868906657516898462547310235378010780\n# MD5 Fingerprint: 3b:9e:c3:86:0f:34:3c:6b:c5:46:c4:8e:1d:e7:19:12\n# SHA1 Fingerprint: a5:46:50:c5:62:ea:95:9a:1a:a7:04:6f:17:58:c7:29:53:3d:03:fa\n# SHA256 Fingerprint: 06:c0:8d:7d:af:d8:76:97:1e:b1:12:4f:e6:7f:84:7e:c0:c7:a1:58:d3:ea:53:cb:e9:40:e2:ea:97:91:f4:c3\n-----BEGIN CERTIFICATE-----\nMIIFgDCCA2igAwIBAgIUHBjYz+VTPyI1RlNUJDxsR9FcSpwwDQYJKoZIhvcNAQEM\nBQAwWDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dp\nZXMsIEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgUlNBIFJvb3QgQ0EwHhcN\nMjQwNTE1MDU0MTU3WhcNNDQwNTE1MDU0MTU2WjBYMQswCQYDVQQGEwJDTjElMCMG\nA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1\nc3RBc2lhIFRMUyBSU0EgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\nAgoCggIBAMMWuBtqpERz5dZO9LnPWwvB0ZqB9WOwj0PBuwhaGnrhB3YmH49pVr7+\nNmDQDIPNlOrnxS1cLwUWAp4KqC/lYCZUlviYQB2srp10Zy9U+5RjmOMmSoPGlbYJ\nQ1DNDX3eRA5gEk9bNb2/mThtfWza4mhzH/kxpRkQcwUqwzIZheo0qt1CHjCNP561\nHmHVb70AcnKtEj+qpklz8oYVlQwQX1Fkzv93uMltrOXVmPGZLmzjyUT5tUMnCE32\nft5EebuyjBza00tsLtbDeLdM1aTk2tyKjg7/D8OmYCYozza/+lcK7Fs/6TAWe8Tb\nxNRkoDD75f0dcZLdKY9BWN4ArTr9PXwaqLEX8E40eFgl1oUh63kd0Nyrz2I8sMeX\ni9bQn9P+PN7F4/w6g3CEIR0JwqH8uyghZVNgepBtljhb//HXeltt08lwSUq6HTrQ\nUNoyIBnkiz/r1RYmNzz7dZ6wB3C4FGB33PYPXFIKvF1tjVEK2sUYyJtt3LCDs3+j\nTnhMmCWr8n4uIF6CFabW2I+s5c0yhsj55NqJ4js+k8UTav/H9xj8Z7XvGCxUq0DT\nbE3txci3OE9kxJRMT6DNrqXGJyV1J23G2pyOsAWZ1SgRxSHUuPzHlqtKZFlhaxP8\nS8ySpg+kUb8OWJDZgoM5pl+z+m6Ss80zDoWo8SnTq1mt1tve1CuBAgMBAAGjQjBA\nMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLgHkXlcBvRG/XtZylomkadFK/hT\nMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwFAAOCAgEAIZtqBSBdGBanEqT3\nRz/NyjuujsCCztxIJXgXbODgcMTWltnZ9r96nBO7U5WS/8+S4PPFJzVXqDuiGev4\niqME3mmL5Dw8veWv0BIb5Ylrc5tvJQJLkIKvQMKtuppgJFqBTQUYo+IzeXoLH5Pt\n7DlK9RME7I10nYEKqG/odv6LTytpEoYKNDbdgptvT+Bz3Ul/KD7JO6NXBNiT2Twp\n2xIQaOHEibgGIOcberyxk2GaGUARtWqFVwHxtlotJnMnlvm5P1vQiJ3koP26TpUJ\ng3933FEFlJ0gcXax7PqJtZwuhfG5WyRasQmr2soaB82G39tp27RIGAAtvKLEiUUj\npQ7hRGU+isFqMB3iYPg6qocJQrmBktwliJiJ8Xw18WLK7nn4GS/+X/jbh87qqA8M\npugLoDzga5SYnH+tBuYc6kIQX+ImFTw3OffXvO645e8D7r0i+yiGNFjEWn9hongP\nXvPKnbwbPKfILfanIhHKA9jnZwqKDss1jjQ52MjqjZ9k4DewbNfFj8GQYSbbJIwe\nSsCI3zWQzj8C9GRh3sfIB5XeMhg6j6JCQCTl1jNdfK7vsU1P1FeQNWrcrgSXSYk0\nly4wBOeY99sLAZDBHwo/+ML+TvrbmnNzFrwFuHnYWa8G5z9nODmxfKuU4CkUpijy\n323imttUQ/hHWKNddBWcwauwxzQ=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH\n# Subject: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH\n# Label: \"D-TRUST EV Root CA 2 2023\"\n# Serial: 139766439402180512324132425437959641711\n# MD5 Fingerprint: 96:b4:78:09:f0:09:cb:77:eb:bb:1b:4d:6f:36:bc:b6\n# SHA1 Fingerprint: a5:5b:d8:47:6c:8f:19:f7:4c:f4:6d:6b:b6:c2:79:82:22:df:54:8b\n# SHA256 Fingerprint: 8e:82:21:b2:e7:d4:00:78:36:a1:67:2f:0d:cc:29:9c:33:bc:07:d3:16:f1:32:fa:1a:20:6d:58:71:50:f1:ce\n-----BEGIN CERTIFICATE-----\nMIIFqTCCA5GgAwIBAgIQaSYJfoBLTKCnjHhiU19abzANBgkqhkiG9w0BAQ0FADBI\nMQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE\nLVRSVVNUIEVWIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA5MTAzM1oXDTM4MDUw\nOTA5MTAzMlowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi\nMCAGA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN\nAQEBBQADggIPADCCAgoCggIBANiOo4mAC7JXUtypU0w3uX9jFxPvp1sjW2l1sJkK\nF8GLxNuo4MwxusLyzV3pt/gdr2rElYfXR8mV2IIEUD2BCP/kPbOx1sWy/YgJ25yE\n7CUXFId/MHibaljJtnMoPDT3mfd/06b4HEV8rSyMlD/YZxBTfiLNTiVR8CUkNRFe\nEMbsh2aJgWi6zCudR3Mfvc2RpHJqnKIbGKBv7FD0fUDCqDDPvXPIEysQEx6Lmqg6\nlHPTGGkKSv/BAQP/eX+1SH977ugpbzZMlWGG2Pmic4ruri+W7mjNPU0oQvlFKzIb\nRlUWaqZLKfm7lVa/Rh3sHZMdwGWyH6FDrlaeoLGPaxK3YG14C8qKXO0elg6DpkiV\njTujIcSuWMYAsoS0I6SWhjW42J7YrDRJmGOVxcttSEfi8i4YHtAxq9107PncjLgc\njmgjutDzUNzPZY9zOjLHfP7KgiJPvo5iR2blzYfi6NUPGJ/lBHJLRjwQ8kTCZFZx\nTnXonMkmdMV9WdEKWw9t/p51HBjGGjp82A0EzM23RWV6sY+4roRIPrN6TagD4uJ+\nARZZaBhDM7DS3LAaQzXupdqpRlyuhoFBAUp0JuyfBr/CBTdkdXgpaP3F9ev+R/nk\nhbDhezGdpn9yo7nELC7MmVcOIQxFAZRl62UJxmMiCzNJkkg8/M3OsD6Onov4/knF\nNXJHAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUqvyREBuH\nkV8Wub9PS5FeAByxMoAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG\nOGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfZXZfcm9vdF9jYV8y\nXzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQCTy6UfmRHsmg1fLBWTxj++EI14\nQvBukEdHjqOSMo1wj/Zbjb6JzkcBahsgIIlbyIIQbODnmaprxiqgYzWRaoUlrRc4\npZt+UPJ26oUFKidBK7GB0aL2QHWpDsvxVUjY7NHss+jOFKE17MJeNRqrphYBBo7q\n3C+jisosketSjl8MmxfPy3MHGcRqwnNU73xDUmPBEcrCRbH0O1P1aa4846XerOhU\nt7KR/aypH/KH5BfGSah82ApB9PI+53c0BFLd6IHyTS9URZ0V4U/M5d40VxDJI3IX\ncI1QcB9WbMy5/zpaT2N6w25lBx2Eof+pDGOJbbJAiDnXH3dotfyc1dZnaVuodNv8\nifYbMvekJKZ2t0dT741Jj6m2g1qllpBFYfXeA08mD6iL8AOWsKwV0HFaanuU5nCT\n2vFp4LJiTZ6P/4mdm13NRemUAiKN4DV/6PEEeXFsVIP4M7kFMhtYVRFP0OUnR3Hs\n7dpn1mKmS00PaaLJvOwiS5THaJQXfuKOKD62xur1NGyfN4gHONuGcfrNlUhDbqNP\ngofXNJhuS5N5YHVpD/Aa1VP6IQzCP+k/HxiMkl14p3ZnGbuy6n/pcAlWVqOwDAst\nNl7F6cTVg8uGF5csbBNvh1qvSaYd2804BC5f4ko1Di1L+KIkBI3Y4WNeApI02phh\nXBxvWHZks/wCuPWdCg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG\n# Subject: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG\n# Label: \"SwissSign RSA TLS Root CA 2022 - 1\"\n# Serial: 388078645722908516278762308316089881486363258315\n# MD5 Fingerprint: 16:2e:e4:19:76:81:85:ba:8e:91:58:f1:15:ef:72:39\n# SHA1 Fingerprint: 81:34:0a:be:4c:cd:ce:cc:e7:7d:cc:8a:d4:57:e2:45:a0:77:5d:ce\n# SHA256 Fingerprint: 19:31:44:f4:31:e0:fd:db:74:07:17:d4:de:92:6a:57:11:33:88:4b:43:60:d3:0e:27:29:13:cb:e6:60:ce:41\n-----BEGIN CERTIFICATE-----\nMIIFkzCCA3ugAwIBAgIUQ/oMX04bgBhE79G0TzUfRPSA7cswDQYJKoZIhvcNAQEL\nBQAwUTELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzErMCkGA1UE\nAxMiU3dpc3NTaWduIFJTQSBUTFMgUm9vdCBDQSAyMDIyIC0gMTAeFw0yMjA2MDgx\nMTA4MjJaFw00NzA2MDgxMTA4MjJaMFExCzAJBgNVBAYTAkNIMRUwEwYDVQQKEwxT\nd2lzc1NpZ24gQUcxKzApBgNVBAMTIlN3aXNzU2lnbiBSU0EgVExTIFJvb3QgQ0Eg\nMjAyMiAtIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLKmjiC8NX\nvDVjvHClO/OMPE5Xlm7DTjak9gLKHqquuN6orx122ro10JFwB9+zBvKK8i5VUXu7\nLCTLf5ImgKO0lPaCoaTo+nUdWfMHamFk4saMla+ju45vVs9xzF6BYQ1t8qsCLqSX\n5XH8irCRIFucdFJtrhUnWXjyCcplDn/L9Ovn3KlMd/YrFgSVrpxxpT8q2kFC5zyE\nEPThPYxr4iuRR1VPuFa+Rd4iUU1OKNlfGUEGjw5NBuBwQCMBauTLE5tzrE0USJIt\n/m2n+IdreXXhvhCxqohAWVTXz8TQm0SzOGlkjIHRI36qOTw7D59Ke4LKa2/KIj4x\n0LDQKhySio/YGZxH5D4MucLNvkEM+KRHBdvBFzA4OmnczcNpI/2aDwLOEGrOyvi5\nKaM2iYauC8BPY7kGWUleDsFpswrzd34unYyzJ5jSmY0lpx+Gs6ZUcDj8fV3oT4MM\n0ZPlEuRU2j7yrTrePjxF8CgPBrnh25d7mUWe3f6VWQQvdT/TromZhqwUtKiE+shd\nOxtYk8EXlFXIC+OCeYSf8wCENO7cMdWP8vpPlkwGqnj73mSiI80fPsWMvDdUDrta\nclXvyFu1cvh43zcgTFeRc5JzrBh3Q4IgaezprClG5QtO+DdziZaKHG29777YtvTK\nwP1H8K4LWCDFyB02rpeNUIMmJCn3nTsPBQIDAQABo2MwYTAPBgNVHRMBAf8EBTAD\nAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBRvjmKLk0Ow4UD2p8P98Q+4\nDxU4pTAdBgNVHQ4EFgQUb45ii5NDsOFA9qfD/fEPuA8VOKUwDQYJKoZIhvcNAQEL\nBQADggIBAKwsKUF9+lz1GpUYvyypiqkkVHX1uECry6gkUSsYP2OprphWKwVDIqO3\n10aewCoSPY6WlkDfDDOLazeROpW7OSltwAJsipQLBwJNGD77+3v1dj2b9l4wBlgz\nHqp41eZUBDqyggmNzhYzWUUo8aWjlw5DI/0LIICQ/+Mmz7hkkeUFjxOgdg3XNwwQ\niJb0Pr6VvfHDffCjw3lHC1ySFWPtUnWK50Zpy1FVCypM9fJkT6lc/2cyjlUtMoIc\ngC9qkfjLvH4YoiaoLqNTKIftV+Vlek4ASltOU8liNr3CjlvrzG4ngRhZi0Rjn9UM\nZfQpZX+RLOV/fuiJz48gy20HQhFRJjKKLjpHE7iNvUcNCfAWpO2Whi4Z2L6MOuhF\nLhG6rlrnub+xzI/goP+4s9GFe3lmozm1O2bYQL7Pt2eLSMkZJVX8vY3PXtpOpvJp\nzv1/THfQwUY1mFwjmwJFQ5Ra3bxHrSL+ul4vkSkphnsh3m5kt8sNjzdbowhq6/Td\nAo9QAwKxuDdollDruF/UKIqlIgyKhPBZLtU30WHlQnNYKoH3dtvi4k0NX/a3vgW0\nrk4N3hY9A4GzJl5LuEsAz/+MF7psYC0nhzck5npgL7XTgwSqT0N1osGDsieYK7EO\ngLrAhV5Cud+xYJHT6xh+cHiudoO+cVrQkOPKwRYlZ0rwtnu64ZzZ\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE Server Root ECC G1 O=OISTE Foundation\n# Subject: CN=OISTE Server Root ECC G1 O=OISTE Foundation\n# Label: \"OISTE Server Root ECC G1\"\n# Serial: 47819833811561661340092227008453318557\n# MD5 Fingerprint: 42:a7:d2:35:ae:02:92:db:19:76:08:de:2f:05:b4:d4\n# SHA1 Fingerprint: 3b:f6:8b:09:ae:2a:92:7b:ba:e3:8d:3f:11:95:d9:e6:44:0c:45:e2\n# SHA256 Fingerprint: ee:c9:97:c0:c3:0f:21:6f:7e:3b:8b:30:7d:2b:ae:42:41:2d:75:3f:c8:21:9d:af:d1:52:0b:25:72:85:0f:49\n-----BEGIN CERTIFICATE-----\nMIICNTCCAbqgAwIBAgIQI/nD1jWvjyhLH/BU6n6XnTAKBggqhkjOPQQDAzBLMQsw\nCQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UEAwwY\nT0lTVEUgU2VydmVyIFJvb3QgRUNDIEcxMB4XDTIzMDUzMTE0NDIyOFoXDTQ4MDUy\nNDE0NDIyN1owSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRp\nb24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IEVDQyBHMTB2MBAGByqGSM49\nAgEGBSuBBAAiA2IABBcv+hK8rBjzCvRE1nZCnrPoH7d5qVi2+GXROiFPqOujvqQy\ncvO2Ackr/XeFblPdreqqLiWStukhEaivtUwL85Zgmjvn6hp4LrQ95SjeHIC6XG4N\n2xml4z+cKrhAS93mT6NjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBQ3\nTYhlz/w9itWj8UnATgwQb0K0nDAdBgNVHQ4EFgQUN02IZc/8PYrVo/FJwE4MEG9C\ntJwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCpKjAd0MKfkFFR\nQD6VVCHNFmb3U2wIFjnQEnx/Yxvf4zgAOdktUyBFCxxgZzFDJe0CMQCSia7pXGKD\nYmH5LVerVrkR3SW+ak5KGoJr3M/TvEqzPNcum9v4KGm8ay3sMaE641c=\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE Server Root RSA G1 O=OISTE Foundation\n# Subject: CN=OISTE Server Root RSA G1 O=OISTE Foundation\n# Label: \" OISTE Server Root RSA G1\"\n# Serial: 113845518112613905024960613408179309848\n# MD5 Fingerprint: 23:a7:9e:d4:70:b8:b9:14:57:41:8a:7e:44:59:e2:68\n# SHA1 Fingerprint: f7:00:34:25:94:88:68:31:e4:34:87:3f:70:fe:86:b3:86:9f:f0:6e\n# SHA256 Fingerprint: 9a:e3:62:32:a5:18:9f:fd:db:35:3d:fd:26:52:0c:01:53:95:d2:27:77:da:c5:9d:b5:7b:98:c0:89:a6:51:e6\n-----BEGIN CERTIFICATE-----\nMIIFgzCCA2ugAwIBAgIQVaXZZ5Qoxu0M+ifdWwFNGDANBgkqhkiG9w0BAQwFADBL\nMQswCQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UE\nAwwYT0lTVEUgU2VydmVyIFJvb3QgUlNBIEcxMB4XDTIzMDUzMTE0MzcxNloXDTQ4\nMDUyNDE0MzcxNVowSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5k\nYXRpb24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IFJTQSBHMTCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKqu9KuCz/vlNwvn1ZatkOhLKdxVYOPM\nvLO8LZK55KN68YG0nnJyQ98/qwsmtO57Gmn7KNByXEptaZnwYx4M0rH/1ow00O7b\nrEi56rAUjtgHqSSY3ekJvqgiG1k50SeH3BzN+Puz6+mTeO0Pzjd8JnduodgsIUzk\nik/HEzxux9UTl7Ko2yRpg1bTacuCErudG/L4NPKYKyqOBGf244ehHa1uzjZ0Dl4z\nO8vbUZeUapU8zhhabkvG/AePLhq5SvdkNCncpo1Q4Y2LS+VIG24ugBA/5J8bZT8R\ntOpXaZ+0AOuFJJkk9SGdl6r7NH8CaxWQrbueWhl/pIzY+m0o/DjH40ytas7ZTpOS\njswMZ78LS5bOZmdTaMsXEY5Z96ycG7mOaES3GK/m5Q9l3JUJsJMStR8+lKXHiHUh\nsd4JJCpM4rzsTGdHwimIuQq6+cF0zowYJmXa92/GjHtoXAvuY8BeS/FOzJ8vD+Ho\nmnqT8eDI278n5mUpezbgMxVz8p1rhAhoKzYHKyfMeNhqhw5HdPSqoBNdZH702xSu\n+zrkL8Fl47l6QGzwBrd7KJvX4V84c5Ss2XCTLdyEr0YconosP4EmQufU2MVshGYR\ni3drVByjtdgQ8K4p92cIiBdcuJd5z+orKu5YM+Vt6SmqZQENghPsJQtdLEByFSnT\nkCz3GkPVavBpAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAU\n8snBDw1jALvsRQ5KH7WxszbNDo0wHQYDVR0OBBYEFPLJwQ8NYwC77EUOSh+1sbM2\nzQ6NMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQwFAAOCAgEANGd5sjrG5T33\nI3K5Ce+SrScfoE4KsvXaFwyihdJ+klH9FWXXXGtkFu6KRcoMQzZENdl//nk6HOjG\n5D1rd9QhEOP28yBOqb6J8xycqd+8MDoX0TJD0KqKchxRKEzdNsjkLWd9kYccnbz8\nqyiWXmFcuCIzGEgWUOrKL+mlSdx/PKQZvDatkuK59EvV6wit53j+F8Bdh3foZ3dP\nAGav9LEDOr4SfEE15fSmG0eLy3n31r8Xbk5l8PjaV8GUgeV6Vg27Rn9vkf195hfk\ngSe7BYhW3SCl95gtkRlpMV+bMPKZrXJAlszYd2abtNUOshD+FKrDgHGdPY3ofRRs\nYWSGRqbXVMW215AWRqWFyp464+YTFrYVI8ypKVL9AMb2kI5Wj4kI3Zaq5tNqqYY1\n9tVFeEJKRvwDyF7YZvZFZSS0vod7VSCd9521Kvy5YhnLbDuv0204bKt7ph6N/Ome\n/msVuduCmsuY33OhkKCgxeDoAaijFJzIwZqsFVAzje18KotzlUBDJvyBpCpfOZC3\nJ8tRd/iWkx7P8nd9H0aTolkelUTFLXVksNb54Dxp6gS1HAviRkRNQzuXSXERvSS2\nwq1yVAb+axj5d9spLFKebXd7Yv0PTY6YMjAwcRLWJTXjn/hvnLXrahut6hDTlhZy\nBiElxky8j3C7DOReIoMt0r7+hVu05L0=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "src/pip/_vendor/certifi/core.py",
    "content": "\"\"\"\ncertifi.py\n~~~~~~~~~~\n\nThis module returns the installation location of cacert.pem or its contents.\n\"\"\"\nimport sys\nimport atexit\n\ndef exit_cacert_ctx() -> None:\n    _CACERT_CTX.__exit__(None, None, None)  # type: ignore[union-attr]\n\n\nif sys.version_info >= (3, 11):\n\n    from importlib.resources import as_file, files\n\n    _CACERT_CTX = None\n    _CACERT_PATH = None\n\n    def where() -> str:\n        # This is slightly terrible, but we want to delay extracting the file\n        # in cases where we're inside of a zipimport situation until someone\n        # actually calls where(), but we don't want to re-extract the file\n        # on every call of where(), so we'll do it once then store it in a\n        # global variable.\n        global _CACERT_CTX\n        global _CACERT_PATH\n        if _CACERT_PATH is None:\n            # This is slightly janky, the importlib.resources API wants you to\n            # manage the cleanup of this file, so it doesn't actually return a\n            # path, it returns a context manager that will give you the path\n            # when you enter it and will do any cleanup when you leave it. In\n            # the common case of not needing a temporary file, it will just\n            # return the file system location and the __exit__() is a no-op.\n            #\n            # We also have to hold onto the actual context manager, because\n            # it will do the cleanup whenever it gets garbage collected, so\n            # we will also store that at the global level as well.\n            _CACERT_CTX = as_file(files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\"))\n            _CACERT_PATH = str(_CACERT_CTX.__enter__())\n            atexit.register(exit_cacert_ctx)\n\n        return _CACERT_PATH\n\n    def contents() -> str:\n        return files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\").read_text(encoding=\"ascii\")\n\nelse:\n\n    from importlib.resources import path as get_path, read_text\n\n    _CACERT_CTX = None\n    _CACERT_PATH = None\n\n    def where() -> str:\n        # This is slightly terrible, but we want to delay extracting the\n        # file in cases where we're inside of a zipimport situation until\n        # someone actually calls where(), but we don't want to re-extract\n        # the file on every call of where(), so we'll do it once then store\n        # it in a global variable.\n        global _CACERT_CTX\n        global _CACERT_PATH\n        if _CACERT_PATH is None:\n            # This is slightly janky, the importlib.resources API wants you\n            # to manage the cleanup of this file, so it doesn't actually\n            # return a path, it returns a context manager that will give\n            # you the path when you enter it and will do any cleanup when\n            # you leave it. In the common case of not needing a temporary\n            # file, it will just return the file system location and the\n            # __exit__() is a no-op.\n            #\n            # We also have to hold onto the actual context manager, because\n            # it will do the cleanup whenever it gets garbage collected, so\n            # we will also store that at the global level as well.\n            _CACERT_CTX = get_path(\"pip._vendor.certifi\", \"cacert.pem\")\n            _CACERT_PATH = str(_CACERT_CTX.__enter__())\n            atexit.register(exit_cacert_ctx)\n\n        return _CACERT_PATH\n\n    def contents() -> str:\n        return read_text(\"pip._vendor.certifi\", \"cacert.pem\", encoding=\"ascii\")\n"
  },
  {
    "path": "src/pip/_vendor/certifi/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/dependency_groups/LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2024-present Stephen Rosen <sirosen0@gmail.com>\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/__init__.py",
    "content": "from ._implementation import (\n    CyclicDependencyError,\n    DependencyGroupInclude,\n    DependencyGroupResolver,\n    resolve,\n)\n\n__all__ = (\n    \"CyclicDependencyError\",\n    \"DependencyGroupInclude\",\n    \"DependencyGroupResolver\",\n    \"resolve\",\n)\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/__main__.py",
    "content": "import argparse\nimport sys\n\nfrom ._implementation import resolve\nfrom ._toml_compat import tomllib\n\n\ndef main() -> None:\n    if tomllib is None:\n        print(\n            \"Usage error: dependency-groups CLI requires tomli or Python 3.11+\",\n            file=sys.stderr,\n        )\n        raise SystemExit(2)\n\n    parser = argparse.ArgumentParser(\n        description=(\n            \"A dependency-groups CLI. Prints out a resolved group, newline-delimited.\"\n        )\n    )\n    parser.add_argument(\n        \"GROUP_NAME\", nargs=\"*\", help=\"The dependency group(s) to resolve.\"\n    )\n    parser.add_argument(\n        \"-f\",\n        \"--pyproject-file\",\n        default=\"pyproject.toml\",\n        help=\"The pyproject.toml file. Defaults to trying in the current directory.\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        help=\"An output file. Defaults to stdout.\",\n    )\n    parser.add_argument(\n        \"-l\",\n        \"--list\",\n        action=\"store_true\",\n        help=\"List the available dependency groups\",\n    )\n    args = parser.parse_args()\n\n    with open(args.pyproject_file, \"rb\") as fp:\n        pyproject = tomllib.load(fp)\n\n    dependency_groups_raw = pyproject.get(\"dependency-groups\", {})\n\n    if args.list:\n        print(*dependency_groups_raw.keys())\n        return\n    if not args.GROUP_NAME:\n        print(\"A GROUP_NAME is required\", file=sys.stderr)\n        raise SystemExit(3)\n\n    content = \"\\n\".join(resolve(dependency_groups_raw, *args.GROUP_NAME))\n\n    if args.output is None or args.output == \"-\":\n        print(content)\n    else:\n        with open(args.output, \"w\", encoding=\"utf-8\") as fp:\n            print(content, file=fp)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/_implementation.py",
    "content": "from __future__ import annotations\n\nimport dataclasses\nimport re\nfrom collections.abc import Mapping\n\nfrom pip._vendor.packaging.requirements import Requirement\n\n\ndef _normalize_name(name: str) -> str:\n    return re.sub(r\"[-_.]+\", \"-\", name).lower()\n\n\ndef _normalize_group_names(\n    dependency_groups: Mapping[str, str | Mapping[str, str]],\n) -> Mapping[str, str | Mapping[str, str]]:\n    original_names: dict[str, list[str]] = {}\n    normalized_groups = {}\n\n    for group_name, value in dependency_groups.items():\n        normed_group_name = _normalize_name(group_name)\n        original_names.setdefault(normed_group_name, []).append(group_name)\n        normalized_groups[normed_group_name] = value\n\n    errors = []\n    for normed_name, names in original_names.items():\n        if len(names) > 1:\n            errors.append(f\"{normed_name} ({', '.join(names)})\")\n    if errors:\n        raise ValueError(f\"Duplicate dependency group names: {', '.join(errors)}\")\n\n    return normalized_groups\n\n\n@dataclasses.dataclass\nclass DependencyGroupInclude:\n    include_group: str\n\n\nclass CyclicDependencyError(ValueError):\n    \"\"\"\n    An error representing the detection of a cycle.\n    \"\"\"\n\n    def __init__(self, requested_group: str, group: str, include_group: str) -> None:\n        self.requested_group = requested_group\n        self.group = group\n        self.include_group = include_group\n\n        if include_group == group:\n            reason = f\"{group} includes itself\"\n        else:\n            reason = f\"{include_group} -> {group}, {group} -> {include_group}\"\n        super().__init__(\n            \"Cyclic dependency group include while resolving \"\n            f\"{requested_group}: {reason}\"\n        )\n\n\nclass DependencyGroupResolver:\n    \"\"\"\n    A resolver for Dependency Group data.\n\n    This class handles caching, name normalization, cycle detection, and other\n    parsing requirements. There are only two public methods for exploring the data:\n    ``lookup()`` and ``resolve()``.\n\n    :param dependency_groups: A mapping, as provided via pyproject\n        ``[dependency-groups]``.\n    \"\"\"\n\n    def __init__(\n        self,\n        dependency_groups: Mapping[str, str | Mapping[str, str]],\n    ) -> None:\n        if not isinstance(dependency_groups, Mapping):\n            raise TypeError(\"Dependency Groups table is not a mapping\")\n        self.dependency_groups = _normalize_group_names(dependency_groups)\n        # a map of group names to parsed data\n        self._parsed_groups: dict[\n            str, tuple[Requirement | DependencyGroupInclude, ...]\n        ] = {}\n        # a map of group names to their ancestors, used for cycle detection\n        self._include_graph_ancestors: dict[str, tuple[str, ...]] = {}\n        # a cache of completed resolutions to Requirement lists\n        self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}\n\n    def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]:\n        \"\"\"\n        Lookup a group name, returning the parsed dependency data for that group.\n        This will not resolve includes.\n\n        :param group: the name of the group to lookup\n\n        :raises ValueError: if the data does not appear to be valid dependency group\n            data\n        :raises TypeError: if the data is not a string\n        :raises LookupError: if group name is absent\n        :raises packaging.requirements.InvalidRequirement: if a specifier is not valid\n        \"\"\"\n        if not isinstance(group, str):\n            raise TypeError(\"Dependency group name is not a str\")\n        group = _normalize_name(group)\n        return self._parse_group(group)\n\n    def resolve(self, group: str) -> tuple[Requirement, ...]:\n        \"\"\"\n        Resolve a dependency group to a list of requirements.\n\n        :param group: the name of the group to resolve\n\n        :raises TypeError: if the inputs appear to be the wrong types\n        :raises ValueError: if the data does not appear to be valid dependency group\n            data\n        :raises LookupError: if group name is absent\n        :raises packaging.requirements.InvalidRequirement: if a specifier is not valid\n        \"\"\"\n        if not isinstance(group, str):\n            raise TypeError(\"Dependency group name is not a str\")\n        group = _normalize_name(group)\n        return self._resolve(group, group)\n\n    def _parse_group(\n        self, group: str\n    ) -> tuple[Requirement | DependencyGroupInclude, ...]:\n        # short circuit -- never do the work twice\n        if group in self._parsed_groups:\n            return self._parsed_groups[group]\n\n        if group not in self.dependency_groups:\n            raise LookupError(f\"Dependency group '{group}' not found\")\n\n        raw_group = self.dependency_groups[group]\n        if not isinstance(raw_group, list):\n            raise TypeError(f\"Dependency group '{group}' is not a list\")\n\n        elements: list[Requirement | DependencyGroupInclude] = []\n        for item in raw_group:\n            if isinstance(item, str):\n                # packaging.requirements.Requirement parsing ensures that this is a\n                # valid PEP 508 Dependency Specifier\n                # raises InvalidRequirement on failure\n                elements.append(Requirement(item))\n            elif isinstance(item, dict):\n                if tuple(item.keys()) != (\"include-group\",):\n                    raise ValueError(f\"Invalid dependency group item: {item}\")\n\n                include_group = next(iter(item.values()))\n                elements.append(DependencyGroupInclude(include_group=include_group))\n            else:\n                raise ValueError(f\"Invalid dependency group item: {item}\")\n\n        self._parsed_groups[group] = tuple(elements)\n        return self._parsed_groups[group]\n\n    def _resolve(self, group: str, requested_group: str) -> tuple[Requirement, ...]:\n        \"\"\"\n        This is a helper for cached resolution to strings.\n\n        :param group: The name of the group to resolve.\n        :param requested_group: The group which was used in the original, user-facing\n            request.\n        \"\"\"\n        if group in self._resolve_cache:\n            return self._resolve_cache[group]\n\n        parsed = self._parse_group(group)\n\n        resolved_group = []\n        for item in parsed:\n            if isinstance(item, Requirement):\n                resolved_group.append(item)\n            elif isinstance(item, DependencyGroupInclude):\n                include_group = _normalize_name(item.include_group)\n                if include_group in self._include_graph_ancestors.get(group, ()):\n                    raise CyclicDependencyError(\n                        requested_group, group, item.include_group\n                    )\n                self._include_graph_ancestors[include_group] = (\n                    *self._include_graph_ancestors.get(group, ()),\n                    group,\n                )\n                resolved_group.extend(self._resolve(include_group, requested_group))\n            else:  # unreachable\n                raise NotImplementedError(\n                    f\"Invalid dependency group item after parse: {item}\"\n                )\n\n        self._resolve_cache[group] = tuple(resolved_group)\n        return self._resolve_cache[group]\n\n\ndef resolve(\n    dependency_groups: Mapping[str, str | Mapping[str, str]], /, *groups: str\n) -> tuple[str, ...]:\n    \"\"\"\n    Resolve a dependency group to a tuple of requirements, as strings.\n\n    :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table\n        from ``pyproject.toml``\n    :param groups: the name of the group(s) to resolve\n\n    :raises TypeError: if the inputs appear to be the wrong types\n    :raises ValueError: if the data does not appear to be valid dependency group data\n    :raises LookupError: if group name is absent\n    :raises packaging.requirements.InvalidRequirement: if a specifier is not valid\n    \"\"\"\n    resolver = DependencyGroupResolver(dependency_groups)\n    return tuple(str(r) for group in groups for r in resolver.resolve(group))\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/_lint_dependency_groups.py",
    "content": "from __future__ import annotations\n\nimport argparse\nimport sys\n\nfrom ._implementation import DependencyGroupResolver\nfrom ._toml_compat import tomllib\n\n\ndef main(*, argv: list[str] | None = None) -> None:\n    if tomllib is None:\n        print(\n            \"Usage error: dependency-groups CLI requires tomli or Python 3.11+\",\n            file=sys.stderr,\n        )\n        raise SystemExit(2)\n\n    parser = argparse.ArgumentParser(\n        description=(\n            \"Lint Dependency Groups for validity. \"\n            \"This will eagerly load and check all of your Dependency Groups.\"\n        )\n    )\n    parser.add_argument(\n        \"-f\",\n        \"--pyproject-file\",\n        default=\"pyproject.toml\",\n        help=\"The pyproject.toml file. Defaults to trying in the current directory.\",\n    )\n    args = parser.parse_args(argv if argv is not None else sys.argv[1:])\n\n    with open(args.pyproject_file, \"rb\") as fp:\n        pyproject = tomllib.load(fp)\n    dependency_groups_raw = pyproject.get(\"dependency-groups\", {})\n\n    errors: list[str] = []\n    try:\n        resolver = DependencyGroupResolver(dependency_groups_raw)\n    except (ValueError, TypeError) as e:\n        errors.append(f\"{type(e).__name__}: {e}\")\n    else:\n        for groupname in resolver.dependency_groups:\n            try:\n                resolver.resolve(groupname)\n            except (LookupError, ValueError, TypeError) as e:\n                errors.append(f\"{type(e).__name__}: {e}\")\n\n    if errors:\n        print(\"errors encountered while examining dependency groups:\")\n        for msg in errors:\n            print(f\"  {msg}\")\n        sys.exit(1)\n    else:\n        print(\"ok\")\n        sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/_pip_wrapper.py",
    "content": "from __future__ import annotations\n\nimport argparse\nimport subprocess\nimport sys\n\nfrom ._implementation import DependencyGroupResolver\nfrom ._toml_compat import tomllib\n\n\ndef _invoke_pip(deps: list[str]) -> None:\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *deps])\n\n\ndef main(*, argv: list[str] | None = None) -> None:\n    if tomllib is None:\n        print(\n            \"Usage error: dependency-groups CLI requires tomli or Python 3.11+\",\n            file=sys.stderr,\n        )\n        raise SystemExit(2)\n\n    parser = argparse.ArgumentParser(description=\"Install Dependency Groups.\")\n    parser.add_argument(\n        \"DEPENDENCY_GROUP\", nargs=\"+\", help=\"The dependency groups to install.\"\n    )\n    parser.add_argument(\n        \"-f\",\n        \"--pyproject-file\",\n        default=\"pyproject.toml\",\n        help=\"The pyproject.toml file. Defaults to trying in the current directory.\",\n    )\n    args = parser.parse_args(argv if argv is not None else sys.argv[1:])\n\n    with open(args.pyproject_file, \"rb\") as fp:\n        pyproject = tomllib.load(fp)\n    dependency_groups_raw = pyproject.get(\"dependency-groups\", {})\n\n    errors: list[str] = []\n    resolved: list[str] = []\n    try:\n        resolver = DependencyGroupResolver(dependency_groups_raw)\n    except (ValueError, TypeError) as e:\n        errors.append(f\"{type(e).__name__}: {e}\")\n    else:\n        for groupname in args.DEPENDENCY_GROUP:\n            try:\n                resolved.extend(str(r) for r in resolver.resolve(groupname))\n            except (LookupError, ValueError, TypeError) as e:\n                errors.append(f\"{type(e).__name__}: {e}\")\n\n    if errors:\n        print(\"errors encountered while examining dependency groups:\")\n        for msg in errors:\n            print(f\"  {msg}\")\n        sys.exit(1)\n\n    _invoke_pip(resolved)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/_toml_compat.py",
    "content": "try:\n    import tomllib\nexcept ImportError:\n    try:\n        from pip._vendor import tomli as tomllib  # type: ignore[no-redef, unused-ignore]\n    except ModuleNotFoundError:  # pragma: no cover\n        tomllib = None  # type: ignore[assignment, unused-ignore]\n\n__all__ = (\"tomllib\",)\n"
  },
  {
    "path": "src/pip/_vendor/dependency_groups/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/distlib/LICENSE.txt",
    "content": "A. HISTORY OF THE SOFTWARE\n==========================\n\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands\nas a successor of a language called ABC.  Guido remains Python's\nprincipal author, although it includes many contributions from others.\n\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us)\nin Reston, Virginia where he released several versions of the\nsoftware.\n\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team.  In October of the same\nyear, the PythonLabs team moved to Digital Creations (now Zope\nCorporation, see http://www.zope.com).  In 2001, the Python Software\nFoundation (PSF, see http://www.python.org/psf/) was formed, a\nnon-profit organization created specifically to own Python-related\nIntellectual Property.  Zope Corporation is a sponsoring member of\nthe PSF.\n\nAll Python releases are Open Source (see http://www.opensource.org for\nthe Open Source Definition).  Historically, most, but not all, Python\nreleases have also been GPL-compatible; the table below summarizes\nthe various releases.\n\n    Release         Derived     Year        Owner       GPL-\n                    from                                compatible? (1)\n\n    0.9.0 thru 1.2              1991-1995   CWI         yes\n    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes\n    1.6             1.5.2       2000        CNRI        no\n    2.0             1.6         2000        BeOpen.com  no\n    1.6.1           1.6         2001        CNRI        yes (2)\n    2.1             2.0+1.6.1   2001        PSF         no\n    2.0.1           2.0+1.6.1   2001        PSF         yes\n    2.1.1           2.1+2.0.1   2001        PSF         yes\n    2.2             2.1.1       2001        PSF         yes\n    2.1.2           2.1.1       2002        PSF         yes\n    2.1.3           2.1.2       2002        PSF         yes\n    2.2.1           2.2         2002        PSF         yes\n    2.2.2           2.2.1       2002        PSF         yes\n    2.2.3           2.2.2       2003        PSF         yes\n    2.3             2.2.2       2002-2003   PSF         yes\n    2.3.1           2.3         2002-2003   PSF         yes\n    2.3.2           2.3.1       2002-2003   PSF         yes\n    2.3.3           2.3.2       2002-2003   PSF         yes\n    2.3.4           2.3.3       2004        PSF         yes\n    2.3.5           2.3.4       2005        PSF         yes\n    2.4             2.3         2004        PSF         yes\n    2.4.1           2.4         2005        PSF         yes\n    2.4.2           2.4.1       2005        PSF         yes\n    2.4.3           2.4.2       2006        PSF         yes\n    2.4.4           2.4.3       2006        PSF         yes\n    2.5             2.4         2006        PSF         yes\n    2.5.1           2.5         2007        PSF         yes\n    2.5.2           2.5.1       2008        PSF         yes\n    2.5.3           2.5.2       2008        PSF         yes\n    2.6             2.5         2008        PSF         yes\n    2.6.1           2.6         2008        PSF         yes\n    2.6.2           2.6.1       2009        PSF         yes\n    2.6.3           2.6.2       2009        PSF         yes\n    2.6.4           2.6.3       2009        PSF         yes\n    2.6.5           2.6.4       2010        PSF         yes\n    3.0             2.6         2008        PSF         yes\n    3.0.1           3.0         2009        PSF         yes\n    3.1             3.0.1       2009        PSF         yes\n    3.1.1           3.1         2009        PSF         yes\n    3.1.2           3.1         2010        PSF         yes\n    3.2             3.1         2010        PSF         yes\n\nFootnotes:\n\n(1) GPL-compatible doesn't mean that we're distributing Python under\n    the GPL.  All Python licenses, unlike the GPL, let you distribute\n    a modified version without making your changes open source.  The\n    GPL-compatible licenses make it possible to combine Python with\n    other software that is released under the GPL; the others don't.\n\n(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,\n    because its license has a choice of law clause.  According to\n    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1\n    is \"not incompatible\" with the GPL.\n\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.\n\n\nB. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON\n===============================================================\n\nPYTHON SOFTWARE FOUNDATION LICENSE VERSION 2\n--------------------------------------------\n\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(\"PSF\"), and the Individual or Organization (\"Licensee\") accessing and\notherwise using this software (\"Python\") in source or binary form and\nits associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, PSF hereby\ngrants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,\nanalyze, test, perform and/or display publicly, prepare derivative works,\ndistribute, and otherwise use Python alone or in any derivative version,\nprovided, however, that PSF's License Agreement and PSF's notice of copyright,\ni.e., \"Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010\nPython Software Foundation; All Rights Reserved\" are retained in Python alone or\nin any derivative version prepared by Licensee.\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python.\n\n4. PSF is making Python available to Licensee on an \"AS IS\"\nbasis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\nFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee.  This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n\n8. By copying, installing or otherwise using Python, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\n-------------------------------------------\n\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n\n1. This LICENSE AGREEMENT is between BeOpen.com (\"BeOpen\"), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (\"Licensee\") accessing and otherwise using\nthis software in source or binary form and its associated\ndocumentation (\"the Software\").\n\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n\n3. BeOpen is making the Software available to Licensee on an \"AS IS\"\nbasis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions.  Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee.  This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party.  As an exception, the \"BeOpen Python\" logos available at\nhttp://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n---------------------------------------\n\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (\"CNRI\"), and the Individual or Organization\n(\"Licensee\") accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., \"Copyright (c)\n1995-2001 Corporation for National Research Initiatives; All Rights\nReserved\" are retained in Python 1.6.1 alone or in any derivative\nversion prepared by Licensee.  Alternately, in lieu of CNRI's License\nAgreement, Licensee may substitute the following text (omitting the\nquotes): \"Python 1.6.1 is made available subject to the terms and\nconditions in CNRI's License Agreement.  This Agreement together with\nPython 1.6.1 may be located on the Internet using the following\nunique, persistent identifier (known as a handle): 1895.22/1013.  This\nAgreement may also be obtained from a proxy server on the Internet\nusing the following URL: http://hdl.handle.net/1895.22/1013\".\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n\n4. CNRI is making Python 1.6.1 available to Licensee on an \"AS IS\"\nbasis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement.  Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee.  This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n\n8. By clicking on the \"ACCEPT\" button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\n\n        ACCEPT\n\n\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\n--------------------------------------------------\n\nCopyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,\nThe Netherlands.  All rights reserved.\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\n\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/distlib/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2024 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nimport logging\n\n__version__ = '0.4.0'\n\n\nclass DistlibException(Exception):\n    pass\n\n\ntry:\n    from logging import NullHandler\nexcept ImportError:  # pragma: no cover\n\n    class NullHandler(logging.Handler):\n\n        def handle(self, record):\n            pass\n\n        def emit(self, record):\n            pass\n\n        def createLock(self):\n            self.lock = None\n\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(NullHandler())\n"
  },
  {
    "path": "src/pip/_vendor/distlib/compat.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2017 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom __future__ import absolute_import\n\nimport os\nimport re\nimport shutil\nimport sys\n\ntry:\n    import ssl\nexcept ImportError:  # pragma: no cover\n    ssl = None\n\nif sys.version_info[0] < 3:  # pragma: no cover\n    from StringIO import StringIO\n    string_types = basestring,\n    text_type = unicode\n    from types import FileType as file_type\n    import __builtin__ as builtins\n    import ConfigParser as configparser\n    from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit\n    from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,\n                        pathname2url, ContentTooShortError, splittype)\n\n    def quote(s):\n        if isinstance(s, unicode):\n            s = s.encode('utf-8')\n        return _quote(s)\n\n    import urllib2\n    from urllib2 import (Request, urlopen, URLError, HTTPError,\n                         HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler,\n                         HTTPRedirectHandler, build_opener)\n    if ssl:\n        from urllib2 import HTTPSHandler\n    import httplib\n    import xmlrpclib\n    import Queue as queue\n    from HTMLParser import HTMLParser\n    import htmlentitydefs\n    raw_input = raw_input\n    from itertools import ifilter as filter\n    from itertools import ifilterfalse as filterfalse\n\n    # Leaving this around for now, in case it needs resurrecting in some way\n    # _userprog = None\n    # def splituser(host):\n    # \"\"\"splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.\"\"\"\n    # global _userprog\n    # if _userprog is None:\n    # import re\n    # _userprog = re.compile('^(.*)@(.*)$')\n\n    # match = _userprog.match(host)\n    # if match: return match.group(1, 2)\n    # return None, host\n\nelse:  # pragma: no cover\n    from io import StringIO\n    string_types = str,\n    text_type = str\n    from io import TextIOWrapper as file_type\n    import builtins\n    import configparser\n    from urllib.parse import (urlparse, urlunparse, urljoin, quote, unquote,\n                              urlsplit, urlunsplit, splittype)\n    from urllib.request import (urlopen, urlretrieve, Request, url2pathname,\n                                pathname2url, HTTPBasicAuthHandler,\n                                HTTPPasswordMgr, HTTPHandler,\n                                HTTPRedirectHandler, build_opener)\n    if ssl:\n        from urllib.request import HTTPSHandler\n    from urllib.error import HTTPError, URLError, ContentTooShortError\n    import http.client as httplib\n    import urllib.request as urllib2\n    import xmlrpc.client as xmlrpclib\n    import queue\n    from html.parser import HTMLParser\n    import html.entities as htmlentitydefs\n    raw_input = input\n    from itertools import filterfalse\n    filter = filter\n\ntry:\n    from ssl import match_hostname, CertificateError\nexcept ImportError:  # pragma: no cover\n\n    class CertificateError(ValueError):\n        pass\n\n    def _dnsname_match(dn, hostname, max_wildcards=1):\n        \"\"\"Matching according to RFC 6125, section 6.4.3\n\n        http://tools.ietf.org/html/rfc6125#section-6.4.3\n        \"\"\"\n        pats = []\n        if not dn:\n            return False\n\n        parts = dn.split('.')\n        leftmost, remainder = parts[0], parts[1:]\n\n        wildcards = leftmost.count('*')\n        if wildcards > max_wildcards:\n            # Issue #17980: avoid denials of service by refusing more\n            # than one wildcard per fragment.  A survey of established\n            # policy among SSL implementations showed it to be a\n            # reasonable choice.\n            raise CertificateError(\n                \"too many wildcards in certificate DNS name: \" + repr(dn))\n\n        # speed up common case w/o wildcards\n        if not wildcards:\n            return dn.lower() == hostname.lower()\n\n        # RFC 6125, section 6.4.3, subitem 1.\n        # The client SHOULD NOT attempt to match a presented identifier in which\n        # the wildcard character comprises a label other than the left-most label.\n        if leftmost == '*':\n            # When '*' is a fragment by itself, it matches a non-empty dotless\n            # fragment.\n            pats.append('[^.]+')\n        elif leftmost.startswith('xn--') or hostname.startswith('xn--'):\n            # RFC 6125, section 6.4.3, subitem 3.\n            # The client SHOULD NOT attempt to match a presented identifier\n            # where the wildcard character is embedded within an A-label or\n            # U-label of an internationalized domain name.\n            pats.append(re.escape(leftmost))\n        else:\n            # Otherwise, '*' matches any dotless string, e.g. www*\n            pats.append(re.escape(leftmost).replace(r'\\*', '[^.]*'))\n\n        # add the remaining fragments, ignore any wildcards\n        for frag in remainder:\n            pats.append(re.escape(frag))\n\n        pat = re.compile(r'\\A' + r'\\.'.join(pats) + r'\\Z', re.IGNORECASE)\n        return pat.match(hostname)\n\n    def match_hostname(cert, hostname):\n        \"\"\"Verify that *cert* (in decoded format as returned by\n        SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125\n        rules are followed, but IP addresses are not accepted for *hostname*.\n\n        CertificateError is raised on failure. On success, the function\n        returns nothing.\n        \"\"\"\n        if not cert:\n            raise ValueError(\"empty or no certificate, match_hostname needs a \"\n                             \"SSL socket or SSL context with either \"\n                             \"CERT_OPTIONAL or CERT_REQUIRED\")\n        dnsnames = []\n        san = cert.get('subjectAltName', ())\n        for key, value in san:\n            if key == 'DNS':\n                if _dnsname_match(value, hostname):\n                    return\n                dnsnames.append(value)\n        if not dnsnames:\n            # The subject is only checked when there is no dNSName entry\n            # in subjectAltName\n            for sub in cert.get('subject', ()):\n                for key, value in sub:\n                    # XXX according to RFC 2818, the most specific Common Name\n                    # must be used.\n                    if key == 'commonName':\n                        if _dnsname_match(value, hostname):\n                            return\n                        dnsnames.append(value)\n        if len(dnsnames) > 1:\n            raise CertificateError(\"hostname %r \"\n                                   \"doesn't match either of %s\" %\n                                   (hostname, ', '.join(map(repr, dnsnames))))\n        elif len(dnsnames) == 1:\n            raise CertificateError(\"hostname %r \"\n                                   \"doesn't match %r\" %\n                                   (hostname, dnsnames[0]))\n        else:\n            raise CertificateError(\"no appropriate commonName or \"\n                                   \"subjectAltName fields were found\")\n\n\ntry:\n    from types import SimpleNamespace as Container\nexcept ImportError:  # pragma: no cover\n\n    class Container(object):\n        \"\"\"\n        A generic container for when multiple values need to be returned\n        \"\"\"\n\n        def __init__(self, **kwargs):\n            self.__dict__.update(kwargs)\n\n\ntry:\n    from shutil import which\nexcept ImportError:  # pragma: no cover\n    # Implementation from Python 3.3\n    def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n        \"\"\"Given a command, mode, and a PATH string, return the path which\n        conforms to the given mode on the PATH, or None if there is no such\n        file.\n\n        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result\n        of os.environ.get(\"PATH\"), or can be overridden with a custom search\n        path.\n\n        \"\"\"\n\n        # Check that a given file can be accessed with the correct mode.\n        # Additionally check that `file` is not a directory, as on Windows\n        # directories pass the os.access check.\n        def _access_check(fn, mode):\n            return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn))\n\n        # If we're given a path with a directory part, look it up directly rather\n        # than referring to PATH directories. This includes checking relative to the\n        # current directory, e.g. ./script\n        if os.path.dirname(cmd):\n            if _access_check(cmd, mode):\n                return cmd\n            return None\n\n        if path is None:\n            path = os.environ.get(\"PATH\", os.defpath)\n        if not path:\n            return None\n        path = path.split(os.pathsep)\n\n        if sys.platform == \"win32\":\n            # The current directory takes precedence on Windows.\n            if os.curdir not in path:\n                path.insert(0, os.curdir)\n\n            # PATHEXT is necessary to check on Windows.\n            pathext = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n            # See if the given file matches any of the expected path extensions.\n            # This will allow us to short circuit when given \"python.exe\".\n            # If it does match, only test that one, otherwise we have to try\n            # others.\n            if any(cmd.lower().endswith(ext.lower()) for ext in pathext):\n                files = [cmd]\n            else:\n                files = [cmd + ext for ext in pathext]\n        else:\n            # On other platforms you don't have things like PATHEXT to tell you\n            # what file suffixes are executable, so just pass on cmd as-is.\n            files = [cmd]\n\n        seen = set()\n        for dir in path:\n            normdir = os.path.normcase(dir)\n            if normdir not in seen:\n                seen.add(normdir)\n                for thefile in files:\n                    name = os.path.join(dir, thefile)\n                    if _access_check(name, mode):\n                        return name\n        return None\n\n\n# ZipFile is a context manager in 2.7, but not in 2.6\n\nfrom zipfile import ZipFile as BaseZipFile\n\nif hasattr(BaseZipFile, '__enter__'):  # pragma: no cover\n    ZipFile = BaseZipFile\nelse:  # pragma: no cover\n    from zipfile import ZipExtFile as BaseZipExtFile\n\n    class ZipExtFile(BaseZipExtFile):\n\n        def __init__(self, base):\n            self.__dict__.update(base.__dict__)\n\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *exc_info):\n            self.close()\n            # return None, so if an exception occurred, it will propagate\n\n    class ZipFile(BaseZipFile):\n\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *exc_info):\n            self.close()\n            # return None, so if an exception occurred, it will propagate\n\n        def open(self, *args, **kwargs):\n            base = BaseZipFile.open(self, *args, **kwargs)\n            return ZipExtFile(base)\n\n\ntry:\n    from platform import python_implementation\nexcept ImportError:  # pragma: no cover\n\n    def python_implementation():\n        \"\"\"Return a string identifying the Python implementation.\"\"\"\n        if 'PyPy' in sys.version:\n            return 'PyPy'\n        if os.name == 'java':\n            return 'Jython'\n        if sys.version.startswith('IronPython'):\n            return 'IronPython'\n        return 'CPython'\n\n\nimport sysconfig\n\ntry:\n    callable = callable\nexcept NameError:  # pragma: no cover\n    from collections.abc import Callable\n\n    def callable(obj):\n        return isinstance(obj, Callable)\n\n\ntry:\n    fsencode = os.fsencode\n    fsdecode = os.fsdecode\nexcept AttributeError:  # pragma: no cover\n    # Issue #99: on some systems (e.g. containerised),\n    # sys.getfilesystemencoding() returns None, and we need a real value,\n    # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and\n    # sys.getfilesystemencoding(): the return value is \"the user’s preference\n    # according to the result of nl_langinfo(CODESET), or None if the\n    # nl_langinfo(CODESET) failed.\"\n    _fsencoding = sys.getfilesystemencoding() or 'utf-8'\n    if _fsencoding == 'mbcs':\n        _fserrors = 'strict'\n    else:\n        _fserrors = 'surrogateescape'\n\n    def fsencode(filename):\n        if isinstance(filename, bytes):\n            return filename\n        elif isinstance(filename, text_type):\n            return filename.encode(_fsencoding, _fserrors)\n        else:\n            raise TypeError(\"expect bytes or str, not %s\" %\n                            type(filename).__name__)\n\n    def fsdecode(filename):\n        if isinstance(filename, text_type):\n            return filename\n        elif isinstance(filename, bytes):\n            return filename.decode(_fsencoding, _fserrors)\n        else:\n            raise TypeError(\"expect bytes or str, not %s\" %\n                            type(filename).__name__)\n\n\ntry:\n    from tokenize import detect_encoding\nexcept ImportError:  # pragma: no cover\n    from codecs import BOM_UTF8, lookup\n\n    cookie_re = re.compile(r\"coding[:=]\\s*([-\\w.]+)\")\n\n    def _get_normal_name(orig_enc):\n        \"\"\"Imitates get_normal_name in tokenizer.c.\"\"\"\n        # Only care about the first 12 characters.\n        enc = orig_enc[:12].lower().replace(\"_\", \"-\")\n        if enc == \"utf-8\" or enc.startswith(\"utf-8-\"):\n            return \"utf-8\"\n        if enc in (\"latin-1\", \"iso-8859-1\", \"iso-latin-1\") or \\\n           enc.startswith((\"latin-1-\", \"iso-8859-1-\", \"iso-latin-1-\")):\n            return \"iso-8859-1\"\n        return orig_enc\n\n    def detect_encoding(readline):\n        \"\"\"\n        The detect_encoding() function is used to detect the encoding that should\n        be used to decode a Python source file.  It requires one argument, readline,\n        in the same way as the tokenize() generator.\n\n        It will call readline a maximum of twice, and return the encoding used\n        (as a string) and a list of any lines (left as bytes) it has read in.\n\n        It detects the encoding from the presence of a utf-8 bom or an encoding\n        cookie as specified in pep-0263.  If both a bom and a cookie are present,\n        but disagree, a SyntaxError will be raised.  If the encoding cookie is an\n        invalid charset, raise a SyntaxError.  Note that if a utf-8 bom is found,\n        'utf-8-sig' is returned.\n\n        If no encoding is specified, then the default of 'utf-8' will be returned.\n        \"\"\"\n        try:\n            filename = readline.__self__.name\n        except AttributeError:\n            filename = None\n        bom_found = False\n        encoding = None\n        default = 'utf-8'\n\n        def read_or_stop():\n            try:\n                return readline()\n            except StopIteration:\n                return b''\n\n        def find_cookie(line):\n            try:\n                # Decode as UTF-8. Either the line is an encoding declaration,\n                # in which case it should be pure ASCII, or it must be UTF-8\n                # per default encoding.\n                line_string = line.decode('utf-8')\n            except UnicodeDecodeError:\n                msg = \"invalid or missing encoding declaration\"\n                if filename is not None:\n                    msg = '{} for {!r}'.format(msg, filename)\n                raise SyntaxError(msg)\n\n            matches = cookie_re.findall(line_string)\n            if not matches:\n                return None\n            encoding = _get_normal_name(matches[0])\n            try:\n                codec = lookup(encoding)\n            except LookupError:\n                # This behaviour mimics the Python interpreter\n                if filename is None:\n                    msg = \"unknown encoding: \" + encoding\n                else:\n                    msg = \"unknown encoding for {!r}: {}\".format(\n                        filename, encoding)\n                raise SyntaxError(msg)\n\n            if bom_found:\n                if codec.name != 'utf-8':\n                    # This behaviour mimics the Python interpreter\n                    if filename is None:\n                        msg = 'encoding problem: utf-8'\n                    else:\n                        msg = 'encoding problem for {!r}: utf-8'.format(\n                            filename)\n                    raise SyntaxError(msg)\n                encoding += '-sig'\n            return encoding\n\n        first = read_or_stop()\n        if first.startswith(BOM_UTF8):\n            bom_found = True\n            first = first[3:]\n            default = 'utf-8-sig'\n        if not first:\n            return default, []\n\n        encoding = find_cookie(first)\n        if encoding:\n            return encoding, [first]\n\n        second = read_or_stop()\n        if not second:\n            return default, [first]\n\n        encoding = find_cookie(second)\n        if encoding:\n            return encoding, [first, second]\n\n        return default, [first, second]\n\n\n# For converting & <-> &amp; etc.\ntry:\n    from html import escape\nexcept ImportError:\n    from cgi import escape\nif sys.version_info[:2] < (3, 4):\n    unescape = HTMLParser().unescape\nelse:\n    from html import unescape\n\ntry:\n    from collections import ChainMap\nexcept ImportError:  # pragma: no cover\n    from collections import MutableMapping\n\n    try:\n        from reprlib import recursive_repr as _recursive_repr\n    except ImportError:\n\n        def _recursive_repr(fillvalue='...'):\n            '''\n            Decorator to make a repr function return fillvalue for a recursive\n            call\n            '''\n\n            def decorating_function(user_function):\n                repr_running = set()\n\n                def wrapper(self):\n                    key = id(self), get_ident()\n                    if key in repr_running:\n                        return fillvalue\n                    repr_running.add(key)\n                    try:\n                        result = user_function(self)\n                    finally:\n                        repr_running.discard(key)\n                    return result\n\n                # Can't use functools.wraps() here because of bootstrap issues\n                wrapper.__module__ = getattr(user_function, '__module__')\n                wrapper.__doc__ = getattr(user_function, '__doc__')\n                wrapper.__name__ = getattr(user_function, '__name__')\n                wrapper.__annotations__ = getattr(user_function,\n                                                  '__annotations__', {})\n                return wrapper\n\n            return decorating_function\n\n    class ChainMap(MutableMapping):\n        '''\n        A ChainMap groups multiple dicts (or other mappings) together\n        to create a single, updateable view.\n\n        The underlying mappings are stored in a list.  That list is public and can\n        accessed or updated using the *maps* attribute.  There is no other state.\n\n        Lookups search the underlying mappings successively until a key is found.\n        In contrast, writes, updates, and deletions only operate on the first\n        mapping.\n        '''\n\n        def __init__(self, *maps):\n            '''Initialize a ChainMap by setting *maps* to the given mappings.\n            If no mappings are provided, a single empty dictionary is used.\n\n            '''\n            self.maps = list(maps) or [{}]  # always at least one map\n\n        def __missing__(self, key):\n            raise KeyError(key)\n\n        def __getitem__(self, key):\n            for mapping in self.maps:\n                try:\n                    return mapping[\n                        key]  # can't use 'key in mapping' with defaultdict\n                except KeyError:\n                    pass\n            return self.__missing__(\n                key)  # support subclasses that define __missing__\n\n        def get(self, key, default=None):\n            return self[key] if key in self else default\n\n        def __len__(self):\n            return len(set().union(\n                *self.maps))  # reuses stored hash values if possible\n\n        def __iter__(self):\n            return iter(set().union(*self.maps))\n\n        def __contains__(self, key):\n            return any(key in m for m in self.maps)\n\n        def __bool__(self):\n            return any(self.maps)\n\n        @_recursive_repr()\n        def __repr__(self):\n            return '{0.__class__.__name__}({1})'.format(\n                self, ', '.join(map(repr, self.maps)))\n\n        @classmethod\n        def fromkeys(cls, iterable, *args):\n            'Create a ChainMap with a single dict created from the iterable.'\n            return cls(dict.fromkeys(iterable, *args))\n\n        def copy(self):\n            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'\n            return self.__class__(self.maps[0].copy(), *self.maps[1:])\n\n        __copy__ = copy\n\n        def new_child(self):  # like Django's Context.push()\n            'New ChainMap with a new dict followed by all previous maps.'\n            return self.__class__({}, *self.maps)\n\n        @property\n        def parents(self):  # like Django's Context.pop()\n            'New ChainMap from maps[1:].'\n            return self.__class__(*self.maps[1:])\n\n        def __setitem__(self, key, value):\n            self.maps[0][key] = value\n\n        def __delitem__(self, key):\n            try:\n                del self.maps[0][key]\n            except KeyError:\n                raise KeyError(\n                    'Key not found in the first mapping: {!r}'.format(key))\n\n        def popitem(self):\n            'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'\n            try:\n                return self.maps[0].popitem()\n            except KeyError:\n                raise KeyError('No keys found in the first mapping.')\n\n        def pop(self, key, *args):\n            'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'\n            try:\n                return self.maps[0].pop(key, *args)\n            except KeyError:\n                raise KeyError(\n                    'Key not found in the first mapping: {!r}'.format(key))\n\n        def clear(self):\n            'Clear maps[0], leaving maps[1:] intact.'\n            self.maps[0].clear()\n\n\ntry:\n    from importlib.util import cache_from_source  # Python >= 3.4\nexcept ImportError:  # pragma: no cover\n\n    def cache_from_source(path, debug_override=None):\n        assert path.endswith('.py')\n        if debug_override is None:\n            debug_override = __debug__\n        if debug_override:\n            suffix = 'c'\n        else:\n            suffix = 'o'\n        return path + suffix\n\n\ntry:\n    from collections import OrderedDict\nexcept ImportError:  # pragma: no cover\n    # {{{ http://code.activestate.com/recipes/576693/ (r9)\n    # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.\n    # Passes Python2.7's test suite and incorporates all the latest updates.\n    try:\n        from thread import get_ident as _get_ident\n    except ImportError:\n        from dummy_thread import get_ident as _get_ident\n\n    try:\n        from _abcoll import KeysView, ValuesView, ItemsView\n    except ImportError:\n        pass\n\n    class OrderedDict(dict):\n        'Dictionary that remembers insertion order'\n\n        # An inherited dict maps keys to values.\n        # The inherited dict provides __getitem__, __len__, __contains__, and get.\n        # The remaining methods are order-aware.\n        # Big-O running times for all methods are the same as for regular dictionaries.\n\n        # The internal self.__map dictionary maps keys to links in a doubly linked list.\n        # The circular doubly linked list starts and ends with a sentinel element.\n        # The sentinel element never gets deleted (this simplifies the algorithm).\n        # Each link is stored as a list of length three:  [PREV, NEXT, KEY].\n\n        def __init__(self, *args, **kwds):\n            '''Initialize an ordered dictionary.  Signature is the same as for\n            regular dictionaries, but keyword arguments are not recommended\n            because their insertion order is arbitrary.\n\n            '''\n            if len(args) > 1:\n                raise TypeError('expected at most 1 arguments, got %d' %\n                                len(args))\n            try:\n                self.__root\n            except AttributeError:\n                self.__root = root = []  # sentinel node\n                root[:] = [root, root, None]\n                self.__map = {}\n            self.__update(*args, **kwds)\n\n        def __setitem__(self, key, value, dict_setitem=dict.__setitem__):\n            'od.__setitem__(i, y) <==> od[i]=y'\n            # Setting a new item creates a new link which goes at the end of the linked\n            # list, and the inherited dictionary is updated with the new key/value pair.\n            if key not in self:\n                root = self.__root\n                last = root[0]\n                last[1] = root[0] = self.__map[key] = [last, root, key]\n            dict_setitem(self, key, value)\n\n        def __delitem__(self, key, dict_delitem=dict.__delitem__):\n            'od.__delitem__(y) <==> del od[y]'\n            # Deleting an existing item uses self.__map to find the link which is\n            # then removed by updating the links in the predecessor and successor nodes.\n            dict_delitem(self, key)\n            link_prev, link_next, key = self.__map.pop(key)\n            link_prev[1] = link_next\n            link_next[0] = link_prev\n\n        def __iter__(self):\n            'od.__iter__() <==> iter(od)'\n            root = self.__root\n            curr = root[1]\n            while curr is not root:\n                yield curr[2]\n                curr = curr[1]\n\n        def __reversed__(self):\n            'od.__reversed__() <==> reversed(od)'\n            root = self.__root\n            curr = root[0]\n            while curr is not root:\n                yield curr[2]\n                curr = curr[0]\n\n        def clear(self):\n            'od.clear() -> None.  Remove all items from od.'\n            try:\n                for node in self.__map.itervalues():\n                    del node[:]\n                root = self.__root\n                root[:] = [root, root, None]\n                self.__map.clear()\n            except AttributeError:\n                pass\n            dict.clear(self)\n\n        def popitem(self, last=True):\n            '''od.popitem() -> (k, v), return and remove a (key, value) pair.\n            Pairs are returned in LIFO order if last is true or FIFO order if false.\n\n            '''\n            if not self:\n                raise KeyError('dictionary is empty')\n            root = self.__root\n            if last:\n                link = root[0]\n                link_prev = link[0]\n                link_prev[1] = root\n                root[0] = link_prev\n            else:\n                link = root[1]\n                link_next = link[1]\n                root[1] = link_next\n                link_next[0] = root\n            key = link[2]\n            del self.__map[key]\n            value = dict.pop(self, key)\n            return key, value\n\n        # -- the following methods do not depend on the internal structure --\n\n        def keys(self):\n            'od.keys() -> list of keys in od'\n            return list(self)\n\n        def values(self):\n            'od.values() -> list of values in od'\n            return [self[key] for key in self]\n\n        def items(self):\n            'od.items() -> list of (key, value) pairs in od'\n            return [(key, self[key]) for key in self]\n\n        def iterkeys(self):\n            'od.iterkeys() -> an iterator over the keys in od'\n            return iter(self)\n\n        def itervalues(self):\n            'od.itervalues -> an iterator over the values in od'\n            for k in self:\n                yield self[k]\n\n        def iteritems(self):\n            'od.iteritems -> an iterator over the (key, value) items in od'\n            for k in self:\n                yield (k, self[k])\n\n        def update(*args, **kwds):\n            '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.\n\n            If E is a dict instance, does:           for k in E: od[k] = E[k]\n            If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]\n            Or if E is an iterable of items, does:   for k, v in E: od[k] = v\n            In either case, this is followed by:     for k, v in F.items(): od[k] = v\n\n            '''\n            if len(args) > 2:\n                raise TypeError('update() takes at most 2 positional '\n                                'arguments (%d given)' % (len(args), ))\n            elif not args:\n                raise TypeError('update() takes at least 1 argument (0 given)')\n            self = args[0]\n            # Make progressively weaker assumptions about \"other\"\n            other = ()\n            if len(args) == 2:\n                other = args[1]\n            if isinstance(other, dict):\n                for key in other:\n                    self[key] = other[key]\n            elif hasattr(other, 'keys'):\n                for key in other.keys():\n                    self[key] = other[key]\n            else:\n                for key, value in other:\n                    self[key] = value\n            for key, value in kwds.items():\n                self[key] = value\n\n        __update = update  # let subclasses override update without breaking __init__\n\n        __marker = object()\n\n        def pop(self, key, default=__marker):\n            '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n            If key is not found, d is returned if given, otherwise KeyError is raised.\n\n            '''\n            if key in self:\n                result = self[key]\n                del self[key]\n                return result\n            if default is self.__marker:\n                raise KeyError(key)\n            return default\n\n        def setdefault(self, key, default=None):\n            'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'\n            if key in self:\n                return self[key]\n            self[key] = default\n            return default\n\n        def __repr__(self, _repr_running=None):\n            'od.__repr__() <==> repr(od)'\n            if not _repr_running:\n                _repr_running = {}\n            call_key = id(self), _get_ident()\n            if call_key in _repr_running:\n                return '...'\n            _repr_running[call_key] = 1\n            try:\n                if not self:\n                    return '%s()' % (self.__class__.__name__, )\n                return '%s(%r)' % (self.__class__.__name__, self.items())\n            finally:\n                del _repr_running[call_key]\n\n        def __reduce__(self):\n            'Return state information for pickling'\n            items = [[k, self[k]] for k in self]\n            inst_dict = vars(self).copy()\n            for k in vars(OrderedDict()):\n                inst_dict.pop(k, None)\n            if inst_dict:\n                return (self.__class__, (items, ), inst_dict)\n            return self.__class__, (items, )\n\n        def copy(self):\n            'od.copy() -> a shallow copy of od'\n            return self.__class__(self)\n\n        @classmethod\n        def fromkeys(cls, iterable, value=None):\n            '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S\n            and values equal to v (which defaults to None).\n\n            '''\n            d = cls()\n            for key in iterable:\n                d[key] = value\n            return d\n\n        def __eq__(self, other):\n            '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive\n            while comparison to a regular mapping is order-insensitive.\n\n            '''\n            if isinstance(other, OrderedDict):\n                return len(self) == len(\n                    other) and self.items() == other.items()\n            return dict.__eq__(self, other)\n\n        def __ne__(self, other):\n            return not self == other\n\n        # -- the following methods are only used in Python 2.7 --\n\n        def viewkeys(self):\n            \"od.viewkeys() -> a set-like object providing a view on od's keys\"\n            return KeysView(self)\n\n        def viewvalues(self):\n            \"od.viewvalues() -> an object providing a view on od's values\"\n            return ValuesView(self)\n\n        def viewitems(self):\n            \"od.viewitems() -> a set-like object providing a view on od's items\"\n            return ItemsView(self)\n\n\ntry:\n    from logging.config import BaseConfigurator, valid_ident\nexcept ImportError:  # pragma: no cover\n    IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)\n\n    def valid_ident(s):\n        m = IDENTIFIER.match(s)\n        if not m:\n            raise ValueError('Not a valid Python identifier: %r' % s)\n        return True\n\n    # The ConvertingXXX classes are wrappers around standard Python containers,\n    # and they serve to convert any suitable values in the container. The\n    # conversion converts base dicts, lists and tuples to their wrapped\n    # equivalents, whereas strings which match a conversion format are converted\n    # appropriately.\n    #\n    # Each wrapper should have a configurator attribute holding the actual\n    # configurator to use for conversion.\n\n    class ConvertingDict(dict):\n        \"\"\"A converting dictionary wrapper.\"\"\"\n\n        def __getitem__(self, key):\n            value = dict.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            # If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n        def get(self, key, default=None):\n            value = dict.get(self, key, default)\n            result = self.configurator.convert(value)\n            # If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n    def pop(self, key, default=None):\n        value = dict.pop(self, key, default)\n        result = self.configurator.convert(value)\n        if value is not result:\n            if type(result) in (ConvertingDict, ConvertingList,\n                                ConvertingTuple):\n                result.parent = self\n                result.key = key\n        return result\n\n    class ConvertingList(list):\n        \"\"\"A converting list wrapper.\"\"\"\n\n        def __getitem__(self, key):\n            value = list.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            # If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n        def pop(self, idx=-1):\n            value = list.pop(self, idx)\n            result = self.configurator.convert(value)\n            if value is not result:\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n            return result\n\n    class ConvertingTuple(tuple):\n        \"\"\"A converting tuple wrapper.\"\"\"\n\n        def __getitem__(self, key):\n            value = tuple.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            if value is not result:\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n    class BaseConfigurator(object):\n        \"\"\"\n        The configurator base class which defines some useful defaults.\n        \"\"\"\n\n        CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')\n\n        WORD_PATTERN = re.compile(r'^\\s*(\\w+)\\s*')\n        DOT_PATTERN = re.compile(r'^\\.\\s*(\\w+)\\s*')\n        INDEX_PATTERN = re.compile(r'^\\[\\s*(\\w+)\\s*\\]\\s*')\n        DIGIT_PATTERN = re.compile(r'^\\d+$')\n\n        value_converters = {\n            'ext': 'ext_convert',\n            'cfg': 'cfg_convert',\n        }\n\n        # We might want to use a different one, e.g. importlib\n        importer = staticmethod(__import__)\n\n        def __init__(self, config):\n            self.config = ConvertingDict(config)\n            self.config.configurator = self\n\n        def resolve(self, s):\n            \"\"\"\n            Resolve strings to objects using standard import and attribute\n            syntax.\n            \"\"\"\n            name = s.split('.')\n            used = name.pop(0)\n            try:\n                found = self.importer(used)\n                for frag in name:\n                    used += '.' + frag\n                    try:\n                        found = getattr(found, frag)\n                    except AttributeError:\n                        self.importer(used)\n                        found = getattr(found, frag)\n                return found\n            except ImportError:\n                e, tb = sys.exc_info()[1:]\n                v = ValueError('Cannot resolve %r: %s' % (s, e))\n                v.__cause__, v.__traceback__ = e, tb\n                raise v\n\n        def ext_convert(self, value):\n            \"\"\"Default converter for the ext:// protocol.\"\"\"\n            return self.resolve(value)\n\n        def cfg_convert(self, value):\n            \"\"\"Default converter for the cfg:// protocol.\"\"\"\n            rest = value\n            m = self.WORD_PATTERN.match(rest)\n            if m is None:\n                raise ValueError(\"Unable to convert %r\" % value)\n            else:\n                rest = rest[m.end():]\n                d = self.config[m.groups()[0]]\n                while rest:\n                    m = self.DOT_PATTERN.match(rest)\n                    if m:\n                        d = d[m.groups()[0]]\n                    else:\n                        m = self.INDEX_PATTERN.match(rest)\n                        if m:\n                            idx = m.groups()[0]\n                            if not self.DIGIT_PATTERN.match(idx):\n                                d = d[idx]\n                            else:\n                                try:\n                                    n = int(\n                                        idx\n                                    )  # try as number first (most likely)\n                                    d = d[n]\n                                except TypeError:\n                                    d = d[idx]\n                    if m:\n                        rest = rest[m.end():]\n                    else:\n                        raise ValueError('Unable to convert '\n                                         '%r at %r' % (value, rest))\n            # rest should be empty\n            return d\n\n        def convert(self, value):\n            \"\"\"\n            Convert values to an appropriate type. dicts, lists and tuples are\n            replaced by their converting alternatives. Strings are checked to\n            see if they have a conversion format and are converted if they do.\n            \"\"\"\n            if not isinstance(value, ConvertingDict) and isinstance(\n                    value, dict):\n                value = ConvertingDict(value)\n                value.configurator = self\n            elif not isinstance(value, ConvertingList) and isinstance(\n                    value, list):\n                value = ConvertingList(value)\n                value.configurator = self\n            elif not isinstance(value, ConvertingTuple) and isinstance(value, tuple):\n                value = ConvertingTuple(value)\n                value.configurator = self\n            elif isinstance(value, string_types):\n                m = self.CONVERT_PATTERN.match(value)\n                if m:\n                    d = m.groupdict()\n                    prefix = d['prefix']\n                    converter = self.value_converters.get(prefix, None)\n                    if converter:\n                        suffix = d['suffix']\n                        converter = getattr(self, converter)\n                        value = converter(suffix)\n            return value\n\n        def configure_custom(self, config):\n            \"\"\"Configure an object with a user-supplied factory.\"\"\"\n            c = config.pop('()')\n            if not callable(c):\n                c = self.resolve(c)\n            props = config.pop('.', None)\n            # Check for valid identifiers\n            kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])\n            result = c(**kwargs)\n            if props:\n                for name, value in props.items():\n                    setattr(result, name, value)\n            return result\n\n        def as_tuple(self, value):\n            \"\"\"Utility function which converts lists to tuples.\"\"\"\n            if isinstance(value, list):\n                value = tuple(value)\n            return value\n"
  },
  {
    "path": "src/pip/_vendor/distlib/resources.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2017 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom __future__ import unicode_literals\n\nimport bisect\nimport io\nimport logging\nimport os\nimport pkgutil\nimport sys\nimport types\nimport zipimport\n\nfrom . import DistlibException\nfrom .util import cached_property, get_cache_base, Cache\n\nlogger = logging.getLogger(__name__)\n\n\ncache = None    # created when needed\n\n\nclass ResourceCache(Cache):\n    def __init__(self, base=None):\n        if base is None:\n            # Use native string to avoid issues on 2.x: see Python #20140.\n            base = os.path.join(get_cache_base(), str('resource-cache'))\n        super(ResourceCache, self).__init__(base)\n\n    def is_stale(self, resource, path):\n        \"\"\"\n        Is the cache stale for the given resource?\n\n        :param resource: The :class:`Resource` being cached.\n        :param path: The path of the resource in the cache.\n        :return: True if the cache is stale.\n        \"\"\"\n        # Cache invalidation is a hard problem :-)\n        return True\n\n    def get(self, resource):\n        \"\"\"\n        Get a resource into the cache,\n\n        :param resource: A :class:`Resource` instance.\n        :return: The pathname of the resource in the cache.\n        \"\"\"\n        prefix, path = resource.finder.get_cache_info(resource)\n        if prefix is None:\n            result = path\n        else:\n            result = os.path.join(self.base, self.prefix_to_dir(prefix), path)\n            dirname = os.path.dirname(result)\n            if not os.path.isdir(dirname):\n                os.makedirs(dirname)\n            if not os.path.exists(result):\n                stale = True\n            else:\n                stale = self.is_stale(resource, path)\n            if stale:\n                # write the bytes of the resource to the cache location\n                with open(result, 'wb') as f:\n                    f.write(resource.bytes)\n        return result\n\n\nclass ResourceBase(object):\n    def __init__(self, finder, name):\n        self.finder = finder\n        self.name = name\n\n\nclass Resource(ResourceBase):\n    \"\"\"\n    A class representing an in-package resource, such as a data file. This is\n    not normally instantiated by user code, but rather by a\n    :class:`ResourceFinder` which manages the resource.\n    \"\"\"\n    is_container = False        # Backwards compatibility\n\n    def as_stream(self):\n        \"\"\"\n        Get the resource as a stream.\n\n        This is not a property to make it obvious that it returns a new stream\n        each time.\n        \"\"\"\n        return self.finder.get_stream(self)\n\n    @cached_property\n    def file_path(self):\n        global cache\n        if cache is None:\n            cache = ResourceCache()\n        return cache.get(self)\n\n    @cached_property\n    def bytes(self):\n        return self.finder.get_bytes(self)\n\n    @cached_property\n    def size(self):\n        return self.finder.get_size(self)\n\n\nclass ResourceContainer(ResourceBase):\n    is_container = True     # Backwards compatibility\n\n    @cached_property\n    def resources(self):\n        return self.finder.get_resources(self)\n\n\nclass ResourceFinder(object):\n    \"\"\"\n    Resource finder for file system resources.\n    \"\"\"\n\n    if sys.platform.startswith('java'):\n        skipped_extensions = ('.pyc', '.pyo', '.class')\n    else:\n        skipped_extensions = ('.pyc', '.pyo')\n\n    def __init__(self, module):\n        self.module = module\n        self.loader = getattr(module, '__loader__', None)\n        self.base = os.path.dirname(getattr(module, '__file__', ''))\n\n    def _adjust_path(self, path):\n        return os.path.realpath(path)\n\n    def _make_path(self, resource_name):\n        # Issue #50: need to preserve type of path on Python 2.x\n        # like os.path._get_sep\n        if isinstance(resource_name, bytes):    # should only happen on 2.x\n            sep = b'/'\n        else:\n            sep = '/'\n        parts = resource_name.split(sep)\n        parts.insert(0, self.base)\n        result = os.path.join(*parts)\n        return self._adjust_path(result)\n\n    def _find(self, path):\n        return os.path.exists(path)\n\n    def get_cache_info(self, resource):\n        return None, resource.path\n\n    def find(self, resource_name):\n        path = self._make_path(resource_name)\n        if not self._find(path):\n            result = None\n        else:\n            if self._is_directory(path):\n                result = ResourceContainer(self, resource_name)\n            else:\n                result = Resource(self, resource_name)\n            result.path = path\n        return result\n\n    def get_stream(self, resource):\n        return open(resource.path, 'rb')\n\n    def get_bytes(self, resource):\n        with open(resource.path, 'rb') as f:\n            return f.read()\n\n    def get_size(self, resource):\n        return os.path.getsize(resource.path)\n\n    def get_resources(self, resource):\n        def allowed(f):\n            return (f != '__pycache__' and not\n                    f.endswith(self.skipped_extensions))\n        return set([f for f in os.listdir(resource.path) if allowed(f)])\n\n    def is_container(self, resource):\n        return self._is_directory(resource.path)\n\n    _is_directory = staticmethod(os.path.isdir)\n\n    def iterator(self, resource_name):\n        resource = self.find(resource_name)\n        if resource is not None:\n            todo = [resource]\n            while todo:\n                resource = todo.pop(0)\n                yield resource\n                if resource.is_container:\n                    rname = resource.name\n                    for name in resource.resources:\n                        if not rname:\n                            new_name = name\n                        else:\n                            new_name = '/'.join([rname, name])\n                        child = self.find(new_name)\n                        if child.is_container:\n                            todo.append(child)\n                        else:\n                            yield child\n\n\nclass ZipResourceFinder(ResourceFinder):\n    \"\"\"\n    Resource finder for resources in .zip files.\n    \"\"\"\n    def __init__(self, module):\n        super(ZipResourceFinder, self).__init__(module)\n        archive = self.loader.archive\n        self.prefix_len = 1 + len(archive)\n        # PyPy doesn't have a _files attr on zipimporter, and you can't set one\n        if hasattr(self.loader, '_files'):\n            self._files = self.loader._files\n        else:\n            self._files = zipimport._zip_directory_cache[archive]\n        self.index = sorted(self._files)\n\n    def _adjust_path(self, path):\n        return path\n\n    def _find(self, path):\n        path = path[self.prefix_len:]\n        if path in self._files:\n            result = True\n        else:\n            if path and path[-1] != os.sep:\n                path = path + os.sep\n            i = bisect.bisect(self.index, path)\n            try:\n                result = self.index[i].startswith(path)\n            except IndexError:\n                result = False\n        if not result:\n            logger.debug('_find failed: %r %r', path, self.loader.prefix)\n        else:\n            logger.debug('_find worked: %r %r', path, self.loader.prefix)\n        return result\n\n    def get_cache_info(self, resource):\n        prefix = self.loader.archive\n        path = resource.path[1 + len(prefix):]\n        return prefix, path\n\n    def get_bytes(self, resource):\n        return self.loader.get_data(resource.path)\n\n    def get_stream(self, resource):\n        return io.BytesIO(self.get_bytes(resource))\n\n    def get_size(self, resource):\n        path = resource.path[self.prefix_len:]\n        return self._files[path][3]\n\n    def get_resources(self, resource):\n        path = resource.path[self.prefix_len:]\n        if path and path[-1] != os.sep:\n            path += os.sep\n        plen = len(path)\n        result = set()\n        i = bisect.bisect(self.index, path)\n        while i < len(self.index):\n            if not self.index[i].startswith(path):\n                break\n            s = self.index[i][plen:]\n            result.add(s.split(os.sep, 1)[0])   # only immediate children\n            i += 1\n        return result\n\n    def _is_directory(self, path):\n        path = path[self.prefix_len:]\n        if path and path[-1] != os.sep:\n            path += os.sep\n        i = bisect.bisect(self.index, path)\n        try:\n            result = self.index[i].startswith(path)\n        except IndexError:\n            result = False\n        return result\n\n\n_finder_registry = {\n    type(None): ResourceFinder,\n    zipimport.zipimporter: ZipResourceFinder\n}\n\ntry:\n    # In Python 3.6, _frozen_importlib -> _frozen_importlib_external\n    try:\n        import _frozen_importlib_external as _fi\n    except ImportError:\n        import _frozen_importlib as _fi\n    _finder_registry[_fi.SourceFileLoader] = ResourceFinder\n    _finder_registry[_fi.FileFinder] = ResourceFinder\n    # See issue #146\n    _finder_registry[_fi.SourcelessFileLoader] = ResourceFinder\n    del _fi\nexcept (ImportError, AttributeError):\n    pass\n\n\ndef register_finder(loader, finder_maker):\n    _finder_registry[type(loader)] = finder_maker\n\n\n_finder_cache = {}\n\n\ndef finder(package):\n    \"\"\"\n    Return a resource finder for a package.\n    :param package: The name of the package.\n    :return: A :class:`ResourceFinder` instance for the package.\n    \"\"\"\n    if package in _finder_cache:\n        result = _finder_cache[package]\n    else:\n        if package not in sys.modules:\n            __import__(package)\n        module = sys.modules[package]\n        path = getattr(module, '__path__', None)\n        if path is None:\n            raise DistlibException('You cannot get a finder for a module, '\n                                   'only for a package')\n        loader = getattr(module, '__loader__', None)\n        finder_maker = _finder_registry.get(type(loader))\n        if finder_maker is None:\n            raise DistlibException('Unable to locate finder for %r' % package)\n        result = finder_maker(module)\n        _finder_cache[package] = result\n    return result\n\n\n_dummy_module = types.ModuleType(str('__dummy__'))\n\n\ndef finder_for_path(path):\n    \"\"\"\n    Return a resource finder for a path, which should represent a container.\n\n    :param path: The path.\n    :return: A :class:`ResourceFinder` instance for the path.\n    \"\"\"\n    result = None\n    # calls any path hooks, gets importer into cache\n    pkgutil.get_importer(path)\n    loader = sys.path_importer_cache.get(path)\n    finder = _finder_registry.get(type(loader))\n    if finder:\n        module = _dummy_module\n        module.__file__ = os.path.join(path, '')\n        module.__loader__ = loader\n        result = finder(module)\n    return result\n"
  },
  {
    "path": "src/pip/_vendor/distlib/scripts.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2023 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom io import BytesIO\nimport logging\nimport os\nimport re\nimport struct\nimport sys\nimport time\nfrom zipfile import ZipInfo\n\nfrom .compat import sysconfig, detect_encoding, ZipFile\nfrom .resources import finder\nfrom .util import (FileOperator, get_export_entry, convert_path, get_executable, get_platform, in_venv)\n\nlogger = logging.getLogger(__name__)\n\n_DEFAULT_MANIFEST = '''\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <assemblyIdentity version=\"1.0.0.0\"\n processorArchitecture=\"X86\"\n name=\"%s\"\n type=\"win32\"/>\n\n <!-- Identify the application security requirements. -->\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>'''.strip()\n\n# check if Python is called on the first line with this expression\nFIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \\t].*)?$')\nSCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-\nimport re\nimport sys\nif __name__ == '__main__':\n    from %(module)s import %(import_name)s\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(%(func)s())\n'''\n\n# Pre-fetch the contents of all executable wrapper stubs.\n# This is to address https://github.com/pypa/pip/issues/12666.\n# When updating pip, we rename the old pip in place before installing the\n# new version. If we try to fetch a wrapper *after* that rename, the finder\n# machinery will be confused as the package is no longer available at the\n# location where it was imported from. So we load everything into memory in\n# advance.\n\nif os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):\n    # Issue 31: don't hardcode an absolute package name, but\n    # determine it relative to the current package\n    DISTLIB_PACKAGE = __name__.rsplit('.', 1)[0]\n\n    WRAPPERS = {\n        r.name: r.bytes\n        for r in finder(DISTLIB_PACKAGE).iterator(\"\")\n        if r.name.endswith(\".exe\")\n    }\n\n\ndef enquote_executable(executable):\n    if ' ' in executable:\n        # make sure we quote only the executable in case of env\n        # for example /usr/bin/env \"/dir with spaces/bin/jython\"\n        # instead of \"/usr/bin/env /dir with spaces/bin/jython\"\n        # otherwise whole\n        if executable.startswith('/usr/bin/env '):\n            env, _executable = executable.split(' ', 1)\n            if ' ' in _executable and not _executable.startswith('\"'):\n                executable = '%s \"%s\"' % (env, _executable)\n        else:\n            if not executable.startswith('\"'):\n                executable = '\"%s\"' % executable\n    return executable\n\n\n# Keep the old name around (for now), as there is at least one project using it!\n_enquote_executable = enquote_executable\n\n\nclass ScriptMaker(object):\n    \"\"\"\n    A class to copy or create scripts from source scripts or callable\n    specifications.\n    \"\"\"\n    script_template = SCRIPT_TEMPLATE\n\n    executable = None  # for shebangs\n\n    def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None):\n        self.source_dir = source_dir\n        self.target_dir = target_dir\n        self.add_launchers = add_launchers\n        self.force = False\n        self.clobber = False\n        # It only makes sense to set mode bits on POSIX.\n        self.set_mode = (os.name == 'posix') or (os.name == 'java' and os._name == 'posix')\n        self.variants = set(('', 'X.Y'))\n        self._fileop = fileop or FileOperator(dry_run)\n\n        self._is_nt = os.name == 'nt' or (os.name == 'java' and os._name == 'nt')\n        self.version_info = sys.version_info\n\n    def _get_alternate_executable(self, executable, options):\n        if options.get('gui', False) and self._is_nt:  # pragma: no cover\n            dn, fn = os.path.split(executable)\n            fn = fn.replace('python', 'pythonw')\n            executable = os.path.join(dn, fn)\n        return executable\n\n    if sys.platform.startswith('java'):  # pragma: no cover\n\n        def _is_shell(self, executable):\n            \"\"\"\n            Determine if the specified executable is a script\n            (contains a #! line)\n            \"\"\"\n            try:\n                with open(executable) as fp:\n                    return fp.read(2) == '#!'\n            except (OSError, IOError):\n                logger.warning('Failed to open %s', executable)\n                return False\n\n        def _fix_jython_executable(self, executable):\n            if self._is_shell(executable):\n                # Workaround for Jython is not needed on Linux systems.\n                import java\n\n                if java.lang.System.getProperty('os.name') == 'Linux':\n                    return executable\n            elif executable.lower().endswith('jython.exe'):\n                # Use wrapper exe for Jython on Windows\n                return executable\n            return '/usr/bin/env %s' % executable\n\n    def _build_shebang(self, executable, post_interp):\n        \"\"\"\n        Build a shebang line. In the simple case (on Windows, or a shebang line\n        which is not too long or contains spaces) use a simple formulation for\n        the shebang. Otherwise, use /bin/sh as the executable, with a contrived\n        shebang which allows the script to run either under Python or sh, using\n        suitable quoting. Thanks to Harald Nordgren for his input.\n\n        See also: http://www.in-ulm.de/~mascheck/various/shebang/#length\n                  https://hg.mozilla.org/mozilla-central/file/tip/mach\n        \"\"\"\n        if os.name != 'posix':\n            simple_shebang = True\n        elif getattr(sys, \"cross_compiling\", False):\n            # In a cross-compiling environment, the shebang will likely be a\n            # script; this *must* be invoked with the \"safe\" version of the\n            # shebang, or else using os.exec() to run the entry script will\n            # fail, raising \"OSError 8 [Errno 8] Exec format error\".\n            simple_shebang = False\n        else:\n            # Add 3 for '#!' prefix and newline suffix.\n            shebang_length = len(executable) + len(post_interp) + 3\n            if sys.platform == 'darwin':\n                max_shebang_length = 512\n            else:\n                max_shebang_length = 127\n            simple_shebang = ((b' ' not in executable) and (shebang_length <= max_shebang_length))\n\n        if simple_shebang:\n            result = b'#!' + executable + post_interp + b'\\n'\n        else:\n            result = b'#!/bin/sh\\n'\n            result += b\"'''exec' \" + executable + post_interp + b' \"$0\" \"$@\"\\n'\n            result += b\"' '''\\n\"\n        return result\n\n    def _get_shebang(self, encoding, post_interp=b'', options=None):\n        enquote = True\n        if self.executable:\n            executable = self.executable\n            enquote = False  # assume this will be taken care of\n        elif not sysconfig.is_python_build():\n            executable = get_executable()\n        elif in_venv():  # pragma: no cover\n            executable = os.path.join(sysconfig.get_path('scripts'), 'python%s' % sysconfig.get_config_var('EXE'))\n        else:  # pragma: no cover\n            if os.name == 'nt':\n                # for Python builds from source on Windows, no Python executables with\n                # a version suffix are created, so we use python.exe\n                executable = os.path.join(sysconfig.get_config_var('BINDIR'),\n                                          'python%s' % (sysconfig.get_config_var('EXE')))\n            else:\n                executable = os.path.join(\n                    sysconfig.get_config_var('BINDIR'),\n                    'python%s%s' % (sysconfig.get_config_var('VERSION'), sysconfig.get_config_var('EXE')))\n        if options:\n            executable = self._get_alternate_executable(executable, options)\n\n        if sys.platform.startswith('java'):  # pragma: no cover\n            executable = self._fix_jython_executable(executable)\n\n        # Normalise case for Windows - COMMENTED OUT\n        # executable = os.path.normcase(executable)\n        # N.B. The normalising operation above has been commented out: See\n        # issue #124. Although paths in Windows are generally case-insensitive,\n        # they aren't always. For example, a path containing a ẞ (which is a\n        # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a\n        # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by\n        # Windows as equivalent in path names.\n\n        # If the user didn't specify an executable, it may be necessary to\n        # cater for executable paths with spaces (not uncommon on Windows)\n        if enquote:\n            executable = enquote_executable(executable)\n        # Issue #51: don't use fsencode, since we later try to\n        # check that the shebang is decodable using utf-8.\n        executable = executable.encode('utf-8')\n        # in case of IronPython, play safe and enable frames support\n        if (sys.platform == 'cli' and '-X:Frames' not in post_interp and\n                '-X:FullFrames' not in post_interp):  # pragma: no cover\n            post_interp += b' -X:Frames'\n        shebang = self._build_shebang(executable, post_interp)\n        # Python parser starts to read a script using UTF-8 until\n        # it gets a #coding:xxx cookie. The shebang has to be the\n        # first line of a file, the #coding:xxx cookie cannot be\n        # written before. So the shebang has to be decodable from\n        # UTF-8.\n        try:\n            shebang.decode('utf-8')\n        except UnicodeDecodeError:  # pragma: no cover\n            raise ValueError('The shebang (%r) is not decodable from utf-8' % shebang)\n        # If the script is encoded to a custom encoding (use a\n        # #coding:xxx cookie), the shebang has to be decodable from\n        # the script encoding too.\n        if encoding != 'utf-8':\n            try:\n                shebang.decode(encoding)\n            except UnicodeDecodeError:  # pragma: no cover\n                raise ValueError('The shebang (%r) is not decodable '\n                                 'from the script encoding (%r)' % (shebang, encoding))\n        return shebang\n\n    def _get_script_text(self, entry):\n        return self.script_template % dict(\n            module=entry.prefix, import_name=entry.suffix.split('.')[0], func=entry.suffix)\n\n    manifest = _DEFAULT_MANIFEST\n\n    def get_manifest(self, exename):\n        base = os.path.basename(exename)\n        return self.manifest % base\n\n    def _write_script(self, names, shebang, script_bytes, filenames, ext):\n        use_launcher = self.add_launchers and self._is_nt\n        if not use_launcher:\n            script_bytes = shebang + script_bytes\n        else:  # pragma: no cover\n            if ext == 'py':\n                launcher = self._get_launcher('t')\n            else:\n                launcher = self._get_launcher('w')\n            stream = BytesIO()\n            with ZipFile(stream, 'w') as zf:\n                source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')\n                if source_date_epoch:\n                    date_time = time.gmtime(int(source_date_epoch))[:6]\n                    zinfo = ZipInfo(filename='__main__.py', date_time=date_time)\n                    zf.writestr(zinfo, script_bytes)\n                else:\n                    zf.writestr('__main__.py', script_bytes)\n            zip_data = stream.getvalue()\n            script_bytes = launcher + shebang + zip_data\n        for name in names:\n            outname = os.path.join(self.target_dir, name)\n            if use_launcher:  # pragma: no cover\n                n, e = os.path.splitext(outname)\n                if e.startswith('.py'):\n                    outname = n\n                outname = '%s.exe' % outname\n                try:\n                    self._fileop.write_binary_file(outname, script_bytes)\n                except Exception:\n                    # Failed writing an executable - it might be in use.\n                    logger.warning('Failed to write executable - trying to '\n                                   'use .deleteme logic')\n                    dfname = '%s.deleteme' % outname\n                    if os.path.exists(dfname):\n                        os.remove(dfname)  # Not allowed to fail here\n                    os.rename(outname, dfname)  # nor here\n                    self._fileop.write_binary_file(outname, script_bytes)\n                    logger.debug('Able to replace executable using '\n                                 '.deleteme logic')\n                    try:\n                        os.remove(dfname)\n                    except Exception:\n                        pass  # still in use - ignore error\n            else:\n                if self._is_nt and not outname.endswith('.' + ext):  # pragma: no cover\n                    outname = '%s.%s' % (outname, ext)\n                if os.path.exists(outname) and not self.clobber:\n                    logger.warning('Skipping existing file %s', outname)\n                    continue\n                self._fileop.write_binary_file(outname, script_bytes)\n                if self.set_mode:\n                    self._fileop.set_executable_mode([outname])\n            filenames.append(outname)\n\n    variant_separator = '-'\n\n    def get_script_filenames(self, name):\n        result = set()\n        if '' in self.variants:\n            result.add(name)\n        if 'X' in self.variants:\n            result.add('%s%s' % (name, self.version_info[0]))\n        if 'X.Y' in self.variants:\n            result.add('%s%s%s.%s' % (name, self.variant_separator, self.version_info[0], self.version_info[1]))\n        return result\n\n    def _make_script(self, entry, filenames, options=None):\n        post_interp = b''\n        if options:\n            args = options.get('interpreter_args', [])\n            if args:\n                args = ' %s' % ' '.join(args)\n                post_interp = args.encode('utf-8')\n        shebang = self._get_shebang('utf-8', post_interp, options=options)\n        script = self._get_script_text(entry).encode('utf-8')\n        scriptnames = self.get_script_filenames(entry.name)\n        if options and options.get('gui', False):\n            ext = 'pyw'\n        else:\n            ext = 'py'\n        self._write_script(scriptnames, shebang, script, filenames, ext)\n\n    def _copy_script(self, script, filenames):\n        adjust = False\n        script = os.path.join(self.source_dir, convert_path(script))\n        outname = os.path.join(self.target_dir, os.path.basename(script))\n        if not self.force and not self._fileop.newer(script, outname):\n            logger.debug('not copying %s (up-to-date)', script)\n            return\n\n        # Always open the file, but ignore failures in dry-run mode --\n        # that way, we'll get accurate feedback if we can read the\n        # script.\n        try:\n            f = open(script, 'rb')\n        except IOError:  # pragma: no cover\n            if not self.dry_run:\n                raise\n            f = None\n        else:\n            first_line = f.readline()\n            if not first_line:  # pragma: no cover\n                logger.warning('%s is an empty file (skipping)', script)\n                return\n\n            match = FIRST_LINE_RE.match(first_line.replace(b'\\r\\n', b'\\n'))\n            if match:\n                adjust = True\n                post_interp = match.group(1) or b''\n\n        if not adjust:\n            if f:\n                f.close()\n            self._fileop.copy_file(script, outname)\n            if self.set_mode:\n                self._fileop.set_executable_mode([outname])\n            filenames.append(outname)\n        else:\n            logger.info('copying and adjusting %s -> %s', script, self.target_dir)\n            if not self._fileop.dry_run:\n                encoding, lines = detect_encoding(f.readline)\n                f.seek(0)\n                shebang = self._get_shebang(encoding, post_interp)\n                if b'pythonw' in first_line:  # pragma: no cover\n                    ext = 'pyw'\n                else:\n                    ext = 'py'\n                n = os.path.basename(outname)\n                self._write_script([n], shebang, f.read(), filenames, ext)\n            if f:\n                f.close()\n\n    @property\n    def dry_run(self):\n        return self._fileop.dry_run\n\n    @dry_run.setter\n    def dry_run(self, value):\n        self._fileop.dry_run = value\n\n    if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):  # pragma: no cover\n        # Executable launcher support.\n        # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/\n\n        def _get_launcher(self, kind):\n            if struct.calcsize('P') == 8:  # 64-bit\n                bits = '64'\n            else:\n                bits = '32'\n            platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''\n            name = '%s%s%s.exe' % (kind, bits, platform_suffix)\n            if name not in WRAPPERS:\n                msg = ('Unable to find resource %s in package %s' %\n                       (name, DISTLIB_PACKAGE))\n                raise ValueError(msg)\n            return WRAPPERS[name]\n\n    # Public API follows\n\n    def make(self, specification, options=None):\n        \"\"\"\n        Make a script.\n\n        :param specification: The specification, which is either a valid export\n                              entry specification (to make a script from a\n                              callable) or a filename (to make a script by\n                              copying from a source location).\n        :param options: A dictionary of options controlling script generation.\n        :return: A list of all absolute pathnames written to.\n        \"\"\"\n        filenames = []\n        entry = get_export_entry(specification)\n        if entry is None:\n            self._copy_script(specification, filenames)\n        else:\n            self._make_script(entry, filenames, options=options)\n        return filenames\n\n    def make_multiple(self, specifications, options=None):\n        \"\"\"\n        Take a list of specifications and make scripts from them,\n        :param specifications: A list of specifications.\n        :return: A list of all absolute pathnames written to,\n        \"\"\"\n        filenames = []\n        for specification in specifications:\n            filenames.extend(self.make(specification, options))\n        return filenames\n"
  },
  {
    "path": "src/pip/_vendor/distlib/util.py",
    "content": "#\n# Copyright (C) 2012-2023 The Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nimport codecs\nfrom collections import deque\nimport contextlib\nimport csv\nfrom glob import iglob as std_iglob\nimport io\nimport json\nimport logging\nimport os\nimport py_compile\nimport re\nimport socket\ntry:\n    import ssl\nexcept ImportError:  # pragma: no cover\n    ssl = None\nimport subprocess\nimport sys\nimport tarfile\nimport tempfile\nimport textwrap\n\ntry:\n    import threading\nexcept ImportError:  # pragma: no cover\n    import dummy_threading as threading\nimport time\n\nfrom . import DistlibException\nfrom .compat import (string_types, text_type, shutil, raw_input, StringIO, cache_from_source, urlopen, urljoin, httplib,\n                     xmlrpclib, HTTPHandler, BaseConfigurator, valid_ident, Container, configparser, URLError, ZipFile,\n                     fsdecode, unquote, urlparse)\n\nlogger = logging.getLogger(__name__)\n\n#\n# Requirement parsing code as per PEP 508\n#\n\nIDENTIFIER = re.compile(r'^([\\w\\.-]+)\\s*')\nVERSION_IDENTIFIER = re.compile(r'^([\\w\\.*+-]+)\\s*')\nCOMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\\s*')\nMARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\\s+in)\\s*')\nOR = re.compile(r'^or\\b\\s*')\nAND = re.compile(r'^and\\b\\s*')\nNON_SPACE = re.compile(r'(\\S+)\\s*')\nSTRING_CHUNK = re.compile(r'([\\s\\w\\.{}()*+#:;,/?!~`@$%^&=|<>\\[\\]-]+)')\n\n\ndef parse_marker(marker_string):\n    \"\"\"\n    Parse a marker string and return a dictionary containing a marker expression.\n\n    The dictionary will contain keys \"op\", \"lhs\" and \"rhs\" for non-terminals in\n    the expression grammar, or strings. A string contained in quotes is to be\n    interpreted as a literal string, and a string not contained in quotes is a\n    variable (such as os_name).\n    \"\"\"\n\n    def marker_var(remaining):\n        # either identifier, or literal string\n        m = IDENTIFIER.match(remaining)\n        if m:\n            result = m.groups()[0]\n            remaining = remaining[m.end():]\n        elif not remaining:\n            raise SyntaxError('unexpected end of input')\n        else:\n            q = remaining[0]\n            if q not in '\\'\"':\n                raise SyntaxError('invalid expression: %s' % remaining)\n            oq = '\\'\"'.replace(q, '')\n            remaining = remaining[1:]\n            parts = [q]\n            while remaining:\n                # either a string chunk, or oq, or q to terminate\n                if remaining[0] == q:\n                    break\n                elif remaining[0] == oq:\n                    parts.append(oq)\n                    remaining = remaining[1:]\n                else:\n                    m = STRING_CHUNK.match(remaining)\n                    if not m:\n                        raise SyntaxError('error in string literal: %s' % remaining)\n                    parts.append(m.groups()[0])\n                    remaining = remaining[m.end():]\n            else:\n                s = ''.join(parts)\n                raise SyntaxError('unterminated string: %s' % s)\n            parts.append(q)\n            result = ''.join(parts)\n            remaining = remaining[1:].lstrip()  # skip past closing quote\n        return result, remaining\n\n    def marker_expr(remaining):\n        if remaining and remaining[0] == '(':\n            result, remaining = marker(remaining[1:].lstrip())\n            if remaining[0] != ')':\n                raise SyntaxError('unterminated parenthesis: %s' % remaining)\n            remaining = remaining[1:].lstrip()\n        else:\n            lhs, remaining = marker_var(remaining)\n            while remaining:\n                m = MARKER_OP.match(remaining)\n                if not m:\n                    break\n                op = m.groups()[0]\n                remaining = remaining[m.end():]\n                rhs, remaining = marker_var(remaining)\n                lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}\n            result = lhs\n        return result, remaining\n\n    def marker_and(remaining):\n        lhs, remaining = marker_expr(remaining)\n        while remaining:\n            m = AND.match(remaining)\n            if not m:\n                break\n            remaining = remaining[m.end():]\n            rhs, remaining = marker_expr(remaining)\n            lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}\n        return lhs, remaining\n\n    def marker(remaining):\n        lhs, remaining = marker_and(remaining)\n        while remaining:\n            m = OR.match(remaining)\n            if not m:\n                break\n            remaining = remaining[m.end():]\n            rhs, remaining = marker_and(remaining)\n            lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}\n        return lhs, remaining\n\n    return marker(marker_string)\n\n\ndef parse_requirement(req):\n    \"\"\"\n    Parse a requirement passed in as a string. Return a Container\n    whose attributes contain the various parts of the requirement.\n    \"\"\"\n    remaining = req.strip()\n    if not remaining or remaining.startswith('#'):\n        return None\n    m = IDENTIFIER.match(remaining)\n    if not m:\n        raise SyntaxError('name expected: %s' % remaining)\n    distname = m.groups()[0]\n    remaining = remaining[m.end():]\n    extras = mark_expr = versions = uri = None\n    if remaining and remaining[0] == '[':\n        i = remaining.find(']', 1)\n        if i < 0:\n            raise SyntaxError('unterminated extra: %s' % remaining)\n        s = remaining[1:i]\n        remaining = remaining[i + 1:].lstrip()\n        extras = []\n        while s:\n            m = IDENTIFIER.match(s)\n            if not m:\n                raise SyntaxError('malformed extra: %s' % s)\n            extras.append(m.groups()[0])\n            s = s[m.end():]\n            if not s:\n                break\n            if s[0] != ',':\n                raise SyntaxError('comma expected in extras: %s' % s)\n            s = s[1:].lstrip()\n        if not extras:\n            extras = None\n    if remaining:\n        if remaining[0] == '@':\n            # it's a URI\n            remaining = remaining[1:].lstrip()\n            m = NON_SPACE.match(remaining)\n            if not m:\n                raise SyntaxError('invalid URI: %s' % remaining)\n            uri = m.groups()[0]\n            t = urlparse(uri)\n            # there are issues with Python and URL parsing, so this test\n            # is a bit crude. See bpo-20271, bpo-23505. Python doesn't\n            # always parse invalid URLs correctly - it should raise\n            # exceptions for malformed URLs\n            if not (t.scheme and t.netloc):\n                raise SyntaxError('Invalid URL: %s' % uri)\n            remaining = remaining[m.end():].lstrip()\n        else:\n\n            def get_versions(ver_remaining):\n                \"\"\"\n                Return a list of operator, version tuples if any are\n                specified, else None.\n                \"\"\"\n                m = COMPARE_OP.match(ver_remaining)\n                versions = None\n                if m:\n                    versions = []\n                    while True:\n                        op = m.groups()[0]\n                        ver_remaining = ver_remaining[m.end():]\n                        m = VERSION_IDENTIFIER.match(ver_remaining)\n                        if not m:\n                            raise SyntaxError('invalid version: %s' % ver_remaining)\n                        v = m.groups()[0]\n                        versions.append((op, v))\n                        ver_remaining = ver_remaining[m.end():]\n                        if not ver_remaining or ver_remaining[0] != ',':\n                            break\n                        ver_remaining = ver_remaining[1:].lstrip()\n                        # Some packages have a trailing comma which would break things\n                        # See issue #148\n                        if not ver_remaining:\n                            break\n                        m = COMPARE_OP.match(ver_remaining)\n                        if not m:\n                            raise SyntaxError('invalid constraint: %s' % ver_remaining)\n                    if not versions:\n                        versions = None\n                return versions, ver_remaining\n\n            if remaining[0] != '(':\n                versions, remaining = get_versions(remaining)\n            else:\n                i = remaining.find(')', 1)\n                if i < 0:\n                    raise SyntaxError('unterminated parenthesis: %s' % remaining)\n                s = remaining[1:i]\n                remaining = remaining[i + 1:].lstrip()\n                # As a special diversion from PEP 508, allow a version number\n                # a.b.c in parentheses as a synonym for ~= a.b.c (because this\n                # is allowed in earlier PEPs)\n                if COMPARE_OP.match(s):\n                    versions, _ = get_versions(s)\n                else:\n                    m = VERSION_IDENTIFIER.match(s)\n                    if not m:\n                        raise SyntaxError('invalid constraint: %s' % s)\n                    v = m.groups()[0]\n                    s = s[m.end():].lstrip()\n                    if s:\n                        raise SyntaxError('invalid constraint: %s' % s)\n                    versions = [('~=', v)]\n\n    if remaining:\n        if remaining[0] != ';':\n            raise SyntaxError('invalid requirement: %s' % remaining)\n        remaining = remaining[1:].lstrip()\n\n        mark_expr, remaining = parse_marker(remaining)\n\n    if remaining and remaining[0] != '#':\n        raise SyntaxError('unexpected trailing data: %s' % remaining)\n\n    if not versions:\n        rs = distname\n    else:\n        rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))\n    return Container(name=distname, extras=extras, constraints=versions, marker=mark_expr, url=uri, requirement=rs)\n\n\ndef get_resources_dests(resources_root, rules):\n    \"\"\"Find destinations for resources files\"\"\"\n\n    def get_rel_path(root, path):\n        # normalizes and returns a lstripped-/-separated path\n        root = root.replace(os.path.sep, '/')\n        path = path.replace(os.path.sep, '/')\n        assert path.startswith(root)\n        return path[len(root):].lstrip('/')\n\n    destinations = {}\n    for base, suffix, dest in rules:\n        prefix = os.path.join(resources_root, base)\n        for abs_base in iglob(prefix):\n            abs_glob = os.path.join(abs_base, suffix)\n            for abs_path in iglob(abs_glob):\n                resource_file = get_rel_path(resources_root, abs_path)\n                if dest is None:  # remove the entry if it was here\n                    destinations.pop(resource_file, None)\n                else:\n                    rel_path = get_rel_path(abs_base, abs_path)\n                    rel_dest = dest.replace(os.path.sep, '/').rstrip('/')\n                    destinations[resource_file] = rel_dest + '/' + rel_path\n    return destinations\n\n\ndef in_venv():\n    if hasattr(sys, 'real_prefix'):\n        # virtualenv venvs\n        result = True\n    else:\n        # PEP 405 venvs\n        result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)\n    return result\n\n\ndef get_executable():\n    # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as\n    # changes to the stub launcher mean that sys.executable always points\n    # to the stub on OS X\n    #    if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'\n    #                                     in os.environ):\n    #        result =  os.environ['__PYVENV_LAUNCHER__']\n    #    else:\n    #        result = sys.executable\n    #    return result\n    # Avoid normcasing: see issue #143\n    # result = os.path.normcase(sys.executable)\n    result = sys.executable\n    if not isinstance(result, text_type):\n        result = fsdecode(result)\n    return result\n\n\ndef proceed(prompt, allowed_chars, error_prompt=None, default=None):\n    p = prompt\n    while True:\n        s = raw_input(p)\n        p = prompt\n        if not s and default:\n            s = default\n        if s:\n            c = s[0].lower()\n            if c in allowed_chars:\n                break\n            if error_prompt:\n                p = '%c: %s\\n%s' % (c, error_prompt, prompt)\n    return c\n\n\ndef extract_by_key(d, keys):\n    if isinstance(keys, string_types):\n        keys = keys.split()\n    result = {}\n    for key in keys:\n        if key in d:\n            result[key] = d[key]\n    return result\n\n\ndef read_exports(stream):\n    if sys.version_info[0] >= 3:\n        # needs to be a text stream\n        stream = codecs.getreader('utf-8')(stream)\n    # Try to load as JSON, falling back on legacy format\n    data = stream.read()\n    stream = StringIO(data)\n    try:\n        jdata = json.load(stream)\n        result = jdata['extensions']['python.exports']['exports']\n        for group, entries in result.items():\n            for k, v in entries.items():\n                s = '%s = %s' % (k, v)\n                entry = get_export_entry(s)\n                assert entry is not None\n                entries[k] = entry\n        return result\n    except Exception:\n        stream.seek(0, 0)\n\n    def read_stream(cp, stream):\n        if hasattr(cp, 'read_file'):\n            cp.read_file(stream)\n        else:\n            cp.readfp(stream)\n\n    cp = configparser.ConfigParser()\n    try:\n        read_stream(cp, stream)\n    except configparser.MissingSectionHeaderError:\n        stream.close()\n        data = textwrap.dedent(data)\n        stream = StringIO(data)\n        read_stream(cp, stream)\n\n    result = {}\n    for key in cp.sections():\n        result[key] = entries = {}\n        for name, value in cp.items(key):\n            s = '%s = %s' % (name, value)\n            entry = get_export_entry(s)\n            assert entry is not None\n            # entry.dist = self\n            entries[name] = entry\n    return result\n\n\ndef write_exports(exports, stream):\n    if sys.version_info[0] >= 3:\n        # needs to be a text stream\n        stream = codecs.getwriter('utf-8')(stream)\n    cp = configparser.ConfigParser()\n    for k, v in exports.items():\n        # TODO check k, v for valid values\n        cp.add_section(k)\n        for entry in v.values():\n            if entry.suffix is None:\n                s = entry.prefix\n            else:\n                s = '%s:%s' % (entry.prefix, entry.suffix)\n            if entry.flags:\n                s = '%s [%s]' % (s, ', '.join(entry.flags))\n            cp.set(k, entry.name, s)\n    cp.write(stream)\n\n\n@contextlib.contextmanager\ndef tempdir():\n    td = tempfile.mkdtemp()\n    try:\n        yield td\n    finally:\n        shutil.rmtree(td)\n\n\n@contextlib.contextmanager\ndef chdir(d):\n    cwd = os.getcwd()\n    try:\n        os.chdir(d)\n        yield\n    finally:\n        os.chdir(cwd)\n\n\n@contextlib.contextmanager\ndef socket_timeout(seconds=15):\n    cto = socket.getdefaulttimeout()\n    try:\n        socket.setdefaulttimeout(seconds)\n        yield\n    finally:\n        socket.setdefaulttimeout(cto)\n\n\nclass cached_property(object):\n\n    def __init__(self, func):\n        self.func = func\n        # for attr in ('__name__', '__module__', '__doc__'):\n        #     setattr(self, attr, getattr(func, attr, None))\n\n    def __get__(self, obj, cls=None):\n        if obj is None:\n            return self\n        value = self.func(obj)\n        object.__setattr__(obj, self.func.__name__, value)\n        # obj.__dict__[self.func.__name__] = value = self.func(obj)\n        return value\n\n\ndef convert_path(pathname):\n    \"\"\"Return 'pathname' as a name that will work on the native filesystem.\n\n    The path is split on '/' and put back together again using the current\n    directory separator.  Needed because filenames in the setup script are\n    always supplied in Unix style, and have to be converted to the local\n    convention before we can actually use them in the filesystem.  Raises\n    ValueError on non-Unix-ish systems if 'pathname' either starts or\n    ends with a slash.\n    \"\"\"\n    if os.sep == '/':\n        return pathname\n    if not pathname:\n        return pathname\n    if pathname[0] == '/':\n        raise ValueError(\"path '%s' cannot be absolute\" % pathname)\n    if pathname[-1] == '/':\n        raise ValueError(\"path '%s' cannot end with '/'\" % pathname)\n\n    paths = pathname.split('/')\n    while os.curdir in paths:\n        paths.remove(os.curdir)\n    if not paths:\n        return os.curdir\n    return os.path.join(*paths)\n\n\nclass FileOperator(object):\n\n    def __init__(self, dry_run=False):\n        self.dry_run = dry_run\n        self.ensured = set()\n        self._init_record()\n\n    def _init_record(self):\n        self.record = False\n        self.files_written = set()\n        self.dirs_created = set()\n\n    def record_as_written(self, path):\n        if self.record:\n            self.files_written.add(path)\n\n    def newer(self, source, target):\n        \"\"\"Tell if the target is newer than the source.\n\n        Returns true if 'source' exists and is more recently modified than\n        'target', or if 'source' exists and 'target' doesn't.\n\n        Returns false if both exist and 'target' is the same age or younger\n        than 'source'. Raise PackagingFileError if 'source' does not exist.\n\n        Note that this test is not very accurate: files created in the same\n        second will have the same \"age\".\n        \"\"\"\n        if not os.path.exists(source):\n            raise DistlibException(\"file '%r' does not exist\" % os.path.abspath(source))\n        if not os.path.exists(target):\n            return True\n\n        return os.stat(source).st_mtime > os.stat(target).st_mtime\n\n    def copy_file(self, infile, outfile, check=True):\n        \"\"\"Copy a file respecting dry-run and force flags.\n        \"\"\"\n        self.ensure_dir(os.path.dirname(outfile))\n        logger.info('Copying %s to %s', infile, outfile)\n        if not self.dry_run:\n            msg = None\n            if check:\n                if os.path.islink(outfile):\n                    msg = '%s is a symlink' % outfile\n                elif os.path.exists(outfile) and not os.path.isfile(outfile):\n                    msg = '%s is a non-regular file' % outfile\n            if msg:\n                raise ValueError(msg + ' which would be overwritten')\n            shutil.copyfile(infile, outfile)\n        self.record_as_written(outfile)\n\n    def copy_stream(self, instream, outfile, encoding=None):\n        assert not os.path.isdir(outfile)\n        self.ensure_dir(os.path.dirname(outfile))\n        logger.info('Copying stream %s to %s', instream, outfile)\n        if not self.dry_run:\n            if encoding is None:\n                outstream = open(outfile, 'wb')\n            else:\n                outstream = codecs.open(outfile, 'w', encoding=encoding)\n            try:\n                shutil.copyfileobj(instream, outstream)\n            finally:\n                outstream.close()\n        self.record_as_written(outfile)\n\n    def write_binary_file(self, path, data):\n        self.ensure_dir(os.path.dirname(path))\n        if not self.dry_run:\n            if os.path.exists(path):\n                os.remove(path)\n            with open(path, 'wb') as f:\n                f.write(data)\n        self.record_as_written(path)\n\n    def write_text_file(self, path, data, encoding):\n        self.write_binary_file(path, data.encode(encoding))\n\n    def set_mode(self, bits, mask, files):\n        if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):\n            # Set the executable bits (owner, group, and world) on\n            # all the files specified.\n            for f in files:\n                if self.dry_run:\n                    logger.info(\"changing mode of %s\", f)\n                else:\n                    mode = (os.stat(f).st_mode | bits) & mask\n                    logger.info(\"changing mode of %s to %o\", f, mode)\n                    os.chmod(f, mode)\n\n    set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)\n\n    def ensure_dir(self, path):\n        path = os.path.abspath(path)\n        if path not in self.ensured and not os.path.exists(path):\n            self.ensured.add(path)\n            d, f = os.path.split(path)\n            self.ensure_dir(d)\n            logger.info('Creating %s' % path)\n            if not self.dry_run:\n                os.mkdir(path)\n            if self.record:\n                self.dirs_created.add(path)\n\n    def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):\n        dpath = cache_from_source(path, not optimize)\n        logger.info('Byte-compiling %s to %s', path, dpath)\n        if not self.dry_run:\n            if force or self.newer(path, dpath):\n                if not prefix:\n                    diagpath = None\n                else:\n                    assert path.startswith(prefix)\n                    diagpath = path[len(prefix):]\n            compile_kwargs = {}\n            if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):\n                if not isinstance(hashed_invalidation, py_compile.PycInvalidationMode):\n                    hashed_invalidation = py_compile.PycInvalidationMode.CHECKED_HASH\n                compile_kwargs['invalidation_mode'] = hashed_invalidation\n            py_compile.compile(path, dpath, diagpath, True, **compile_kwargs)  # raise error\n        self.record_as_written(dpath)\n        return dpath\n\n    def ensure_removed(self, path):\n        if os.path.exists(path):\n            if os.path.isdir(path) and not os.path.islink(path):\n                logger.debug('Removing directory tree at %s', path)\n                if not self.dry_run:\n                    shutil.rmtree(path)\n                if self.record:\n                    if path in self.dirs_created:\n                        self.dirs_created.remove(path)\n            else:\n                if os.path.islink(path):\n                    s = 'link'\n                else:\n                    s = 'file'\n                logger.debug('Removing %s %s', s, path)\n                if not self.dry_run:\n                    os.remove(path)\n                if self.record:\n                    if path in self.files_written:\n                        self.files_written.remove(path)\n\n    def is_writable(self, path):\n        result = False\n        while not result:\n            if os.path.exists(path):\n                result = os.access(path, os.W_OK)\n                break\n            parent = os.path.dirname(path)\n            if parent == path:\n                break\n            path = parent\n        return result\n\n    def commit(self):\n        \"\"\"\n        Commit recorded changes, turn off recording, return\n        changes.\n        \"\"\"\n        assert self.record\n        result = self.files_written, self.dirs_created\n        self._init_record()\n        return result\n\n    def rollback(self):\n        if not self.dry_run:\n            for f in list(self.files_written):\n                if os.path.exists(f):\n                    os.remove(f)\n            # dirs should all be empty now, except perhaps for\n            # __pycache__ subdirs\n            # reverse so that subdirs appear before their parents\n            dirs = sorted(self.dirs_created, reverse=True)\n            for d in dirs:\n                flist = os.listdir(d)\n                if flist:\n                    assert flist == ['__pycache__']\n                    sd = os.path.join(d, flist[0])\n                    os.rmdir(sd)\n                os.rmdir(d)  # should fail if non-empty\n        self._init_record()\n\n\ndef resolve(module_name, dotted_path):\n    if module_name in sys.modules:\n        mod = sys.modules[module_name]\n    else:\n        mod = __import__(module_name)\n    if dotted_path is None:\n        result = mod\n    else:\n        parts = dotted_path.split('.')\n        result = getattr(mod, parts.pop(0))\n        for p in parts:\n            result = getattr(result, p)\n    return result\n\n\nclass ExportEntry(object):\n\n    def __init__(self, name, prefix, suffix, flags):\n        self.name = name\n        self.prefix = prefix\n        self.suffix = suffix\n        self.flags = flags\n\n    @cached_property\n    def value(self):\n        return resolve(self.prefix, self.suffix)\n\n    def __repr__(self):  # pragma: no cover\n        return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix, self.suffix, self.flags)\n\n    def __eq__(self, other):\n        if not isinstance(other, ExportEntry):\n            result = False\n        else:\n            result = (self.name == other.name and self.prefix == other.prefix and self.suffix == other.suffix and\n                      self.flags == other.flags)\n        return result\n\n    __hash__ = object.__hash__\n\n\nENTRY_RE = re.compile(\n    r'''(?P<name>([^\\[]\\S*))\n                      \\s*=\\s*(?P<callable>(\\w+)([:\\.]\\w+)*)\n                      \\s*(\\[\\s*(?P<flags>[\\w-]+(=\\w+)?(,\\s*\\w+(=\\w+)?)*)\\s*\\])?\n                      ''', re.VERBOSE)\n\n\ndef get_export_entry(specification):\n    m = ENTRY_RE.search(specification)\n    if not m:\n        result = None\n        if '[' in specification or ']' in specification:\n            raise DistlibException(\"Invalid specification \"\n                                   \"'%s'\" % specification)\n    else:\n        d = m.groupdict()\n        name = d['name']\n        path = d['callable']\n        colons = path.count(':')\n        if colons == 0:\n            prefix, suffix = path, None\n        else:\n            if colons != 1:\n                raise DistlibException(\"Invalid specification \"\n                                       \"'%s'\" % specification)\n            prefix, suffix = path.split(':')\n        flags = d['flags']\n        if flags is None:\n            if '[' in specification or ']' in specification:\n                raise DistlibException(\"Invalid specification \"\n                                       \"'%s'\" % specification)\n            flags = []\n        else:\n            flags = [f.strip() for f in flags.split(',')]\n        result = ExportEntry(name, prefix, suffix, flags)\n    return result\n\n\ndef get_cache_base(suffix=None):\n    \"\"\"\n    Return the default base location for distlib caches. If the directory does\n    not exist, it is created. Use the suffix provided for the base directory,\n    and default to '.distlib' if it isn't provided.\n\n    On Windows, if LOCALAPPDATA is defined in the environment, then it is\n    assumed to be a directory, and will be the parent directory of the result.\n    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home\n    directory - using os.expanduser('~') - will be the parent directory of\n    the result.\n\n    The result is just the directory '.distlib' in the parent directory as\n    determined above, or with the name specified with ``suffix``.\n    \"\"\"\n    if suffix is None:\n        suffix = '.distlib'\n    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:\n        result = os.path.expandvars('$localappdata')\n    else:\n        # Assume posix, or old Windows\n        result = os.path.expanduser('~')\n    # we use 'isdir' instead of 'exists', because we want to\n    # fail if there's a file with that name\n    if os.path.isdir(result):\n        usable = os.access(result, os.W_OK)\n        if not usable:\n            logger.warning('Directory exists but is not writable: %s', result)\n    else:\n        try:\n            os.makedirs(result)\n            usable = True\n        except OSError:\n            logger.warning('Unable to create %s', result, exc_info=True)\n            usable = False\n    if not usable:\n        result = tempfile.mkdtemp()\n        logger.warning('Default location unusable, using %s', result)\n    return os.path.join(result, suffix)\n\n\ndef path_to_cache_dir(path, use_abspath=True):\n    \"\"\"\n    Convert an absolute path to a directory name for use in a cache.\n\n    The algorithm used is:\n\n    #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.\n    #. Any occurrence of ``os.sep`` is replaced with ``'--'``.\n    #. ``'.cache'`` is appended.\n    \"\"\"\n    d, p = os.path.splitdrive(os.path.abspath(path) if use_abspath else path)\n    if d:\n        d = d.replace(':', '---')\n    p = p.replace(os.sep, '--')\n    return d + p + '.cache'\n\n\ndef ensure_slash(s):\n    if not s.endswith('/'):\n        return s + '/'\n    return s\n\n\ndef parse_credentials(netloc):\n    username = password = None\n    if '@' in netloc:\n        prefix, netloc = netloc.rsplit('@', 1)\n        if ':' not in prefix:\n            username = prefix\n        else:\n            username, password = prefix.split(':', 1)\n    if username:\n        username = unquote(username)\n    if password:\n        password = unquote(password)\n    return username, password, netloc\n\n\ndef get_process_umask():\n    result = os.umask(0o22)\n    os.umask(result)\n    return result\n\n\ndef is_string_sequence(seq):\n    result = True\n    i = None\n    for i, s in enumerate(seq):\n        if not isinstance(s, string_types):\n            result = False\n            break\n    assert i is not None\n    return result\n\n\nPROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'\n                                      '([a-z0-9_.+-]+)', re.I)\nPYTHON_VERSION = re.compile(r'-py(\\d\\.?\\d?)')\n\n\ndef split_filename(filename, project_name=None):\n    \"\"\"\n    Extract name, version, python version from a filename (no extension)\n\n    Return name, version, pyver or None\n    \"\"\"\n    result = None\n    pyver = None\n    filename = unquote(filename).replace(' ', '-')\n    m = PYTHON_VERSION.search(filename)\n    if m:\n        pyver = m.group(1)\n        filename = filename[:m.start()]\n    if project_name and len(filename) > len(project_name) + 1:\n        m = re.match(re.escape(project_name) + r'\\b', filename)\n        if m:\n            n = m.end()\n            result = filename[:n], filename[n + 1:], pyver\n    if result is None:\n        m = PROJECT_NAME_AND_VERSION.match(filename)\n        if m:\n            result = m.group(1), m.group(3), pyver\n    return result\n\n\n# Allow spaces in name because of legacy dists like \"Twisted Core\"\nNAME_VERSION_RE = re.compile(r'(?P<name>[\\w .-]+)\\s*'\n                             r'\\(\\s*(?P<ver>[^\\s)]+)\\)$')\n\n\ndef parse_name_and_version(p):\n    \"\"\"\n    A utility method used to get name and version from a string.\n\n    From e.g. a Provides-Dist value.\n\n    :param p: A value in a form 'foo (1.0)'\n    :return: The name and version as a tuple.\n    \"\"\"\n    m = NAME_VERSION_RE.match(p)\n    if not m:\n        raise DistlibException('Ill-formed name/version string: \\'%s\\'' % p)\n    d = m.groupdict()\n    return d['name'].strip().lower(), d['ver']\n\n\ndef get_extras(requested, available):\n    result = set()\n    requested = set(requested or [])\n    available = set(available or [])\n    if '*' in requested:\n        requested.remove('*')\n        result |= available\n    for r in requested:\n        if r == '-':\n            result.add(r)\n        elif r.startswith('-'):\n            unwanted = r[1:]\n            if unwanted not in available:\n                logger.warning('undeclared extra: %s' % unwanted)\n            if unwanted in result:\n                result.remove(unwanted)\n        else:\n            if r not in available:\n                logger.warning('undeclared extra: %s' % r)\n            result.add(r)\n    return result\n\n\n#\n# Extended metadata functionality\n#\n\n\ndef _get_external_data(url):\n    result = {}\n    try:\n        # urlopen might fail if it runs into redirections,\n        # because of Python issue #13696. Fixed in locators\n        # using a custom redirect handler.\n        resp = urlopen(url)\n        headers = resp.info()\n        ct = headers.get('Content-Type')\n        if not ct.startswith('application/json'):\n            logger.debug('Unexpected response for JSON request: %s', ct)\n        else:\n            reader = codecs.getreader('utf-8')(resp)\n            # data = reader.read().decode('utf-8')\n            # result = json.loads(data)\n            result = json.load(reader)\n    except Exception as e:\n        logger.exception('Failed to get external data for %s: %s', url, e)\n    return result\n\n\n_external_data_base_url = 'https://www.red-dove.com/pypi/projects/'\n\n\ndef get_project_data(name):\n    url = '%s/%s/project.json' % (name[0].upper(), name)\n    url = urljoin(_external_data_base_url, url)\n    result = _get_external_data(url)\n    return result\n\n\ndef get_package_data(name, version):\n    url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)\n    url = urljoin(_external_data_base_url, url)\n    return _get_external_data(url)\n\n\nclass Cache(object):\n    \"\"\"\n    A class implementing a cache for resources that need to live in the file system\n    e.g. shared libraries. This class was moved from resources to here because it\n    could be used by other modules, e.g. the wheel module.\n    \"\"\"\n\n    def __init__(self, base):\n        \"\"\"\n        Initialise an instance.\n\n        :param base: The base directory where the cache should be located.\n        \"\"\"\n        # we use 'isdir' instead of 'exists', because we want to\n        # fail if there's a file with that name\n        if not os.path.isdir(base):  # pragma: no cover\n            os.makedirs(base)\n        if (os.stat(base).st_mode & 0o77) != 0:\n            logger.warning('Directory \\'%s\\' is not private', base)\n        self.base = os.path.abspath(os.path.normpath(base))\n\n    def prefix_to_dir(self, prefix, use_abspath=True):\n        \"\"\"\n        Converts a resource prefix to a directory name in the cache.\n        \"\"\"\n        return path_to_cache_dir(prefix, use_abspath=use_abspath)\n\n    def clear(self):\n        \"\"\"\n        Clear the cache.\n        \"\"\"\n        not_removed = []\n        for fn in os.listdir(self.base):\n            fn = os.path.join(self.base, fn)\n            try:\n                if os.path.islink(fn) or os.path.isfile(fn):\n                    os.remove(fn)\n                elif os.path.isdir(fn):\n                    shutil.rmtree(fn)\n            except Exception:\n                not_removed.append(fn)\n        return not_removed\n\n\nclass EventMixin(object):\n    \"\"\"\n    A very simple publish/subscribe system.\n    \"\"\"\n\n    def __init__(self):\n        self._subscribers = {}\n\n    def add(self, event, subscriber, append=True):\n        \"\"\"\n        Add a subscriber for an event.\n\n        :param event: The name of an event.\n        :param subscriber: The subscriber to be added (and called when the\n                           event is published).\n        :param append: Whether to append or prepend the subscriber to an\n                       existing subscriber list for the event.\n        \"\"\"\n        subs = self._subscribers\n        if event not in subs:\n            subs[event] = deque([subscriber])\n        else:\n            sq = subs[event]\n            if append:\n                sq.append(subscriber)\n            else:\n                sq.appendleft(subscriber)\n\n    def remove(self, event, subscriber):\n        \"\"\"\n        Remove a subscriber for an event.\n\n        :param event: The name of an event.\n        :param subscriber: The subscriber to be removed.\n        \"\"\"\n        subs = self._subscribers\n        if event not in subs:\n            raise ValueError('No subscribers: %r' % event)\n        subs[event].remove(subscriber)\n\n    def get_subscribers(self, event):\n        \"\"\"\n        Return an iterator for the subscribers for an event.\n        :param event: The event to return subscribers for.\n        \"\"\"\n        return iter(self._subscribers.get(event, ()))\n\n    def publish(self, event, *args, **kwargs):\n        \"\"\"\n        Publish a event and return a list of values returned by its\n        subscribers.\n\n        :param event: The event to publish.\n        :param args: The positional arguments to pass to the event's\n                     subscribers.\n        :param kwargs: The keyword arguments to pass to the event's\n                       subscribers.\n        \"\"\"\n        result = []\n        for subscriber in self.get_subscribers(event):\n            try:\n                value = subscriber(event, *args, **kwargs)\n            except Exception:\n                logger.exception('Exception during event publication')\n                value = None\n            result.append(value)\n        logger.debug('publish %s: args = %s, kwargs = %s, result = %s', event, args, kwargs, result)\n        return result\n\n\n#\n# Simple sequencing\n#\nclass Sequencer(object):\n\n    def __init__(self):\n        self._preds = {}\n        self._succs = {}\n        self._nodes = set()  # nodes with no preds/succs\n\n    def add_node(self, node):\n        self._nodes.add(node)\n\n    def remove_node(self, node, edges=False):\n        if node in self._nodes:\n            self._nodes.remove(node)\n        if edges:\n            for p in set(self._preds.get(node, ())):\n                self.remove(p, node)\n            for s in set(self._succs.get(node, ())):\n                self.remove(node, s)\n            # Remove empties\n            for k, v in list(self._preds.items()):\n                if not v:\n                    del self._preds[k]\n            for k, v in list(self._succs.items()):\n                if not v:\n                    del self._succs[k]\n\n    def add(self, pred, succ):\n        assert pred != succ\n        self._preds.setdefault(succ, set()).add(pred)\n        self._succs.setdefault(pred, set()).add(succ)\n\n    def remove(self, pred, succ):\n        assert pred != succ\n        try:\n            preds = self._preds[succ]\n            succs = self._succs[pred]\n        except KeyError:  # pragma: no cover\n            raise ValueError('%r not a successor of anything' % succ)\n        try:\n            preds.remove(pred)\n            succs.remove(succ)\n        except KeyError:  # pragma: no cover\n            raise ValueError('%r not a successor of %r' % (succ, pred))\n\n    def is_step(self, step):\n        return (step in self._preds or step in self._succs or step in self._nodes)\n\n    def get_steps(self, final):\n        if not self.is_step(final):\n            raise ValueError('Unknown: %r' % final)\n        result = []\n        todo = []\n        seen = set()\n        todo.append(final)\n        while todo:\n            step = todo.pop(0)\n            if step in seen:\n                # if a step was already seen,\n                # move it to the end (so it will appear earlier\n                # when reversed on return) ... but not for the\n                # final step, as that would be confusing for\n                # users\n                if step != final:\n                    result.remove(step)\n                    result.append(step)\n            else:\n                seen.add(step)\n                result.append(step)\n                preds = self._preds.get(step, ())\n                todo.extend(preds)\n        return reversed(result)\n\n    @property\n    def strong_connections(self):\n        # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm\n        index_counter = [0]\n        stack = []\n        lowlinks = {}\n        index = {}\n        result = []\n\n        graph = self._succs\n\n        def strongconnect(node):\n            # set the depth index for this node to the smallest unused index\n            index[node] = index_counter[0]\n            lowlinks[node] = index_counter[0]\n            index_counter[0] += 1\n            stack.append(node)\n\n            # Consider successors\n            try:\n                successors = graph[node]\n            except Exception:\n                successors = []\n            for successor in successors:\n                if successor not in lowlinks:\n                    # Successor has not yet been visited\n                    strongconnect(successor)\n                    lowlinks[node] = min(lowlinks[node], lowlinks[successor])\n                elif successor in stack:\n                    # the successor is in the stack and hence in the current\n                    # strongly connected component (SCC)\n                    lowlinks[node] = min(lowlinks[node], index[successor])\n\n            # If `node` is a root node, pop the stack and generate an SCC\n            if lowlinks[node] == index[node]:\n                connected_component = []\n\n                while True:\n                    successor = stack.pop()\n                    connected_component.append(successor)\n                    if successor == node:\n                        break\n                component = tuple(connected_component)\n                # storing the result\n                result.append(component)\n\n        for node in graph:\n            if node not in lowlinks:\n                strongconnect(node)\n\n        return result\n\n    @property\n    def dot(self):\n        result = ['digraph G {']\n        for succ in self._preds:\n            preds = self._preds[succ]\n            for pred in preds:\n                result.append('  %s -> %s;' % (pred, succ))\n        for node in self._nodes:\n            result.append('  %s;' % node)\n        result.append('}')\n        return '\\n'.join(result)\n\n\n#\n# Unarchiving functionality for zip, tar, tgz, tbz, whl\n#\n\nARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz', '.whl')\n\n\ndef unarchive(archive_filename, dest_dir, format=None, check=True):\n\n    def check_path(path):\n        if not isinstance(path, text_type):\n            path = path.decode('utf-8')\n        p = os.path.abspath(os.path.join(dest_dir, path))\n        if not p.startswith(dest_dir) or p[plen] != os.sep:\n            raise ValueError('path outside destination: %r' % p)\n\n    dest_dir = os.path.abspath(dest_dir)\n    plen = len(dest_dir)\n    archive = None\n    if format is None:\n        if archive_filename.endswith(('.zip', '.whl')):\n            format = 'zip'\n        elif archive_filename.endswith(('.tar.gz', '.tgz')):\n            format = 'tgz'\n            mode = 'r:gz'\n        elif archive_filename.endswith(('.tar.bz2', '.tbz')):\n            format = 'tbz'\n            mode = 'r:bz2'\n        elif archive_filename.endswith('.tar'):\n            format = 'tar'\n            mode = 'r'\n        else:  # pragma: no cover\n            raise ValueError('Unknown format for %r' % archive_filename)\n    try:\n        if format == 'zip':\n            archive = ZipFile(archive_filename, 'r')\n            if check:\n                names = archive.namelist()\n                for name in names:\n                    check_path(name)\n        else:\n            archive = tarfile.open(archive_filename, mode)\n            if check:\n                names = archive.getnames()\n                for name in names:\n                    check_path(name)\n        if format != 'zip' and sys.version_info[0] < 3:\n            # See Python issue 17153. If the dest path contains Unicode,\n            # tarfile extraction fails on Python 2.x if a member path name\n            # contains non-ASCII characters - it leads to an implicit\n            # bytes -> unicode conversion using ASCII to decode.\n            for tarinfo in archive.getmembers():\n                if not isinstance(tarinfo.name, text_type):\n                    tarinfo.name = tarinfo.name.decode('utf-8')\n\n        # Limit extraction of dangerous items, if this Python\n        # allows it easily. If not, just trust the input.\n        # See: https://docs.python.org/3/library/tarfile.html#extraction-filters\n        def extraction_filter(member, path):\n            \"\"\"Run tarfile.tar_filter, but raise the expected ValueError\"\"\"\n            # This is only called if the current Python has tarfile filters\n            try:\n                return tarfile.tar_filter(member, path)\n            except tarfile.FilterError as exc:\n                raise ValueError(str(exc))\n\n        archive.extraction_filter = extraction_filter\n\n        archive.extractall(dest_dir)\n\n    finally:\n        if archive:\n            archive.close()\n\n\ndef zip_dir(directory):\n    \"\"\"zip a directory tree into a BytesIO object\"\"\"\n    result = io.BytesIO()\n    dlen = len(directory)\n    with ZipFile(result, \"w\") as zf:\n        for root, dirs, files in os.walk(directory):\n            for name in files:\n                full = os.path.join(root, name)\n                rel = root[dlen:]\n                dest = os.path.join(rel, name)\n                zf.write(full, dest)\n    return result\n\n\n#\n# Simple progress bar\n#\n\nUNITS = ('', 'K', 'M', 'G', 'T', 'P')\n\n\nclass Progress(object):\n    unknown = 'UNKNOWN'\n\n    def __init__(self, minval=0, maxval=100):\n        assert maxval is None or maxval >= minval\n        self.min = self.cur = minval\n        self.max = maxval\n        self.started = None\n        self.elapsed = 0\n        self.done = False\n\n    def update(self, curval):\n        assert self.min <= curval\n        assert self.max is None or curval <= self.max\n        self.cur = curval\n        now = time.time()\n        if self.started is None:\n            self.started = now\n        else:\n            self.elapsed = now - self.started\n\n    def increment(self, incr):\n        assert incr >= 0\n        self.update(self.cur + incr)\n\n    def start(self):\n        self.update(self.min)\n        return self\n\n    def stop(self):\n        if self.max is not None:\n            self.update(self.max)\n        self.done = True\n\n    @property\n    def maximum(self):\n        return self.unknown if self.max is None else self.max\n\n    @property\n    def percentage(self):\n        if self.done:\n            result = '100 %'\n        elif self.max is None:\n            result = ' ?? %'\n        else:\n            v = 100.0 * (self.cur - self.min) / (self.max - self.min)\n            result = '%3d %%' % v\n        return result\n\n    def format_duration(self, duration):\n        if (duration <= 0) and self.max is None or self.cur == self.min:\n            result = '??:??:??'\n        # elif duration < 1:\n        #     result = '--:--:--'\n        else:\n            result = time.strftime('%H:%M:%S', time.gmtime(duration))\n        return result\n\n    @property\n    def ETA(self):\n        if self.done:\n            prefix = 'Done'\n            t = self.elapsed\n            # import pdb; pdb.set_trace()\n        else:\n            prefix = 'ETA '\n            if self.max is None:\n                t = -1\n            elif self.elapsed == 0 or (self.cur == self.min):\n                t = 0\n            else:\n                # import pdb; pdb.set_trace()\n                t = float(self.max - self.min)\n                t /= self.cur - self.min\n                t = (t - 1) * self.elapsed\n        return '%s: %s' % (prefix, self.format_duration(t))\n\n    @property\n    def speed(self):\n        if self.elapsed == 0:\n            result = 0.0\n        else:\n            result = (self.cur - self.min) / self.elapsed\n        for unit in UNITS:\n            if result < 1000:\n                break\n            result /= 1000.0\n        return '%d %sB/s' % (result, unit)\n\n\n#\n# Glob functionality\n#\n\nRICH_GLOB = re.compile(r'\\{([^}]*)\\}')\n_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\\\,{]\\*\\*|\\*\\*[^/\\\\,}]')\n_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\\}|\\{[^}]*$')\n\n\ndef iglob(path_glob):\n    \"\"\"Extended globbing function that supports ** and {opt1,opt2,opt3}.\"\"\"\n    if _CHECK_RECURSIVE_GLOB.search(path_glob):\n        msg = \"\"\"invalid glob %r: recursive glob \"**\" must be used alone\"\"\"\n        raise ValueError(msg % path_glob)\n    if _CHECK_MISMATCH_SET.search(path_glob):\n        msg = \"\"\"invalid glob %r: mismatching set marker '{' or '}'\"\"\"\n        raise ValueError(msg % path_glob)\n    return _iglob(path_glob)\n\n\ndef _iglob(path_glob):\n    rich_path_glob = RICH_GLOB.split(path_glob, 1)\n    if len(rich_path_glob) > 1:\n        assert len(rich_path_glob) == 3, rich_path_glob\n        prefix, set, suffix = rich_path_glob\n        for item in set.split(','):\n            for path in _iglob(''.join((prefix, item, suffix))):\n                yield path\n    else:\n        if '**' not in path_glob:\n            for item in std_iglob(path_glob):\n                yield item\n        else:\n            prefix, radical = path_glob.split('**', 1)\n            if prefix == '':\n                prefix = '.'\n            if radical == '':\n                radical = '*'\n            else:\n                # we support both\n                radical = radical.lstrip('/')\n                radical = radical.lstrip('\\\\')\n            for path, dir, files in os.walk(prefix):\n                path = os.path.normpath(path)\n                for fn in _iglob(os.path.join(path, radical)):\n                    yield fn\n\n\nif ssl:\n    from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, CertificateError)\n\n    #\n    # HTTPSConnection which verifies certificates/matches domains\n    #\n\n    class HTTPSConnection(httplib.HTTPSConnection):\n        ca_certs = None  # set this to the path to the certs file (.pem)\n        check_domain = True  # only used if ca_certs is not None\n\n        # noinspection PyPropertyAccess\n        def connect(self):\n            sock = socket.create_connection((self.host, self.port), self.timeout)\n            if getattr(self, '_tunnel_host', False):\n                self.sock = sock\n                self._tunnel()\n\n            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n            if hasattr(ssl, 'OP_NO_SSLv2'):\n                context.options |= ssl.OP_NO_SSLv2\n            if getattr(self, 'cert_file', None):\n                context.load_cert_chain(self.cert_file, self.key_file)\n            kwargs = {}\n            if self.ca_certs:\n                context.verify_mode = ssl.CERT_REQUIRED\n                context.load_verify_locations(cafile=self.ca_certs)\n                if getattr(ssl, 'HAS_SNI', False):\n                    kwargs['server_hostname'] = self.host\n\n            self.sock = context.wrap_socket(sock, **kwargs)\n            if self.ca_certs and self.check_domain:\n                try:\n                    match_hostname(self.sock.getpeercert(), self.host)\n                    logger.debug('Host verified: %s', self.host)\n                except CertificateError:  # pragma: no cover\n                    self.sock.shutdown(socket.SHUT_RDWR)\n                    self.sock.close()\n                    raise\n\n    class HTTPSHandler(BaseHTTPSHandler):\n\n        def __init__(self, ca_certs, check_domain=True):\n            BaseHTTPSHandler.__init__(self)\n            self.ca_certs = ca_certs\n            self.check_domain = check_domain\n\n        def _conn_maker(self, *args, **kwargs):\n            \"\"\"\n            This is called to create a connection instance. Normally you'd\n            pass a connection class to do_open, but it doesn't actually check for\n            a class, and just expects a callable. As long as we behave just as a\n            constructor would have, we should be OK. If it ever changes so that\n            we *must* pass a class, we'll create an UnsafeHTTPSConnection class\n            which just sets check_domain to False in the class definition, and\n            choose which one to pass to do_open.\n            \"\"\"\n            result = HTTPSConnection(*args, **kwargs)\n            if self.ca_certs:\n                result.ca_certs = self.ca_certs\n                result.check_domain = self.check_domain\n            return result\n\n        def https_open(self, req):\n            try:\n                return self.do_open(self._conn_maker, req)\n            except URLError as e:\n                if 'certificate verify failed' in str(e.reason):\n                    raise CertificateError('Unable to verify server certificate '\n                                           'for %s' % req.host)\n                else:\n                    raise\n\n    #\n    # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-\n    # Middle proxy using HTTP listens on port 443, or an index mistakenly serves\n    # HTML containing a http://xyz link when it should be https://xyz),\n    # you can use the following handler class, which does not allow HTTP traffic.\n    #\n    # It works by inheriting from HTTPHandler - so build_opener won't add a\n    # handler for HTTP itself.\n    #\n    class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):\n\n        def http_open(self, req):\n            raise URLError('Unexpected HTTP request on what should be a secure '\n                           'connection: %s' % req)\n\n\n#\n# XML-RPC with timeouts\n#\nclass Transport(xmlrpclib.Transport):\n\n    def __init__(self, timeout, use_datetime=0):\n        self.timeout = timeout\n        xmlrpclib.Transport.__init__(self, use_datetime)\n\n    def make_connection(self, host):\n        h, eh, x509 = self.get_host_info(host)\n        if not self._connection or host != self._connection[0]:\n            self._extra_headers = eh\n            self._connection = host, httplib.HTTPConnection(h)\n        return self._connection[1]\n\n\nif ssl:\n\n    class SafeTransport(xmlrpclib.SafeTransport):\n\n        def __init__(self, timeout, use_datetime=0):\n            self.timeout = timeout\n            xmlrpclib.SafeTransport.__init__(self, use_datetime)\n\n        def make_connection(self, host):\n            h, eh, kwargs = self.get_host_info(host)\n            if not kwargs:\n                kwargs = {}\n            kwargs['timeout'] = self.timeout\n            if not self._connection or host != self._connection[0]:\n                self._extra_headers = eh\n                self._connection = host, httplib.HTTPSConnection(h, None, **kwargs)\n            return self._connection[1]\n\n\nclass ServerProxy(xmlrpclib.ServerProxy):\n\n    def __init__(self, uri, **kwargs):\n        self.timeout = timeout = kwargs.pop('timeout', None)\n        # The above classes only come into play if a timeout\n        # is specified\n        if timeout is not None:\n            # scheme = splittype(uri)  # deprecated as of Python 3.8\n            scheme = urlparse(uri)[0]\n            use_datetime = kwargs.get('use_datetime', 0)\n            if scheme == 'https':\n                tcls = SafeTransport\n            else:\n                tcls = Transport\n            kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)\n            self.transport = t\n        xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)\n\n\n#\n# CSV functionality. This is provided because on 2.x, the csv module can't\n# handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.\n#\n\n\ndef _csv_open(fn, mode, **kwargs):\n    if sys.version_info[0] < 3:\n        mode += 'b'\n    else:\n        kwargs['newline'] = ''\n        # Python 3 determines encoding from locale. Force 'utf-8'\n        # file encoding to match other forced utf-8 encoding\n        kwargs['encoding'] = 'utf-8'\n    return open(fn, mode, **kwargs)\n\n\nclass CSVBase(object):\n    defaults = {\n        'delimiter': str(','),  # The strs are used because we need native\n        'quotechar': str('\"'),  # str in the csv API (2.x won't take\n        'lineterminator': str('\\n')  # Unicode)\n    }\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *exc_info):\n        self.stream.close()\n\n\nclass CSVReader(CSVBase):\n\n    def __init__(self, **kwargs):\n        if 'stream' in kwargs:\n            stream = kwargs['stream']\n            if sys.version_info[0] >= 3:\n                # needs to be a text stream\n                stream = codecs.getreader('utf-8')(stream)\n            self.stream = stream\n        else:\n            self.stream = _csv_open(kwargs['path'], 'r')\n        self.reader = csv.reader(self.stream, **self.defaults)\n\n    def __iter__(self):\n        return self\n\n    def next(self):\n        result = next(self.reader)\n        if sys.version_info[0] < 3:\n            for i, item in enumerate(result):\n                if not isinstance(item, text_type):\n                    result[i] = item.decode('utf-8')\n        return result\n\n    __next__ = next\n\n\nclass CSVWriter(CSVBase):\n\n    def __init__(self, fn, **kwargs):\n        self.stream = _csv_open(fn, 'w')\n        self.writer = csv.writer(self.stream, **self.defaults)\n\n    def writerow(self, row):\n        if sys.version_info[0] < 3:\n            r = []\n            for item in row:\n                if isinstance(item, text_type):\n                    item = item.encode('utf-8')\n                r.append(item)\n            row = r\n        self.writer.writerow(row)\n\n\n#\n#   Configurator functionality\n#\n\n\nclass Configurator(BaseConfigurator):\n\n    value_converters = dict(BaseConfigurator.value_converters)\n    value_converters['inc'] = 'inc_convert'\n\n    def __init__(self, config, base=None):\n        super(Configurator, self).__init__(config)\n        self.base = base or os.getcwd()\n\n    def configure_custom(self, config):\n\n        def convert(o):\n            if isinstance(o, (list, tuple)):\n                result = type(o)([convert(i) for i in o])\n            elif isinstance(o, dict):\n                if '()' in o:\n                    result = self.configure_custom(o)\n                else:\n                    result = {}\n                    for k in o:\n                        result[k] = convert(o[k])\n            else:\n                result = self.convert(o)\n            return result\n\n        c = config.pop('()')\n        if not callable(c):\n            c = self.resolve(c)\n        props = config.pop('.', None)\n        # Check for valid identifiers\n        args = config.pop('[]', ())\n        if args:\n            args = tuple([convert(o) for o in args])\n        items = [(k, convert(config[k])) for k in config if valid_ident(k)]\n        kwargs = dict(items)\n        result = c(*args, **kwargs)\n        if props:\n            for n, v in props.items():\n                setattr(result, n, convert(v))\n        return result\n\n    def __getitem__(self, key):\n        result = self.config[key]\n        if isinstance(result, dict) and '()' in result:\n            self.config[key] = result = self.configure_custom(result)\n        return result\n\n    def inc_convert(self, value):\n        \"\"\"Default converter for the inc:// protocol.\"\"\"\n        if not os.path.isabs(value):\n            value = os.path.join(self.base, value)\n        with codecs.open(value, 'r', encoding='utf-8') as f:\n            result = json.load(f)\n        return result\n\n\nclass SubprocessMixin(object):\n    \"\"\"\n    Mixin for running subprocesses and capturing their output\n    \"\"\"\n\n    def __init__(self, verbose=False, progress=None):\n        self.verbose = verbose\n        self.progress = progress\n\n    def reader(self, stream, context):\n        \"\"\"\n        Read lines from a subprocess' output stream and either pass to a progress\n        callable (if specified) or write progress information to sys.stderr.\n        \"\"\"\n        progress = self.progress\n        verbose = self.verbose\n        while True:\n            s = stream.readline()\n            if not s:\n                break\n            if progress is not None:\n                progress(s, context)\n            else:\n                if not verbose:\n                    sys.stderr.write('.')\n                else:\n                    sys.stderr.write(s.decode('utf-8'))\n                sys.stderr.flush()\n        stream.close()\n\n    def run_command(self, cmd, **kwargs):\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)\n        t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))\n        t1.start()\n        t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))\n        t2.start()\n        p.wait()\n        t1.join()\n        t2.join()\n        if self.progress is not None:\n            self.progress('done.', 'main')\n        elif self.verbose:\n            sys.stderr.write('done.\\n')\n        return p\n\n\ndef normalize_name(name):\n    \"\"\"Normalize a python package name a la PEP 503\"\"\"\n    # https://www.python.org/dev/peps/pep-0503/#normalized-names\n    return re.sub('[-_.]+', '-', name).lower()\n\n\n# def _get_pypirc_command():\n# \"\"\"\n# Get the distutils command for interacting with PyPI configurations.\n# :return: the command.\n# \"\"\"\n# from distutils.core import Distribution\n# from distutils.config import PyPIRCCommand\n# d = Distribution()\n# return PyPIRCCommand(d)\n\n\nclass PyPIRCFile(object):\n\n    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'\n    DEFAULT_REALM = 'pypi'\n\n    def __init__(self, fn=None, url=None):\n        if fn is None:\n            fn = os.path.join(os.path.expanduser('~'), '.pypirc')\n        self.filename = fn\n        self.url = url\n\n    def read(self):\n        result = {}\n\n        if os.path.exists(self.filename):\n            repository = self.url or self.DEFAULT_REPOSITORY\n\n            config = configparser.RawConfigParser()\n            config.read(self.filename)\n            sections = config.sections()\n            if 'distutils' in sections:\n                # let's get the list of servers\n                index_servers = config.get('distutils', 'index-servers')\n                _servers = [server.strip() for server in index_servers.split('\\n') if server.strip() != '']\n                if _servers == []:\n                    # nothing set, let's try to get the default pypi\n                    if 'pypi' in sections:\n                        _servers = ['pypi']\n                else:\n                    for server in _servers:\n                        result = {'server': server}\n                        result['username'] = config.get(server, 'username')\n\n                        # optional params\n                        for key, default in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM),\n                                             ('password', None)):\n                            if config.has_option(server, key):\n                                result[key] = config.get(server, key)\n                            else:\n                                result[key] = default\n\n                        # work around people having \"repository\" for the \"pypi\"\n                        # section of their config set to the HTTP (rather than\n                        # HTTPS) URL\n                        if (server == 'pypi' and repository in (self.DEFAULT_REPOSITORY, 'pypi')):\n                            result['repository'] = self.DEFAULT_REPOSITORY\n                        elif (result['server'] != repository and result['repository'] != repository):\n                            result = {}\n            elif 'server-login' in sections:\n                # old format\n                server = 'server-login'\n                if config.has_option(server, 'repository'):\n                    repository = config.get(server, 'repository')\n                else:\n                    repository = self.DEFAULT_REPOSITORY\n                result = {\n                    'username': config.get(server, 'username'),\n                    'password': config.get(server, 'password'),\n                    'repository': repository,\n                    'server': server,\n                    'realm': self.DEFAULT_REALM\n                }\n        return result\n\n    def update(self, username, password):\n        # import pdb; pdb.set_trace()\n        config = configparser.RawConfigParser()\n        fn = self.filename\n        config.read(fn)\n        if not config.has_section('pypi'):\n            config.add_section('pypi')\n        config.set('pypi', 'username', username)\n        config.set('pypi', 'password', password)\n        with open(fn, 'w') as f:\n            config.write(f)\n\n\ndef _load_pypirc(index):\n    \"\"\"\n    Read the PyPI access configuration as supported by distutils.\n    \"\"\"\n    return PyPIRCFile(url=index.url).read()\n\n\ndef _store_pypirc(index):\n    PyPIRCFile().update(index.username, index.password)\n\n\n#\n# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor\n# tweaks\n#\n\n\ndef get_host_platform():\n    \"\"\"Return a string that identifies the current platform.  This is used mainly to\n    distinguish platform-specific build directories and platform-specific built\n    distributions.  Typically includes the OS name and version and the\n    architecture (as supplied by 'os.uname()'), although the exact information\n    included depends on the OS; eg. on Linux, the kernel version isn't\n    particularly important.\n\n    Examples of returned values:\n       linux-i586\n       linux-alpha (?)\n       solaris-2.6-sun4u\n\n    Windows will return one of:\n       win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)\n       win32 (all others - specifically, sys.platform is returned)\n\n    For other non-POSIX platforms, currently just returns 'sys.platform'.\n\n    \"\"\"\n    if os.name == 'nt':\n        if 'amd64' in sys.version.lower():\n            return 'win-amd64'\n        if '(arm)' in sys.version.lower():\n            return 'win-arm32'\n        if '(arm64)' in sys.version.lower():\n            return 'win-arm64'\n        return sys.platform\n\n    # Set for cross builds explicitly\n    if \"_PYTHON_HOST_PLATFORM\" in os.environ:\n        return os.environ[\"_PYTHON_HOST_PLATFORM\"]\n\n    if os.name != 'posix' or not hasattr(os, 'uname'):\n        # XXX what about the architecture? NT is Intel or Alpha,\n        # Mac OS is M68k or PPC, etc.\n        return sys.platform\n\n    # Try to distinguish various flavours of Unix\n\n    (osname, host, release, version, machine) = os.uname()\n\n    # Convert the OS name to lowercase, remove '/' characters, and translate\n    # spaces (for \"Power Macintosh\")\n    osname = osname.lower().replace('/', '')\n    machine = machine.replace(' ', '_').replace('/', '-')\n\n    if osname[:5] == 'linux':\n        # At least on Linux/Intel, 'machine' is the processor --\n        # i386, etc.\n        # XXX what about Alpha, SPARC, etc?\n        return \"%s-%s\" % (osname, machine)\n\n    elif osname[:5] == 'sunos':\n        if release[0] >= '5':  # SunOS 5 == Solaris 2\n            osname = 'solaris'\n            release = '%d.%s' % (int(release[0]) - 3, release[2:])\n            # We can't use 'platform.architecture()[0]' because a\n            # bootstrap problem. We use a dict to get an error\n            # if some suspicious happens.\n            bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}\n            machine += '.%s' % bitness[sys.maxsize]\n        # fall through to standard osname-release-machine representation\n    elif osname[:3] == 'aix':\n        from _aix_support import aix_platform\n        return aix_platform()\n    elif osname[:6] == 'cygwin':\n        osname = 'cygwin'\n        rel_re = re.compile(r'[\\d.]+', re.ASCII)\n        m = rel_re.match(release)\n        if m:\n            release = m.group()\n    elif osname[:6] == 'darwin':\n        import _osx_support\n        try:\n            from distutils import sysconfig\n        except ImportError:\n            import sysconfig\n        osname, release, machine = _osx_support.get_platform_osx(sysconfig.get_config_vars(), osname, release, machine)\n\n    return '%s-%s-%s' % (osname, release, machine)\n\n\n_TARGET_TO_PLAT = {\n    'x86': 'win32',\n    'x64': 'win-amd64',\n    'arm': 'win-arm32',\n}\n\n\ndef get_platform():\n    if os.name != 'nt':\n        return get_host_platform()\n    cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')\n    if cross_compilation_target not in _TARGET_TO_PLAT:\n        return get_host_platform()\n    return _TARGET_TO_PLAT[cross_compilation_target]\n"
  },
  {
    "path": "src/pip/_vendor/distlib.pyi",
    "content": "from distlib import *"
  },
  {
    "path": "src/pip/_vendor/distro/LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "src/pip/_vendor/distro/__init__.py",
    "content": "from .distro import (\n    NORMALIZED_DISTRO_ID,\n    NORMALIZED_LSB_ID,\n    NORMALIZED_OS_ID,\n    LinuxDistribution,\n    __version__,\n    build_number,\n    codename,\n    distro_release_attr,\n    distro_release_info,\n    id,\n    info,\n    like,\n    linux_distribution,\n    lsb_release_attr,\n    lsb_release_info,\n    major_version,\n    minor_version,\n    name,\n    os_release_attr,\n    os_release_info,\n    uname_attr,\n    uname_info,\n    version,\n    version_parts,\n)\n\n__all__ = [\n    \"NORMALIZED_DISTRO_ID\",\n    \"NORMALIZED_LSB_ID\",\n    \"NORMALIZED_OS_ID\",\n    \"LinuxDistribution\",\n    \"build_number\",\n    \"codename\",\n    \"distro_release_attr\",\n    \"distro_release_info\",\n    \"id\",\n    \"info\",\n    \"like\",\n    \"linux_distribution\",\n    \"lsb_release_attr\",\n    \"lsb_release_info\",\n    \"major_version\",\n    \"minor_version\",\n    \"name\",\n    \"os_release_attr\",\n    \"os_release_info\",\n    \"uname_attr\",\n    \"uname_info\",\n    \"version\",\n    \"version_parts\",\n]\n\n__version__ = __version__\n"
  },
  {
    "path": "src/pip/_vendor/distro/__main__.py",
    "content": "from .distro import main\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/distro/distro.py",
    "content": "#!/usr/bin/env python\n# Copyright 2015-2021 Nir Cohen\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThe ``distro`` package (``distro`` stands for Linux Distribution) provides\ninformation about the Linux distribution it runs on, such as a reliable\nmachine-readable distro ID, or version information.\n\nIt is the recommended replacement for Python's original\n:py:func:`platform.linux_distribution` function, but it provides much more\nfunctionality. An alternative implementation became necessary because Python\n3.5 deprecated this function, and Python 3.8 removed it altogether. Its\npredecessor function :py:func:`platform.dist` was already deprecated since\nPython 2.6 and removed in Python 3.8. Still, there are many cases in which\naccess to OS distribution information is needed. See `Python issue 1322\n<https://bugs.python.org/issue1322>`_ for more information.\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport re\nimport shlex\nimport subprocess\nimport sys\nimport warnings\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    Optional,\n    Sequence,\n    TextIO,\n    Tuple,\n    Type,\n)\n\ntry:\n    from typing import TypedDict\nexcept ImportError:\n    # Python 3.7\n    TypedDict = dict\n\n__version__ = \"1.9.0\"\n\n\nclass VersionDict(TypedDict):\n    major: str\n    minor: str\n    build_number: str\n\n\nclass InfoDict(TypedDict):\n    id: str\n    version: str\n    version_parts: VersionDict\n    like: str\n    codename: str\n\n\n_UNIXCONFDIR = os.environ.get(\"UNIXCONFDIR\", \"/etc\")\n_UNIXUSRLIBDIR = os.environ.get(\"UNIXUSRLIBDIR\", \"/usr/lib\")\n_OS_RELEASE_BASENAME = \"os-release\"\n\n#: Translation table for normalizing the \"ID\" attribute defined in os-release\n#: files, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as defined in the os-release file, translated to lower case,\n#:   with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_OS_ID = {\n    \"ol\": \"oracle\",  # Oracle Linux\n    \"opensuse-leap\": \"opensuse\",  # Newer versions of OpenSuSE report as opensuse-leap\n}\n\n#: Translation table for normalizing the \"Distributor ID\" attribute returned by\n#: the lsb_release command, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as returned by the lsb_release command, translated to lower\n#:   case, with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_LSB_ID = {\n    \"enterpriseenterpriseas\": \"oracle\",  # Oracle Enterprise Linux 4\n    \"enterpriseenterpriseserver\": \"oracle\",  # Oracle Linux 5\n    \"redhatenterpriseworkstation\": \"rhel\",  # RHEL 6, 7 Workstation\n    \"redhatenterpriseserver\": \"rhel\",  # RHEL 6, 7 Server\n    \"redhatenterprisecomputenode\": \"rhel\",  # RHEL 6 ComputeNode\n}\n\n#: Translation table for normalizing the distro ID derived from the file name\n#: of distro release files, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as derived from the file name of a distro release file,\n#:   translated to lower case, with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_DISTRO_ID = {\n    \"redhat\": \"rhel\",  # RHEL 6.x, 7.x\n}\n\n# Pattern for content of distro release file (reversed)\n_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(\n    r\"(?:[^)]*\\)(.*)\\()? *(?:STL )?([\\d.+\\-a-z]*\\d) *(?:esaeler *)?(.+)\"\n)\n\n# Pattern for base file name of distro release file\n_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r\"(\\w+)[-_](release|version)$\")\n\n# Base file names to be looked up for if _UNIXCONFDIR is not readable.\n_DISTRO_RELEASE_BASENAMES = [\n    \"SuSE-release\",\n    \"altlinux-release\",\n    \"arch-release\",\n    \"base-release\",\n    \"centos-release\",\n    \"fedora-release\",\n    \"gentoo-release\",\n    \"mageia-release\",\n    \"mandrake-release\",\n    \"mandriva-release\",\n    \"mandrivalinux-release\",\n    \"manjaro-release\",\n    \"oracle-release\",\n    \"redhat-release\",\n    \"rocky-release\",\n    \"sl-release\",\n    \"slackware-version\",\n]\n\n# Base file names to be ignored when searching for distro release file\n_DISTRO_RELEASE_IGNORE_BASENAMES = (\n    \"debian_version\",\n    \"lsb-release\",\n    \"oem-release\",\n    _OS_RELEASE_BASENAME,\n    \"system-release\",\n    \"plesk-release\",\n    \"iredmail-release\",\n    \"board-release\",\n    \"ec2_version\",\n)\n\n\ndef linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:\n    \"\"\"\n    .. deprecated:: 1.6.0\n\n        :func:`distro.linux_distribution()` is deprecated. It should only be\n        used as a compatibility shim with Python's\n        :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,\n        :func:`distro.version` and :func:`distro.name` instead.\n\n    Return information about the current OS distribution as a tuple\n    ``(id_name, version, codename)`` with items as follows:\n\n    * ``id_name``:  If *full_distribution_name* is false, the result of\n      :func:`distro.id`. Otherwise, the result of :func:`distro.name`.\n\n    * ``version``:  The result of :func:`distro.version`.\n\n    * ``codename``:  The extra item (usually in parentheses) after the\n      os-release version number, or the result of :func:`distro.codename`.\n\n    The interface of this function is compatible with the original\n    :py:func:`platform.linux_distribution` function, supporting a subset of\n    its parameters.\n\n    The data it returns may not exactly be the same, because it uses more data\n    sources than the original function, and that may lead to different data if\n    the OS distribution is not consistent across multiple data sources it\n    provides (there are indeed such distributions ...).\n\n    Another reason for differences is the fact that the :func:`distro.id`\n    method normalizes the distro ID string to a reliable machine-readable value\n    for a number of popular OS distributions.\n    \"\"\"\n    warnings.warn(\n        \"distro.linux_distribution() is deprecated. It should only be used as a \"\n        \"compatibility shim with Python's platform.linux_distribution(). Please use \"\n        \"distro.id(), distro.version() and distro.name() instead.\",\n        DeprecationWarning,\n        stacklevel=2,\n    )\n    return _distro.linux_distribution(full_distribution_name)\n\n\ndef id() -> str:\n    \"\"\"\n    Return the distro ID of the current distribution, as a\n    machine-readable string.\n\n    For a number of OS distributions, the returned distro ID value is\n    *reliable*, in the sense that it is documented and that it does not change\n    across releases of the distribution.\n\n    This package maintains the following reliable distro ID values:\n\n    ==============  =========================================\n    Distro ID       Distribution\n    ==============  =========================================\n    \"ubuntu\"        Ubuntu\n    \"debian\"        Debian\n    \"rhel\"          RedHat Enterprise Linux\n    \"centos\"        CentOS\n    \"fedora\"        Fedora\n    \"sles\"          SUSE Linux Enterprise Server\n    \"opensuse\"      openSUSE\n    \"amzn\"          Amazon Linux\n    \"arch\"          Arch Linux\n    \"buildroot\"     Buildroot\n    \"cloudlinux\"    CloudLinux OS\n    \"exherbo\"       Exherbo Linux\n    \"gentoo\"        GenToo Linux\n    \"ibm_powerkvm\"  IBM PowerKVM\n    \"kvmibm\"        KVM for IBM z Systems\n    \"linuxmint\"     Linux Mint\n    \"mageia\"        Mageia\n    \"mandriva\"      Mandriva Linux\n    \"parallels\"     Parallels\n    \"pidora\"        Pidora\n    \"raspbian\"      Raspbian\n    \"oracle\"        Oracle Linux (and Oracle Enterprise Linux)\n    \"scientific\"    Scientific Linux\n    \"slackware\"     Slackware\n    \"xenserver\"     XenServer\n    \"openbsd\"       OpenBSD\n    \"netbsd\"        NetBSD\n    \"freebsd\"       FreeBSD\n    \"midnightbsd\"   MidnightBSD\n    \"rocky\"         Rocky Linux\n    \"aix\"           AIX\n    \"guix\"          Guix System\n    \"altlinux\"      ALT Linux\n    ==============  =========================================\n\n    If you have a need to get distros for reliable IDs added into this set,\n    or if you find that the :func:`distro.id` function returns a different\n    distro ID for one of the listed distros, please create an issue in the\n    `distro issue tracker`_.\n\n    **Lookup hierarchy and transformations:**\n\n    First, the ID is obtained from the following sources, in the specified\n    order. The first available and non-empty value is used:\n\n    * the value of the \"ID\" attribute of the os-release file,\n\n    * the value of the \"Distributor ID\" attribute returned by the lsb_release\n      command,\n\n    * the first part of the file name of the distro release file,\n\n    The so determined ID value then passes the following transformations,\n    before it is returned by this method:\n\n    * it is translated to lower case,\n\n    * blanks (which should not be there anyway) are translated to underscores,\n\n    * a normalization of the ID is performed, based upon\n      `normalization tables`_. The purpose of this normalization is to ensure\n      that the ID is as reliable as possible, even across incompatible changes\n      in the OS distributions. A common reason for an incompatible change is\n      the addition of an os-release file, or the addition of the lsb_release\n      command, with ID values that differ from what was previously determined\n      from the distro release file name.\n    \"\"\"\n    return _distro.id()\n\n\ndef name(pretty: bool = False) -> str:\n    \"\"\"\n    Return the name of the current OS distribution, as a human-readable\n    string.\n\n    If *pretty* is false, the name is returned without version or codename.\n    (e.g. \"CentOS Linux\")\n\n    If *pretty* is true, the version and codename are appended.\n    (e.g. \"CentOS Linux 7.1.1503 (Core)\")\n\n    **Lookup hierarchy:**\n\n    The name is obtained from the following sources, in the specified order.\n    The first available and non-empty value is used:\n\n    * If *pretty* is false:\n\n      - the value of the \"NAME\" attribute of the os-release file,\n\n      - the value of the \"Distributor ID\" attribute returned by the lsb_release\n        command,\n\n      - the value of the \"<name>\" field of the distro release file.\n\n    * If *pretty* is true:\n\n      - the value of the \"PRETTY_NAME\" attribute of the os-release file,\n\n      - the value of the \"Description\" attribute returned by the lsb_release\n        command,\n\n      - the value of the \"<name>\" field of the distro release file, appended\n        with the value of the pretty version (\"<version_id>\" and \"<codename>\"\n        fields) of the distro release file, if available.\n    \"\"\"\n    return _distro.name(pretty)\n\n\ndef version(pretty: bool = False, best: bool = False) -> str:\n    \"\"\"\n    Return the version of the current OS distribution, as a human-readable\n    string.\n\n    If *pretty* is false, the version is returned without codename (e.g.\n    \"7.0\").\n\n    If *pretty* is true, the codename in parenthesis is appended, if the\n    codename is non-empty (e.g. \"7.0 (Maipo)\").\n\n    Some distributions provide version numbers with different precisions in\n    the different sources of distribution information. Examining the different\n    sources in a fixed priority order does not always yield the most precise\n    version (e.g. for Debian 8.2, or CentOS 7.1).\n\n    Some other distributions may not provide this kind of information. In these\n    cases, an empty string would be returned. This behavior can be observed\n    with rolling releases distributions (e.g. Arch Linux).\n\n    The *best* parameter can be used to control the approach for the returned\n    version:\n\n    If *best* is false, the first non-empty version number in priority order of\n    the examined sources is returned.\n\n    If *best* is true, the most precise version number out of all examined\n    sources is returned.\n\n    **Lookup hierarchy:**\n\n    In all cases, the version number is obtained from the following sources.\n    If *best* is false, this order represents the priority order:\n\n    * the value of the \"VERSION_ID\" attribute of the os-release file,\n    * the value of the \"Release\" attribute returned by the lsb_release\n      command,\n    * the version number parsed from the \"<version_id>\" field of the first line\n      of the distro release file,\n    * the version number parsed from the \"PRETTY_NAME\" attribute of the\n      os-release file, if it follows the format of the distro release files.\n    * the version number parsed from the \"Description\" attribute returned by\n      the lsb_release command, if it follows the format of the distro release\n      files.\n    \"\"\"\n    return _distro.version(pretty, best)\n\n\ndef version_parts(best: bool = False) -> Tuple[str, str, str]:\n    \"\"\"\n    Return the version of the current OS distribution as a tuple\n    ``(major, minor, build_number)`` with items as follows:\n\n    * ``major``:  The result of :func:`distro.major_version`.\n\n    * ``minor``:  The result of :func:`distro.minor_version`.\n\n    * ``build_number``:  The result of :func:`distro.build_number`.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.version_parts(best)\n\n\ndef major_version(best: bool = False) -> str:\n    \"\"\"\n    Return the major version of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The major version is the first\n    part of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.major_version(best)\n\n\ndef minor_version(best: bool = False) -> str:\n    \"\"\"\n    Return the minor version of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The minor version is the second\n    part of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.minor_version(best)\n\n\ndef build_number(best: bool = False) -> str:\n    \"\"\"\n    Return the build number of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The build number is the third part\n    of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.build_number(best)\n\n\ndef like() -> str:\n    \"\"\"\n    Return a space-separated list of distro IDs of distributions that are\n    closely related to the current OS distribution in regards to packaging\n    and programming interfaces, for example distributions the current\n    distribution is a derivative from.\n\n    **Lookup hierarchy:**\n\n    This information item is only provided by the os-release file.\n    For details, see the description of the \"ID_LIKE\" attribute in the\n    `os-release man page\n    <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.\n    \"\"\"\n    return _distro.like()\n\n\ndef codename() -> str:\n    \"\"\"\n    Return the codename for the release of the current OS distribution,\n    as a string.\n\n    If the distribution does not have a codename, an empty string is returned.\n\n    Note that the returned codename is not always really a codename. For\n    example, openSUSE returns \"x86_64\". This function does not handle such\n    cases in any special way and just returns the string it finds, if any.\n\n    **Lookup hierarchy:**\n\n    * the codename within the \"VERSION\" attribute of the os-release file, if\n      provided,\n\n    * the value of the \"Codename\" attribute returned by the lsb_release\n      command,\n\n    * the value of the \"<codename>\" field of the distro release file.\n    \"\"\"\n    return _distro.codename()\n\n\ndef info(pretty: bool = False, best: bool = False) -> InfoDict:\n    \"\"\"\n    Return certain machine-readable information items about the current OS\n    distribution in a dictionary, as shown in the following example:\n\n    .. sourcecode:: python\n\n        {\n            'id': 'rhel',\n            'version': '7.0',\n            'version_parts': {\n                'major': '7',\n                'minor': '0',\n                'build_number': ''\n            },\n            'like': 'fedora',\n            'codename': 'Maipo'\n        }\n\n    The dictionary structure and keys are always the same, regardless of which\n    information items are available in the underlying data sources. The values\n    for the various keys are as follows:\n\n    * ``id``:  The result of :func:`distro.id`.\n\n    * ``version``:  The result of :func:`distro.version`.\n\n    * ``version_parts -> major``:  The result of :func:`distro.major_version`.\n\n    * ``version_parts -> minor``:  The result of :func:`distro.minor_version`.\n\n    * ``version_parts -> build_number``:  The result of\n      :func:`distro.build_number`.\n\n    * ``like``:  The result of :func:`distro.like`.\n\n    * ``codename``:  The result of :func:`distro.codename`.\n\n    For a description of the *pretty* and *best* parameters, see the\n    :func:`distro.version` method.\n    \"\"\"\n    return _distro.info(pretty, best)\n\n\ndef os_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the os-release file data source of the current OS distribution.\n\n    See `os-release file`_ for details about these information items.\n    \"\"\"\n    return _distro.os_release_info()\n\n\ndef lsb_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the lsb_release command data source of the current OS distribution.\n\n    See `lsb_release command output`_ for details about these information\n    items.\n    \"\"\"\n    return _distro.lsb_release_info()\n\n\ndef distro_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the distro release file data source of the current OS distribution.\n\n    See `distro release file`_ for details about these information items.\n    \"\"\"\n    return _distro.distro_release_info()\n\n\ndef uname_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the distro release file data source of the current OS distribution.\n    \"\"\"\n    return _distro.uname_info()\n\n\ndef os_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the os-release file data source\n    of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `os-release file`_ for details about these information items.\n    \"\"\"\n    return _distro.os_release_attr(attribute)\n\n\ndef lsb_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the lsb_release command output\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `lsb_release command output`_ for details about these information\n    items.\n    \"\"\"\n    return _distro.lsb_release_attr(attribute)\n\n\ndef distro_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the distro release file\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `distro release file`_ for details about these information items.\n    \"\"\"\n    return _distro.distro_release_attr(attribute)\n\n\ndef uname_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the distro release file\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n                The empty string, if the item does not exist.\n    \"\"\"\n    return _distro.uname_attr(attribute)\n\n\ntry:\n    from functools import cached_property\nexcept ImportError:\n    # Python < 3.8\n    class cached_property:  # type: ignore\n        \"\"\"A version of @property which caches the value.  On access, it calls the\n        underlying function and sets the value in `__dict__` so future accesses\n        will not re-call the property.\n        \"\"\"\n\n        def __init__(self, f: Callable[[Any], Any]) -> None:\n            self._fname = f.__name__\n            self._f = f\n\n        def __get__(self, obj: Any, owner: Type[Any]) -> Any:\n            assert obj is not None, f\"call {self._fname} on an instance\"\n            ret = obj.__dict__[self._fname] = self._f(obj)\n            return ret\n\n\nclass LinuxDistribution:\n    \"\"\"\n    Provides information about a OS distribution.\n\n    This package creates a private module-global instance of this class with\n    default initialization arguments, that is used by the\n    `consolidated accessor functions`_ and `single source accessor functions`_.\n    By using default initialization arguments, that module-global instance\n    returns data about the current OS distribution (i.e. the distro this\n    package runs on).\n\n    Normally, it is not necessary to create additional instances of this class.\n    However, in situations where control is needed over the exact data sources\n    that are used, instances of this class can be created with a specific\n    distro release file, or a specific os-release file, or without invoking the\n    lsb_release command.\n    \"\"\"\n\n    def __init__(\n        self,\n        include_lsb: Optional[bool] = None,\n        os_release_file: str = \"\",\n        distro_release_file: str = \"\",\n        include_uname: Optional[bool] = None,\n        root_dir: Optional[str] = None,\n        include_oslevel: Optional[bool] = None,\n    ) -> None:\n        \"\"\"\n        The initialization method of this class gathers information from the\n        available data sources, and stores that in private instance attributes.\n        Subsequent access to the information items uses these private instance\n        attributes, so that the data sources are read only once.\n\n        Parameters:\n\n        * ``include_lsb`` (bool): Controls whether the\n          `lsb_release command output`_ is included as a data source.\n\n          If the lsb_release command is not available in the program execution\n          path, the data source for the lsb_release command will be empty.\n\n        * ``os_release_file`` (string): The path name of the\n          `os-release file`_ that is to be used as a data source.\n\n          An empty string (the default) will cause the default path name to\n          be used (see `os-release file`_ for details).\n\n          If the specified or defaulted os-release file does not exist, the\n          data source for the os-release file will be empty.\n\n        * ``distro_release_file`` (string): The path name of the\n          `distro release file`_ that is to be used as a data source.\n\n          An empty string (the default) will cause a default search algorithm\n          to be used (see `distro release file`_ for details).\n\n          If the specified distro release file does not exist, or if no default\n          distro release file can be found, the data source for the distro\n          release file will be empty.\n\n        * ``include_uname`` (bool): Controls whether uname command output is\n          included as a data source. If the uname command is not available in\n          the program execution path the data source for the uname command will\n          be empty.\n\n        * ``root_dir`` (string): The absolute path to the root directory to use\n          to find distro-related information files. Note that ``include_*``\n          parameters must not be enabled in combination with ``root_dir``.\n\n        * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command\n          output is included as a data source. If the oslevel command is not\n          available in the program execution path the data source will be\n          empty.\n\n        Public instance attributes:\n\n        * ``os_release_file`` (string): The path name of the\n          `os-release file`_ that is actually used as a data source. The\n          empty string if no distro release file is used as a data source.\n\n        * ``distro_release_file`` (string): The path name of the\n          `distro release file`_ that is actually used as a data source. The\n          empty string if no distro release file is used as a data source.\n\n        * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.\n          This controls whether the lsb information will be loaded.\n\n        * ``include_uname`` (bool): The result of the ``include_uname``\n          parameter. This controls whether the uname information will\n          be loaded.\n\n        * ``include_oslevel`` (bool): The result of the ``include_oslevel``\n          parameter. This controls whether (AIX) oslevel information will be\n          loaded.\n\n        * ``root_dir`` (string): The result of the ``root_dir`` parameter.\n          The absolute path to the root directory to use to find distro-related\n          information files.\n\n        Raises:\n\n        * :py:exc:`ValueError`: Initialization parameters combination is not\n           supported.\n\n        * :py:exc:`OSError`: Some I/O issue with an os-release file or distro\n          release file.\n\n        * :py:exc:`UnicodeError`: A data source has unexpected characters or\n          uses an unexpected encoding.\n        \"\"\"\n        self.root_dir = root_dir\n        self.etc_dir = os.path.join(root_dir, \"etc\") if root_dir else _UNIXCONFDIR\n        self.usr_lib_dir = (\n            os.path.join(root_dir, \"usr/lib\") if root_dir else _UNIXUSRLIBDIR\n        )\n\n        if os_release_file:\n            self.os_release_file = os_release_file\n        else:\n            etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)\n            usr_lib_os_release_file = os.path.join(\n                self.usr_lib_dir, _OS_RELEASE_BASENAME\n            )\n\n            # NOTE: The idea is to respect order **and** have it set\n            #       at all times for API backwards compatibility.\n            if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(\n                usr_lib_os_release_file\n            ):\n                self.os_release_file = etc_dir_os_release_file\n            else:\n                self.os_release_file = usr_lib_os_release_file\n\n        self.distro_release_file = distro_release_file or \"\"  # updated later\n\n        is_root_dir_defined = root_dir is not None\n        if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):\n            raise ValueError(\n                \"Including subprocess data sources from specific root_dir is disallowed\"\n                \" to prevent false information\"\n            )\n        self.include_lsb = (\n            include_lsb if include_lsb is not None else not is_root_dir_defined\n        )\n        self.include_uname = (\n            include_uname if include_uname is not None else not is_root_dir_defined\n        )\n        self.include_oslevel = (\n            include_oslevel if include_oslevel is not None else not is_root_dir_defined\n        )\n\n    def __repr__(self) -> str:\n        \"\"\"Return repr of all info\"\"\"\n        return (\n            \"LinuxDistribution(\"\n            \"os_release_file={self.os_release_file!r}, \"\n            \"distro_release_file={self.distro_release_file!r}, \"\n            \"include_lsb={self.include_lsb!r}, \"\n            \"include_uname={self.include_uname!r}, \"\n            \"include_oslevel={self.include_oslevel!r}, \"\n            \"root_dir={self.root_dir!r}, \"\n            \"_os_release_info={self._os_release_info!r}, \"\n            \"_lsb_release_info={self._lsb_release_info!r}, \"\n            \"_distro_release_info={self._distro_release_info!r}, \"\n            \"_uname_info={self._uname_info!r}, \"\n            \"_oslevel_info={self._oslevel_info!r})\".format(self=self)\n        )\n\n    def linux_distribution(\n        self, full_distribution_name: bool = True\n    ) -> Tuple[str, str, str]:\n        \"\"\"\n        Return information about the OS distribution that is compatible\n        with Python's :func:`platform.linux_distribution`, supporting a subset\n        of its parameters.\n\n        For details, see :func:`distro.linux_distribution`.\n        \"\"\"\n        return (\n            self.name() if full_distribution_name else self.id(),\n            self.version(),\n            self._os_release_info.get(\"release_codename\") or self.codename(),\n        )\n\n    def id(self) -> str:\n        \"\"\"Return the distro ID of the OS distribution, as a string.\n\n        For details, see :func:`distro.id`.\n        \"\"\"\n\n        def normalize(distro_id: str, table: Dict[str, str]) -> str:\n            distro_id = distro_id.lower().replace(\" \", \"_\")\n            return table.get(distro_id, distro_id)\n\n        distro_id = self.os_release_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_OS_ID)\n\n        distro_id = self.lsb_release_attr(\"distributor_id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_LSB_ID)\n\n        distro_id = self.distro_release_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n\n        distro_id = self.uname_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n\n        return \"\"\n\n    def name(self, pretty: bool = False) -> str:\n        \"\"\"\n        Return the name of the OS distribution, as a string.\n\n        For details, see :func:`distro.name`.\n        \"\"\"\n        name = (\n            self.os_release_attr(\"name\")\n            or self.lsb_release_attr(\"distributor_id\")\n            or self.distro_release_attr(\"name\")\n            or self.uname_attr(\"name\")\n        )\n        if pretty:\n            name = self.os_release_attr(\"pretty_name\") or self.lsb_release_attr(\n                \"description\"\n            )\n            if not name:\n                name = self.distro_release_attr(\"name\") or self.uname_attr(\"name\")\n                version = self.version(pretty=True)\n                if version:\n                    name = f\"{name} {version}\"\n        return name or \"\"\n\n    def version(self, pretty: bool = False, best: bool = False) -> str:\n        \"\"\"\n        Return the version of the OS distribution, as a string.\n\n        For details, see :func:`distro.version`.\n        \"\"\"\n        versions = [\n            self.os_release_attr(\"version_id\"),\n            self.lsb_release_attr(\"release\"),\n            self.distro_release_attr(\"version_id\"),\n            self._parse_distro_release_content(self.os_release_attr(\"pretty_name\")).get(\n                \"version_id\", \"\"\n            ),\n            self._parse_distro_release_content(\n                self.lsb_release_attr(\"description\")\n            ).get(\"version_id\", \"\"),\n            self.uname_attr(\"release\"),\n        ]\n        if self.uname_attr(\"id\").startswith(\"aix\"):\n            # On AIX platforms, prefer oslevel command output.\n            versions.insert(0, self.oslevel_info())\n        elif self.id() == \"debian\" or \"debian\" in self.like().split():\n            # On Debian-like, add debian_version file content to candidates list.\n            versions.append(self._debian_version)\n        version = \"\"\n        if best:\n            # This algorithm uses the last version in priority order that has\n            # the best precision. If the versions are not in conflict, that\n            # does not matter; otherwise, using the last one instead of the\n            # first one might be considered a surprise.\n            for v in versions:\n                if v.count(\".\") > version.count(\".\") or version == \"\":\n                    version = v\n        else:\n            for v in versions:\n                if v != \"\":\n                    version = v\n                    break\n        if pretty and version and self.codename():\n            version = f\"{version} ({self.codename()})\"\n        return version\n\n    def version_parts(self, best: bool = False) -> Tuple[str, str, str]:\n        \"\"\"\n        Return the version of the OS distribution, as a tuple of version\n        numbers.\n\n        For details, see :func:`distro.version_parts`.\n        \"\"\"\n        version_str = self.version(best=best)\n        if version_str:\n            version_regex = re.compile(r\"(\\d+)\\.?(\\d+)?\\.?(\\d+)?\")\n            matches = version_regex.match(version_str)\n            if matches:\n                major, minor, build_number = matches.groups()\n                return major, minor or \"\", build_number or \"\"\n        return \"\", \"\", \"\"\n\n    def major_version(self, best: bool = False) -> str:\n        \"\"\"\n        Return the major version number of the current distribution.\n\n        For details, see :func:`distro.major_version`.\n        \"\"\"\n        return self.version_parts(best)[0]\n\n    def minor_version(self, best: bool = False) -> str:\n        \"\"\"\n        Return the minor version number of the current distribution.\n\n        For details, see :func:`distro.minor_version`.\n        \"\"\"\n        return self.version_parts(best)[1]\n\n    def build_number(self, best: bool = False) -> str:\n        \"\"\"\n        Return the build number of the current distribution.\n\n        For details, see :func:`distro.build_number`.\n        \"\"\"\n        return self.version_parts(best)[2]\n\n    def like(self) -> str:\n        \"\"\"\n        Return the IDs of distributions that are like the OS distribution.\n\n        For details, see :func:`distro.like`.\n        \"\"\"\n        return self.os_release_attr(\"id_like\") or \"\"\n\n    def codename(self) -> str:\n        \"\"\"\n        Return the codename of the OS distribution.\n\n        For details, see :func:`distro.codename`.\n        \"\"\"\n        try:\n            # Handle os_release specially since distros might purposefully set\n            # this to empty string to have no codename\n            return self._os_release_info[\"codename\"]\n        except KeyError:\n            return (\n                self.lsb_release_attr(\"codename\")\n                or self.distro_release_attr(\"codename\")\n                or \"\"\n            )\n\n    def info(self, pretty: bool = False, best: bool = False) -> InfoDict:\n        \"\"\"\n        Return certain machine-readable information about the OS\n        distribution.\n\n        For details, see :func:`distro.info`.\n        \"\"\"\n        return InfoDict(\n            id=self.id(),\n            version=self.version(pretty, best),\n            version_parts=VersionDict(\n                major=self.major_version(best),\n                minor=self.minor_version(best),\n                build_number=self.build_number(best),\n            ),\n            like=self.like(),\n            codename=self.codename(),\n        )\n\n    def os_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the os-release file data source of the OS distribution.\n\n        For details, see :func:`distro.os_release_info`.\n        \"\"\"\n        return self._os_release_info\n\n    def lsb_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the lsb_release command data source of the OS\n        distribution.\n\n        For details, see :func:`distro.lsb_release_info`.\n        \"\"\"\n        return self._lsb_release_info\n\n    def distro_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the distro release file data source of the OS\n        distribution.\n\n        For details, see :func:`distro.distro_release_info`.\n        \"\"\"\n        return self._distro_release_info\n\n    def uname_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the uname command data source of the OS distribution.\n\n        For details, see :func:`distro.uname_info`.\n        \"\"\"\n        return self._uname_info\n\n    def oslevel_info(self) -> str:\n        \"\"\"\n        Return AIX' oslevel command output.\n        \"\"\"\n        return self._oslevel_info\n\n    def os_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the os-release file data\n        source of the OS distribution.\n\n        For details, see :func:`distro.os_release_attr`.\n        \"\"\"\n        return self._os_release_info.get(attribute, \"\")\n\n    def lsb_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the lsb_release command\n        output data source of the OS distribution.\n\n        For details, see :func:`distro.lsb_release_attr`.\n        \"\"\"\n        return self._lsb_release_info.get(attribute, \"\")\n\n    def distro_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the distro release file\n        data source of the OS distribution.\n\n        For details, see :func:`distro.distro_release_attr`.\n        \"\"\"\n        return self._distro_release_info.get(attribute, \"\")\n\n    def uname_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the uname command\n        output data source of the OS distribution.\n\n        For details, see :func:`distro.uname_attr`.\n        \"\"\"\n        return self._uname_info.get(attribute, \"\")\n\n    @cached_property\n    def _os_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the specified os-release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if os.path.isfile(self.os_release_file):\n            with open(self.os_release_file, encoding=\"utf-8\") as release_file:\n                return self._parse_os_release_content(release_file)\n        return {}\n\n    @staticmethod\n    def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:\n        \"\"\"\n        Parse the lines of an os-release file.\n\n        Parameters:\n\n        * lines: Iterable through the lines in the os-release file.\n                 Each line must be a unicode string or a UTF-8 encoded byte\n                 string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        props = {}\n        lexer = shlex.shlex(lines, posix=True)\n        lexer.whitespace_split = True\n\n        tokens = list(lexer)\n        for token in tokens:\n            # At this point, all shell-like parsing has been done (i.e.\n            # comments processed, quotes and backslash escape sequences\n            # processed, multi-line values assembled, trailing newlines\n            # stripped, etc.), so the tokens are now either:\n            # * variable assignments: var=value\n            # * commands or their arguments (not allowed in os-release)\n            # Ignore any tokens that are not variable assignments\n            if \"=\" in token:\n                k, v = token.split(\"=\", 1)\n                props[k.lower()] = v\n\n        if \"version\" in props:\n            # extract release codename (if any) from version attribute\n            match = re.search(r\"\\((\\D+)\\)|,\\s*(\\D+)\", props[\"version\"])\n            if match:\n                release_codename = match.group(1) or match.group(2)\n                props[\"codename\"] = props[\"release_codename\"] = release_codename\n\n        if \"version_codename\" in props:\n            # os-release added a version_codename field.  Use that in\n            # preference to anything else Note that some distros purposefully\n            # do not have code names.  They should be setting\n            # version_codename=\"\"\n            props[\"codename\"] = props[\"version_codename\"]\n        elif \"ubuntu_codename\" in props:\n            # Same as above but a non-standard field name used on older Ubuntus\n            props[\"codename\"] = props[\"ubuntu_codename\"]\n\n        return props\n\n    @cached_property\n    def _lsb_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the lsb_release command output.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if not self.include_lsb:\n            return {}\n        try:\n            cmd = (\"lsb_release\", \"-a\")\n            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)\n        # Command not found or lsb_release returned error\n        except (OSError, subprocess.CalledProcessError):\n            return {}\n        content = self._to_str(stdout).splitlines()\n        return self._parse_lsb_release_content(content)\n\n    @staticmethod\n    def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:\n        \"\"\"\n        Parse the output of the lsb_release command.\n\n        Parameters:\n\n        * lines: Iterable through the lines of the lsb_release output.\n                 Each line must be a unicode string or a UTF-8 encoded byte\n                 string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        props = {}\n        for line in lines:\n            kv = line.strip(\"\\n\").split(\":\", 1)\n            if len(kv) != 2:\n                # Ignore lines without colon.\n                continue\n            k, v = kv\n            props.update({k.replace(\" \", \"_\").lower(): v.strip()})\n        return props\n\n    @cached_property\n    def _uname_info(self) -> Dict[str, str]:\n        if not self.include_uname:\n            return {}\n        try:\n            cmd = (\"uname\", \"-rs\")\n            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)\n        except OSError:\n            return {}\n        content = self._to_str(stdout).splitlines()\n        return self._parse_uname_content(content)\n\n    @cached_property\n    def _oslevel_info(self) -> str:\n        if not self.include_oslevel:\n            return \"\"\n        try:\n            stdout = subprocess.check_output(\"oslevel\", stderr=subprocess.DEVNULL)\n        except (OSError, subprocess.CalledProcessError):\n            return \"\"\n        return self._to_str(stdout).strip()\n\n    @cached_property\n    def _debian_version(self) -> str:\n        try:\n            with open(\n                os.path.join(self.etc_dir, \"debian_version\"), encoding=\"ascii\"\n            ) as fp:\n                return fp.readline().rstrip()\n        except FileNotFoundError:\n            return \"\"\n\n    @staticmethod\n    def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:\n        if not lines:\n            return {}\n        props = {}\n        match = re.search(r\"^([^\\s]+)\\s+([\\d\\.]+)\", lines[0].strip())\n        if match:\n            name, version = match.groups()\n\n            # This is to prevent the Linux kernel version from\n            # appearing as the 'best' version on otherwise\n            # identifiable distributions.\n            if name == \"Linux\":\n                return {}\n            props[\"id\"] = name.lower()\n            props[\"name\"] = name\n            props[\"release\"] = version\n        return props\n\n    @staticmethod\n    def _to_str(bytestring: bytes) -> str:\n        encoding = sys.getfilesystemencoding()\n        return bytestring.decode(encoding)\n\n    @cached_property\n    def _distro_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the specified distro release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if self.distro_release_file:\n            # If it was specified, we use it and parse what we can, even if\n            # its file name or content does not match the expected pattern.\n            distro_info = self._parse_distro_release_file(self.distro_release_file)\n            basename = os.path.basename(self.distro_release_file)\n            # The file name pattern for user-specified distro release files\n            # is somewhat more tolerant (compared to when searching for the\n            # file), because we want to use what was specified as best as\n            # possible.\n            match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)\n        else:\n            try:\n                basenames = [\n                    basename\n                    for basename in os.listdir(self.etc_dir)\n                    if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES\n                    and os.path.isfile(os.path.join(self.etc_dir, basename))\n                ]\n                # We sort for repeatability in cases where there are multiple\n                # distro specific files; e.g. CentOS, Oracle, Enterprise all\n                # containing `redhat-release` on top of their own.\n                basenames.sort()\n            except OSError:\n                # This may occur when /etc is not readable but we can't be\n                # sure about the *-release files. Check common entries of\n                # /etc for information. If they turn out to not be there the\n                # error is handled in `_parse_distro_release_file()`.\n                basenames = _DISTRO_RELEASE_BASENAMES\n            for basename in basenames:\n                match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)\n                if match is None:\n                    continue\n                filepath = os.path.join(self.etc_dir, basename)\n                distro_info = self._parse_distro_release_file(filepath)\n                # The name is always present if the pattern matches.\n                if \"name\" not in distro_info:\n                    continue\n                self.distro_release_file = filepath\n                break\n            else:  # the loop didn't \"break\": no candidate.\n                return {}\n\n        if match is not None:\n            distro_info[\"id\"] = match.group(1)\n\n        # CloudLinux < 7: manually enrich info with proper id.\n        if \"cloudlinux\" in distro_info.get(\"name\", \"\").lower():\n            distro_info[\"id\"] = \"cloudlinux\"\n\n        return distro_info\n\n    def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:\n        \"\"\"\n        Parse a distro release file.\n\n        Parameters:\n\n        * filepath: Path name of the distro release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        try:\n            with open(filepath, encoding=\"utf-8\") as fp:\n                # Only parse the first line. For instance, on SLES there\n                # are multiple lines. We don't want them...\n                return self._parse_distro_release_content(fp.readline())\n        except OSError:\n            # Ignore not being able to read a specific, seemingly version\n            # related file.\n            # See https://github.com/python-distro/distro/issues/162\n            return {}\n\n    @staticmethod\n    def _parse_distro_release_content(line: str) -> Dict[str, str]:\n        \"\"\"\n        Parse a line from a distro release file.\n\n        Parameters:\n        * line: Line from the distro release file. Must be a unicode string\n                or a UTF-8 encoded byte string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])\n        distro_info = {}\n        if matches:\n            # regexp ensures non-None\n            distro_info[\"name\"] = matches.group(3)[::-1]\n            if matches.group(2):\n                distro_info[\"version_id\"] = matches.group(2)[::-1]\n            if matches.group(1):\n                distro_info[\"codename\"] = matches.group(1)[::-1]\n        elif line:\n            distro_info[\"name\"] = line.strip()\n        return distro_info\n\n\n_distro = LinuxDistribution()\n\n\ndef main() -> None:\n    logger = logging.getLogger(__name__)\n    logger.setLevel(logging.DEBUG)\n    logger.addHandler(logging.StreamHandler(sys.stdout))\n\n    parser = argparse.ArgumentParser(description=\"OS distro info tool\")\n    parser.add_argument(\n        \"--json\", \"-j\", help=\"Output in machine readable format\", action=\"store_true\"\n    )\n\n    parser.add_argument(\n        \"--root-dir\",\n        \"-r\",\n        type=str,\n        dest=\"root_dir\",\n        help=\"Path to the root filesystem directory (defaults to /)\",\n    )\n\n    args = parser.parse_args()\n\n    if args.root_dir:\n        dist = LinuxDistribution(\n            include_lsb=False,\n            include_uname=False,\n            include_oslevel=False,\n            root_dir=args.root_dir,\n        )\n    else:\n        dist = _distro\n\n    if args.json:\n        logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))\n    else:\n        logger.info(\"Name: %s\", dist.name(pretty=True))\n        distribution_version = dist.version(pretty=True)\n        logger.info(\"Version: %s\", distribution_version)\n        distribution_codename = dist.codename()\n        logger.info(\"Codename: %s\", distribution_codename)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/distro/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/idna/LICENSE.md",
    "content": "BSD 3-Clause License\n\nCopyright (c) 2013-2025, Kim Davies and contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "src/pip/_vendor/idna/__init__.py",
    "content": "from .core import (\n    IDNABidiError,\n    IDNAError,\n    InvalidCodepoint,\n    InvalidCodepointContext,\n    alabel,\n    check_bidi,\n    check_hyphen_ok,\n    check_initial_combiner,\n    check_label,\n    check_nfc,\n    decode,\n    encode,\n    ulabel,\n    uts46_remap,\n    valid_contextj,\n    valid_contexto,\n    valid_label_length,\n    valid_string_length,\n)\nfrom .intranges import intranges_contain\nfrom .package_data import __version__\n\n__all__ = [\n    \"__version__\",\n    \"IDNABidiError\",\n    \"IDNAError\",\n    \"InvalidCodepoint\",\n    \"InvalidCodepointContext\",\n    \"alabel\",\n    \"check_bidi\",\n    \"check_hyphen_ok\",\n    \"check_initial_combiner\",\n    \"check_label\",\n    \"check_nfc\",\n    \"decode\",\n    \"encode\",\n    \"intranges_contain\",\n    \"ulabel\",\n    \"uts46_remap\",\n    \"valid_contextj\",\n    \"valid_contexto\",\n    \"valid_label_length\",\n    \"valid_string_length\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/idna/codec.py",
    "content": "import codecs\nimport re\nfrom typing import Any, Optional, Tuple\n\nfrom .core import IDNAError, alabel, decode, encode, ulabel\n\n_unicode_dots_re = re.compile(\"[\\u002e\\u3002\\uff0e\\uff61]\")\n\n\nclass Codec(codecs.Codec):\n    def encode(self, data: str, errors: str = \"strict\") -> Tuple[bytes, int]:\n        if errors != \"strict\":\n            raise IDNAError('Unsupported error handling \"{}\"'.format(errors))\n\n        if not data:\n            return b\"\", 0\n\n        return encode(data), len(data)\n\n    def decode(self, data: bytes, errors: str = \"strict\") -> Tuple[str, int]:\n        if errors != \"strict\":\n            raise IDNAError('Unsupported error handling \"{}\"'.format(errors))\n\n        if not data:\n            return \"\", 0\n\n        return decode(data), len(data)\n\n\nclass IncrementalEncoder(codecs.BufferedIncrementalEncoder):\n    def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[bytes, int]:\n        if errors != \"strict\":\n            raise IDNAError('Unsupported error handling \"{}\"'.format(errors))\n\n        if not data:\n            return b\"\", 0\n\n        labels = _unicode_dots_re.split(data)\n        trailing_dot = b\"\"\n        if labels:\n            if not labels[-1]:\n                trailing_dot = b\".\"\n                del labels[-1]\n            elif not final:\n                # Keep potentially unfinished label until the next call\n                del labels[-1]\n                if labels:\n                    trailing_dot = b\".\"\n\n        result = []\n        size = 0\n        for label in labels:\n            result.append(alabel(label))\n            if size:\n                size += 1\n            size += len(label)\n\n        # Join with U+002E\n        result_bytes = b\".\".join(result) + trailing_dot\n        size += len(trailing_dot)\n        return result_bytes, size\n\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, data: Any, errors: str, final: bool) -> Tuple[str, int]:\n        if errors != \"strict\":\n            raise IDNAError('Unsupported error handling \"{}\"'.format(errors))\n\n        if not data:\n            return (\"\", 0)\n\n        if not isinstance(data, str):\n            data = str(data, \"ascii\")\n\n        labels = _unicode_dots_re.split(data)\n        trailing_dot = \"\"\n        if labels:\n            if not labels[-1]:\n                trailing_dot = \".\"\n                del labels[-1]\n            elif not final:\n                # Keep potentially unfinished label until the next call\n                del labels[-1]\n                if labels:\n                    trailing_dot = \".\"\n\n        result = []\n        size = 0\n        for label in labels:\n            result.append(ulabel(label))\n            if size:\n                size += 1\n            size += len(label)\n\n        result_str = \".\".join(result) + trailing_dot\n        size += len(trailing_dot)\n        return (result_str, size)\n\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    pass\n\n\nclass StreamReader(Codec, codecs.StreamReader):\n    pass\n\n\ndef search_function(name: str) -> Optional[codecs.CodecInfo]:\n    if name != \"idna2008\":\n        return None\n    return codecs.CodecInfo(\n        name=name,\n        encode=Codec().encode,\n        decode=Codec().decode,  # type: ignore\n        incrementalencoder=IncrementalEncoder,\n        incrementaldecoder=IncrementalDecoder,\n        streamwriter=StreamWriter,\n        streamreader=StreamReader,\n    )\n\n\ncodecs.register(search_function)\n"
  },
  {
    "path": "src/pip/_vendor/idna/compat.py",
    "content": "from typing import Any, Union\n\nfrom .core import decode, encode\n\n\ndef ToASCII(label: str) -> bytes:\n    return encode(label)\n\n\ndef ToUnicode(label: Union[bytes, bytearray]) -> str:\n    return decode(label)\n\n\ndef nameprep(s: Any) -> None:\n    raise NotImplementedError(\"IDNA 2008 does not utilise nameprep protocol\")\n"
  },
  {
    "path": "src/pip/_vendor/idna/core.py",
    "content": "import bisect\nimport re\nimport unicodedata\nfrom typing import Optional, Union\n\nfrom . import idnadata\nfrom .intranges import intranges_contain\n\n_virama_combining_class = 9\n_alabel_prefix = b\"xn--\"\n_unicode_dots_re = re.compile(\"[\\u002e\\u3002\\uff0e\\uff61]\")\n\n\nclass IDNAError(UnicodeError):\n    \"\"\"Base exception for all IDNA-encoding related problems\"\"\"\n\n    pass\n\n\nclass IDNABidiError(IDNAError):\n    \"\"\"Exception when bidirectional requirements are not satisfied\"\"\"\n\n    pass\n\n\nclass InvalidCodepoint(IDNAError):\n    \"\"\"Exception when a disallowed or unallocated codepoint is used\"\"\"\n\n    pass\n\n\nclass InvalidCodepointContext(IDNAError):\n    \"\"\"Exception when the codepoint is not valid in the context it is used\"\"\"\n\n    pass\n\n\ndef _combining_class(cp: int) -> int:\n    v = unicodedata.combining(chr(cp))\n    if v == 0:\n        if not unicodedata.name(chr(cp)):\n            raise ValueError(\"Unknown character in unicodedata\")\n    return v\n\n\ndef _is_script(cp: str, script: str) -> bool:\n    return intranges_contain(ord(cp), idnadata.scripts[script])\n\n\ndef _punycode(s: str) -> bytes:\n    return s.encode(\"punycode\")\n\n\ndef _unot(s: int) -> str:\n    return \"U+{:04X}\".format(s)\n\n\ndef valid_label_length(label: Union[bytes, str]) -> bool:\n    if len(label) > 63:\n        return False\n    return True\n\n\ndef valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:\n    if len(label) > (254 if trailing_dot else 253):\n        return False\n    return True\n\n\ndef check_bidi(label: str, check_ltr: bool = False) -> bool:\n    # Bidi rules should only be applied if string contains RTL characters\n    bidi_label = False\n    for idx, cp in enumerate(label, 1):\n        direction = unicodedata.bidirectional(cp)\n        if direction == \"\":\n            # String likely comes from a newer version of Unicode\n            raise IDNABidiError(\"Unknown directionality in label {} at position {}\".format(repr(label), idx))\n        if direction in [\"R\", \"AL\", \"AN\"]:\n            bidi_label = True\n    if not bidi_label and not check_ltr:\n        return True\n\n    # Bidi rule 1\n    direction = unicodedata.bidirectional(label[0])\n    if direction in [\"R\", \"AL\"]:\n        rtl = True\n    elif direction == \"L\":\n        rtl = False\n    else:\n        raise IDNABidiError(\"First codepoint in label {} must be directionality L, R or AL\".format(repr(label)))\n\n    valid_ending = False\n    number_type: Optional[str] = None\n    for idx, cp in enumerate(label, 1):\n        direction = unicodedata.bidirectional(cp)\n\n        if rtl:\n            # Bidi rule 2\n            if direction not in [\n                \"R\",\n                \"AL\",\n                \"AN\",\n                \"EN\",\n                \"ES\",\n                \"CS\",\n                \"ET\",\n                \"ON\",\n                \"BN\",\n                \"NSM\",\n            ]:\n                raise IDNABidiError(\"Invalid direction for codepoint at position {} in a right-to-left label\".format(idx))\n            # Bidi rule 3\n            if direction in [\"R\", \"AL\", \"EN\", \"AN\"]:\n                valid_ending = True\n            elif direction != \"NSM\":\n                valid_ending = False\n            # Bidi rule 4\n            if direction in [\"AN\", \"EN\"]:\n                if not number_type:\n                    number_type = direction\n                else:\n                    if number_type != direction:\n                        raise IDNABidiError(\"Can not mix numeral types in a right-to-left label\")\n        else:\n            # Bidi rule 5\n            if direction not in [\"L\", \"EN\", \"ES\", \"CS\", \"ET\", \"ON\", \"BN\", \"NSM\"]:\n                raise IDNABidiError(\"Invalid direction for codepoint at position {} in a left-to-right label\".format(idx))\n            # Bidi rule 6\n            if direction in [\"L\", \"EN\"]:\n                valid_ending = True\n            elif direction != \"NSM\":\n                valid_ending = False\n\n    if not valid_ending:\n        raise IDNABidiError(\"Label ends with illegal codepoint directionality\")\n\n    return True\n\n\ndef check_initial_combiner(label: str) -> bool:\n    if unicodedata.category(label[0])[0] == \"M\":\n        raise IDNAError(\"Label begins with an illegal combining character\")\n    return True\n\n\ndef check_hyphen_ok(label: str) -> bool:\n    if label[2:4] == \"--\":\n        raise IDNAError(\"Label has disallowed hyphens in 3rd and 4th position\")\n    if label[0] == \"-\" or label[-1] == \"-\":\n        raise IDNAError(\"Label must not start or end with a hyphen\")\n    return True\n\n\ndef check_nfc(label: str) -> None:\n    if unicodedata.normalize(\"NFC\", label) != label:\n        raise IDNAError(\"Label must be in Normalization Form C\")\n\n\ndef valid_contextj(label: str, pos: int) -> bool:\n    cp_value = ord(label[pos])\n\n    if cp_value == 0x200C:\n        if pos > 0:\n            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:\n                return True\n\n        ok = False\n        for i in range(pos - 1, -1, -1):\n            joining_type = idnadata.joining_types.get(ord(label[i]))\n            if joining_type == ord(\"T\"):\n                continue\n            elif joining_type in [ord(\"L\"), ord(\"D\")]:\n                ok = True\n                break\n            else:\n                break\n\n        if not ok:\n            return False\n\n        ok = False\n        for i in range(pos + 1, len(label)):\n            joining_type = idnadata.joining_types.get(ord(label[i]))\n            if joining_type == ord(\"T\"):\n                continue\n            elif joining_type in [ord(\"R\"), ord(\"D\")]:\n                ok = True\n                break\n            else:\n                break\n        return ok\n\n    if cp_value == 0x200D:\n        if pos > 0:\n            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:\n                return True\n        return False\n\n    else:\n        return False\n\n\ndef valid_contexto(label: str, pos: int, exception: bool = False) -> bool:\n    cp_value = ord(label[pos])\n\n    if cp_value == 0x00B7:\n        if 0 < pos < len(label) - 1:\n            if ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C:\n                return True\n        return False\n\n    elif cp_value == 0x0375:\n        if pos < len(label) - 1 and len(label) > 1:\n            return _is_script(label[pos + 1], \"Greek\")\n        return False\n\n    elif cp_value == 0x05F3 or cp_value == 0x05F4:\n        if pos > 0:\n            return _is_script(label[pos - 1], \"Hebrew\")\n        return False\n\n    elif cp_value == 0x30FB:\n        for cp in label:\n            if cp == \"\\u30fb\":\n                continue\n            if _is_script(cp, \"Hiragana\") or _is_script(cp, \"Katakana\") or _is_script(cp, \"Han\"):\n                return True\n        return False\n\n    elif 0x660 <= cp_value <= 0x669:\n        for cp in label:\n            if 0x6F0 <= ord(cp) <= 0x06F9:\n                return False\n        return True\n\n    elif 0x6F0 <= cp_value <= 0x6F9:\n        for cp in label:\n            if 0x660 <= ord(cp) <= 0x0669:\n                return False\n        return True\n\n    return False\n\n\ndef check_label(label: Union[str, bytes, bytearray]) -> None:\n    if isinstance(label, (bytes, bytearray)):\n        label = label.decode(\"utf-8\")\n    if len(label) == 0:\n        raise IDNAError(\"Empty Label\")\n\n    check_nfc(label)\n    check_hyphen_ok(label)\n    check_initial_combiner(label)\n\n    for pos, cp in enumerate(label):\n        cp_value = ord(cp)\n        if intranges_contain(cp_value, idnadata.codepoint_classes[\"PVALID\"]):\n            continue\n        elif intranges_contain(cp_value, idnadata.codepoint_classes[\"CONTEXTJ\"]):\n            try:\n                if not valid_contextj(label, pos):\n                    raise InvalidCodepointContext(\n                        \"Joiner {} not allowed at position {} in {}\".format(_unot(cp_value), pos + 1, repr(label))\n                    )\n            except ValueError:\n                raise IDNAError(\n                    \"Unknown codepoint adjacent to joiner {} at position {} in {}\".format(\n                        _unot(cp_value), pos + 1, repr(label)\n                    )\n                )\n        elif intranges_contain(cp_value, idnadata.codepoint_classes[\"CONTEXTO\"]):\n            if not valid_contexto(label, pos):\n                raise InvalidCodepointContext(\n                    \"Codepoint {} not allowed at position {} in {}\".format(_unot(cp_value), pos + 1, repr(label))\n                )\n        else:\n            raise InvalidCodepoint(\n                \"Codepoint {} at position {} of {} not allowed\".format(_unot(cp_value), pos + 1, repr(label))\n            )\n\n    check_bidi(label)\n\n\ndef alabel(label: str) -> bytes:\n    try:\n        label_bytes = label.encode(\"ascii\")\n        ulabel(label_bytes)\n        if not valid_label_length(label_bytes):\n            raise IDNAError(\"Label too long\")\n        return label_bytes\n    except UnicodeEncodeError:\n        pass\n\n    check_label(label)\n    label_bytes = _alabel_prefix + _punycode(label)\n\n    if not valid_label_length(label_bytes):\n        raise IDNAError(\"Label too long\")\n\n    return label_bytes\n\n\ndef ulabel(label: Union[str, bytes, bytearray]) -> str:\n    if not isinstance(label, (bytes, bytearray)):\n        try:\n            label_bytes = label.encode(\"ascii\")\n        except UnicodeEncodeError:\n            check_label(label)\n            return label\n    else:\n        label_bytes = bytes(label)\n\n    label_bytes = label_bytes.lower()\n    if label_bytes.startswith(_alabel_prefix):\n        label_bytes = label_bytes[len(_alabel_prefix) :]\n        if not label_bytes:\n            raise IDNAError(\"Malformed A-label, no Punycode eligible content found\")\n        if label_bytes.decode(\"ascii\")[-1] == \"-\":\n            raise IDNAError(\"A-label must not end with a hyphen\")\n    else:\n        check_label(label_bytes)\n        return label_bytes.decode(\"ascii\")\n\n    try:\n        label = label_bytes.decode(\"punycode\")\n    except UnicodeError:\n        raise IDNAError(\"Invalid A-label\")\n    check_label(label)\n    return label\n\n\ndef uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:\n    \"\"\"Re-map the characters in the string according to UTS46 processing.\"\"\"\n    from .uts46data import uts46data\n\n    output = \"\"\n\n    for pos, char in enumerate(domain):\n        code_point = ord(char)\n        try:\n            uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, \"Z\")) - 1]\n            status = uts46row[1]\n            replacement: Optional[str] = None\n            if len(uts46row) == 3:\n                replacement = uts46row[2]\n            if (\n                status == \"V\"\n                or (status == \"D\" and not transitional)\n                or (status == \"3\" and not std3_rules and replacement is None)\n            ):\n                output += char\n            elif replacement is not None and (\n                status == \"M\" or (status == \"3\" and not std3_rules) or (status == \"D\" and transitional)\n            ):\n                output += replacement\n            elif status != \"I\":\n                raise IndexError()\n        except IndexError:\n            raise InvalidCodepoint(\n                \"Codepoint {} not allowed at position {} in {}\".format(_unot(code_point), pos + 1, repr(domain))\n            )\n\n    return unicodedata.normalize(\"NFC\", output)\n\n\ndef encode(\n    s: Union[str, bytes, bytearray],\n    strict: bool = False,\n    uts46: bool = False,\n    std3_rules: bool = False,\n    transitional: bool = False,\n) -> bytes:\n    if not isinstance(s, str):\n        try:\n            s = str(s, \"ascii\")\n        except UnicodeDecodeError:\n            raise IDNAError(\"should pass a unicode string to the function rather than a byte string.\")\n    if uts46:\n        s = uts46_remap(s, std3_rules, transitional)\n    trailing_dot = False\n    result = []\n    if strict:\n        labels = s.split(\".\")\n    else:\n        labels = _unicode_dots_re.split(s)\n    if not labels or labels == [\"\"]:\n        raise IDNAError(\"Empty domain\")\n    if labels[-1] == \"\":\n        del labels[-1]\n        trailing_dot = True\n    for label in labels:\n        s = alabel(label)\n        if s:\n            result.append(s)\n        else:\n            raise IDNAError(\"Empty label\")\n    if trailing_dot:\n        result.append(b\"\")\n    s = b\".\".join(result)\n    if not valid_string_length(s, trailing_dot):\n        raise IDNAError(\"Domain too long\")\n    return s\n\n\ndef decode(\n    s: Union[str, bytes, bytearray],\n    strict: bool = False,\n    uts46: bool = False,\n    std3_rules: bool = False,\n) -> str:\n    try:\n        if not isinstance(s, str):\n            s = str(s, \"ascii\")\n    except UnicodeDecodeError:\n        raise IDNAError(\"Invalid ASCII in A-label\")\n    if uts46:\n        s = uts46_remap(s, std3_rules, False)\n    trailing_dot = False\n    result = []\n    if not strict:\n        labels = _unicode_dots_re.split(s)\n    else:\n        labels = s.split(\".\")\n    if not labels or labels == [\"\"]:\n        raise IDNAError(\"Empty domain\")\n    if not labels[-1]:\n        del labels[-1]\n        trailing_dot = True\n    for label in labels:\n        s = ulabel(label)\n        if s:\n            result.append(s)\n        else:\n            raise IDNAError(\"Empty label\")\n    if trailing_dot:\n        result.append(\"\")\n    return \".\".join(result)\n"
  },
  {
    "path": "src/pip/_vendor/idna/idnadata.py",
    "content": "# This file is automatically generated by tools/idna-data\n\n__version__ = \"16.0.0\"\n\nscripts = {\n    \"Greek\": (\n        0x37000000374,\n        0x37500000378,\n        0x37A0000037E,\n        0x37F00000380,\n        0x38400000385,\n        0x38600000387,\n        0x3880000038B,\n        0x38C0000038D,\n        0x38E000003A2,\n        0x3A3000003E2,\n        0x3F000000400,\n        0x1D2600001D2B,\n        0x1D5D00001D62,\n        0x1D6600001D6B,\n        0x1DBF00001DC0,\n        0x1F0000001F16,\n        0x1F1800001F1E,\n        0x1F2000001F46,\n        0x1F4800001F4E,\n        0x1F5000001F58,\n        0x1F5900001F5A,\n        0x1F5B00001F5C,\n        0x1F5D00001F5E,\n        0x1F5F00001F7E,\n        0x1F8000001FB5,\n        0x1FB600001FC5,\n        0x1FC600001FD4,\n        0x1FD600001FDC,\n        0x1FDD00001FF0,\n        0x1FF200001FF5,\n        0x1FF600001FFF,\n        0x212600002127,\n        0xAB650000AB66,\n        0x101400001018F,\n        0x101A0000101A1,\n        0x1D2000001D246,\n    ),\n    \"Han\": (\n        0x2E8000002E9A,\n        0x2E9B00002EF4,\n        0x2F0000002FD6,\n        0x300500003006,\n        0x300700003008,\n        0x30210000302A,\n        0x30380000303C,\n        0x340000004DC0,\n        0x4E000000A000,\n        0xF9000000FA6E,\n        0xFA700000FADA,\n        0x16FE200016FE4,\n        0x16FF000016FF2,\n        0x200000002A6E0,\n        0x2A7000002B73A,\n        0x2B7400002B81E,\n        0x2B8200002CEA2,\n        0x2CEB00002EBE1,\n        0x2EBF00002EE5E,\n        0x2F8000002FA1E,\n        0x300000003134B,\n        0x31350000323B0,\n    ),\n    \"Hebrew\": (\n        0x591000005C8,\n        0x5D0000005EB,\n        0x5EF000005F5,\n        0xFB1D0000FB37,\n        0xFB380000FB3D,\n        0xFB3E0000FB3F,\n        0xFB400000FB42,\n        0xFB430000FB45,\n        0xFB460000FB50,\n    ),\n    \"Hiragana\": (\n        0x304100003097,\n        0x309D000030A0,\n        0x1B0010001B120,\n        0x1B1320001B133,\n        0x1B1500001B153,\n        0x1F2000001F201,\n    ),\n    \"Katakana\": (\n        0x30A1000030FB,\n        0x30FD00003100,\n        0x31F000003200,\n        0x32D0000032FF,\n        0x330000003358,\n        0xFF660000FF70,\n        0xFF710000FF9E,\n        0x1AFF00001AFF4,\n        0x1AFF50001AFFC,\n        0x1AFFD0001AFFF,\n        0x1B0000001B001,\n        0x1B1200001B123,\n        0x1B1550001B156,\n        0x1B1640001B168,\n    ),\n}\njoining_types = {\n    0xAD: 84,\n    0x300: 84,\n    0x301: 84,\n    0x302: 84,\n    0x303: 84,\n    0x304: 84,\n    0x305: 84,\n    0x306: 84,\n    0x307: 84,\n    0x308: 84,\n    0x309: 84,\n    0x30A: 84,\n    0x30B: 84,\n    0x30C: 84,\n    0x30D: 84,\n    0x30E: 84,\n    0x30F: 84,\n    0x310: 84,\n    0x311: 84,\n    0x312: 84,\n    0x313: 84,\n    0x314: 84,\n    0x315: 84,\n    0x316: 84,\n    0x317: 84,\n    0x318: 84,\n    0x319: 84,\n    0x31A: 84,\n    0x31B: 84,\n    0x31C: 84,\n    0x31D: 84,\n    0x31E: 84,\n    0x31F: 84,\n    0x320: 84,\n    0x321: 84,\n    0x322: 84,\n    0x323: 84,\n    0x324: 84,\n    0x325: 84,\n    0x326: 84,\n    0x327: 84,\n    0x328: 84,\n    0x329: 84,\n    0x32A: 84,\n    0x32B: 84,\n    0x32C: 84,\n    0x32D: 84,\n    0x32E: 84,\n    0x32F: 84,\n    0x330: 84,\n    0x331: 84,\n    0x332: 84,\n    0x333: 84,\n    0x334: 84,\n    0x335: 84,\n    0x336: 84,\n    0x337: 84,\n    0x338: 84,\n    0x339: 84,\n    0x33A: 84,\n    0x33B: 84,\n    0x33C: 84,\n    0x33D: 84,\n    0x33E: 84,\n    0x33F: 84,\n    0x340: 84,\n    0x341: 84,\n    0x342: 84,\n    0x343: 84,\n    0x344: 84,\n    0x345: 84,\n    0x346: 84,\n    0x347: 84,\n    0x348: 84,\n    0x349: 84,\n    0x34A: 84,\n    0x34B: 84,\n    0x34C: 84,\n    0x34D: 84,\n    0x34E: 84,\n    0x34F: 84,\n    0x350: 84,\n    0x351: 84,\n    0x352: 84,\n    0x353: 84,\n    0x354: 84,\n    0x355: 84,\n    0x356: 84,\n    0x357: 84,\n    0x358: 84,\n    0x359: 84,\n    0x35A: 84,\n    0x35B: 84,\n    0x35C: 84,\n    0x35D: 84,\n    0x35E: 84,\n    0x35F: 84,\n    0x360: 84,\n    0x361: 84,\n    0x362: 84,\n    0x363: 84,\n    0x364: 84,\n    0x365: 84,\n    0x366: 84,\n    0x367: 84,\n    0x368: 84,\n    0x369: 84,\n    0x36A: 84,\n    0x36B: 84,\n    0x36C: 84,\n    0x36D: 84,\n    0x36E: 84,\n    0x36F: 84,\n    0x483: 84,\n    0x484: 84,\n    0x485: 84,\n    0x486: 84,\n    0x487: 84,\n    0x488: 84,\n    0x489: 84,\n    0x591: 84,\n    0x592: 84,\n    0x593: 84,\n    0x594: 84,\n    0x595: 84,\n    0x596: 84,\n    0x597: 84,\n    0x598: 84,\n    0x599: 84,\n    0x59A: 84,\n    0x59B: 84,\n    0x59C: 84,\n    0x59D: 84,\n    0x59E: 84,\n    0x59F: 84,\n    0x5A0: 84,\n    0x5A1: 84,\n    0x5A2: 84,\n    0x5A3: 84,\n    0x5A4: 84,\n    0x5A5: 84,\n    0x5A6: 84,\n    0x5A7: 84,\n    0x5A8: 84,\n    0x5A9: 84,\n    0x5AA: 84,\n    0x5AB: 84,\n    0x5AC: 84,\n    0x5AD: 84,\n    0x5AE: 84,\n    0x5AF: 84,\n    0x5B0: 84,\n    0x5B1: 84,\n    0x5B2: 84,\n    0x5B3: 84,\n    0x5B4: 84,\n    0x5B5: 84,\n    0x5B6: 84,\n    0x5B7: 84,\n    0x5B8: 84,\n    0x5B9: 84,\n    0x5BA: 84,\n    0x5BB: 84,\n    0x5BC: 84,\n    0x5BD: 84,\n    0x5BF: 84,\n    0x5C1: 84,\n    0x5C2: 84,\n    0x5C4: 84,\n    0x5C5: 84,\n    0x5C7: 84,\n    0x610: 84,\n    0x611: 84,\n    0x612: 84,\n    0x613: 84,\n    0x614: 84,\n    0x615: 84,\n    0x616: 84,\n    0x617: 84,\n    0x618: 84,\n    0x619: 84,\n    0x61A: 84,\n    0x61C: 84,\n    0x620: 68,\n    0x622: 82,\n    0x623: 82,\n    0x624: 82,\n    0x625: 82,\n    0x626: 68,\n    0x627: 82,\n    0x628: 68,\n    0x629: 82,\n    0x62A: 68,\n    0x62B: 68,\n    0x62C: 68,\n    0x62D: 68,\n    0x62E: 68,\n    0x62F: 82,\n    0x630: 82,\n    0x631: 82,\n    0x632: 82,\n    0x633: 68,\n    0x634: 68,\n    0x635: 68,\n    0x636: 68,\n    0x637: 68,\n    0x638: 68,\n    0x639: 68,\n    0x63A: 68,\n    0x63B: 68,\n    0x63C: 68,\n    0x63D: 68,\n    0x63E: 68,\n    0x63F: 68,\n    0x640: 67,\n    0x641: 68,\n    0x642: 68,\n    0x643: 68,\n    0x644: 68,\n    0x645: 68,\n    0x646: 68,\n    0x647: 68,\n    0x648: 82,\n    0x649: 68,\n    0x64A: 68,\n    0x64B: 84,\n    0x64C: 84,\n    0x64D: 84,\n    0x64E: 84,\n    0x64F: 84,\n    0x650: 84,\n    0x651: 84,\n    0x652: 84,\n    0x653: 84,\n    0x654: 84,\n    0x655: 84,\n    0x656: 84,\n    0x657: 84,\n    0x658: 84,\n    0x659: 84,\n    0x65A: 84,\n    0x65B: 84,\n    0x65C: 84,\n    0x65D: 84,\n    0x65E: 84,\n    0x65F: 84,\n    0x66E: 68,\n    0x66F: 68,\n    0x670: 84,\n    0x671: 82,\n    0x672: 82,\n    0x673: 82,\n    0x675: 82,\n    0x676: 82,\n    0x677: 82,\n    0x678: 68,\n    0x679: 68,\n    0x67A: 68,\n    0x67B: 68,\n    0x67C: 68,\n    0x67D: 68,\n    0x67E: 68,\n    0x67F: 68,\n    0x680: 68,\n    0x681: 68,\n    0x682: 68,\n    0x683: 68,\n    0x684: 68,\n    0x685: 68,\n    0x686: 68,\n    0x687: 68,\n    0x688: 82,\n    0x689: 82,\n    0x68A: 82,\n    0x68B: 82,\n    0x68C: 82,\n    0x68D: 82,\n    0x68E: 82,\n    0x68F: 82,\n    0x690: 82,\n    0x691: 82,\n    0x692: 82,\n    0x693: 82,\n    0x694: 82,\n    0x695: 82,\n    0x696: 82,\n    0x697: 82,\n    0x698: 82,\n    0x699: 82,\n    0x69A: 68,\n    0x69B: 68,\n    0x69C: 68,\n    0x69D: 68,\n    0x69E: 68,\n    0x69F: 68,\n    0x6A0: 68,\n    0x6A1: 68,\n    0x6A2: 68,\n    0x6A3: 68,\n    0x6A4: 68,\n    0x6A5: 68,\n    0x6A6: 68,\n    0x6A7: 68,\n    0x6A8: 68,\n    0x6A9: 68,\n    0x6AA: 68,\n    0x6AB: 68,\n    0x6AC: 68,\n    0x6AD: 68,\n    0x6AE: 68,\n    0x6AF: 68,\n    0x6B0: 68,\n    0x6B1: 68,\n    0x6B2: 68,\n    0x6B3: 68,\n    0x6B4: 68,\n    0x6B5: 68,\n    0x6B6: 68,\n    0x6B7: 68,\n    0x6B8: 68,\n    0x6B9: 68,\n    0x6BA: 68,\n    0x6BB: 68,\n    0x6BC: 68,\n    0x6BD: 68,\n    0x6BE: 68,\n    0x6BF: 68,\n    0x6C0: 82,\n    0x6C1: 68,\n    0x6C2: 68,\n    0x6C3: 82,\n    0x6C4: 82,\n    0x6C5: 82,\n    0x6C6: 82,\n    0x6C7: 82,\n    0x6C8: 82,\n    0x6C9: 82,\n    0x6CA: 82,\n    0x6CB: 82,\n    0x6CC: 68,\n    0x6CD: 82,\n    0x6CE: 68,\n    0x6CF: 82,\n    0x6D0: 68,\n    0x6D1: 68,\n    0x6D2: 82,\n    0x6D3: 82,\n    0x6D5: 82,\n    0x6D6: 84,\n    0x6D7: 84,\n    0x6D8: 84,\n    0x6D9: 84,\n    0x6DA: 84,\n    0x6DB: 84,\n    0x6DC: 84,\n    0x6DF: 84,\n    0x6E0: 84,\n    0x6E1: 84,\n    0x6E2: 84,\n    0x6E3: 84,\n    0x6E4: 84,\n    0x6E7: 84,\n    0x6E8: 84,\n    0x6EA: 84,\n    0x6EB: 84,\n    0x6EC: 84,\n    0x6ED: 84,\n    0x6EE: 82,\n    0x6EF: 82,\n    0x6FA: 68,\n    0x6FB: 68,\n    0x6FC: 68,\n    0x6FF: 68,\n    0x70F: 84,\n    0x710: 82,\n    0x711: 84,\n    0x712: 68,\n    0x713: 68,\n    0x714: 68,\n    0x715: 82,\n    0x716: 82,\n    0x717: 82,\n    0x718: 82,\n    0x719: 82,\n    0x71A: 68,\n    0x71B: 68,\n    0x71C: 68,\n    0x71D: 68,\n    0x71E: 82,\n    0x71F: 68,\n    0x720: 68,\n    0x721: 68,\n    0x722: 68,\n    0x723: 68,\n    0x724: 68,\n    0x725: 68,\n    0x726: 68,\n    0x727: 68,\n    0x728: 82,\n    0x729: 68,\n    0x72A: 82,\n    0x72B: 68,\n    0x72C: 82,\n    0x72D: 68,\n    0x72E: 68,\n    0x72F: 82,\n    0x730: 84,\n    0x731: 84,\n    0x732: 84,\n    0x733: 84,\n    0x734: 84,\n    0x735: 84,\n    0x736: 84,\n    0x737: 84,\n    0x738: 84,\n    0x739: 84,\n    0x73A: 84,\n    0x73B: 84,\n    0x73C: 84,\n    0x73D: 84,\n    0x73E: 84,\n    0x73F: 84,\n    0x740: 84,\n    0x741: 84,\n    0x742: 84,\n    0x743: 84,\n    0x744: 84,\n    0x745: 84,\n    0x746: 84,\n    0x747: 84,\n    0x748: 84,\n    0x749: 84,\n    0x74A: 84,\n    0x74D: 82,\n    0x74E: 68,\n    0x74F: 68,\n    0x750: 68,\n    0x751: 68,\n    0x752: 68,\n    0x753: 68,\n    0x754: 68,\n    0x755: 68,\n    0x756: 68,\n    0x757: 68,\n    0x758: 68,\n    0x759: 82,\n    0x75A: 82,\n    0x75B: 82,\n    0x75C: 68,\n    0x75D: 68,\n    0x75E: 68,\n    0x75F: 68,\n    0x760: 68,\n    0x761: 68,\n    0x762: 68,\n    0x763: 68,\n    0x764: 68,\n    0x765: 68,\n    0x766: 68,\n    0x767: 68,\n    0x768: 68,\n    0x769: 68,\n    0x76A: 68,\n    0x76B: 82,\n    0x76C: 82,\n    0x76D: 68,\n    0x76E: 68,\n    0x76F: 68,\n    0x770: 68,\n    0x771: 82,\n    0x772: 68,\n    0x773: 82,\n    0x774: 82,\n    0x775: 68,\n    0x776: 68,\n    0x777: 68,\n    0x778: 82,\n    0x779: 82,\n    0x77A: 68,\n    0x77B: 68,\n    0x77C: 68,\n    0x77D: 68,\n    0x77E: 68,\n    0x77F: 68,\n    0x7A6: 84,\n    0x7A7: 84,\n    0x7A8: 84,\n    0x7A9: 84,\n    0x7AA: 84,\n    0x7AB: 84,\n    0x7AC: 84,\n    0x7AD: 84,\n    0x7AE: 84,\n    0x7AF: 84,\n    0x7B0: 84,\n    0x7CA: 68,\n    0x7CB: 68,\n    0x7CC: 68,\n    0x7CD: 68,\n    0x7CE: 68,\n    0x7CF: 68,\n    0x7D0: 68,\n    0x7D1: 68,\n    0x7D2: 68,\n    0x7D3: 68,\n    0x7D4: 68,\n    0x7D5: 68,\n    0x7D6: 68,\n    0x7D7: 68,\n    0x7D8: 68,\n    0x7D9: 68,\n    0x7DA: 68,\n    0x7DB: 68,\n    0x7DC: 68,\n    0x7DD: 68,\n    0x7DE: 68,\n    0x7DF: 68,\n    0x7E0: 68,\n    0x7E1: 68,\n    0x7E2: 68,\n    0x7E3: 68,\n    0x7E4: 68,\n    0x7E5: 68,\n    0x7E6: 68,\n    0x7E7: 68,\n    0x7E8: 68,\n    0x7E9: 68,\n    0x7EA: 68,\n    0x7EB: 84,\n    0x7EC: 84,\n    0x7ED: 84,\n    0x7EE: 84,\n    0x7EF: 84,\n    0x7F0: 84,\n    0x7F1: 84,\n    0x7F2: 84,\n    0x7F3: 84,\n    0x7FA: 67,\n    0x7FD: 84,\n    0x816: 84,\n    0x817: 84,\n    0x818: 84,\n    0x819: 84,\n    0x81B: 84,\n    0x81C: 84,\n    0x81D: 84,\n    0x81E: 84,\n    0x81F: 84,\n    0x820: 84,\n    0x821: 84,\n    0x822: 84,\n    0x823: 84,\n    0x825: 84,\n    0x826: 84,\n    0x827: 84,\n    0x829: 84,\n    0x82A: 84,\n    0x82B: 84,\n    0x82C: 84,\n    0x82D: 84,\n    0x840: 82,\n    0x841: 68,\n    0x842: 68,\n    0x843: 68,\n    0x844: 68,\n    0x845: 68,\n    0x846: 82,\n    0x847: 82,\n    0x848: 68,\n    0x849: 82,\n    0x84A: 68,\n    0x84B: 68,\n    0x84C: 68,\n    0x84D: 68,\n    0x84E: 68,\n    0x84F: 68,\n    0x850: 68,\n    0x851: 68,\n    0x852: 68,\n    0x853: 68,\n    0x854: 82,\n    0x855: 68,\n    0x856: 82,\n    0x857: 82,\n    0x858: 82,\n    0x859: 84,\n    0x85A: 84,\n    0x85B: 84,\n    0x860: 68,\n    0x862: 68,\n    0x863: 68,\n    0x864: 68,\n    0x865: 68,\n    0x867: 82,\n    0x868: 68,\n    0x869: 82,\n    0x86A: 82,\n    0x870: 82,\n    0x871: 82,\n    0x872: 82,\n    0x873: 82,\n    0x874: 82,\n    0x875: 82,\n    0x876: 82,\n    0x877: 82,\n    0x878: 82,\n    0x879: 82,\n    0x87A: 82,\n    0x87B: 82,\n    0x87C: 82,\n    0x87D: 82,\n    0x87E: 82,\n    0x87F: 82,\n    0x880: 82,\n    0x881: 82,\n    0x882: 82,\n    0x883: 67,\n    0x884: 67,\n    0x885: 67,\n    0x886: 68,\n    0x889: 68,\n    0x88A: 68,\n    0x88B: 68,\n    0x88C: 68,\n    0x88D: 68,\n    0x88E: 82,\n    0x897: 84,\n    0x898: 84,\n    0x899: 84,\n    0x89A: 84,\n    0x89B: 84,\n    0x89C: 84,\n    0x89D: 84,\n    0x89E: 84,\n    0x89F: 84,\n    0x8A0: 68,\n    0x8A1: 68,\n    0x8A2: 68,\n    0x8A3: 68,\n    0x8A4: 68,\n    0x8A5: 68,\n    0x8A6: 68,\n    0x8A7: 68,\n    0x8A8: 68,\n    0x8A9: 68,\n    0x8AA: 82,\n    0x8AB: 82,\n    0x8AC: 82,\n    0x8AE: 82,\n    0x8AF: 68,\n    0x8B0: 68,\n    0x8B1: 82,\n    0x8B2: 82,\n    0x8B3: 68,\n    0x8B4: 68,\n    0x8B5: 68,\n    0x8B6: 68,\n    0x8B7: 68,\n    0x8B8: 68,\n    0x8B9: 82,\n    0x8BA: 68,\n    0x8BB: 68,\n    0x8BC: 68,\n    0x8BD: 68,\n    0x8BE: 68,\n    0x8BF: 68,\n    0x8C0: 68,\n    0x8C1: 68,\n    0x8C2: 68,\n    0x8C3: 68,\n    0x8C4: 68,\n    0x8C5: 68,\n    0x8C6: 68,\n    0x8C7: 68,\n    0x8C8: 68,\n    0x8CA: 84,\n    0x8CB: 84,\n    0x8CC: 84,\n    0x8CD: 84,\n    0x8CE: 84,\n    0x8CF: 84,\n    0x8D0: 84,\n    0x8D1: 84,\n    0x8D2: 84,\n    0x8D3: 84,\n    0x8D4: 84,\n    0x8D5: 84,\n    0x8D6: 84,\n    0x8D7: 84,\n    0x8D8: 84,\n    0x8D9: 84,\n    0x8DA: 84,\n    0x8DB: 84,\n    0x8DC: 84,\n    0x8DD: 84,\n    0x8DE: 84,\n    0x8DF: 84,\n    0x8E0: 84,\n    0x8E1: 84,\n    0x8E3: 84,\n    0x8E4: 84,\n    0x8E5: 84,\n    0x8E6: 84,\n    0x8E7: 84,\n    0x8E8: 84,\n    0x8E9: 84,\n    0x8EA: 84,\n    0x8EB: 84,\n    0x8EC: 84,\n    0x8ED: 84,\n    0x8EE: 84,\n    0x8EF: 84,\n    0x8F0: 84,\n    0x8F1: 84,\n    0x8F2: 84,\n    0x8F3: 84,\n    0x8F4: 84,\n    0x8F5: 84,\n    0x8F6: 84,\n    0x8F7: 84,\n    0x8F8: 84,\n    0x8F9: 84,\n    0x8FA: 84,\n    0x8FB: 84,\n    0x8FC: 84,\n    0x8FD: 84,\n    0x8FE: 84,\n    0x8FF: 84,\n    0x900: 84,\n    0x901: 84,\n    0x902: 84,\n    0x93A: 84,\n    0x93C: 84,\n    0x941: 84,\n    0x942: 84,\n    0x943: 84,\n    0x944: 84,\n    0x945: 84,\n    0x946: 84,\n    0x947: 84,\n    0x948: 84,\n    0x94D: 84,\n    0x951: 84,\n    0x952: 84,\n    0x953: 84,\n    0x954: 84,\n    0x955: 84,\n    0x956: 84,\n    0x957: 84,\n    0x962: 84,\n    0x963: 84,\n    0x981: 84,\n    0x9BC: 84,\n    0x9C1: 84,\n    0x9C2: 84,\n    0x9C3: 84,\n    0x9C4: 84,\n    0x9CD: 84,\n    0x9E2: 84,\n    0x9E3: 84,\n    0x9FE: 84,\n    0xA01: 84,\n    0xA02: 84,\n    0xA3C: 84,\n    0xA41: 84,\n    0xA42: 84,\n    0xA47: 84,\n    0xA48: 84,\n    0xA4B: 84,\n    0xA4C: 84,\n    0xA4D: 84,\n    0xA51: 84,\n    0xA70: 84,\n    0xA71: 84,\n    0xA75: 84,\n    0xA81: 84,\n    0xA82: 84,\n    0xABC: 84,\n    0xAC1: 84,\n    0xAC2: 84,\n    0xAC3: 84,\n    0xAC4: 84,\n    0xAC5: 84,\n    0xAC7: 84,\n    0xAC8: 84,\n    0xACD: 84,\n    0xAE2: 84,\n    0xAE3: 84,\n    0xAFA: 84,\n    0xAFB: 84,\n    0xAFC: 84,\n    0xAFD: 84,\n    0xAFE: 84,\n    0xAFF: 84,\n    0xB01: 84,\n    0xB3C: 84,\n    0xB3F: 84,\n    0xB41: 84,\n    0xB42: 84,\n    0xB43: 84,\n    0xB44: 84,\n    0xB4D: 84,\n    0xB55: 84,\n    0xB56: 84,\n    0xB62: 84,\n    0xB63: 84,\n    0xB82: 84,\n    0xBC0: 84,\n    0xBCD: 84,\n    0xC00: 84,\n    0xC04: 84,\n    0xC3C: 84,\n    0xC3E: 84,\n    0xC3F: 84,\n    0xC40: 84,\n    0xC46: 84,\n    0xC47: 84,\n    0xC48: 84,\n    0xC4A: 84,\n    0xC4B: 84,\n    0xC4C: 84,\n    0xC4D: 84,\n    0xC55: 84,\n    0xC56: 84,\n    0xC62: 84,\n    0xC63: 84,\n    0xC81: 84,\n    0xCBC: 84,\n    0xCBF: 84,\n    0xCC6: 84,\n    0xCCC: 84,\n    0xCCD: 84,\n    0xCE2: 84,\n    0xCE3: 84,\n    0xD00: 84,\n    0xD01: 84,\n    0xD3B: 84,\n    0xD3C: 84,\n    0xD41: 84,\n    0xD42: 84,\n    0xD43: 84,\n    0xD44: 84,\n    0xD4D: 84,\n    0xD62: 84,\n    0xD63: 84,\n    0xD81: 84,\n    0xDCA: 84,\n    0xDD2: 84,\n    0xDD3: 84,\n    0xDD4: 84,\n    0xDD6: 84,\n    0xE31: 84,\n    0xE34: 84,\n    0xE35: 84,\n    0xE36: 84,\n    0xE37: 84,\n    0xE38: 84,\n    0xE39: 84,\n    0xE3A: 84,\n    0xE47: 84,\n    0xE48: 84,\n    0xE49: 84,\n    0xE4A: 84,\n    0xE4B: 84,\n    0xE4C: 84,\n    0xE4D: 84,\n    0xE4E: 84,\n    0xEB1: 84,\n    0xEB4: 84,\n    0xEB5: 84,\n    0xEB6: 84,\n    0xEB7: 84,\n    0xEB8: 84,\n    0xEB9: 84,\n    0xEBA: 84,\n    0xEBB: 84,\n    0xEBC: 84,\n    0xEC8: 84,\n    0xEC9: 84,\n    0xECA: 84,\n    0xECB: 84,\n    0xECC: 84,\n    0xECD: 84,\n    0xECE: 84,\n    0xF18: 84,\n    0xF19: 84,\n    0xF35: 84,\n    0xF37: 84,\n    0xF39: 84,\n    0xF71: 84,\n    0xF72: 84,\n    0xF73: 84,\n    0xF74: 84,\n    0xF75: 84,\n    0xF76: 84,\n    0xF77: 84,\n    0xF78: 84,\n    0xF79: 84,\n    0xF7A: 84,\n    0xF7B: 84,\n    0xF7C: 84,\n    0xF7D: 84,\n    0xF7E: 84,\n    0xF80: 84,\n    0xF81: 84,\n    0xF82: 84,\n    0xF83: 84,\n    0xF84: 84,\n    0xF86: 84,\n    0xF87: 84,\n    0xF8D: 84,\n    0xF8E: 84,\n    0xF8F: 84,\n    0xF90: 84,\n    0xF91: 84,\n    0xF92: 84,\n    0xF93: 84,\n    0xF94: 84,\n    0xF95: 84,\n    0xF96: 84,\n    0xF97: 84,\n    0xF99: 84,\n    0xF9A: 84,\n    0xF9B: 84,\n    0xF9C: 84,\n    0xF9D: 84,\n    0xF9E: 84,\n    0xF9F: 84,\n    0xFA0: 84,\n    0xFA1: 84,\n    0xFA2: 84,\n    0xFA3: 84,\n    0xFA4: 84,\n    0xFA5: 84,\n    0xFA6: 84,\n    0xFA7: 84,\n    0xFA8: 84,\n    0xFA9: 84,\n    0xFAA: 84,\n    0xFAB: 84,\n    0xFAC: 84,\n    0xFAD: 84,\n    0xFAE: 84,\n    0xFAF: 84,\n    0xFB0: 84,\n    0xFB1: 84,\n    0xFB2: 84,\n    0xFB3: 84,\n    0xFB4: 84,\n    0xFB5: 84,\n    0xFB6: 84,\n    0xFB7: 84,\n    0xFB8: 84,\n    0xFB9: 84,\n    0xFBA: 84,\n    0xFBB: 84,\n    0xFBC: 84,\n    0xFC6: 84,\n    0x102D: 84,\n    0x102E: 84,\n    0x102F: 84,\n    0x1030: 84,\n    0x1032: 84,\n    0x1033: 84,\n    0x1034: 84,\n    0x1035: 84,\n    0x1036: 84,\n    0x1037: 84,\n    0x1039: 84,\n    0x103A: 84,\n    0x103D: 84,\n    0x103E: 84,\n    0x1058: 84,\n    0x1059: 84,\n    0x105E: 84,\n    0x105F: 84,\n    0x1060: 84,\n    0x1071: 84,\n    0x1072: 84,\n    0x1073: 84,\n    0x1074: 84,\n    0x1082: 84,\n    0x1085: 84,\n    0x1086: 84,\n    0x108D: 84,\n    0x109D: 84,\n    0x135D: 84,\n    0x135E: 84,\n    0x135F: 84,\n    0x1712: 84,\n    0x1713: 84,\n    0x1714: 84,\n    0x1732: 84,\n    0x1733: 84,\n    0x1752: 84,\n    0x1753: 84,\n    0x1772: 84,\n    0x1773: 84,\n    0x17B4: 84,\n    0x17B5: 84,\n    0x17B7: 84,\n    0x17B8: 84,\n    0x17B9: 84,\n    0x17BA: 84,\n    0x17BB: 84,\n    0x17BC: 84,\n    0x17BD: 84,\n    0x17C6: 84,\n    0x17C9: 84,\n    0x17CA: 84,\n    0x17CB: 84,\n    0x17CC: 84,\n    0x17CD: 84,\n    0x17CE: 84,\n    0x17CF: 84,\n    0x17D0: 84,\n    0x17D1: 84,\n    0x17D2: 84,\n    0x17D3: 84,\n    0x17DD: 84,\n    0x1807: 68,\n    0x180A: 67,\n    0x180B: 84,\n    0x180C: 84,\n    0x180D: 84,\n    0x180F: 84,\n    0x1820: 68,\n    0x1821: 68,\n    0x1822: 68,\n    0x1823: 68,\n    0x1824: 68,\n    0x1825: 68,\n    0x1826: 68,\n    0x1827: 68,\n    0x1828: 68,\n    0x1829: 68,\n    0x182A: 68,\n    0x182B: 68,\n    0x182C: 68,\n    0x182D: 68,\n    0x182E: 68,\n    0x182F: 68,\n    0x1830: 68,\n    0x1831: 68,\n    0x1832: 68,\n    0x1833: 68,\n    0x1834: 68,\n    0x1835: 68,\n    0x1836: 68,\n    0x1837: 68,\n    0x1838: 68,\n    0x1839: 68,\n    0x183A: 68,\n    0x183B: 68,\n    0x183C: 68,\n    0x183D: 68,\n    0x183E: 68,\n    0x183F: 68,\n    0x1840: 68,\n    0x1841: 68,\n    0x1842: 68,\n    0x1843: 68,\n    0x1844: 68,\n    0x1845: 68,\n    0x1846: 68,\n    0x1847: 68,\n    0x1848: 68,\n    0x1849: 68,\n    0x184A: 68,\n    0x184B: 68,\n    0x184C: 68,\n    0x184D: 68,\n    0x184E: 68,\n    0x184F: 68,\n    0x1850: 68,\n    0x1851: 68,\n    0x1852: 68,\n    0x1853: 68,\n    0x1854: 68,\n    0x1855: 68,\n    0x1856: 68,\n    0x1857: 68,\n    0x1858: 68,\n    0x1859: 68,\n    0x185A: 68,\n    0x185B: 68,\n    0x185C: 68,\n    0x185D: 68,\n    0x185E: 68,\n    0x185F: 68,\n    0x1860: 68,\n    0x1861: 68,\n    0x1862: 68,\n    0x1863: 68,\n    0x1864: 68,\n    0x1865: 68,\n    0x1866: 68,\n    0x1867: 68,\n    0x1868: 68,\n    0x1869: 68,\n    0x186A: 68,\n    0x186B: 68,\n    0x186C: 68,\n    0x186D: 68,\n    0x186E: 68,\n    0x186F: 68,\n    0x1870: 68,\n    0x1871: 68,\n    0x1872: 68,\n    0x1873: 68,\n    0x1874: 68,\n    0x1875: 68,\n    0x1876: 68,\n    0x1877: 68,\n    0x1878: 68,\n    0x1885: 84,\n    0x1886: 84,\n    0x1887: 68,\n    0x1888: 68,\n    0x1889: 68,\n    0x188A: 68,\n    0x188B: 68,\n    0x188C: 68,\n    0x188D: 68,\n    0x188E: 68,\n    0x188F: 68,\n    0x1890: 68,\n    0x1891: 68,\n    0x1892: 68,\n    0x1893: 68,\n    0x1894: 68,\n    0x1895: 68,\n    0x1896: 68,\n    0x1897: 68,\n    0x1898: 68,\n    0x1899: 68,\n    0x189A: 68,\n    0x189B: 68,\n    0x189C: 68,\n    0x189D: 68,\n    0x189E: 68,\n    0x189F: 68,\n    0x18A0: 68,\n    0x18A1: 68,\n    0x18A2: 68,\n    0x18A3: 68,\n    0x18A4: 68,\n    0x18A5: 68,\n    0x18A6: 68,\n    0x18A7: 68,\n    0x18A8: 68,\n    0x18A9: 84,\n    0x18AA: 68,\n    0x1920: 84,\n    0x1921: 84,\n    0x1922: 84,\n    0x1927: 84,\n    0x1928: 84,\n    0x1932: 84,\n    0x1939: 84,\n    0x193A: 84,\n    0x193B: 84,\n    0x1A17: 84,\n    0x1A18: 84,\n    0x1A1B: 84,\n    0x1A56: 84,\n    0x1A58: 84,\n    0x1A59: 84,\n    0x1A5A: 84,\n    0x1A5B: 84,\n    0x1A5C: 84,\n    0x1A5D: 84,\n    0x1A5E: 84,\n    0x1A60: 84,\n    0x1A62: 84,\n    0x1A65: 84,\n    0x1A66: 84,\n    0x1A67: 84,\n    0x1A68: 84,\n    0x1A69: 84,\n    0x1A6A: 84,\n    0x1A6B: 84,\n    0x1A6C: 84,\n    0x1A73: 84,\n    0x1A74: 84,\n    0x1A75: 84,\n    0x1A76: 84,\n    0x1A77: 84,\n    0x1A78: 84,\n    0x1A79: 84,\n    0x1A7A: 84,\n    0x1A7B: 84,\n    0x1A7C: 84,\n    0x1A7F: 84,\n    0x1AB0: 84,\n    0x1AB1: 84,\n    0x1AB2: 84,\n    0x1AB3: 84,\n    0x1AB4: 84,\n    0x1AB5: 84,\n    0x1AB6: 84,\n    0x1AB7: 84,\n    0x1AB8: 84,\n    0x1AB9: 84,\n    0x1ABA: 84,\n    0x1ABB: 84,\n    0x1ABC: 84,\n    0x1ABD: 84,\n    0x1ABE: 84,\n    0x1ABF: 84,\n    0x1AC0: 84,\n    0x1AC1: 84,\n    0x1AC2: 84,\n    0x1AC3: 84,\n    0x1AC4: 84,\n    0x1AC5: 84,\n    0x1AC6: 84,\n    0x1AC7: 84,\n    0x1AC8: 84,\n    0x1AC9: 84,\n    0x1ACA: 84,\n    0x1ACB: 84,\n    0x1ACC: 84,\n    0x1ACD: 84,\n    0x1ACE: 84,\n    0x1B00: 84,\n    0x1B01: 84,\n    0x1B02: 84,\n    0x1B03: 84,\n    0x1B34: 84,\n    0x1B36: 84,\n    0x1B37: 84,\n    0x1B38: 84,\n    0x1B39: 84,\n    0x1B3A: 84,\n    0x1B3C: 84,\n    0x1B42: 84,\n    0x1B6B: 84,\n    0x1B6C: 84,\n    0x1B6D: 84,\n    0x1B6E: 84,\n    0x1B6F: 84,\n    0x1B70: 84,\n    0x1B71: 84,\n    0x1B72: 84,\n    0x1B73: 84,\n    0x1B80: 84,\n    0x1B81: 84,\n    0x1BA2: 84,\n    0x1BA3: 84,\n    0x1BA4: 84,\n    0x1BA5: 84,\n    0x1BA8: 84,\n    0x1BA9: 84,\n    0x1BAB: 84,\n    0x1BAC: 84,\n    0x1BAD: 84,\n    0x1BE6: 84,\n    0x1BE8: 84,\n    0x1BE9: 84,\n    0x1BED: 84,\n    0x1BEF: 84,\n    0x1BF0: 84,\n    0x1BF1: 84,\n    0x1C2C: 84,\n    0x1C2D: 84,\n    0x1C2E: 84,\n    0x1C2F: 84,\n    0x1C30: 84,\n    0x1C31: 84,\n    0x1C32: 84,\n    0x1C33: 84,\n    0x1C36: 84,\n    0x1C37: 84,\n    0x1CD0: 84,\n    0x1CD1: 84,\n    0x1CD2: 84,\n    0x1CD4: 84,\n    0x1CD5: 84,\n    0x1CD6: 84,\n    0x1CD7: 84,\n    0x1CD8: 84,\n    0x1CD9: 84,\n    0x1CDA: 84,\n    0x1CDB: 84,\n    0x1CDC: 84,\n    0x1CDD: 84,\n    0x1CDE: 84,\n    0x1CDF: 84,\n    0x1CE0: 84,\n    0x1CE2: 84,\n    0x1CE3: 84,\n    0x1CE4: 84,\n    0x1CE5: 84,\n    0x1CE6: 84,\n    0x1CE7: 84,\n    0x1CE8: 84,\n    0x1CED: 84,\n    0x1CF4: 84,\n    0x1CF8: 84,\n    0x1CF9: 84,\n    0x1DC0: 84,\n    0x1DC1: 84,\n    0x1DC2: 84,\n    0x1DC3: 84,\n    0x1DC4: 84,\n    0x1DC5: 84,\n    0x1DC6: 84,\n    0x1DC7: 84,\n    0x1DC8: 84,\n    0x1DC9: 84,\n    0x1DCA: 84,\n    0x1DCB: 84,\n    0x1DCC: 84,\n    0x1DCD: 84,\n    0x1DCE: 84,\n    0x1DCF: 84,\n    0x1DD0: 84,\n    0x1DD1: 84,\n    0x1DD2: 84,\n    0x1DD3: 84,\n    0x1DD4: 84,\n    0x1DD5: 84,\n    0x1DD6: 84,\n    0x1DD7: 84,\n    0x1DD8: 84,\n    0x1DD9: 84,\n    0x1DDA: 84,\n    0x1DDB: 84,\n    0x1DDC: 84,\n    0x1DDD: 84,\n    0x1DDE: 84,\n    0x1DDF: 84,\n    0x1DE0: 84,\n    0x1DE1: 84,\n    0x1DE2: 84,\n    0x1DE3: 84,\n    0x1DE4: 84,\n    0x1DE5: 84,\n    0x1DE6: 84,\n    0x1DE7: 84,\n    0x1DE8: 84,\n    0x1DE9: 84,\n    0x1DEA: 84,\n    0x1DEB: 84,\n    0x1DEC: 84,\n    0x1DED: 84,\n    0x1DEE: 84,\n    0x1DEF: 84,\n    0x1DF0: 84,\n    0x1DF1: 84,\n    0x1DF2: 84,\n    0x1DF3: 84,\n    0x1DF4: 84,\n    0x1DF5: 84,\n    0x1DF6: 84,\n    0x1DF7: 84,\n    0x1DF8: 84,\n    0x1DF9: 84,\n    0x1DFA: 84,\n    0x1DFB: 84,\n    0x1DFC: 84,\n    0x1DFD: 84,\n    0x1DFE: 84,\n    0x1DFF: 84,\n    0x200B: 84,\n    0x200D: 67,\n    0x200E: 84,\n    0x200F: 84,\n    0x202A: 84,\n    0x202B: 84,\n    0x202C: 84,\n    0x202D: 84,\n    0x202E: 84,\n    0x2060: 84,\n    0x2061: 84,\n    0x2062: 84,\n    0x2063: 84,\n    0x2064: 84,\n    0x206A: 84,\n    0x206B: 84,\n    0x206C: 84,\n    0x206D: 84,\n    0x206E: 84,\n    0x206F: 84,\n    0x20D0: 84,\n    0x20D1: 84,\n    0x20D2: 84,\n    0x20D3: 84,\n    0x20D4: 84,\n    0x20D5: 84,\n    0x20D6: 84,\n    0x20D7: 84,\n    0x20D8: 84,\n    0x20D9: 84,\n    0x20DA: 84,\n    0x20DB: 84,\n    0x20DC: 84,\n    0x20DD: 84,\n    0x20DE: 84,\n    0x20DF: 84,\n    0x20E0: 84,\n    0x20E1: 84,\n    0x20E2: 84,\n    0x20E3: 84,\n    0x20E4: 84,\n    0x20E5: 84,\n    0x20E6: 84,\n    0x20E7: 84,\n    0x20E8: 84,\n    0x20E9: 84,\n    0x20EA: 84,\n    0x20EB: 84,\n    0x20EC: 84,\n    0x20ED: 84,\n    0x20EE: 84,\n    0x20EF: 84,\n    0x20F0: 84,\n    0x2CEF: 84,\n    0x2CF0: 84,\n    0x2CF1: 84,\n    0x2D7F: 84,\n    0x2DE0: 84,\n    0x2DE1: 84,\n    0x2DE2: 84,\n    0x2DE3: 84,\n    0x2DE4: 84,\n    0x2DE5: 84,\n    0x2DE6: 84,\n    0x2DE7: 84,\n    0x2DE8: 84,\n    0x2DE9: 84,\n    0x2DEA: 84,\n    0x2DEB: 84,\n    0x2DEC: 84,\n    0x2DED: 84,\n    0x2DEE: 84,\n    0x2DEF: 84,\n    0x2DF0: 84,\n    0x2DF1: 84,\n    0x2DF2: 84,\n    0x2DF3: 84,\n    0x2DF4: 84,\n    0x2DF5: 84,\n    0x2DF6: 84,\n    0x2DF7: 84,\n    0x2DF8: 84,\n    0x2DF9: 84,\n    0x2DFA: 84,\n    0x2DFB: 84,\n    0x2DFC: 84,\n    0x2DFD: 84,\n    0x2DFE: 84,\n    0x2DFF: 84,\n    0x302A: 84,\n    0x302B: 84,\n    0x302C: 84,\n    0x302D: 84,\n    0x3099: 84,\n    0x309A: 84,\n    0xA66F: 84,\n    0xA670: 84,\n    0xA671: 84,\n    0xA672: 84,\n    0xA674: 84,\n    0xA675: 84,\n    0xA676: 84,\n    0xA677: 84,\n    0xA678: 84,\n    0xA679: 84,\n    0xA67A: 84,\n    0xA67B: 84,\n    0xA67C: 84,\n    0xA67D: 84,\n    0xA69E: 84,\n    0xA69F: 84,\n    0xA6F0: 84,\n    0xA6F1: 84,\n    0xA802: 84,\n    0xA806: 84,\n    0xA80B: 84,\n    0xA825: 84,\n    0xA826: 84,\n    0xA82C: 84,\n    0xA840: 68,\n    0xA841: 68,\n    0xA842: 68,\n    0xA843: 68,\n    0xA844: 68,\n    0xA845: 68,\n    0xA846: 68,\n    0xA847: 68,\n    0xA848: 68,\n    0xA849: 68,\n    0xA84A: 68,\n    0xA84B: 68,\n    0xA84C: 68,\n    0xA84D: 68,\n    0xA84E: 68,\n    0xA84F: 68,\n    0xA850: 68,\n    0xA851: 68,\n    0xA852: 68,\n    0xA853: 68,\n    0xA854: 68,\n    0xA855: 68,\n    0xA856: 68,\n    0xA857: 68,\n    0xA858: 68,\n    0xA859: 68,\n    0xA85A: 68,\n    0xA85B: 68,\n    0xA85C: 68,\n    0xA85D: 68,\n    0xA85E: 68,\n    0xA85F: 68,\n    0xA860: 68,\n    0xA861: 68,\n    0xA862: 68,\n    0xA863: 68,\n    0xA864: 68,\n    0xA865: 68,\n    0xA866: 68,\n    0xA867: 68,\n    0xA868: 68,\n    0xA869: 68,\n    0xA86A: 68,\n    0xA86B: 68,\n    0xA86C: 68,\n    0xA86D: 68,\n    0xA86E: 68,\n    0xA86F: 68,\n    0xA870: 68,\n    0xA871: 68,\n    0xA872: 76,\n    0xA8C4: 84,\n    0xA8C5: 84,\n    0xA8E0: 84,\n    0xA8E1: 84,\n    0xA8E2: 84,\n    0xA8E3: 84,\n    0xA8E4: 84,\n    0xA8E5: 84,\n    0xA8E6: 84,\n    0xA8E7: 84,\n    0xA8E8: 84,\n    0xA8E9: 84,\n    0xA8EA: 84,\n    0xA8EB: 84,\n    0xA8EC: 84,\n    0xA8ED: 84,\n    0xA8EE: 84,\n    0xA8EF: 84,\n    0xA8F0: 84,\n    0xA8F1: 84,\n    0xA8FF: 84,\n    0xA926: 84,\n    0xA927: 84,\n    0xA928: 84,\n    0xA929: 84,\n    0xA92A: 84,\n    0xA92B: 84,\n    0xA92C: 84,\n    0xA92D: 84,\n    0xA947: 84,\n    0xA948: 84,\n    0xA949: 84,\n    0xA94A: 84,\n    0xA94B: 84,\n    0xA94C: 84,\n    0xA94D: 84,\n    0xA94E: 84,\n    0xA94F: 84,\n    0xA950: 84,\n    0xA951: 84,\n    0xA980: 84,\n    0xA981: 84,\n    0xA982: 84,\n    0xA9B3: 84,\n    0xA9B6: 84,\n    0xA9B7: 84,\n    0xA9B8: 84,\n    0xA9B9: 84,\n    0xA9BC: 84,\n    0xA9BD: 84,\n    0xA9E5: 84,\n    0xAA29: 84,\n    0xAA2A: 84,\n    0xAA2B: 84,\n    0xAA2C: 84,\n    0xAA2D: 84,\n    0xAA2E: 84,\n    0xAA31: 84,\n    0xAA32: 84,\n    0xAA35: 84,\n    0xAA36: 84,\n    0xAA43: 84,\n    0xAA4C: 84,\n    0xAA7C: 84,\n    0xAAB0: 84,\n    0xAAB2: 84,\n    0xAAB3: 84,\n    0xAAB4: 84,\n    0xAAB7: 84,\n    0xAAB8: 84,\n    0xAABE: 84,\n    0xAABF: 84,\n    0xAAC1: 84,\n    0xAAEC: 84,\n    0xAAED: 84,\n    0xAAF6: 84,\n    0xABE5: 84,\n    0xABE8: 84,\n    0xABED: 84,\n    0xFB1E: 84,\n    0xFE00: 84,\n    0xFE01: 84,\n    0xFE02: 84,\n    0xFE03: 84,\n    0xFE04: 84,\n    0xFE05: 84,\n    0xFE06: 84,\n    0xFE07: 84,\n    0xFE08: 84,\n    0xFE09: 84,\n    0xFE0A: 84,\n    0xFE0B: 84,\n    0xFE0C: 84,\n    0xFE0D: 84,\n    0xFE0E: 84,\n    0xFE0F: 84,\n    0xFE20: 84,\n    0xFE21: 84,\n    0xFE22: 84,\n    0xFE23: 84,\n    0xFE24: 84,\n    0xFE25: 84,\n    0xFE26: 84,\n    0xFE27: 84,\n    0xFE28: 84,\n    0xFE29: 84,\n    0xFE2A: 84,\n    0xFE2B: 84,\n    0xFE2C: 84,\n    0xFE2D: 84,\n    0xFE2E: 84,\n    0xFE2F: 84,\n    0xFEFF: 84,\n    0xFFF9: 84,\n    0xFFFA: 84,\n    0xFFFB: 84,\n    0x101FD: 84,\n    0x102E0: 84,\n    0x10376: 84,\n    0x10377: 84,\n    0x10378: 84,\n    0x10379: 84,\n    0x1037A: 84,\n    0x10A01: 84,\n    0x10A02: 84,\n    0x10A03: 84,\n    0x10A05: 84,\n    0x10A06: 84,\n    0x10A0C: 84,\n    0x10A0D: 84,\n    0x10A0E: 84,\n    0x10A0F: 84,\n    0x10A38: 84,\n    0x10A39: 84,\n    0x10A3A: 84,\n    0x10A3F: 84,\n    0x10AC0: 68,\n    0x10AC1: 68,\n    0x10AC2: 68,\n    0x10AC3: 68,\n    0x10AC4: 68,\n    0x10AC5: 82,\n    0x10AC7: 82,\n    0x10AC9: 82,\n    0x10ACA: 82,\n    0x10ACD: 76,\n    0x10ACE: 82,\n    0x10ACF: 82,\n    0x10AD0: 82,\n    0x10AD1: 82,\n    0x10AD2: 82,\n    0x10AD3: 68,\n    0x10AD4: 68,\n    0x10AD5: 68,\n    0x10AD6: 68,\n    0x10AD7: 76,\n    0x10AD8: 68,\n    0x10AD9: 68,\n    0x10ADA: 68,\n    0x10ADB: 68,\n    0x10ADC: 68,\n    0x10ADD: 82,\n    0x10ADE: 68,\n    0x10ADF: 68,\n    0x10AE0: 68,\n    0x10AE1: 82,\n    0x10AE4: 82,\n    0x10AE5: 84,\n    0x10AE6: 84,\n    0x10AEB: 68,\n    0x10AEC: 68,\n    0x10AED: 68,\n    0x10AEE: 68,\n    0x10AEF: 82,\n    0x10B80: 68,\n    0x10B81: 82,\n    0x10B82: 68,\n    0x10B83: 82,\n    0x10B84: 82,\n    0x10B85: 82,\n    0x10B86: 68,\n    0x10B87: 68,\n    0x10B88: 68,\n    0x10B89: 82,\n    0x10B8A: 68,\n    0x10B8B: 68,\n    0x10B8C: 82,\n    0x10B8D: 68,\n    0x10B8E: 82,\n    0x10B8F: 82,\n    0x10B90: 68,\n    0x10B91: 82,\n    0x10BA9: 82,\n    0x10BAA: 82,\n    0x10BAB: 82,\n    0x10BAC: 82,\n    0x10BAD: 68,\n    0x10BAE: 68,\n    0x10D00: 76,\n    0x10D01: 68,\n    0x10D02: 68,\n    0x10D03: 68,\n    0x10D04: 68,\n    0x10D05: 68,\n    0x10D06: 68,\n    0x10D07: 68,\n    0x10D08: 68,\n    0x10D09: 68,\n    0x10D0A: 68,\n    0x10D0B: 68,\n    0x10D0C: 68,\n    0x10D0D: 68,\n    0x10D0E: 68,\n    0x10D0F: 68,\n    0x10D10: 68,\n    0x10D11: 68,\n    0x10D12: 68,\n    0x10D13: 68,\n    0x10D14: 68,\n    0x10D15: 68,\n    0x10D16: 68,\n    0x10D17: 68,\n    0x10D18: 68,\n    0x10D19: 68,\n    0x10D1A: 68,\n    0x10D1B: 68,\n    0x10D1C: 68,\n    0x10D1D: 68,\n    0x10D1E: 68,\n    0x10D1F: 68,\n    0x10D20: 68,\n    0x10D21: 68,\n    0x10D22: 82,\n    0x10D23: 68,\n    0x10D24: 84,\n    0x10D25: 84,\n    0x10D26: 84,\n    0x10D27: 84,\n    0x10D69: 84,\n    0x10D6A: 84,\n    0x10D6B: 84,\n    0x10D6C: 84,\n    0x10D6D: 84,\n    0x10EAB: 84,\n    0x10EAC: 84,\n    0x10EC2: 82,\n    0x10EC3: 68,\n    0x10EC4: 68,\n    0x10EFC: 84,\n    0x10EFD: 84,\n    0x10EFE: 84,\n    0x10EFF: 84,\n    0x10F30: 68,\n    0x10F31: 68,\n    0x10F32: 68,\n    0x10F33: 82,\n    0x10F34: 68,\n    0x10F35: 68,\n    0x10F36: 68,\n    0x10F37: 68,\n    0x10F38: 68,\n    0x10F39: 68,\n    0x10F3A: 68,\n    0x10F3B: 68,\n    0x10F3C: 68,\n    0x10F3D: 68,\n    0x10F3E: 68,\n    0x10F3F: 68,\n    0x10F40: 68,\n    0x10F41: 68,\n    0x10F42: 68,\n    0x10F43: 68,\n    0x10F44: 68,\n    0x10F46: 84,\n    0x10F47: 84,\n    0x10F48: 84,\n    0x10F49: 84,\n    0x10F4A: 84,\n    0x10F4B: 84,\n    0x10F4C: 84,\n    0x10F4D: 84,\n    0x10F4E: 84,\n    0x10F4F: 84,\n    0x10F50: 84,\n    0x10F51: 68,\n    0x10F52: 68,\n    0x10F53: 68,\n    0x10F54: 82,\n    0x10F70: 68,\n    0x10F71: 68,\n    0x10F72: 68,\n    0x10F73: 68,\n    0x10F74: 82,\n    0x10F75: 82,\n    0x10F76: 68,\n    0x10F77: 68,\n    0x10F78: 68,\n    0x10F79: 68,\n    0x10F7A: 68,\n    0x10F7B: 68,\n    0x10F7C: 68,\n    0x10F7D: 68,\n    0x10F7E: 68,\n    0x10F7F: 68,\n    0x10F80: 68,\n    0x10F81: 68,\n    0x10F82: 84,\n    0x10F83: 84,\n    0x10F84: 84,\n    0x10F85: 84,\n    0x10FB0: 68,\n    0x10FB2: 68,\n    0x10FB3: 68,\n    0x10FB4: 82,\n    0x10FB5: 82,\n    0x10FB6: 82,\n    0x10FB8: 68,\n    0x10FB9: 82,\n    0x10FBA: 82,\n    0x10FBB: 68,\n    0x10FBC: 68,\n    0x10FBD: 82,\n    0x10FBE: 68,\n    0x10FBF: 68,\n    0x10FC1: 68,\n    0x10FC2: 82,\n    0x10FC3: 82,\n    0x10FC4: 68,\n    0x10FC9: 82,\n    0x10FCA: 68,\n    0x10FCB: 76,\n    0x11001: 84,\n    0x11038: 84,\n    0x11039: 84,\n    0x1103A: 84,\n    0x1103B: 84,\n    0x1103C: 84,\n    0x1103D: 84,\n    0x1103E: 84,\n    0x1103F: 84,\n    0x11040: 84,\n    0x11041: 84,\n    0x11042: 84,\n    0x11043: 84,\n    0x11044: 84,\n    0x11045: 84,\n    0x11046: 84,\n    0x11070: 84,\n    0x11073: 84,\n    0x11074: 84,\n    0x1107F: 84,\n    0x11080: 84,\n    0x11081: 84,\n    0x110B3: 84,\n    0x110B4: 84,\n    0x110B5: 84,\n    0x110B6: 84,\n    0x110B9: 84,\n    0x110BA: 84,\n    0x110C2: 84,\n    0x11100: 84,\n    0x11101: 84,\n    0x11102: 84,\n    0x11127: 84,\n    0x11128: 84,\n    0x11129: 84,\n    0x1112A: 84,\n    0x1112B: 84,\n    0x1112D: 84,\n    0x1112E: 84,\n    0x1112F: 84,\n    0x11130: 84,\n    0x11131: 84,\n    0x11132: 84,\n    0x11133: 84,\n    0x11134: 84,\n    0x11173: 84,\n    0x11180: 84,\n    0x11181: 84,\n    0x111B6: 84,\n    0x111B7: 84,\n    0x111B8: 84,\n    0x111B9: 84,\n    0x111BA: 84,\n    0x111BB: 84,\n    0x111BC: 84,\n    0x111BD: 84,\n    0x111BE: 84,\n    0x111C9: 84,\n    0x111CA: 84,\n    0x111CB: 84,\n    0x111CC: 84,\n    0x111CF: 84,\n    0x1122F: 84,\n    0x11230: 84,\n    0x11231: 84,\n    0x11234: 84,\n    0x11236: 84,\n    0x11237: 84,\n    0x1123E: 84,\n    0x11241: 84,\n    0x112DF: 84,\n    0x112E3: 84,\n    0x112E4: 84,\n    0x112E5: 84,\n    0x112E6: 84,\n    0x112E7: 84,\n    0x112E8: 84,\n    0x112E9: 84,\n    0x112EA: 84,\n    0x11300: 84,\n    0x11301: 84,\n    0x1133B: 84,\n    0x1133C: 84,\n    0x11340: 84,\n    0x11366: 84,\n    0x11367: 84,\n    0x11368: 84,\n    0x11369: 84,\n    0x1136A: 84,\n    0x1136B: 84,\n    0x1136C: 84,\n    0x11370: 84,\n    0x11371: 84,\n    0x11372: 84,\n    0x11373: 84,\n    0x11374: 84,\n    0x113BB: 84,\n    0x113BC: 84,\n    0x113BD: 84,\n    0x113BE: 84,\n    0x113BF: 84,\n    0x113C0: 84,\n    0x113CE: 84,\n    0x113D0: 84,\n    0x113D2: 84,\n    0x113E1: 84,\n    0x113E2: 84,\n    0x11438: 84,\n    0x11439: 84,\n    0x1143A: 84,\n    0x1143B: 84,\n    0x1143C: 84,\n    0x1143D: 84,\n    0x1143E: 84,\n    0x1143F: 84,\n    0x11442: 84,\n    0x11443: 84,\n    0x11444: 84,\n    0x11446: 84,\n    0x1145E: 84,\n    0x114B3: 84,\n    0x114B4: 84,\n    0x114B5: 84,\n    0x114B6: 84,\n    0x114B7: 84,\n    0x114B8: 84,\n    0x114BA: 84,\n    0x114BF: 84,\n    0x114C0: 84,\n    0x114C2: 84,\n    0x114C3: 84,\n    0x115B2: 84,\n    0x115B3: 84,\n    0x115B4: 84,\n    0x115B5: 84,\n    0x115BC: 84,\n    0x115BD: 84,\n    0x115BF: 84,\n    0x115C0: 84,\n    0x115DC: 84,\n    0x115DD: 84,\n    0x11633: 84,\n    0x11634: 84,\n    0x11635: 84,\n    0x11636: 84,\n    0x11637: 84,\n    0x11638: 84,\n    0x11639: 84,\n    0x1163A: 84,\n    0x1163D: 84,\n    0x1163F: 84,\n    0x11640: 84,\n    0x116AB: 84,\n    0x116AD: 84,\n    0x116B0: 84,\n    0x116B1: 84,\n    0x116B2: 84,\n    0x116B3: 84,\n    0x116B4: 84,\n    0x116B5: 84,\n    0x116B7: 84,\n    0x1171D: 84,\n    0x1171F: 84,\n    0x11722: 84,\n    0x11723: 84,\n    0x11724: 84,\n    0x11725: 84,\n    0x11727: 84,\n    0x11728: 84,\n    0x11729: 84,\n    0x1172A: 84,\n    0x1172B: 84,\n    0x1182F: 84,\n    0x11830: 84,\n    0x11831: 84,\n    0x11832: 84,\n    0x11833: 84,\n    0x11834: 84,\n    0x11835: 84,\n    0x11836: 84,\n    0x11837: 84,\n    0x11839: 84,\n    0x1183A: 84,\n    0x1193B: 84,\n    0x1193C: 84,\n    0x1193E: 84,\n    0x11943: 84,\n    0x119D4: 84,\n    0x119D5: 84,\n    0x119D6: 84,\n    0x119D7: 84,\n    0x119DA: 84,\n    0x119DB: 84,\n    0x119E0: 84,\n    0x11A01: 84,\n    0x11A02: 84,\n    0x11A03: 84,\n    0x11A04: 84,\n    0x11A05: 84,\n    0x11A06: 84,\n    0x11A07: 84,\n    0x11A08: 84,\n    0x11A09: 84,\n    0x11A0A: 84,\n    0x11A33: 84,\n    0x11A34: 84,\n    0x11A35: 84,\n    0x11A36: 84,\n    0x11A37: 84,\n    0x11A38: 84,\n    0x11A3B: 84,\n    0x11A3C: 84,\n    0x11A3D: 84,\n    0x11A3E: 84,\n    0x11A47: 84,\n    0x11A51: 84,\n    0x11A52: 84,\n    0x11A53: 84,\n    0x11A54: 84,\n    0x11A55: 84,\n    0x11A56: 84,\n    0x11A59: 84,\n    0x11A5A: 84,\n    0x11A5B: 84,\n    0x11A8A: 84,\n    0x11A8B: 84,\n    0x11A8C: 84,\n    0x11A8D: 84,\n    0x11A8E: 84,\n    0x11A8F: 84,\n    0x11A90: 84,\n    0x11A91: 84,\n    0x11A92: 84,\n    0x11A93: 84,\n    0x11A94: 84,\n    0x11A95: 84,\n    0x11A96: 84,\n    0x11A98: 84,\n    0x11A99: 84,\n    0x11C30: 84,\n    0x11C31: 84,\n    0x11C32: 84,\n    0x11C33: 84,\n    0x11C34: 84,\n    0x11C35: 84,\n    0x11C36: 84,\n    0x11C38: 84,\n    0x11C39: 84,\n    0x11C3A: 84,\n    0x11C3B: 84,\n    0x11C3C: 84,\n    0x11C3D: 84,\n    0x11C3F: 84,\n    0x11C92: 84,\n    0x11C93: 84,\n    0x11C94: 84,\n    0x11C95: 84,\n    0x11C96: 84,\n    0x11C97: 84,\n    0x11C98: 84,\n    0x11C99: 84,\n    0x11C9A: 84,\n    0x11C9B: 84,\n    0x11C9C: 84,\n    0x11C9D: 84,\n    0x11C9E: 84,\n    0x11C9F: 84,\n    0x11CA0: 84,\n    0x11CA1: 84,\n    0x11CA2: 84,\n    0x11CA3: 84,\n    0x11CA4: 84,\n    0x11CA5: 84,\n    0x11CA6: 84,\n    0x11CA7: 84,\n    0x11CAA: 84,\n    0x11CAB: 84,\n    0x11CAC: 84,\n    0x11CAD: 84,\n    0x11CAE: 84,\n    0x11CAF: 84,\n    0x11CB0: 84,\n    0x11CB2: 84,\n    0x11CB3: 84,\n    0x11CB5: 84,\n    0x11CB6: 84,\n    0x11D31: 84,\n    0x11D32: 84,\n    0x11D33: 84,\n    0x11D34: 84,\n    0x11D35: 84,\n    0x11D36: 84,\n    0x11D3A: 84,\n    0x11D3C: 84,\n    0x11D3D: 84,\n    0x11D3F: 84,\n    0x11D40: 84,\n    0x11D41: 84,\n    0x11D42: 84,\n    0x11D43: 84,\n    0x11D44: 84,\n    0x11D45: 84,\n    0x11D47: 84,\n    0x11D90: 84,\n    0x11D91: 84,\n    0x11D95: 84,\n    0x11D97: 84,\n    0x11EF3: 84,\n    0x11EF4: 84,\n    0x11F00: 84,\n    0x11F01: 84,\n    0x11F36: 84,\n    0x11F37: 84,\n    0x11F38: 84,\n    0x11F39: 84,\n    0x11F3A: 84,\n    0x11F40: 84,\n    0x11F42: 84,\n    0x11F5A: 84,\n    0x13430: 84,\n    0x13431: 84,\n    0x13432: 84,\n    0x13433: 84,\n    0x13434: 84,\n    0x13435: 84,\n    0x13436: 84,\n    0x13437: 84,\n    0x13438: 84,\n    0x13439: 84,\n    0x1343A: 84,\n    0x1343B: 84,\n    0x1343C: 84,\n    0x1343D: 84,\n    0x1343E: 84,\n    0x1343F: 84,\n    0x13440: 84,\n    0x13447: 84,\n    0x13448: 84,\n    0x13449: 84,\n    0x1344A: 84,\n    0x1344B: 84,\n    0x1344C: 84,\n    0x1344D: 84,\n    0x1344E: 84,\n    0x1344F: 84,\n    0x13450: 84,\n    0x13451: 84,\n    0x13452: 84,\n    0x13453: 84,\n    0x13454: 84,\n    0x13455: 84,\n    0x1611E: 84,\n    0x1611F: 84,\n    0x16120: 84,\n    0x16121: 84,\n    0x16122: 84,\n    0x16123: 84,\n    0x16124: 84,\n    0x16125: 84,\n    0x16126: 84,\n    0x16127: 84,\n    0x16128: 84,\n    0x16129: 84,\n    0x1612D: 84,\n    0x1612E: 84,\n    0x1612F: 84,\n    0x16AF0: 84,\n    0x16AF1: 84,\n    0x16AF2: 84,\n    0x16AF3: 84,\n    0x16AF4: 84,\n    0x16B30: 84,\n    0x16B31: 84,\n    0x16B32: 84,\n    0x16B33: 84,\n    0x16B34: 84,\n    0x16B35: 84,\n    0x16B36: 84,\n    0x16F4F: 84,\n    0x16F8F: 84,\n    0x16F90: 84,\n    0x16F91: 84,\n    0x16F92: 84,\n    0x16FE4: 84,\n    0x1BC9D: 84,\n    0x1BC9E: 84,\n    0x1BCA0: 84,\n    0x1BCA1: 84,\n    0x1BCA2: 84,\n    0x1BCA3: 84,\n    0x1CF00: 84,\n    0x1CF01: 84,\n    0x1CF02: 84,\n    0x1CF03: 84,\n    0x1CF04: 84,\n    0x1CF05: 84,\n    0x1CF06: 84,\n    0x1CF07: 84,\n    0x1CF08: 84,\n    0x1CF09: 84,\n    0x1CF0A: 84,\n    0x1CF0B: 84,\n    0x1CF0C: 84,\n    0x1CF0D: 84,\n    0x1CF0E: 84,\n    0x1CF0F: 84,\n    0x1CF10: 84,\n    0x1CF11: 84,\n    0x1CF12: 84,\n    0x1CF13: 84,\n    0x1CF14: 84,\n    0x1CF15: 84,\n    0x1CF16: 84,\n    0x1CF17: 84,\n    0x1CF18: 84,\n    0x1CF19: 84,\n    0x1CF1A: 84,\n    0x1CF1B: 84,\n    0x1CF1C: 84,\n    0x1CF1D: 84,\n    0x1CF1E: 84,\n    0x1CF1F: 84,\n    0x1CF20: 84,\n    0x1CF21: 84,\n    0x1CF22: 84,\n    0x1CF23: 84,\n    0x1CF24: 84,\n    0x1CF25: 84,\n    0x1CF26: 84,\n    0x1CF27: 84,\n    0x1CF28: 84,\n    0x1CF29: 84,\n    0x1CF2A: 84,\n    0x1CF2B: 84,\n    0x1CF2C: 84,\n    0x1CF2D: 84,\n    0x1CF30: 84,\n    0x1CF31: 84,\n    0x1CF32: 84,\n    0x1CF33: 84,\n    0x1CF34: 84,\n    0x1CF35: 84,\n    0x1CF36: 84,\n    0x1CF37: 84,\n    0x1CF38: 84,\n    0x1CF39: 84,\n    0x1CF3A: 84,\n    0x1CF3B: 84,\n    0x1CF3C: 84,\n    0x1CF3D: 84,\n    0x1CF3E: 84,\n    0x1CF3F: 84,\n    0x1CF40: 84,\n    0x1CF41: 84,\n    0x1CF42: 84,\n    0x1CF43: 84,\n    0x1CF44: 84,\n    0x1CF45: 84,\n    0x1CF46: 84,\n    0x1D167: 84,\n    0x1D168: 84,\n    0x1D169: 84,\n    0x1D173: 84,\n    0x1D174: 84,\n    0x1D175: 84,\n    0x1D176: 84,\n    0x1D177: 84,\n    0x1D178: 84,\n    0x1D179: 84,\n    0x1D17A: 84,\n    0x1D17B: 84,\n    0x1D17C: 84,\n    0x1D17D: 84,\n    0x1D17E: 84,\n    0x1D17F: 84,\n    0x1D180: 84,\n    0x1D181: 84,\n    0x1D182: 84,\n    0x1D185: 84,\n    0x1D186: 84,\n    0x1D187: 84,\n    0x1D188: 84,\n    0x1D189: 84,\n    0x1D18A: 84,\n    0x1D18B: 84,\n    0x1D1AA: 84,\n    0x1D1AB: 84,\n    0x1D1AC: 84,\n    0x1D1AD: 84,\n    0x1D242: 84,\n    0x1D243: 84,\n    0x1D244: 84,\n    0x1DA00: 84,\n    0x1DA01: 84,\n    0x1DA02: 84,\n    0x1DA03: 84,\n    0x1DA04: 84,\n    0x1DA05: 84,\n    0x1DA06: 84,\n    0x1DA07: 84,\n    0x1DA08: 84,\n    0x1DA09: 84,\n    0x1DA0A: 84,\n    0x1DA0B: 84,\n    0x1DA0C: 84,\n    0x1DA0D: 84,\n    0x1DA0E: 84,\n    0x1DA0F: 84,\n    0x1DA10: 84,\n    0x1DA11: 84,\n    0x1DA12: 84,\n    0x1DA13: 84,\n    0x1DA14: 84,\n    0x1DA15: 84,\n    0x1DA16: 84,\n    0x1DA17: 84,\n    0x1DA18: 84,\n    0x1DA19: 84,\n    0x1DA1A: 84,\n    0x1DA1B: 84,\n    0x1DA1C: 84,\n    0x1DA1D: 84,\n    0x1DA1E: 84,\n    0x1DA1F: 84,\n    0x1DA20: 84,\n    0x1DA21: 84,\n    0x1DA22: 84,\n    0x1DA23: 84,\n    0x1DA24: 84,\n    0x1DA25: 84,\n    0x1DA26: 84,\n    0x1DA27: 84,\n    0x1DA28: 84,\n    0x1DA29: 84,\n    0x1DA2A: 84,\n    0x1DA2B: 84,\n    0x1DA2C: 84,\n    0x1DA2D: 84,\n    0x1DA2E: 84,\n    0x1DA2F: 84,\n    0x1DA30: 84,\n    0x1DA31: 84,\n    0x1DA32: 84,\n    0x1DA33: 84,\n    0x1DA34: 84,\n    0x1DA35: 84,\n    0x1DA36: 84,\n    0x1DA3B: 84,\n    0x1DA3C: 84,\n    0x1DA3D: 84,\n    0x1DA3E: 84,\n    0x1DA3F: 84,\n    0x1DA40: 84,\n    0x1DA41: 84,\n    0x1DA42: 84,\n    0x1DA43: 84,\n    0x1DA44: 84,\n    0x1DA45: 84,\n    0x1DA46: 84,\n    0x1DA47: 84,\n    0x1DA48: 84,\n    0x1DA49: 84,\n    0x1DA4A: 84,\n    0x1DA4B: 84,\n    0x1DA4C: 84,\n    0x1DA4D: 84,\n    0x1DA4E: 84,\n    0x1DA4F: 84,\n    0x1DA50: 84,\n    0x1DA51: 84,\n    0x1DA52: 84,\n    0x1DA53: 84,\n    0x1DA54: 84,\n    0x1DA55: 84,\n    0x1DA56: 84,\n    0x1DA57: 84,\n    0x1DA58: 84,\n    0x1DA59: 84,\n    0x1DA5A: 84,\n    0x1DA5B: 84,\n    0x1DA5C: 84,\n    0x1DA5D: 84,\n    0x1DA5E: 84,\n    0x1DA5F: 84,\n    0x1DA60: 84,\n    0x1DA61: 84,\n    0x1DA62: 84,\n    0x1DA63: 84,\n    0x1DA64: 84,\n    0x1DA65: 84,\n    0x1DA66: 84,\n    0x1DA67: 84,\n    0x1DA68: 84,\n    0x1DA69: 84,\n    0x1DA6A: 84,\n    0x1DA6B: 84,\n    0x1DA6C: 84,\n    0x1DA75: 84,\n    0x1DA84: 84,\n    0x1DA9B: 84,\n    0x1DA9C: 84,\n    0x1DA9D: 84,\n    0x1DA9E: 84,\n    0x1DA9F: 84,\n    0x1DAA1: 84,\n    0x1DAA2: 84,\n    0x1DAA3: 84,\n    0x1DAA4: 84,\n    0x1DAA5: 84,\n    0x1DAA6: 84,\n    0x1DAA7: 84,\n    0x1DAA8: 84,\n    0x1DAA9: 84,\n    0x1DAAA: 84,\n    0x1DAAB: 84,\n    0x1DAAC: 84,\n    0x1DAAD: 84,\n    0x1DAAE: 84,\n    0x1DAAF: 84,\n    0x1E000: 84,\n    0x1E001: 84,\n    0x1E002: 84,\n    0x1E003: 84,\n    0x1E004: 84,\n    0x1E005: 84,\n    0x1E006: 84,\n    0x1E008: 84,\n    0x1E009: 84,\n    0x1E00A: 84,\n    0x1E00B: 84,\n    0x1E00C: 84,\n    0x1E00D: 84,\n    0x1E00E: 84,\n    0x1E00F: 84,\n    0x1E010: 84,\n    0x1E011: 84,\n    0x1E012: 84,\n    0x1E013: 84,\n    0x1E014: 84,\n    0x1E015: 84,\n    0x1E016: 84,\n    0x1E017: 84,\n    0x1E018: 84,\n    0x1E01B: 84,\n    0x1E01C: 84,\n    0x1E01D: 84,\n    0x1E01E: 84,\n    0x1E01F: 84,\n    0x1E020: 84,\n    0x1E021: 84,\n    0x1E023: 84,\n    0x1E024: 84,\n    0x1E026: 84,\n    0x1E027: 84,\n    0x1E028: 84,\n    0x1E029: 84,\n    0x1E02A: 84,\n    0x1E08F: 84,\n    0x1E130: 84,\n    0x1E131: 84,\n    0x1E132: 84,\n    0x1E133: 84,\n    0x1E134: 84,\n    0x1E135: 84,\n    0x1E136: 84,\n    0x1E2AE: 84,\n    0x1E2EC: 84,\n    0x1E2ED: 84,\n    0x1E2EE: 84,\n    0x1E2EF: 84,\n    0x1E4EC: 84,\n    0x1E4ED: 84,\n    0x1E4EE: 84,\n    0x1E4EF: 84,\n    0x1E5EE: 84,\n    0x1E5EF: 84,\n    0x1E8D0: 84,\n    0x1E8D1: 84,\n    0x1E8D2: 84,\n    0x1E8D3: 84,\n    0x1E8D4: 84,\n    0x1E8D5: 84,\n    0x1E8D6: 84,\n    0x1E900: 68,\n    0x1E901: 68,\n    0x1E902: 68,\n    0x1E903: 68,\n    0x1E904: 68,\n    0x1E905: 68,\n    0x1E906: 68,\n    0x1E907: 68,\n    0x1E908: 68,\n    0x1E909: 68,\n    0x1E90A: 68,\n    0x1E90B: 68,\n    0x1E90C: 68,\n    0x1E90D: 68,\n    0x1E90E: 68,\n    0x1E90F: 68,\n    0x1E910: 68,\n    0x1E911: 68,\n    0x1E912: 68,\n    0x1E913: 68,\n    0x1E914: 68,\n    0x1E915: 68,\n    0x1E916: 68,\n    0x1E917: 68,\n    0x1E918: 68,\n    0x1E919: 68,\n    0x1E91A: 68,\n    0x1E91B: 68,\n    0x1E91C: 68,\n    0x1E91D: 68,\n    0x1E91E: 68,\n    0x1E91F: 68,\n    0x1E920: 68,\n    0x1E921: 68,\n    0x1E922: 68,\n    0x1E923: 68,\n    0x1E924: 68,\n    0x1E925: 68,\n    0x1E926: 68,\n    0x1E927: 68,\n    0x1E928: 68,\n    0x1E929: 68,\n    0x1E92A: 68,\n    0x1E92B: 68,\n    0x1E92C: 68,\n    0x1E92D: 68,\n    0x1E92E: 68,\n    0x1E92F: 68,\n    0x1E930: 68,\n    0x1E931: 68,\n    0x1E932: 68,\n    0x1E933: 68,\n    0x1E934: 68,\n    0x1E935: 68,\n    0x1E936: 68,\n    0x1E937: 68,\n    0x1E938: 68,\n    0x1E939: 68,\n    0x1E93A: 68,\n    0x1E93B: 68,\n    0x1E93C: 68,\n    0x1E93D: 68,\n    0x1E93E: 68,\n    0x1E93F: 68,\n    0x1E940: 68,\n    0x1E941: 68,\n    0x1E942: 68,\n    0x1E943: 68,\n    0x1E944: 84,\n    0x1E945: 84,\n    0x1E946: 84,\n    0x1E947: 84,\n    0x1E948: 84,\n    0x1E949: 84,\n    0x1E94A: 84,\n    0x1E94B: 84,\n    0xE0001: 84,\n    0xE0020: 84,\n    0xE0021: 84,\n    0xE0022: 84,\n    0xE0023: 84,\n    0xE0024: 84,\n    0xE0025: 84,\n    0xE0026: 84,\n    0xE0027: 84,\n    0xE0028: 84,\n    0xE0029: 84,\n    0xE002A: 84,\n    0xE002B: 84,\n    0xE002C: 84,\n    0xE002D: 84,\n    0xE002E: 84,\n    0xE002F: 84,\n    0xE0030: 84,\n    0xE0031: 84,\n    0xE0032: 84,\n    0xE0033: 84,\n    0xE0034: 84,\n    0xE0035: 84,\n    0xE0036: 84,\n    0xE0037: 84,\n    0xE0038: 84,\n    0xE0039: 84,\n    0xE003A: 84,\n    0xE003B: 84,\n    0xE003C: 84,\n    0xE003D: 84,\n    0xE003E: 84,\n    0xE003F: 84,\n    0xE0040: 84,\n    0xE0041: 84,\n    0xE0042: 84,\n    0xE0043: 84,\n    0xE0044: 84,\n    0xE0045: 84,\n    0xE0046: 84,\n    0xE0047: 84,\n    0xE0048: 84,\n    0xE0049: 84,\n    0xE004A: 84,\n    0xE004B: 84,\n    0xE004C: 84,\n    0xE004D: 84,\n    0xE004E: 84,\n    0xE004F: 84,\n    0xE0050: 84,\n    0xE0051: 84,\n    0xE0052: 84,\n    0xE0053: 84,\n    0xE0054: 84,\n    0xE0055: 84,\n    0xE0056: 84,\n    0xE0057: 84,\n    0xE0058: 84,\n    0xE0059: 84,\n    0xE005A: 84,\n    0xE005B: 84,\n    0xE005C: 84,\n    0xE005D: 84,\n    0xE005E: 84,\n    0xE005F: 84,\n    0xE0060: 84,\n    0xE0061: 84,\n    0xE0062: 84,\n    0xE0063: 84,\n    0xE0064: 84,\n    0xE0065: 84,\n    0xE0066: 84,\n    0xE0067: 84,\n    0xE0068: 84,\n    0xE0069: 84,\n    0xE006A: 84,\n    0xE006B: 84,\n    0xE006C: 84,\n    0xE006D: 84,\n    0xE006E: 84,\n    0xE006F: 84,\n    0xE0070: 84,\n    0xE0071: 84,\n    0xE0072: 84,\n    0xE0073: 84,\n    0xE0074: 84,\n    0xE0075: 84,\n    0xE0076: 84,\n    0xE0077: 84,\n    0xE0078: 84,\n    0xE0079: 84,\n    0xE007A: 84,\n    0xE007B: 84,\n    0xE007C: 84,\n    0xE007D: 84,\n    0xE007E: 84,\n    0xE007F: 84,\n    0xE0100: 84,\n    0xE0101: 84,\n    0xE0102: 84,\n    0xE0103: 84,\n    0xE0104: 84,\n    0xE0105: 84,\n    0xE0106: 84,\n    0xE0107: 84,\n    0xE0108: 84,\n    0xE0109: 84,\n    0xE010A: 84,\n    0xE010B: 84,\n    0xE010C: 84,\n    0xE010D: 84,\n    0xE010E: 84,\n    0xE010F: 84,\n    0xE0110: 84,\n    0xE0111: 84,\n    0xE0112: 84,\n    0xE0113: 84,\n    0xE0114: 84,\n    0xE0115: 84,\n    0xE0116: 84,\n    0xE0117: 84,\n    0xE0118: 84,\n    0xE0119: 84,\n    0xE011A: 84,\n    0xE011B: 84,\n    0xE011C: 84,\n    0xE011D: 84,\n    0xE011E: 84,\n    0xE011F: 84,\n    0xE0120: 84,\n    0xE0121: 84,\n    0xE0122: 84,\n    0xE0123: 84,\n    0xE0124: 84,\n    0xE0125: 84,\n    0xE0126: 84,\n    0xE0127: 84,\n    0xE0128: 84,\n    0xE0129: 84,\n    0xE012A: 84,\n    0xE012B: 84,\n    0xE012C: 84,\n    0xE012D: 84,\n    0xE012E: 84,\n    0xE012F: 84,\n    0xE0130: 84,\n    0xE0131: 84,\n    0xE0132: 84,\n    0xE0133: 84,\n    0xE0134: 84,\n    0xE0135: 84,\n    0xE0136: 84,\n    0xE0137: 84,\n    0xE0138: 84,\n    0xE0139: 84,\n    0xE013A: 84,\n    0xE013B: 84,\n    0xE013C: 84,\n    0xE013D: 84,\n    0xE013E: 84,\n    0xE013F: 84,\n    0xE0140: 84,\n    0xE0141: 84,\n    0xE0142: 84,\n    0xE0143: 84,\n    0xE0144: 84,\n    0xE0145: 84,\n    0xE0146: 84,\n    0xE0147: 84,\n    0xE0148: 84,\n    0xE0149: 84,\n    0xE014A: 84,\n    0xE014B: 84,\n    0xE014C: 84,\n    0xE014D: 84,\n    0xE014E: 84,\n    0xE014F: 84,\n    0xE0150: 84,\n    0xE0151: 84,\n    0xE0152: 84,\n    0xE0153: 84,\n    0xE0154: 84,\n    0xE0155: 84,\n    0xE0156: 84,\n    0xE0157: 84,\n    0xE0158: 84,\n    0xE0159: 84,\n    0xE015A: 84,\n    0xE015B: 84,\n    0xE015C: 84,\n    0xE015D: 84,\n    0xE015E: 84,\n    0xE015F: 84,\n    0xE0160: 84,\n    0xE0161: 84,\n    0xE0162: 84,\n    0xE0163: 84,\n    0xE0164: 84,\n    0xE0165: 84,\n    0xE0166: 84,\n    0xE0167: 84,\n    0xE0168: 84,\n    0xE0169: 84,\n    0xE016A: 84,\n    0xE016B: 84,\n    0xE016C: 84,\n    0xE016D: 84,\n    0xE016E: 84,\n    0xE016F: 84,\n    0xE0170: 84,\n    0xE0171: 84,\n    0xE0172: 84,\n    0xE0173: 84,\n    0xE0174: 84,\n    0xE0175: 84,\n    0xE0176: 84,\n    0xE0177: 84,\n    0xE0178: 84,\n    0xE0179: 84,\n    0xE017A: 84,\n    0xE017B: 84,\n    0xE017C: 84,\n    0xE017D: 84,\n    0xE017E: 84,\n    0xE017F: 84,\n    0xE0180: 84,\n    0xE0181: 84,\n    0xE0182: 84,\n    0xE0183: 84,\n    0xE0184: 84,\n    0xE0185: 84,\n    0xE0186: 84,\n    0xE0187: 84,\n    0xE0188: 84,\n    0xE0189: 84,\n    0xE018A: 84,\n    0xE018B: 84,\n    0xE018C: 84,\n    0xE018D: 84,\n    0xE018E: 84,\n    0xE018F: 84,\n    0xE0190: 84,\n    0xE0191: 84,\n    0xE0192: 84,\n    0xE0193: 84,\n    0xE0194: 84,\n    0xE0195: 84,\n    0xE0196: 84,\n    0xE0197: 84,\n    0xE0198: 84,\n    0xE0199: 84,\n    0xE019A: 84,\n    0xE019B: 84,\n    0xE019C: 84,\n    0xE019D: 84,\n    0xE019E: 84,\n    0xE019F: 84,\n    0xE01A0: 84,\n    0xE01A1: 84,\n    0xE01A2: 84,\n    0xE01A3: 84,\n    0xE01A4: 84,\n    0xE01A5: 84,\n    0xE01A6: 84,\n    0xE01A7: 84,\n    0xE01A8: 84,\n    0xE01A9: 84,\n    0xE01AA: 84,\n    0xE01AB: 84,\n    0xE01AC: 84,\n    0xE01AD: 84,\n    0xE01AE: 84,\n    0xE01AF: 84,\n    0xE01B0: 84,\n    0xE01B1: 84,\n    0xE01B2: 84,\n    0xE01B3: 84,\n    0xE01B4: 84,\n    0xE01B5: 84,\n    0xE01B6: 84,\n    0xE01B7: 84,\n    0xE01B8: 84,\n    0xE01B9: 84,\n    0xE01BA: 84,\n    0xE01BB: 84,\n    0xE01BC: 84,\n    0xE01BD: 84,\n    0xE01BE: 84,\n    0xE01BF: 84,\n    0xE01C0: 84,\n    0xE01C1: 84,\n    0xE01C2: 84,\n    0xE01C3: 84,\n    0xE01C4: 84,\n    0xE01C5: 84,\n    0xE01C6: 84,\n    0xE01C7: 84,\n    0xE01C8: 84,\n    0xE01C9: 84,\n    0xE01CA: 84,\n    0xE01CB: 84,\n    0xE01CC: 84,\n    0xE01CD: 84,\n    0xE01CE: 84,\n    0xE01CF: 84,\n    0xE01D0: 84,\n    0xE01D1: 84,\n    0xE01D2: 84,\n    0xE01D3: 84,\n    0xE01D4: 84,\n    0xE01D5: 84,\n    0xE01D6: 84,\n    0xE01D7: 84,\n    0xE01D8: 84,\n    0xE01D9: 84,\n    0xE01DA: 84,\n    0xE01DB: 84,\n    0xE01DC: 84,\n    0xE01DD: 84,\n    0xE01DE: 84,\n    0xE01DF: 84,\n    0xE01E0: 84,\n    0xE01E1: 84,\n    0xE01E2: 84,\n    0xE01E3: 84,\n    0xE01E4: 84,\n    0xE01E5: 84,\n    0xE01E6: 84,\n    0xE01E7: 84,\n    0xE01E8: 84,\n    0xE01E9: 84,\n    0xE01EA: 84,\n    0xE01EB: 84,\n    0xE01EC: 84,\n    0xE01ED: 84,\n    0xE01EE: 84,\n    0xE01EF: 84,\n}\ncodepoint_classes = {\n    \"PVALID\": (\n        0x2D0000002E,\n        0x300000003A,\n        0x610000007B,\n        0xDF000000F7,\n        0xF800000100,\n        0x10100000102,\n        0x10300000104,\n        0x10500000106,\n        0x10700000108,\n        0x1090000010A,\n        0x10B0000010C,\n        0x10D0000010E,\n        0x10F00000110,\n        0x11100000112,\n        0x11300000114,\n        0x11500000116,\n        0x11700000118,\n        0x1190000011A,\n        0x11B0000011C,\n        0x11D0000011E,\n        0x11F00000120,\n        0x12100000122,\n        0x12300000124,\n        0x12500000126,\n        0x12700000128,\n        0x1290000012A,\n        0x12B0000012C,\n        0x12D0000012E,\n        0x12F00000130,\n        0x13100000132,\n        0x13500000136,\n        0x13700000139,\n        0x13A0000013B,\n        0x13C0000013D,\n        0x13E0000013F,\n        0x14200000143,\n        0x14400000145,\n        0x14600000147,\n        0x14800000149,\n        0x14B0000014C,\n        0x14D0000014E,\n        0x14F00000150,\n        0x15100000152,\n        0x15300000154,\n        0x15500000156,\n        0x15700000158,\n        0x1590000015A,\n        0x15B0000015C,\n        0x15D0000015E,\n        0x15F00000160,\n        0x16100000162,\n        0x16300000164,\n        0x16500000166,\n        0x16700000168,\n        0x1690000016A,\n        0x16B0000016C,\n        0x16D0000016E,\n        0x16F00000170,\n        0x17100000172,\n        0x17300000174,\n        0x17500000176,\n        0x17700000178,\n        0x17A0000017B,\n        0x17C0000017D,\n        0x17E0000017F,\n        0x18000000181,\n        0x18300000184,\n        0x18500000186,\n        0x18800000189,\n        0x18C0000018E,\n        0x19200000193,\n        0x19500000196,\n        0x1990000019C,\n        0x19E0000019F,\n        0x1A1000001A2,\n        0x1A3000001A4,\n        0x1A5000001A6,\n        0x1A8000001A9,\n        0x1AA000001AC,\n        0x1AD000001AE,\n        0x1B0000001B1,\n        0x1B4000001B5,\n        0x1B6000001B7,\n        0x1B9000001BC,\n        0x1BD000001C4,\n        0x1CE000001CF,\n        0x1D0000001D1,\n        0x1D2000001D3,\n        0x1D4000001D5,\n        0x1D6000001D7,\n        0x1D8000001D9,\n        0x1DA000001DB,\n        0x1DC000001DE,\n        0x1DF000001E0,\n        0x1E1000001E2,\n        0x1E3000001E4,\n        0x1E5000001E6,\n        0x1E7000001E8,\n        0x1E9000001EA,\n        0x1EB000001EC,\n        0x1ED000001EE,\n        0x1EF000001F1,\n        0x1F5000001F6,\n        0x1F9000001FA,\n        0x1FB000001FC,\n        0x1FD000001FE,\n        0x1FF00000200,\n        0x20100000202,\n        0x20300000204,\n        0x20500000206,\n        0x20700000208,\n        0x2090000020A,\n        0x20B0000020C,\n        0x20D0000020E,\n        0x20F00000210,\n        0x21100000212,\n        0x21300000214,\n        0x21500000216,\n        0x21700000218,\n        0x2190000021A,\n        0x21B0000021C,\n        0x21D0000021E,\n        0x21F00000220,\n        0x22100000222,\n        0x22300000224,\n        0x22500000226,\n        0x22700000228,\n        0x2290000022A,\n        0x22B0000022C,\n        0x22D0000022E,\n        0x22F00000230,\n        0x23100000232,\n        0x2330000023A,\n        0x23C0000023D,\n        0x23F00000241,\n        0x24200000243,\n        0x24700000248,\n        0x2490000024A,\n        0x24B0000024C,\n        0x24D0000024E,\n        0x24F000002B0,\n        0x2B9000002C2,\n        0x2C6000002D2,\n        0x2EC000002ED,\n        0x2EE000002EF,\n        0x30000000340,\n        0x34200000343,\n        0x3460000034F,\n        0x35000000370,\n        0x37100000372,\n        0x37300000374,\n        0x37700000378,\n        0x37B0000037E,\n        0x39000000391,\n        0x3AC000003CF,\n        0x3D7000003D8,\n        0x3D9000003DA,\n        0x3DB000003DC,\n        0x3DD000003DE,\n        0x3DF000003E0,\n        0x3E1000003E2,\n        0x3E3000003E4,\n        0x3E5000003E6,\n        0x3E7000003E8,\n        0x3E9000003EA,\n        0x3EB000003EC,\n        0x3ED000003EE,\n        0x3EF000003F0,\n        0x3F3000003F4,\n        0x3F8000003F9,\n        0x3FB000003FD,\n        0x43000000460,\n        0x46100000462,\n        0x46300000464,\n        0x46500000466,\n        0x46700000468,\n        0x4690000046A,\n        0x46B0000046C,\n        0x46D0000046E,\n        0x46F00000470,\n        0x47100000472,\n        0x47300000474,\n        0x47500000476,\n        0x47700000478,\n        0x4790000047A,\n        0x47B0000047C,\n        0x47D0000047E,\n        0x47F00000480,\n        0x48100000482,\n        0x48300000488,\n        0x48B0000048C,\n        0x48D0000048E,\n        0x48F00000490,\n        0x49100000492,\n        0x49300000494,\n        0x49500000496,\n        0x49700000498,\n        0x4990000049A,\n        0x49B0000049C,\n        0x49D0000049E,\n        0x49F000004A0,\n        0x4A1000004A2,\n        0x4A3000004A4,\n        0x4A5000004A6,\n        0x4A7000004A8,\n        0x4A9000004AA,\n        0x4AB000004AC,\n        0x4AD000004AE,\n        0x4AF000004B0,\n        0x4B1000004B2,\n        0x4B3000004B4,\n        0x4B5000004B6,\n        0x4B7000004B8,\n        0x4B9000004BA,\n        0x4BB000004BC,\n        0x4BD000004BE,\n        0x4BF000004C0,\n        0x4C2000004C3,\n        0x4C4000004C5,\n        0x4C6000004C7,\n        0x4C8000004C9,\n        0x4CA000004CB,\n        0x4CC000004CD,\n        0x4CE000004D0,\n        0x4D1000004D2,\n        0x4D3000004D4,\n        0x4D5000004D6,\n        0x4D7000004D8,\n        0x4D9000004DA,\n        0x4DB000004DC,\n        0x4DD000004DE,\n        0x4DF000004E0,\n        0x4E1000004E2,\n        0x4E3000004E4,\n        0x4E5000004E6,\n        0x4E7000004E8,\n        0x4E9000004EA,\n        0x4EB000004EC,\n        0x4ED000004EE,\n        0x4EF000004F0,\n        0x4F1000004F2,\n        0x4F3000004F4,\n        0x4F5000004F6,\n        0x4F7000004F8,\n        0x4F9000004FA,\n        0x4FB000004FC,\n        0x4FD000004FE,\n        0x4FF00000500,\n        0x50100000502,\n        0x50300000504,\n        0x50500000506,\n        0x50700000508,\n        0x5090000050A,\n        0x50B0000050C,\n        0x50D0000050E,\n        0x50F00000510,\n        0x51100000512,\n        0x51300000514,\n        0x51500000516,\n        0x51700000518,\n        0x5190000051A,\n        0x51B0000051C,\n        0x51D0000051E,\n        0x51F00000520,\n        0x52100000522,\n        0x52300000524,\n        0x52500000526,\n        0x52700000528,\n        0x5290000052A,\n        0x52B0000052C,\n        0x52D0000052E,\n        0x52F00000530,\n        0x5590000055A,\n        0x56000000587,\n        0x58800000589,\n        0x591000005BE,\n        0x5BF000005C0,\n        0x5C1000005C3,\n        0x5C4000005C6,\n        0x5C7000005C8,\n        0x5D0000005EB,\n        0x5EF000005F3,\n        0x6100000061B,\n        0x62000000640,\n        0x64100000660,\n        0x66E00000675,\n        0x679000006D4,\n        0x6D5000006DD,\n        0x6DF000006E9,\n        0x6EA000006F0,\n        0x6FA00000700,\n        0x7100000074B,\n        0x74D000007B2,\n        0x7C0000007F6,\n        0x7FD000007FE,\n        0x8000000082E,\n        0x8400000085C,\n        0x8600000086B,\n        0x87000000888,\n        0x8890000088F,\n        0x897000008E2,\n        0x8E300000958,\n        0x96000000964,\n        0x96600000970,\n        0x97100000984,\n        0x9850000098D,\n        0x98F00000991,\n        0x993000009A9,\n        0x9AA000009B1,\n        0x9B2000009B3,\n        0x9B6000009BA,\n        0x9BC000009C5,\n        0x9C7000009C9,\n        0x9CB000009CF,\n        0x9D7000009D8,\n        0x9E0000009E4,\n        0x9E6000009F2,\n        0x9FC000009FD,\n        0x9FE000009FF,\n        0xA0100000A04,\n        0xA0500000A0B,\n        0xA0F00000A11,\n        0xA1300000A29,\n        0xA2A00000A31,\n        0xA3200000A33,\n        0xA3500000A36,\n        0xA3800000A3A,\n        0xA3C00000A3D,\n        0xA3E00000A43,\n        0xA4700000A49,\n        0xA4B00000A4E,\n        0xA5100000A52,\n        0xA5C00000A5D,\n        0xA6600000A76,\n        0xA8100000A84,\n        0xA8500000A8E,\n        0xA8F00000A92,\n        0xA9300000AA9,\n        0xAAA00000AB1,\n        0xAB200000AB4,\n        0xAB500000ABA,\n        0xABC00000AC6,\n        0xAC700000ACA,\n        0xACB00000ACE,\n        0xAD000000AD1,\n        0xAE000000AE4,\n        0xAE600000AF0,\n        0xAF900000B00,\n        0xB0100000B04,\n        0xB0500000B0D,\n        0xB0F00000B11,\n        0xB1300000B29,\n        0xB2A00000B31,\n        0xB3200000B34,\n        0xB3500000B3A,\n        0xB3C00000B45,\n        0xB4700000B49,\n        0xB4B00000B4E,\n        0xB5500000B58,\n        0xB5F00000B64,\n        0xB6600000B70,\n        0xB7100000B72,\n        0xB8200000B84,\n        0xB8500000B8B,\n        0xB8E00000B91,\n        0xB9200000B96,\n        0xB9900000B9B,\n        0xB9C00000B9D,\n        0xB9E00000BA0,\n        0xBA300000BA5,\n        0xBA800000BAB,\n        0xBAE00000BBA,\n        0xBBE00000BC3,\n        0xBC600000BC9,\n        0xBCA00000BCE,\n        0xBD000000BD1,\n        0xBD700000BD8,\n        0xBE600000BF0,\n        0xC0000000C0D,\n        0xC0E00000C11,\n        0xC1200000C29,\n        0xC2A00000C3A,\n        0xC3C00000C45,\n        0xC4600000C49,\n        0xC4A00000C4E,\n        0xC5500000C57,\n        0xC5800000C5B,\n        0xC5D00000C5E,\n        0xC6000000C64,\n        0xC6600000C70,\n        0xC8000000C84,\n        0xC8500000C8D,\n        0xC8E00000C91,\n        0xC9200000CA9,\n        0xCAA00000CB4,\n        0xCB500000CBA,\n        0xCBC00000CC5,\n        0xCC600000CC9,\n        0xCCA00000CCE,\n        0xCD500000CD7,\n        0xCDD00000CDF,\n        0xCE000000CE4,\n        0xCE600000CF0,\n        0xCF100000CF4,\n        0xD0000000D0D,\n        0xD0E00000D11,\n        0xD1200000D45,\n        0xD4600000D49,\n        0xD4A00000D4F,\n        0xD5400000D58,\n        0xD5F00000D64,\n        0xD6600000D70,\n        0xD7A00000D80,\n        0xD8100000D84,\n        0xD8500000D97,\n        0xD9A00000DB2,\n        0xDB300000DBC,\n        0xDBD00000DBE,\n        0xDC000000DC7,\n        0xDCA00000DCB,\n        0xDCF00000DD5,\n        0xDD600000DD7,\n        0xDD800000DE0,\n        0xDE600000DF0,\n        0xDF200000DF4,\n        0xE0100000E33,\n        0xE3400000E3B,\n        0xE4000000E4F,\n        0xE5000000E5A,\n        0xE8100000E83,\n        0xE8400000E85,\n        0xE8600000E8B,\n        0xE8C00000EA4,\n        0xEA500000EA6,\n        0xEA700000EB3,\n        0xEB400000EBE,\n        0xEC000000EC5,\n        0xEC600000EC7,\n        0xEC800000ECF,\n        0xED000000EDA,\n        0xEDE00000EE0,\n        0xF0000000F01,\n        0xF0B00000F0C,\n        0xF1800000F1A,\n        0xF2000000F2A,\n        0xF3500000F36,\n        0xF3700000F38,\n        0xF3900000F3A,\n        0xF3E00000F43,\n        0xF4400000F48,\n        0xF4900000F4D,\n        0xF4E00000F52,\n        0xF5300000F57,\n        0xF5800000F5C,\n        0xF5D00000F69,\n        0xF6A00000F6D,\n        0xF7100000F73,\n        0xF7400000F75,\n        0xF7A00000F81,\n        0xF8200000F85,\n        0xF8600000F93,\n        0xF9400000F98,\n        0xF9900000F9D,\n        0xF9E00000FA2,\n        0xFA300000FA7,\n        0xFA800000FAC,\n        0xFAD00000FB9,\n        0xFBA00000FBD,\n        0xFC600000FC7,\n        0x10000000104A,\n        0x10500000109E,\n        0x10D0000010FB,\n        0x10FD00001100,\n        0x120000001249,\n        0x124A0000124E,\n        0x125000001257,\n        0x125800001259,\n        0x125A0000125E,\n        0x126000001289,\n        0x128A0000128E,\n        0x1290000012B1,\n        0x12B2000012B6,\n        0x12B8000012BF,\n        0x12C0000012C1,\n        0x12C2000012C6,\n        0x12C8000012D7,\n        0x12D800001311,\n        0x131200001316,\n        0x13180000135B,\n        0x135D00001360,\n        0x138000001390,\n        0x13A0000013F6,\n        0x14010000166D,\n        0x166F00001680,\n        0x16810000169B,\n        0x16A0000016EB,\n        0x16F1000016F9,\n        0x170000001716,\n        0x171F00001735,\n        0x174000001754,\n        0x17600000176D,\n        0x176E00001771,\n        0x177200001774,\n        0x1780000017B4,\n        0x17B6000017D4,\n        0x17D7000017D8,\n        0x17DC000017DE,\n        0x17E0000017EA,\n        0x18100000181A,\n        0x182000001879,\n        0x1880000018AB,\n        0x18B0000018F6,\n        0x19000000191F,\n        0x19200000192C,\n        0x19300000193C,\n        0x19460000196E,\n        0x197000001975,\n        0x1980000019AC,\n        0x19B0000019CA,\n        0x19D0000019DA,\n        0x1A0000001A1C,\n        0x1A2000001A5F,\n        0x1A6000001A7D,\n        0x1A7F00001A8A,\n        0x1A9000001A9A,\n        0x1AA700001AA8,\n        0x1AB000001ABE,\n        0x1ABF00001ACF,\n        0x1B0000001B4D,\n        0x1B5000001B5A,\n        0x1B6B00001B74,\n        0x1B8000001BF4,\n        0x1C0000001C38,\n        0x1C4000001C4A,\n        0x1C4D00001C7E,\n        0x1C8A00001C8B,\n        0x1CD000001CD3,\n        0x1CD400001CFB,\n        0x1D0000001D2C,\n        0x1D2F00001D30,\n        0x1D3B00001D3C,\n        0x1D4E00001D4F,\n        0x1D6B00001D78,\n        0x1D7900001D9B,\n        0x1DC000001E00,\n        0x1E0100001E02,\n        0x1E0300001E04,\n        0x1E0500001E06,\n        0x1E0700001E08,\n        0x1E0900001E0A,\n        0x1E0B00001E0C,\n        0x1E0D00001E0E,\n        0x1E0F00001E10,\n        0x1E1100001E12,\n        0x1E1300001E14,\n        0x1E1500001E16,\n        0x1E1700001E18,\n        0x1E1900001E1A,\n        0x1E1B00001E1C,\n        0x1E1D00001E1E,\n        0x1E1F00001E20,\n        0x1E2100001E22,\n        0x1E2300001E24,\n        0x1E2500001E26,\n        0x1E2700001E28,\n        0x1E2900001E2A,\n        0x1E2B00001E2C,\n        0x1E2D00001E2E,\n        0x1E2F00001E30,\n        0x1E3100001E32,\n        0x1E3300001E34,\n        0x1E3500001E36,\n        0x1E3700001E38,\n        0x1E3900001E3A,\n        0x1E3B00001E3C,\n        0x1E3D00001E3E,\n        0x1E3F00001E40,\n        0x1E4100001E42,\n        0x1E4300001E44,\n        0x1E4500001E46,\n        0x1E4700001E48,\n        0x1E4900001E4A,\n        0x1E4B00001E4C,\n        0x1E4D00001E4E,\n        0x1E4F00001E50,\n        0x1E5100001E52,\n        0x1E5300001E54,\n        0x1E5500001E56,\n        0x1E5700001E58,\n        0x1E5900001E5A,\n        0x1E5B00001E5C,\n        0x1E5D00001E5E,\n        0x1E5F00001E60,\n        0x1E6100001E62,\n        0x1E6300001E64,\n        0x1E6500001E66,\n        0x1E6700001E68,\n        0x1E6900001E6A,\n        0x1E6B00001E6C,\n        0x1E6D00001E6E,\n        0x1E6F00001E70,\n        0x1E7100001E72,\n        0x1E7300001E74,\n        0x1E7500001E76,\n        0x1E7700001E78,\n        0x1E7900001E7A,\n        0x1E7B00001E7C,\n        0x1E7D00001E7E,\n        0x1E7F00001E80,\n        0x1E8100001E82,\n        0x1E8300001E84,\n        0x1E8500001E86,\n        0x1E8700001E88,\n        0x1E8900001E8A,\n        0x1E8B00001E8C,\n        0x1E8D00001E8E,\n        0x1E8F00001E90,\n        0x1E9100001E92,\n        0x1E9300001E94,\n        0x1E9500001E9A,\n        0x1E9C00001E9E,\n        0x1E9F00001EA0,\n        0x1EA100001EA2,\n        0x1EA300001EA4,\n        0x1EA500001EA6,\n        0x1EA700001EA8,\n        0x1EA900001EAA,\n        0x1EAB00001EAC,\n        0x1EAD00001EAE,\n        0x1EAF00001EB0,\n        0x1EB100001EB2,\n        0x1EB300001EB4,\n        0x1EB500001EB6,\n        0x1EB700001EB8,\n        0x1EB900001EBA,\n        0x1EBB00001EBC,\n        0x1EBD00001EBE,\n        0x1EBF00001EC0,\n        0x1EC100001EC2,\n        0x1EC300001EC4,\n        0x1EC500001EC6,\n        0x1EC700001EC8,\n        0x1EC900001ECA,\n        0x1ECB00001ECC,\n        0x1ECD00001ECE,\n        0x1ECF00001ED0,\n        0x1ED100001ED2,\n        0x1ED300001ED4,\n        0x1ED500001ED6,\n        0x1ED700001ED8,\n        0x1ED900001EDA,\n        0x1EDB00001EDC,\n        0x1EDD00001EDE,\n        0x1EDF00001EE0,\n        0x1EE100001EE2,\n        0x1EE300001EE4,\n        0x1EE500001EE6,\n        0x1EE700001EE8,\n        0x1EE900001EEA,\n        0x1EEB00001EEC,\n        0x1EED00001EEE,\n        0x1EEF00001EF0,\n        0x1EF100001EF2,\n        0x1EF300001EF4,\n        0x1EF500001EF6,\n        0x1EF700001EF8,\n        0x1EF900001EFA,\n        0x1EFB00001EFC,\n        0x1EFD00001EFE,\n        0x1EFF00001F08,\n        0x1F1000001F16,\n        0x1F2000001F28,\n        0x1F3000001F38,\n        0x1F4000001F46,\n        0x1F5000001F58,\n        0x1F6000001F68,\n        0x1F7000001F71,\n        0x1F7200001F73,\n        0x1F7400001F75,\n        0x1F7600001F77,\n        0x1F7800001F79,\n        0x1F7A00001F7B,\n        0x1F7C00001F7D,\n        0x1FB000001FB2,\n        0x1FB600001FB7,\n        0x1FC600001FC7,\n        0x1FD000001FD3,\n        0x1FD600001FD8,\n        0x1FE000001FE3,\n        0x1FE400001FE8,\n        0x1FF600001FF7,\n        0x214E0000214F,\n        0x218400002185,\n        0x2C3000002C60,\n        0x2C6100002C62,\n        0x2C6500002C67,\n        0x2C6800002C69,\n        0x2C6A00002C6B,\n        0x2C6C00002C6D,\n        0x2C7100002C72,\n        0x2C7300002C75,\n        0x2C7600002C7C,\n        0x2C8100002C82,\n        0x2C8300002C84,\n        0x2C8500002C86,\n        0x2C8700002C88,\n        0x2C8900002C8A,\n        0x2C8B00002C8C,\n        0x2C8D00002C8E,\n        0x2C8F00002C90,\n        0x2C9100002C92,\n        0x2C9300002C94,\n        0x2C9500002C96,\n        0x2C9700002C98,\n        0x2C9900002C9A,\n        0x2C9B00002C9C,\n        0x2C9D00002C9E,\n        0x2C9F00002CA0,\n        0x2CA100002CA2,\n        0x2CA300002CA4,\n        0x2CA500002CA6,\n        0x2CA700002CA8,\n        0x2CA900002CAA,\n        0x2CAB00002CAC,\n        0x2CAD00002CAE,\n        0x2CAF00002CB0,\n        0x2CB100002CB2,\n        0x2CB300002CB4,\n        0x2CB500002CB6,\n        0x2CB700002CB8,\n        0x2CB900002CBA,\n        0x2CBB00002CBC,\n        0x2CBD00002CBE,\n        0x2CBF00002CC0,\n        0x2CC100002CC2,\n        0x2CC300002CC4,\n        0x2CC500002CC6,\n        0x2CC700002CC8,\n        0x2CC900002CCA,\n        0x2CCB00002CCC,\n        0x2CCD00002CCE,\n        0x2CCF00002CD0,\n        0x2CD100002CD2,\n        0x2CD300002CD4,\n        0x2CD500002CD6,\n        0x2CD700002CD8,\n        0x2CD900002CDA,\n        0x2CDB00002CDC,\n        0x2CDD00002CDE,\n        0x2CDF00002CE0,\n        0x2CE100002CE2,\n        0x2CE300002CE5,\n        0x2CEC00002CED,\n        0x2CEE00002CF2,\n        0x2CF300002CF4,\n        0x2D0000002D26,\n        0x2D2700002D28,\n        0x2D2D00002D2E,\n        0x2D3000002D68,\n        0x2D7F00002D97,\n        0x2DA000002DA7,\n        0x2DA800002DAF,\n        0x2DB000002DB7,\n        0x2DB800002DBF,\n        0x2DC000002DC7,\n        0x2DC800002DCF,\n        0x2DD000002DD7,\n        0x2DD800002DDF,\n        0x2DE000002E00,\n        0x2E2F00002E30,\n        0x300500003008,\n        0x302A0000302E,\n        0x303C0000303D,\n        0x304100003097,\n        0x30990000309B,\n        0x309D0000309F,\n        0x30A1000030FB,\n        0x30FC000030FF,\n        0x310500003130,\n        0x31A0000031C0,\n        0x31F000003200,\n        0x340000004DC0,\n        0x4E000000A48D,\n        0xA4D00000A4FE,\n        0xA5000000A60D,\n        0xA6100000A62C,\n        0xA6410000A642,\n        0xA6430000A644,\n        0xA6450000A646,\n        0xA6470000A648,\n        0xA6490000A64A,\n        0xA64B0000A64C,\n        0xA64D0000A64E,\n        0xA64F0000A650,\n        0xA6510000A652,\n        0xA6530000A654,\n        0xA6550000A656,\n        0xA6570000A658,\n        0xA6590000A65A,\n        0xA65B0000A65C,\n        0xA65D0000A65E,\n        0xA65F0000A660,\n        0xA6610000A662,\n        0xA6630000A664,\n        0xA6650000A666,\n        0xA6670000A668,\n        0xA6690000A66A,\n        0xA66B0000A66C,\n        0xA66D0000A670,\n        0xA6740000A67E,\n        0xA67F0000A680,\n        0xA6810000A682,\n        0xA6830000A684,\n        0xA6850000A686,\n        0xA6870000A688,\n        0xA6890000A68A,\n        0xA68B0000A68C,\n        0xA68D0000A68E,\n        0xA68F0000A690,\n        0xA6910000A692,\n        0xA6930000A694,\n        0xA6950000A696,\n        0xA6970000A698,\n        0xA6990000A69A,\n        0xA69B0000A69C,\n        0xA69E0000A6E6,\n        0xA6F00000A6F2,\n        0xA7170000A720,\n        0xA7230000A724,\n        0xA7250000A726,\n        0xA7270000A728,\n        0xA7290000A72A,\n        0xA72B0000A72C,\n        0xA72D0000A72E,\n        0xA72F0000A732,\n        0xA7330000A734,\n        0xA7350000A736,\n        0xA7370000A738,\n        0xA7390000A73A,\n        0xA73B0000A73C,\n        0xA73D0000A73E,\n        0xA73F0000A740,\n        0xA7410000A742,\n        0xA7430000A744,\n        0xA7450000A746,\n        0xA7470000A748,\n        0xA7490000A74A,\n        0xA74B0000A74C,\n        0xA74D0000A74E,\n        0xA74F0000A750,\n        0xA7510000A752,\n        0xA7530000A754,\n        0xA7550000A756,\n        0xA7570000A758,\n        0xA7590000A75A,\n        0xA75B0000A75C,\n        0xA75D0000A75E,\n        0xA75F0000A760,\n        0xA7610000A762,\n        0xA7630000A764,\n        0xA7650000A766,\n        0xA7670000A768,\n        0xA7690000A76A,\n        0xA76B0000A76C,\n        0xA76D0000A76E,\n        0xA76F0000A770,\n        0xA7710000A779,\n        0xA77A0000A77B,\n        0xA77C0000A77D,\n        0xA77F0000A780,\n        0xA7810000A782,\n        0xA7830000A784,\n        0xA7850000A786,\n        0xA7870000A789,\n        0xA78C0000A78D,\n        0xA78E0000A790,\n        0xA7910000A792,\n        0xA7930000A796,\n        0xA7970000A798,\n        0xA7990000A79A,\n        0xA79B0000A79C,\n        0xA79D0000A79E,\n        0xA79F0000A7A0,\n        0xA7A10000A7A2,\n        0xA7A30000A7A4,\n        0xA7A50000A7A6,\n        0xA7A70000A7A8,\n        0xA7A90000A7AA,\n        0xA7AF0000A7B0,\n        0xA7B50000A7B6,\n        0xA7B70000A7B8,\n        0xA7B90000A7BA,\n        0xA7BB0000A7BC,\n        0xA7BD0000A7BE,\n        0xA7BF0000A7C0,\n        0xA7C10000A7C2,\n        0xA7C30000A7C4,\n        0xA7C80000A7C9,\n        0xA7CA0000A7CB,\n        0xA7CD0000A7CE,\n        0xA7D10000A7D2,\n        0xA7D30000A7D4,\n        0xA7D50000A7D6,\n        0xA7D70000A7D8,\n        0xA7D90000A7DA,\n        0xA7DB0000A7DC,\n        0xA7F60000A7F8,\n        0xA7FA0000A828,\n        0xA82C0000A82D,\n        0xA8400000A874,\n        0xA8800000A8C6,\n        0xA8D00000A8DA,\n        0xA8E00000A8F8,\n        0xA8FB0000A8FC,\n        0xA8FD0000A92E,\n        0xA9300000A954,\n        0xA9800000A9C1,\n        0xA9CF0000A9DA,\n        0xA9E00000A9FF,\n        0xAA000000AA37,\n        0xAA400000AA4E,\n        0xAA500000AA5A,\n        0xAA600000AA77,\n        0xAA7A0000AAC3,\n        0xAADB0000AADE,\n        0xAAE00000AAF0,\n        0xAAF20000AAF7,\n        0xAB010000AB07,\n        0xAB090000AB0F,\n        0xAB110000AB17,\n        0xAB200000AB27,\n        0xAB280000AB2F,\n        0xAB300000AB5B,\n        0xAB600000AB69,\n        0xABC00000ABEB,\n        0xABEC0000ABEE,\n        0xABF00000ABFA,\n        0xAC000000D7A4,\n        0xFA0E0000FA10,\n        0xFA110000FA12,\n        0xFA130000FA15,\n        0xFA1F0000FA20,\n        0xFA210000FA22,\n        0xFA230000FA25,\n        0xFA270000FA2A,\n        0xFB1E0000FB1F,\n        0xFE200000FE30,\n        0xFE730000FE74,\n        0x100000001000C,\n        0x1000D00010027,\n        0x100280001003B,\n        0x1003C0001003E,\n        0x1003F0001004E,\n        0x100500001005E,\n        0x10080000100FB,\n        0x101FD000101FE,\n        0x102800001029D,\n        0x102A0000102D1,\n        0x102E0000102E1,\n        0x1030000010320,\n        0x1032D00010341,\n        0x103420001034A,\n        0x103500001037B,\n        0x103800001039E,\n        0x103A0000103C4,\n        0x103C8000103D0,\n        0x104280001049E,\n        0x104A0000104AA,\n        0x104D8000104FC,\n        0x1050000010528,\n        0x1053000010564,\n        0x10597000105A2,\n        0x105A3000105B2,\n        0x105B3000105BA,\n        0x105BB000105BD,\n        0x105C0000105F4,\n        0x1060000010737,\n        0x1074000010756,\n        0x1076000010768,\n        0x1078000010781,\n        0x1080000010806,\n        0x1080800010809,\n        0x1080A00010836,\n        0x1083700010839,\n        0x1083C0001083D,\n        0x1083F00010856,\n        0x1086000010877,\n        0x108800001089F,\n        0x108E0000108F3,\n        0x108F4000108F6,\n        0x1090000010916,\n        0x109200001093A,\n        0x10980000109B8,\n        0x109BE000109C0,\n        0x10A0000010A04,\n        0x10A0500010A07,\n        0x10A0C00010A14,\n        0x10A1500010A18,\n        0x10A1900010A36,\n        0x10A3800010A3B,\n        0x10A3F00010A40,\n        0x10A6000010A7D,\n        0x10A8000010A9D,\n        0x10AC000010AC8,\n        0x10AC900010AE7,\n        0x10B0000010B36,\n        0x10B4000010B56,\n        0x10B6000010B73,\n        0x10B8000010B92,\n        0x10C0000010C49,\n        0x10CC000010CF3,\n        0x10D0000010D28,\n        0x10D3000010D3A,\n        0x10D4000010D50,\n        0x10D6900010D6E,\n        0x10D6F00010D86,\n        0x10E8000010EAA,\n        0x10EAB00010EAD,\n        0x10EB000010EB2,\n        0x10EC200010EC5,\n        0x10EFC00010F1D,\n        0x10F2700010F28,\n        0x10F3000010F51,\n        0x10F7000010F86,\n        0x10FB000010FC5,\n        0x10FE000010FF7,\n        0x1100000011047,\n        0x1106600011076,\n        0x1107F000110BB,\n        0x110C2000110C3,\n        0x110D0000110E9,\n        0x110F0000110FA,\n        0x1110000011135,\n        0x1113600011140,\n        0x1114400011148,\n        0x1115000011174,\n        0x1117600011177,\n        0x11180000111C5,\n        0x111C9000111CD,\n        0x111CE000111DB,\n        0x111DC000111DD,\n        0x1120000011212,\n        0x1121300011238,\n        0x1123E00011242,\n        0x1128000011287,\n        0x1128800011289,\n        0x1128A0001128E,\n        0x1128F0001129E,\n        0x1129F000112A9,\n        0x112B0000112EB,\n        0x112F0000112FA,\n        0x1130000011304,\n        0x113050001130D,\n        0x1130F00011311,\n        0x1131300011329,\n        0x1132A00011331,\n        0x1133200011334,\n        0x113350001133A,\n        0x1133B00011345,\n        0x1134700011349,\n        0x1134B0001134E,\n        0x1135000011351,\n        0x1135700011358,\n        0x1135D00011364,\n        0x113660001136D,\n        0x1137000011375,\n        0x113800001138A,\n        0x1138B0001138C,\n        0x1138E0001138F,\n        0x11390000113B6,\n        0x113B7000113C1,\n        0x113C2000113C3,\n        0x113C5000113C6,\n        0x113C7000113CB,\n        0x113CC000113D4,\n        0x113E1000113E3,\n        0x114000001144B,\n        0x114500001145A,\n        0x1145E00011462,\n        0x11480000114C6,\n        0x114C7000114C8,\n        0x114D0000114DA,\n        0x11580000115B6,\n        0x115B8000115C1,\n        0x115D8000115DE,\n        0x1160000011641,\n        0x1164400011645,\n        0x116500001165A,\n        0x11680000116B9,\n        0x116C0000116CA,\n        0x116D0000116E4,\n        0x117000001171B,\n        0x1171D0001172C,\n        0x117300001173A,\n        0x1174000011747,\n        0x118000001183B,\n        0x118C0000118EA,\n        0x118FF00011907,\n        0x119090001190A,\n        0x1190C00011914,\n        0x1191500011917,\n        0x1191800011936,\n        0x1193700011939,\n        0x1193B00011944,\n        0x119500001195A,\n        0x119A0000119A8,\n        0x119AA000119D8,\n        0x119DA000119E2,\n        0x119E3000119E5,\n        0x11A0000011A3F,\n        0x11A4700011A48,\n        0x11A5000011A9A,\n        0x11A9D00011A9E,\n        0x11AB000011AF9,\n        0x11BC000011BE1,\n        0x11BF000011BFA,\n        0x11C0000011C09,\n        0x11C0A00011C37,\n        0x11C3800011C41,\n        0x11C5000011C5A,\n        0x11C7200011C90,\n        0x11C9200011CA8,\n        0x11CA900011CB7,\n        0x11D0000011D07,\n        0x11D0800011D0A,\n        0x11D0B00011D37,\n        0x11D3A00011D3B,\n        0x11D3C00011D3E,\n        0x11D3F00011D48,\n        0x11D5000011D5A,\n        0x11D6000011D66,\n        0x11D6700011D69,\n        0x11D6A00011D8F,\n        0x11D9000011D92,\n        0x11D9300011D99,\n        0x11DA000011DAA,\n        0x11EE000011EF7,\n        0x11F0000011F11,\n        0x11F1200011F3B,\n        0x11F3E00011F43,\n        0x11F5000011F5B,\n        0x11FB000011FB1,\n        0x120000001239A,\n        0x1248000012544,\n        0x12F9000012FF1,\n        0x1300000013430,\n        0x1344000013456,\n        0x13460000143FB,\n        0x1440000014647,\n        0x161000001613A,\n        0x1680000016A39,\n        0x16A4000016A5F,\n        0x16A6000016A6A,\n        0x16A7000016ABF,\n        0x16AC000016ACA,\n        0x16AD000016AEE,\n        0x16AF000016AF5,\n        0x16B0000016B37,\n        0x16B4000016B44,\n        0x16B5000016B5A,\n        0x16B6300016B78,\n        0x16B7D00016B90,\n        0x16D4000016D6D,\n        0x16D7000016D7A,\n        0x16E6000016E80,\n        0x16F0000016F4B,\n        0x16F4F00016F88,\n        0x16F8F00016FA0,\n        0x16FE000016FE2,\n        0x16FE300016FE5,\n        0x16FF000016FF2,\n        0x17000000187F8,\n        0x1880000018CD6,\n        0x18CFF00018D09,\n        0x1AFF00001AFF4,\n        0x1AFF50001AFFC,\n        0x1AFFD0001AFFF,\n        0x1B0000001B123,\n        0x1B1320001B133,\n        0x1B1500001B153,\n        0x1B1550001B156,\n        0x1B1640001B168,\n        0x1B1700001B2FC,\n        0x1BC000001BC6B,\n        0x1BC700001BC7D,\n        0x1BC800001BC89,\n        0x1BC900001BC9A,\n        0x1BC9D0001BC9F,\n        0x1CCF00001CCFA,\n        0x1CF000001CF2E,\n        0x1CF300001CF47,\n        0x1DA000001DA37,\n        0x1DA3B0001DA6D,\n        0x1DA750001DA76,\n        0x1DA840001DA85,\n        0x1DA9B0001DAA0,\n        0x1DAA10001DAB0,\n        0x1DF000001DF1F,\n        0x1DF250001DF2B,\n        0x1E0000001E007,\n        0x1E0080001E019,\n        0x1E01B0001E022,\n        0x1E0230001E025,\n        0x1E0260001E02B,\n        0x1E08F0001E090,\n        0x1E1000001E12D,\n        0x1E1300001E13E,\n        0x1E1400001E14A,\n        0x1E14E0001E14F,\n        0x1E2900001E2AF,\n        0x1E2C00001E2FA,\n        0x1E4D00001E4FA,\n        0x1E5D00001E5FB,\n        0x1E7E00001E7E7,\n        0x1E7E80001E7EC,\n        0x1E7ED0001E7EF,\n        0x1E7F00001E7FF,\n        0x1E8000001E8C5,\n        0x1E8D00001E8D7,\n        0x1E9220001E94C,\n        0x1E9500001E95A,\n        0x200000002A6E0,\n        0x2A7000002B73A,\n        0x2B7400002B81E,\n        0x2B8200002CEA2,\n        0x2CEB00002EBE1,\n        0x2EBF00002EE5E,\n        0x300000003134B,\n        0x31350000323B0,\n    ),\n    \"CONTEXTJ\": (0x200C0000200E,),\n    \"CONTEXTO\": (\n        0xB7000000B8,\n        0x37500000376,\n        0x5F3000005F5,\n        0x6600000066A,\n        0x6F0000006FA,\n        0x30FB000030FC,\n    ),\n}\n"
  },
  {
    "path": "src/pip/_vendor/idna/intranges.py",
    "content": "\"\"\"\nGiven a list of integers, made up of (hopefully) a small number of long runs\nof consecutive integers, compute a representation of the form\n((start1, end1), (start2, end2) ...). Then answer the question \"was x present\nin the original list?\" in time O(log(# runs)).\n\"\"\"\n\nimport bisect\nfrom typing import List, Tuple\n\n\ndef intranges_from_list(list_: List[int]) -> Tuple[int, ...]:\n    \"\"\"Represent a list of integers as a sequence of ranges:\n    ((start_0, end_0), (start_1, end_1), ...), such that the original\n    integers are exactly those x such that start_i <= x < end_i for some i.\n\n    Ranges are encoded as single integers (start << 32 | end), not as tuples.\n    \"\"\"\n\n    sorted_list = sorted(list_)\n    ranges = []\n    last_write = -1\n    for i in range(len(sorted_list)):\n        if i + 1 < len(sorted_list):\n            if sorted_list[i] == sorted_list[i + 1] - 1:\n                continue\n        current_range = sorted_list[last_write + 1 : i + 1]\n        ranges.append(_encode_range(current_range[0], current_range[-1] + 1))\n        last_write = i\n\n    return tuple(ranges)\n\n\ndef _encode_range(start: int, end: int) -> int:\n    return (start << 32) | end\n\n\ndef _decode_range(r: int) -> Tuple[int, int]:\n    return (r >> 32), (r & ((1 << 32) - 1))\n\n\ndef intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:\n    \"\"\"Determine if `int_` falls into one of the ranges in `ranges`.\"\"\"\n    tuple_ = _encode_range(int_, 0)\n    pos = bisect.bisect_left(ranges, tuple_)\n    # we could be immediately ahead of a tuple (start, end)\n    # with start < int_ <= end\n    if pos > 0:\n        left, right = _decode_range(ranges[pos - 1])\n        if left <= int_ < right:\n            return True\n    # or we could be immediately behind a tuple (int_, end)\n    if pos < len(ranges):\n        left, _ = _decode_range(ranges[pos])\n        if left == int_:\n            return True\n    return False\n"
  },
  {
    "path": "src/pip/_vendor/idna/package_data.py",
    "content": "__version__ = \"3.11\"\n"
  },
  {
    "path": "src/pip/_vendor/idna/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/idna/uts46data.py",
    "content": "# This file is automatically generated by tools/idna-data\n# vim: set fileencoding=utf-8 :\n\nfrom typing import List, Tuple, Union\n\n\"\"\"IDNA Mapping Table from UTS46.\"\"\"\n\n\n__version__ = \"16.0.0\"\n\n\ndef _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x0, \"V\"),\n        (0x1, \"V\"),\n        (0x2, \"V\"),\n        (0x3, \"V\"),\n        (0x4, \"V\"),\n        (0x5, \"V\"),\n        (0x6, \"V\"),\n        (0x7, \"V\"),\n        (0x8, \"V\"),\n        (0x9, \"V\"),\n        (0xA, \"V\"),\n        (0xB, \"V\"),\n        (0xC, \"V\"),\n        (0xD, \"V\"),\n        (0xE, \"V\"),\n        (0xF, \"V\"),\n        (0x10, \"V\"),\n        (0x11, \"V\"),\n        (0x12, \"V\"),\n        (0x13, \"V\"),\n        (0x14, \"V\"),\n        (0x15, \"V\"),\n        (0x16, \"V\"),\n        (0x17, \"V\"),\n        (0x18, \"V\"),\n        (0x19, \"V\"),\n        (0x1A, \"V\"),\n        (0x1B, \"V\"),\n        (0x1C, \"V\"),\n        (0x1D, \"V\"),\n        (0x1E, \"V\"),\n        (0x1F, \"V\"),\n        (0x20, \"V\"),\n        (0x21, \"V\"),\n        (0x22, \"V\"),\n        (0x23, \"V\"),\n        (0x24, \"V\"),\n        (0x25, \"V\"),\n        (0x26, \"V\"),\n        (0x27, \"V\"),\n        (0x28, \"V\"),\n        (0x29, \"V\"),\n        (0x2A, \"V\"),\n        (0x2B, \"V\"),\n        (0x2C, \"V\"),\n        (0x2D, \"V\"),\n        (0x2E, \"V\"),\n        (0x2F, \"V\"),\n        (0x30, \"V\"),\n        (0x31, \"V\"),\n        (0x32, \"V\"),\n        (0x33, \"V\"),\n        (0x34, \"V\"),\n        (0x35, \"V\"),\n        (0x36, \"V\"),\n        (0x37, \"V\"),\n        (0x38, \"V\"),\n        (0x39, \"V\"),\n        (0x3A, \"V\"),\n        (0x3B, \"V\"),\n        (0x3C, \"V\"),\n        (0x3D, \"V\"),\n        (0x3E, \"V\"),\n        (0x3F, \"V\"),\n        (0x40, \"V\"),\n        (0x41, \"M\", \"a\"),\n        (0x42, \"M\", \"b\"),\n        (0x43, \"M\", \"c\"),\n        (0x44, \"M\", \"d\"),\n        (0x45, \"M\", \"e\"),\n        (0x46, \"M\", \"f\"),\n        (0x47, \"M\", \"g\"),\n        (0x48, \"M\", \"h\"),\n        (0x49, \"M\", \"i\"),\n        (0x4A, \"M\", \"j\"),\n        (0x4B, \"M\", \"k\"),\n        (0x4C, \"M\", \"l\"),\n        (0x4D, \"M\", \"m\"),\n        (0x4E, \"M\", \"n\"),\n        (0x4F, \"M\", \"o\"),\n        (0x50, \"M\", \"p\"),\n        (0x51, \"M\", \"q\"),\n        (0x52, \"M\", \"r\"),\n        (0x53, \"M\", \"s\"),\n        (0x54, \"M\", \"t\"),\n        (0x55, \"M\", \"u\"),\n        (0x56, \"M\", \"v\"),\n        (0x57, \"M\", \"w\"),\n        (0x58, \"M\", \"x\"),\n        (0x59, \"M\", \"y\"),\n        (0x5A, \"M\", \"z\"),\n        (0x5B, \"V\"),\n        (0x5C, \"V\"),\n        (0x5D, \"V\"),\n        (0x5E, \"V\"),\n        (0x5F, \"V\"),\n        (0x60, \"V\"),\n        (0x61, \"V\"),\n        (0x62, \"V\"),\n        (0x63, \"V\"),\n    ]\n\n\ndef _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x64, \"V\"),\n        (0x65, \"V\"),\n        (0x66, \"V\"),\n        (0x67, \"V\"),\n        (0x68, \"V\"),\n        (0x69, \"V\"),\n        (0x6A, \"V\"),\n        (0x6B, \"V\"),\n        (0x6C, \"V\"),\n        (0x6D, \"V\"),\n        (0x6E, \"V\"),\n        (0x6F, \"V\"),\n        (0x70, \"V\"),\n        (0x71, \"V\"),\n        (0x72, \"V\"),\n        (0x73, \"V\"),\n        (0x74, \"V\"),\n        (0x75, \"V\"),\n        (0x76, \"V\"),\n        (0x77, \"V\"),\n        (0x78, \"V\"),\n        (0x79, \"V\"),\n        (0x7A, \"V\"),\n        (0x7B, \"V\"),\n        (0x7C, \"V\"),\n        (0x7D, \"V\"),\n        (0x7E, \"V\"),\n        (0x7F, \"V\"),\n        (0x80, \"X\"),\n        (0x81, \"X\"),\n        (0x82, \"X\"),\n        (0x83, \"X\"),\n        (0x84, \"X\"),\n        (0x85, \"X\"),\n        (0x86, \"X\"),\n        (0x87, \"X\"),\n        (0x88, \"X\"),\n        (0x89, \"X\"),\n        (0x8A, \"X\"),\n        (0x8B, \"X\"),\n        (0x8C, \"X\"),\n        (0x8D, \"X\"),\n        (0x8E, \"X\"),\n        (0x8F, \"X\"),\n        (0x90, \"X\"),\n        (0x91, \"X\"),\n        (0x92, \"X\"),\n        (0x93, \"X\"),\n        (0x94, \"X\"),\n        (0x95, \"X\"),\n        (0x96, \"X\"),\n        (0x97, \"X\"),\n        (0x98, \"X\"),\n        (0x99, \"X\"),\n        (0x9A, \"X\"),\n        (0x9B, \"X\"),\n        (0x9C, \"X\"),\n        (0x9D, \"X\"),\n        (0x9E, \"X\"),\n        (0x9F, \"X\"),\n        (0xA0, \"M\", \" \"),\n        (0xA1, \"V\"),\n        (0xA2, \"V\"),\n        (0xA3, \"V\"),\n        (0xA4, \"V\"),\n        (0xA5, \"V\"),\n        (0xA6, \"V\"),\n        (0xA7, \"V\"),\n        (0xA8, \"M\", \" ̈\"),\n        (0xA9, \"V\"),\n        (0xAA, \"M\", \"a\"),\n        (0xAB, \"V\"),\n        (0xAC, \"V\"),\n        (0xAD, \"I\"),\n        (0xAE, \"V\"),\n        (0xAF, \"M\", \" ̄\"),\n        (0xB0, \"V\"),\n        (0xB1, \"V\"),\n        (0xB2, \"M\", \"2\"),\n        (0xB3, \"M\", \"3\"),\n        (0xB4, \"M\", \" ́\"),\n        (0xB5, \"M\", \"μ\"),\n        (0xB6, \"V\"),\n        (0xB7, \"V\"),\n        (0xB8, \"M\", \" ̧\"),\n        (0xB9, \"M\", \"1\"),\n        (0xBA, \"M\", \"o\"),\n        (0xBB, \"V\"),\n        (0xBC, \"M\", \"1⁄4\"),\n        (0xBD, \"M\", \"1⁄2\"),\n        (0xBE, \"M\", \"3⁄4\"),\n        (0xBF, \"V\"),\n        (0xC0, \"M\", \"à\"),\n        (0xC1, \"M\", \"á\"),\n        (0xC2, \"M\", \"â\"),\n        (0xC3, \"M\", \"ã\"),\n        (0xC4, \"M\", \"ä\"),\n        (0xC5, \"M\", \"å\"),\n        (0xC6, \"M\", \"æ\"),\n        (0xC7, \"M\", \"ç\"),\n    ]\n\n\ndef _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xC8, \"M\", \"è\"),\n        (0xC9, \"M\", \"é\"),\n        (0xCA, \"M\", \"ê\"),\n        (0xCB, \"M\", \"ë\"),\n        (0xCC, \"M\", \"ì\"),\n        (0xCD, \"M\", \"í\"),\n        (0xCE, \"M\", \"î\"),\n        (0xCF, \"M\", \"ï\"),\n        (0xD0, \"M\", \"ð\"),\n        (0xD1, \"M\", \"ñ\"),\n        (0xD2, \"M\", \"ò\"),\n        (0xD3, \"M\", \"ó\"),\n        (0xD4, \"M\", \"ô\"),\n        (0xD5, \"M\", \"õ\"),\n        (0xD6, \"M\", \"ö\"),\n        (0xD7, \"V\"),\n        (0xD8, \"M\", \"ø\"),\n        (0xD9, \"M\", \"ù\"),\n        (0xDA, \"M\", \"ú\"),\n        (0xDB, \"M\", \"û\"),\n        (0xDC, \"M\", \"ü\"),\n        (0xDD, \"M\", \"ý\"),\n        (0xDE, \"M\", \"þ\"),\n        (0xDF, \"D\", \"ss\"),\n        (0xE0, \"V\"),\n        (0xE1, \"V\"),\n        (0xE2, \"V\"),\n        (0xE3, \"V\"),\n        (0xE4, \"V\"),\n        (0xE5, \"V\"),\n        (0xE6, \"V\"),\n        (0xE7, \"V\"),\n        (0xE8, \"V\"),\n        (0xE9, \"V\"),\n        (0xEA, \"V\"),\n        (0xEB, \"V\"),\n        (0xEC, \"V\"),\n        (0xED, \"V\"),\n        (0xEE, \"V\"),\n        (0xEF, \"V\"),\n        (0xF0, \"V\"),\n        (0xF1, \"V\"),\n        (0xF2, \"V\"),\n        (0xF3, \"V\"),\n        (0xF4, \"V\"),\n        (0xF5, \"V\"),\n        (0xF6, \"V\"),\n        (0xF7, \"V\"),\n        (0xF8, \"V\"),\n        (0xF9, \"V\"),\n        (0xFA, \"V\"),\n        (0xFB, \"V\"),\n        (0xFC, \"V\"),\n        (0xFD, \"V\"),\n        (0xFE, \"V\"),\n        (0xFF, \"V\"),\n        (0x100, \"M\", \"ā\"),\n        (0x101, \"V\"),\n        (0x102, \"M\", \"ă\"),\n        (0x103, \"V\"),\n        (0x104, \"M\", \"ą\"),\n        (0x105, \"V\"),\n        (0x106, \"M\", \"ć\"),\n        (0x107, \"V\"),\n        (0x108, \"M\", \"ĉ\"),\n        (0x109, \"V\"),\n        (0x10A, \"M\", \"ċ\"),\n        (0x10B, \"V\"),\n        (0x10C, \"M\", \"č\"),\n        (0x10D, \"V\"),\n        (0x10E, \"M\", \"ď\"),\n        (0x10F, \"V\"),\n        (0x110, \"M\", \"đ\"),\n        (0x111, \"V\"),\n        (0x112, \"M\", \"ē\"),\n        (0x113, \"V\"),\n        (0x114, \"M\", \"ĕ\"),\n        (0x115, \"V\"),\n        (0x116, \"M\", \"ė\"),\n        (0x117, \"V\"),\n        (0x118, \"M\", \"ę\"),\n        (0x119, \"V\"),\n        (0x11A, \"M\", \"ě\"),\n        (0x11B, \"V\"),\n        (0x11C, \"M\", \"ĝ\"),\n        (0x11D, \"V\"),\n        (0x11E, \"M\", \"ğ\"),\n        (0x11F, \"V\"),\n        (0x120, \"M\", \"ġ\"),\n        (0x121, \"V\"),\n        (0x122, \"M\", \"ģ\"),\n        (0x123, \"V\"),\n        (0x124, \"M\", \"ĥ\"),\n        (0x125, \"V\"),\n        (0x126, \"M\", \"ħ\"),\n        (0x127, \"V\"),\n        (0x128, \"M\", \"ĩ\"),\n        (0x129, \"V\"),\n        (0x12A, \"M\", \"ī\"),\n        (0x12B, \"V\"),\n    ]\n\n\ndef _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x12C, \"M\", \"ĭ\"),\n        (0x12D, \"V\"),\n        (0x12E, \"M\", \"į\"),\n        (0x12F, \"V\"),\n        (0x130, \"M\", \"i̇\"),\n        (0x131, \"V\"),\n        (0x132, \"M\", \"ij\"),\n        (0x134, \"M\", \"ĵ\"),\n        (0x135, \"V\"),\n        (0x136, \"M\", \"ķ\"),\n        (0x137, \"V\"),\n        (0x139, \"M\", \"ĺ\"),\n        (0x13A, \"V\"),\n        (0x13B, \"M\", \"ļ\"),\n        (0x13C, \"V\"),\n        (0x13D, \"M\", \"ľ\"),\n        (0x13E, \"V\"),\n        (0x13F, \"M\", \"l·\"),\n        (0x141, \"M\", \"ł\"),\n        (0x142, \"V\"),\n        (0x143, \"M\", \"ń\"),\n        (0x144, \"V\"),\n        (0x145, \"M\", \"ņ\"),\n        (0x146, \"V\"),\n        (0x147, \"M\", \"ň\"),\n        (0x148, \"V\"),\n        (0x149, \"M\", \"ʼn\"),\n        (0x14A, \"M\", \"ŋ\"),\n        (0x14B, \"V\"),\n        (0x14C, \"M\", \"ō\"),\n        (0x14D, \"V\"),\n        (0x14E, \"M\", \"ŏ\"),\n        (0x14F, \"V\"),\n        (0x150, \"M\", \"ő\"),\n        (0x151, \"V\"),\n        (0x152, \"M\", \"œ\"),\n        (0x153, \"V\"),\n        (0x154, \"M\", \"ŕ\"),\n        (0x155, \"V\"),\n        (0x156, \"M\", \"ŗ\"),\n        (0x157, \"V\"),\n        (0x158, \"M\", \"ř\"),\n        (0x159, \"V\"),\n        (0x15A, \"M\", \"ś\"),\n        (0x15B, \"V\"),\n        (0x15C, \"M\", \"ŝ\"),\n        (0x15D, \"V\"),\n        (0x15E, \"M\", \"ş\"),\n        (0x15F, \"V\"),\n        (0x160, \"M\", \"š\"),\n        (0x161, \"V\"),\n        (0x162, \"M\", \"ţ\"),\n        (0x163, \"V\"),\n        (0x164, \"M\", \"ť\"),\n        (0x165, \"V\"),\n        (0x166, \"M\", \"ŧ\"),\n        (0x167, \"V\"),\n        (0x168, \"M\", \"ũ\"),\n        (0x169, \"V\"),\n        (0x16A, \"M\", \"ū\"),\n        (0x16B, \"V\"),\n        (0x16C, \"M\", \"ŭ\"),\n        (0x16D, \"V\"),\n        (0x16E, \"M\", \"ů\"),\n        (0x16F, \"V\"),\n        (0x170, \"M\", \"ű\"),\n        (0x171, \"V\"),\n        (0x172, \"M\", \"ų\"),\n        (0x173, \"V\"),\n        (0x174, \"M\", \"ŵ\"),\n        (0x175, \"V\"),\n        (0x176, \"M\", \"ŷ\"),\n        (0x177, \"V\"),\n        (0x178, \"M\", \"ÿ\"),\n        (0x179, \"M\", \"ź\"),\n        (0x17A, \"V\"),\n        (0x17B, \"M\", \"ż\"),\n        (0x17C, \"V\"),\n        (0x17D, \"M\", \"ž\"),\n        (0x17E, \"V\"),\n        (0x17F, \"M\", \"s\"),\n        (0x180, \"V\"),\n        (0x181, \"M\", \"ɓ\"),\n        (0x182, \"M\", \"ƃ\"),\n        (0x183, \"V\"),\n        (0x184, \"M\", \"ƅ\"),\n        (0x185, \"V\"),\n        (0x186, \"M\", \"ɔ\"),\n        (0x187, \"M\", \"ƈ\"),\n        (0x188, \"V\"),\n        (0x189, \"M\", \"ɖ\"),\n        (0x18A, \"M\", \"ɗ\"),\n        (0x18B, \"M\", \"ƌ\"),\n        (0x18C, \"V\"),\n        (0x18E, \"M\", \"ǝ\"),\n        (0x18F, \"M\", \"ə\"),\n        (0x190, \"M\", \"ɛ\"),\n        (0x191, \"M\", \"ƒ\"),\n        (0x192, \"V\"),\n        (0x193, \"M\", \"ɠ\"),\n    ]\n\n\ndef _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x194, \"M\", \"ɣ\"),\n        (0x195, \"V\"),\n        (0x196, \"M\", \"ɩ\"),\n        (0x197, \"M\", \"ɨ\"),\n        (0x198, \"M\", \"ƙ\"),\n        (0x199, \"V\"),\n        (0x19C, \"M\", \"ɯ\"),\n        (0x19D, \"M\", \"ɲ\"),\n        (0x19E, \"V\"),\n        (0x19F, \"M\", \"ɵ\"),\n        (0x1A0, \"M\", \"ơ\"),\n        (0x1A1, \"V\"),\n        (0x1A2, \"M\", \"ƣ\"),\n        (0x1A3, \"V\"),\n        (0x1A4, \"M\", \"ƥ\"),\n        (0x1A5, \"V\"),\n        (0x1A6, \"M\", \"ʀ\"),\n        (0x1A7, \"M\", \"ƨ\"),\n        (0x1A8, \"V\"),\n        (0x1A9, \"M\", \"ʃ\"),\n        (0x1AA, \"V\"),\n        (0x1AC, \"M\", \"ƭ\"),\n        (0x1AD, \"V\"),\n        (0x1AE, \"M\", \"ʈ\"),\n        (0x1AF, \"M\", \"ư\"),\n        (0x1B0, \"V\"),\n        (0x1B1, \"M\", \"ʊ\"),\n        (0x1B2, \"M\", \"ʋ\"),\n        (0x1B3, \"M\", \"ƴ\"),\n        (0x1B4, \"V\"),\n        (0x1B5, \"M\", \"ƶ\"),\n        (0x1B6, \"V\"),\n        (0x1B7, \"M\", \"ʒ\"),\n        (0x1B8, \"M\", \"ƹ\"),\n        (0x1B9, \"V\"),\n        (0x1BC, \"M\", \"ƽ\"),\n        (0x1BD, \"V\"),\n        (0x1C4, \"M\", \"dž\"),\n        (0x1C7, \"M\", \"lj\"),\n        (0x1CA, \"M\", \"nj\"),\n        (0x1CD, \"M\", \"ǎ\"),\n        (0x1CE, \"V\"),\n        (0x1CF, \"M\", \"ǐ\"),\n        (0x1D0, \"V\"),\n        (0x1D1, \"M\", \"ǒ\"),\n        (0x1D2, \"V\"),\n        (0x1D3, \"M\", \"ǔ\"),\n        (0x1D4, \"V\"),\n        (0x1D5, \"M\", \"ǖ\"),\n        (0x1D6, \"V\"),\n        (0x1D7, \"M\", \"ǘ\"),\n        (0x1D8, \"V\"),\n        (0x1D9, \"M\", \"ǚ\"),\n        (0x1DA, \"V\"),\n        (0x1DB, \"M\", \"ǜ\"),\n        (0x1DC, \"V\"),\n        (0x1DE, \"M\", \"ǟ\"),\n        (0x1DF, \"V\"),\n        (0x1E0, \"M\", \"ǡ\"),\n        (0x1E1, \"V\"),\n        (0x1E2, \"M\", \"ǣ\"),\n        (0x1E3, \"V\"),\n        (0x1E4, \"M\", \"ǥ\"),\n        (0x1E5, \"V\"),\n        (0x1E6, \"M\", \"ǧ\"),\n        (0x1E7, \"V\"),\n        (0x1E8, \"M\", \"ǩ\"),\n        (0x1E9, \"V\"),\n        (0x1EA, \"M\", \"ǫ\"),\n        (0x1EB, \"V\"),\n        (0x1EC, \"M\", \"ǭ\"),\n        (0x1ED, \"V\"),\n        (0x1EE, \"M\", \"ǯ\"),\n        (0x1EF, \"V\"),\n        (0x1F1, \"M\", \"dz\"),\n        (0x1F4, \"M\", \"ǵ\"),\n        (0x1F5, \"V\"),\n        (0x1F6, \"M\", \"ƕ\"),\n        (0x1F7, \"M\", \"ƿ\"),\n        (0x1F8, \"M\", \"ǹ\"),\n        (0x1F9, \"V\"),\n        (0x1FA, \"M\", \"ǻ\"),\n        (0x1FB, \"V\"),\n        (0x1FC, \"M\", \"ǽ\"),\n        (0x1FD, \"V\"),\n        (0x1FE, \"M\", \"ǿ\"),\n        (0x1FF, \"V\"),\n        (0x200, \"M\", \"ȁ\"),\n        (0x201, \"V\"),\n        (0x202, \"M\", \"ȃ\"),\n        (0x203, \"V\"),\n        (0x204, \"M\", \"ȅ\"),\n        (0x205, \"V\"),\n        (0x206, \"M\", \"ȇ\"),\n        (0x207, \"V\"),\n        (0x208, \"M\", \"ȉ\"),\n        (0x209, \"V\"),\n        (0x20A, \"M\", \"ȋ\"),\n        (0x20B, \"V\"),\n        (0x20C, \"M\", \"ȍ\"),\n    ]\n\n\ndef _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x20D, \"V\"),\n        (0x20E, \"M\", \"ȏ\"),\n        (0x20F, \"V\"),\n        (0x210, \"M\", \"ȑ\"),\n        (0x211, \"V\"),\n        (0x212, \"M\", \"ȓ\"),\n        (0x213, \"V\"),\n        (0x214, \"M\", \"ȕ\"),\n        (0x215, \"V\"),\n        (0x216, \"M\", \"ȗ\"),\n        (0x217, \"V\"),\n        (0x218, \"M\", \"ș\"),\n        (0x219, \"V\"),\n        (0x21A, \"M\", \"ț\"),\n        (0x21B, \"V\"),\n        (0x21C, \"M\", \"ȝ\"),\n        (0x21D, \"V\"),\n        (0x21E, \"M\", \"ȟ\"),\n        (0x21F, \"V\"),\n        (0x220, \"M\", \"ƞ\"),\n        (0x221, \"V\"),\n        (0x222, \"M\", \"ȣ\"),\n        (0x223, \"V\"),\n        (0x224, \"M\", \"ȥ\"),\n        (0x225, \"V\"),\n        (0x226, \"M\", \"ȧ\"),\n        (0x227, \"V\"),\n        (0x228, \"M\", \"ȩ\"),\n        (0x229, \"V\"),\n        (0x22A, \"M\", \"ȫ\"),\n        (0x22B, \"V\"),\n        (0x22C, \"M\", \"ȭ\"),\n        (0x22D, \"V\"),\n        (0x22E, \"M\", \"ȯ\"),\n        (0x22F, \"V\"),\n        (0x230, \"M\", \"ȱ\"),\n        (0x231, \"V\"),\n        (0x232, \"M\", \"ȳ\"),\n        (0x233, \"V\"),\n        (0x23A, \"M\", \"ⱥ\"),\n        (0x23B, \"M\", \"ȼ\"),\n        (0x23C, \"V\"),\n        (0x23D, \"M\", \"ƚ\"),\n        (0x23E, \"M\", \"ⱦ\"),\n        (0x23F, \"V\"),\n        (0x241, \"M\", \"ɂ\"),\n        (0x242, \"V\"),\n        (0x243, \"M\", \"ƀ\"),\n        (0x244, \"M\", \"ʉ\"),\n        (0x245, \"M\", \"ʌ\"),\n        (0x246, \"M\", \"ɇ\"),\n        (0x247, \"V\"),\n        (0x248, \"M\", \"ɉ\"),\n        (0x249, \"V\"),\n        (0x24A, \"M\", \"ɋ\"),\n        (0x24B, \"V\"),\n        (0x24C, \"M\", \"ɍ\"),\n        (0x24D, \"V\"),\n        (0x24E, \"M\", \"ɏ\"),\n        (0x24F, \"V\"),\n        (0x2B0, \"M\", \"h\"),\n        (0x2B1, \"M\", \"ɦ\"),\n        (0x2B2, \"M\", \"j\"),\n        (0x2B3, \"M\", \"r\"),\n        (0x2B4, \"M\", \"ɹ\"),\n        (0x2B5, \"M\", \"ɻ\"),\n        (0x2B6, \"M\", \"ʁ\"),\n        (0x2B7, \"M\", \"w\"),\n        (0x2B8, \"M\", \"y\"),\n        (0x2B9, \"V\"),\n        (0x2D8, \"M\", \" ̆\"),\n        (0x2D9, \"M\", \" ̇\"),\n        (0x2DA, \"M\", \" ̊\"),\n        (0x2DB, \"M\", \" ̨\"),\n        (0x2DC, \"M\", \" ̃\"),\n        (0x2DD, \"M\", \" ̋\"),\n        (0x2DE, \"V\"),\n        (0x2E0, \"M\", \"ɣ\"),\n        (0x2E1, \"M\", \"l\"),\n        (0x2E2, \"M\", \"s\"),\n        (0x2E3, \"M\", \"x\"),\n        (0x2E4, \"M\", \"ʕ\"),\n        (0x2E5, \"V\"),\n        (0x340, \"M\", \"̀\"),\n        (0x341, \"M\", \"́\"),\n        (0x342, \"V\"),\n        (0x343, \"M\", \"̓\"),\n        (0x344, \"M\", \"̈́\"),\n        (0x345, \"M\", \"ι\"),\n        (0x346, \"V\"),\n        (0x34F, \"I\"),\n        (0x350, \"V\"),\n        (0x370, \"M\", \"ͱ\"),\n        (0x371, \"V\"),\n        (0x372, \"M\", \"ͳ\"),\n        (0x373, \"V\"),\n        (0x374, \"M\", \"ʹ\"),\n        (0x375, \"V\"),\n        (0x376, \"M\", \"ͷ\"),\n        (0x377, \"V\"),\n    ]\n\n\ndef _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x378, \"X\"),\n        (0x37A, \"M\", \" ι\"),\n        (0x37B, \"V\"),\n        (0x37E, \"M\", \";\"),\n        (0x37F, \"M\", \"ϳ\"),\n        (0x380, \"X\"),\n        (0x384, \"M\", \" ́\"),\n        (0x385, \"M\", \" ̈́\"),\n        (0x386, \"M\", \"ά\"),\n        (0x387, \"M\", \"·\"),\n        (0x388, \"M\", \"έ\"),\n        (0x389, \"M\", \"ή\"),\n        (0x38A, \"M\", \"ί\"),\n        (0x38B, \"X\"),\n        (0x38C, \"M\", \"ό\"),\n        (0x38D, \"X\"),\n        (0x38E, \"M\", \"ύ\"),\n        (0x38F, \"M\", \"ώ\"),\n        (0x390, \"V\"),\n        (0x391, \"M\", \"α\"),\n        (0x392, \"M\", \"β\"),\n        (0x393, \"M\", \"γ\"),\n        (0x394, \"M\", \"δ\"),\n        (0x395, \"M\", \"ε\"),\n        (0x396, \"M\", \"ζ\"),\n        (0x397, \"M\", \"η\"),\n        (0x398, \"M\", \"θ\"),\n        (0x399, \"M\", \"ι\"),\n        (0x39A, \"M\", \"κ\"),\n        (0x39B, \"M\", \"λ\"),\n        (0x39C, \"M\", \"μ\"),\n        (0x39D, \"M\", \"ν\"),\n        (0x39E, \"M\", \"ξ\"),\n        (0x39F, \"M\", \"ο\"),\n        (0x3A0, \"M\", \"π\"),\n        (0x3A1, \"M\", \"ρ\"),\n        (0x3A2, \"X\"),\n        (0x3A3, \"M\", \"σ\"),\n        (0x3A4, \"M\", \"τ\"),\n        (0x3A5, \"M\", \"υ\"),\n        (0x3A6, \"M\", \"φ\"),\n        (0x3A7, \"M\", \"χ\"),\n        (0x3A8, \"M\", \"ψ\"),\n        (0x3A9, \"M\", \"ω\"),\n        (0x3AA, \"M\", \"ϊ\"),\n        (0x3AB, \"M\", \"ϋ\"),\n        (0x3AC, \"V\"),\n        (0x3C2, \"D\", \"σ\"),\n        (0x3C3, \"V\"),\n        (0x3CF, \"M\", \"ϗ\"),\n        (0x3D0, \"M\", \"β\"),\n        (0x3D1, \"M\", \"θ\"),\n        (0x3D2, \"M\", \"υ\"),\n        (0x3D3, \"M\", \"ύ\"),\n        (0x3D4, \"M\", \"ϋ\"),\n        (0x3D5, \"M\", \"φ\"),\n        (0x3D6, \"M\", \"π\"),\n        (0x3D7, \"V\"),\n        (0x3D8, \"M\", \"ϙ\"),\n        (0x3D9, \"V\"),\n        (0x3DA, \"M\", \"ϛ\"),\n        (0x3DB, \"V\"),\n        (0x3DC, \"M\", \"ϝ\"),\n        (0x3DD, \"V\"),\n        (0x3DE, \"M\", \"ϟ\"),\n        (0x3DF, \"V\"),\n        (0x3E0, \"M\", \"ϡ\"),\n        (0x3E1, \"V\"),\n        (0x3E2, \"M\", \"ϣ\"),\n        (0x3E3, \"V\"),\n        (0x3E4, \"M\", \"ϥ\"),\n        (0x3E5, \"V\"),\n        (0x3E6, \"M\", \"ϧ\"),\n        (0x3E7, \"V\"),\n        (0x3E8, \"M\", \"ϩ\"),\n        (0x3E9, \"V\"),\n        (0x3EA, \"M\", \"ϫ\"),\n        (0x3EB, \"V\"),\n        (0x3EC, \"M\", \"ϭ\"),\n        (0x3ED, \"V\"),\n        (0x3EE, \"M\", \"ϯ\"),\n        (0x3EF, \"V\"),\n        (0x3F0, \"M\", \"κ\"),\n        (0x3F1, \"M\", \"ρ\"),\n        (0x3F2, \"M\", \"σ\"),\n        (0x3F3, \"V\"),\n        (0x3F4, \"M\", \"θ\"),\n        (0x3F5, \"M\", \"ε\"),\n        (0x3F6, \"V\"),\n        (0x3F7, \"M\", \"ϸ\"),\n        (0x3F8, \"V\"),\n        (0x3F9, \"M\", \"σ\"),\n        (0x3FA, \"M\", \"ϻ\"),\n        (0x3FB, \"V\"),\n        (0x3FD, \"M\", \"ͻ\"),\n        (0x3FE, \"M\", \"ͼ\"),\n        (0x3FF, \"M\", \"ͽ\"),\n        (0x400, \"M\", \"ѐ\"),\n        (0x401, \"M\", \"ё\"),\n        (0x402, \"M\", \"ђ\"),\n    ]\n\n\ndef _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x403, \"M\", \"ѓ\"),\n        (0x404, \"M\", \"є\"),\n        (0x405, \"M\", \"ѕ\"),\n        (0x406, \"M\", \"і\"),\n        (0x407, \"M\", \"ї\"),\n        (0x408, \"M\", \"ј\"),\n        (0x409, \"M\", \"љ\"),\n        (0x40A, \"M\", \"њ\"),\n        (0x40B, \"M\", \"ћ\"),\n        (0x40C, \"M\", \"ќ\"),\n        (0x40D, \"M\", \"ѝ\"),\n        (0x40E, \"M\", \"ў\"),\n        (0x40F, \"M\", \"џ\"),\n        (0x410, \"M\", \"а\"),\n        (0x411, \"M\", \"б\"),\n        (0x412, \"M\", \"в\"),\n        (0x413, \"M\", \"г\"),\n        (0x414, \"M\", \"д\"),\n        (0x415, \"M\", \"е\"),\n        (0x416, \"M\", \"ж\"),\n        (0x417, \"M\", \"з\"),\n        (0x418, \"M\", \"и\"),\n        (0x419, \"M\", \"й\"),\n        (0x41A, \"M\", \"к\"),\n        (0x41B, \"M\", \"л\"),\n        (0x41C, \"M\", \"м\"),\n        (0x41D, \"M\", \"н\"),\n        (0x41E, \"M\", \"о\"),\n        (0x41F, \"M\", \"п\"),\n        (0x420, \"M\", \"р\"),\n        (0x421, \"M\", \"с\"),\n        (0x422, \"M\", \"т\"),\n        (0x423, \"M\", \"у\"),\n        (0x424, \"M\", \"ф\"),\n        (0x425, \"M\", \"х\"),\n        (0x426, \"M\", \"ц\"),\n        (0x427, \"M\", \"ч\"),\n        (0x428, \"M\", \"ш\"),\n        (0x429, \"M\", \"щ\"),\n        (0x42A, \"M\", \"ъ\"),\n        (0x42B, \"M\", \"ы\"),\n        (0x42C, \"M\", \"ь\"),\n        (0x42D, \"M\", \"э\"),\n        (0x42E, \"M\", \"ю\"),\n        (0x42F, \"M\", \"я\"),\n        (0x430, \"V\"),\n        (0x460, \"M\", \"ѡ\"),\n        (0x461, \"V\"),\n        (0x462, \"M\", \"ѣ\"),\n        (0x463, \"V\"),\n        (0x464, \"M\", \"ѥ\"),\n        (0x465, \"V\"),\n        (0x466, \"M\", \"ѧ\"),\n        (0x467, \"V\"),\n        (0x468, \"M\", \"ѩ\"),\n        (0x469, \"V\"),\n        (0x46A, \"M\", \"ѫ\"),\n        (0x46B, \"V\"),\n        (0x46C, \"M\", \"ѭ\"),\n        (0x46D, \"V\"),\n        (0x46E, \"M\", \"ѯ\"),\n        (0x46F, \"V\"),\n        (0x470, \"M\", \"ѱ\"),\n        (0x471, \"V\"),\n        (0x472, \"M\", \"ѳ\"),\n        (0x473, \"V\"),\n        (0x474, \"M\", \"ѵ\"),\n        (0x475, \"V\"),\n        (0x476, \"M\", \"ѷ\"),\n        (0x477, \"V\"),\n        (0x478, \"M\", \"ѹ\"),\n        (0x479, \"V\"),\n        (0x47A, \"M\", \"ѻ\"),\n        (0x47B, \"V\"),\n        (0x47C, \"M\", \"ѽ\"),\n        (0x47D, \"V\"),\n        (0x47E, \"M\", \"ѿ\"),\n        (0x47F, \"V\"),\n        (0x480, \"M\", \"ҁ\"),\n        (0x481, \"V\"),\n        (0x48A, \"M\", \"ҋ\"),\n        (0x48B, \"V\"),\n        (0x48C, \"M\", \"ҍ\"),\n        (0x48D, \"V\"),\n        (0x48E, \"M\", \"ҏ\"),\n        (0x48F, \"V\"),\n        (0x490, \"M\", \"ґ\"),\n        (0x491, \"V\"),\n        (0x492, \"M\", \"ғ\"),\n        (0x493, \"V\"),\n        (0x494, \"M\", \"ҕ\"),\n        (0x495, \"V\"),\n        (0x496, \"M\", \"җ\"),\n        (0x497, \"V\"),\n        (0x498, \"M\", \"ҙ\"),\n        (0x499, \"V\"),\n        (0x49A, \"M\", \"қ\"),\n        (0x49B, \"V\"),\n        (0x49C, \"M\", \"ҝ\"),\n        (0x49D, \"V\"),\n    ]\n\n\ndef _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x49E, \"M\", \"ҟ\"),\n        (0x49F, \"V\"),\n        (0x4A0, \"M\", \"ҡ\"),\n        (0x4A1, \"V\"),\n        (0x4A2, \"M\", \"ң\"),\n        (0x4A3, \"V\"),\n        (0x4A4, \"M\", \"ҥ\"),\n        (0x4A5, \"V\"),\n        (0x4A6, \"M\", \"ҧ\"),\n        (0x4A7, \"V\"),\n        (0x4A8, \"M\", \"ҩ\"),\n        (0x4A9, \"V\"),\n        (0x4AA, \"M\", \"ҫ\"),\n        (0x4AB, \"V\"),\n        (0x4AC, \"M\", \"ҭ\"),\n        (0x4AD, \"V\"),\n        (0x4AE, \"M\", \"ү\"),\n        (0x4AF, \"V\"),\n        (0x4B0, \"M\", \"ұ\"),\n        (0x4B1, \"V\"),\n        (0x4B2, \"M\", \"ҳ\"),\n        (0x4B3, \"V\"),\n        (0x4B4, \"M\", \"ҵ\"),\n        (0x4B5, \"V\"),\n        (0x4B6, \"M\", \"ҷ\"),\n        (0x4B7, \"V\"),\n        (0x4B8, \"M\", \"ҹ\"),\n        (0x4B9, \"V\"),\n        (0x4BA, \"M\", \"һ\"),\n        (0x4BB, \"V\"),\n        (0x4BC, \"M\", \"ҽ\"),\n        (0x4BD, \"V\"),\n        (0x4BE, \"M\", \"ҿ\"),\n        (0x4BF, \"V\"),\n        (0x4C0, \"M\", \"ӏ\"),\n        (0x4C1, \"M\", \"ӂ\"),\n        (0x4C2, \"V\"),\n        (0x4C3, \"M\", \"ӄ\"),\n        (0x4C4, \"V\"),\n        (0x4C5, \"M\", \"ӆ\"),\n        (0x4C6, \"V\"),\n        (0x4C7, \"M\", \"ӈ\"),\n        (0x4C8, \"V\"),\n        (0x4C9, \"M\", \"ӊ\"),\n        (0x4CA, \"V\"),\n        (0x4CB, \"M\", \"ӌ\"),\n        (0x4CC, \"V\"),\n        (0x4CD, \"M\", \"ӎ\"),\n        (0x4CE, \"V\"),\n        (0x4D0, \"M\", \"ӑ\"),\n        (0x4D1, \"V\"),\n        (0x4D2, \"M\", \"ӓ\"),\n        (0x4D3, \"V\"),\n        (0x4D4, \"M\", \"ӕ\"),\n        (0x4D5, \"V\"),\n        (0x4D6, \"M\", \"ӗ\"),\n        (0x4D7, \"V\"),\n        (0x4D8, \"M\", \"ә\"),\n        (0x4D9, \"V\"),\n        (0x4DA, \"M\", \"ӛ\"),\n        (0x4DB, \"V\"),\n        (0x4DC, \"M\", \"ӝ\"),\n        (0x4DD, \"V\"),\n        (0x4DE, \"M\", \"ӟ\"),\n        (0x4DF, \"V\"),\n        (0x4E0, \"M\", \"ӡ\"),\n        (0x4E1, \"V\"),\n        (0x4E2, \"M\", \"ӣ\"),\n        (0x4E3, \"V\"),\n        (0x4E4, \"M\", \"ӥ\"),\n        (0x4E5, \"V\"),\n        (0x4E6, \"M\", \"ӧ\"),\n        (0x4E7, \"V\"),\n        (0x4E8, \"M\", \"ө\"),\n        (0x4E9, \"V\"),\n        (0x4EA, \"M\", \"ӫ\"),\n        (0x4EB, \"V\"),\n        (0x4EC, \"M\", \"ӭ\"),\n        (0x4ED, \"V\"),\n        (0x4EE, \"M\", \"ӯ\"),\n        (0x4EF, \"V\"),\n        (0x4F0, \"M\", \"ӱ\"),\n        (0x4F1, \"V\"),\n        (0x4F2, \"M\", \"ӳ\"),\n        (0x4F3, \"V\"),\n        (0x4F4, \"M\", \"ӵ\"),\n        (0x4F5, \"V\"),\n        (0x4F6, \"M\", \"ӷ\"),\n        (0x4F7, \"V\"),\n        (0x4F8, \"M\", \"ӹ\"),\n        (0x4F9, \"V\"),\n        (0x4FA, \"M\", \"ӻ\"),\n        (0x4FB, \"V\"),\n        (0x4FC, \"M\", \"ӽ\"),\n        (0x4FD, \"V\"),\n        (0x4FE, \"M\", \"ӿ\"),\n        (0x4FF, \"V\"),\n        (0x500, \"M\", \"ԁ\"),\n        (0x501, \"V\"),\n        (0x502, \"M\", \"ԃ\"),\n    ]\n\n\ndef _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x503, \"V\"),\n        (0x504, \"M\", \"ԅ\"),\n        (0x505, \"V\"),\n        (0x506, \"M\", \"ԇ\"),\n        (0x507, \"V\"),\n        (0x508, \"M\", \"ԉ\"),\n        (0x509, \"V\"),\n        (0x50A, \"M\", \"ԋ\"),\n        (0x50B, \"V\"),\n        (0x50C, \"M\", \"ԍ\"),\n        (0x50D, \"V\"),\n        (0x50E, \"M\", \"ԏ\"),\n        (0x50F, \"V\"),\n        (0x510, \"M\", \"ԑ\"),\n        (0x511, \"V\"),\n        (0x512, \"M\", \"ԓ\"),\n        (0x513, \"V\"),\n        (0x514, \"M\", \"ԕ\"),\n        (0x515, \"V\"),\n        (0x516, \"M\", \"ԗ\"),\n        (0x517, \"V\"),\n        (0x518, \"M\", \"ԙ\"),\n        (0x519, \"V\"),\n        (0x51A, \"M\", \"ԛ\"),\n        (0x51B, \"V\"),\n        (0x51C, \"M\", \"ԝ\"),\n        (0x51D, \"V\"),\n        (0x51E, \"M\", \"ԟ\"),\n        (0x51F, \"V\"),\n        (0x520, \"M\", \"ԡ\"),\n        (0x521, \"V\"),\n        (0x522, \"M\", \"ԣ\"),\n        (0x523, \"V\"),\n        (0x524, \"M\", \"ԥ\"),\n        (0x525, \"V\"),\n        (0x526, \"M\", \"ԧ\"),\n        (0x527, \"V\"),\n        (0x528, \"M\", \"ԩ\"),\n        (0x529, \"V\"),\n        (0x52A, \"M\", \"ԫ\"),\n        (0x52B, \"V\"),\n        (0x52C, \"M\", \"ԭ\"),\n        (0x52D, \"V\"),\n        (0x52E, \"M\", \"ԯ\"),\n        (0x52F, \"V\"),\n        (0x530, \"X\"),\n        (0x531, \"M\", \"ա\"),\n        (0x532, \"M\", \"բ\"),\n        (0x533, \"M\", \"գ\"),\n        (0x534, \"M\", \"դ\"),\n        (0x535, \"M\", \"ե\"),\n        (0x536, \"M\", \"զ\"),\n        (0x537, \"M\", \"է\"),\n        (0x538, \"M\", \"ը\"),\n        (0x539, \"M\", \"թ\"),\n        (0x53A, \"M\", \"ժ\"),\n        (0x53B, \"M\", \"ի\"),\n        (0x53C, \"M\", \"լ\"),\n        (0x53D, \"M\", \"խ\"),\n        (0x53E, \"M\", \"ծ\"),\n        (0x53F, \"M\", \"կ\"),\n        (0x540, \"M\", \"հ\"),\n        (0x541, \"M\", \"ձ\"),\n        (0x542, \"M\", \"ղ\"),\n        (0x543, \"M\", \"ճ\"),\n        (0x544, \"M\", \"մ\"),\n        (0x545, \"M\", \"յ\"),\n        (0x546, \"M\", \"ն\"),\n        (0x547, \"M\", \"շ\"),\n        (0x548, \"M\", \"ո\"),\n        (0x549, \"M\", \"չ\"),\n        (0x54A, \"M\", \"պ\"),\n        (0x54B, \"M\", \"ջ\"),\n        (0x54C, \"M\", \"ռ\"),\n        (0x54D, \"M\", \"ս\"),\n        (0x54E, \"M\", \"վ\"),\n        (0x54F, \"M\", \"տ\"),\n        (0x550, \"M\", \"ր\"),\n        (0x551, \"M\", \"ց\"),\n        (0x552, \"M\", \"ւ\"),\n        (0x553, \"M\", \"փ\"),\n        (0x554, \"M\", \"ք\"),\n        (0x555, \"M\", \"օ\"),\n        (0x556, \"M\", \"ֆ\"),\n        (0x557, \"X\"),\n        (0x559, \"V\"),\n        (0x587, \"M\", \"եւ\"),\n        (0x588, \"V\"),\n        (0x58B, \"X\"),\n        (0x58D, \"V\"),\n        (0x590, \"X\"),\n        (0x591, \"V\"),\n        (0x5C8, \"X\"),\n        (0x5D0, \"V\"),\n        (0x5EB, \"X\"),\n        (0x5EF, \"V\"),\n        (0x5F5, \"X\"),\n        (0x606, \"V\"),\n        (0x61C, \"X\"),\n        (0x61D, \"V\"),\n    ]\n\n\ndef _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x675, \"M\", \"اٴ\"),\n        (0x676, \"M\", \"وٴ\"),\n        (0x677, \"M\", \"ۇٴ\"),\n        (0x678, \"M\", \"يٴ\"),\n        (0x679, \"V\"),\n        (0x6DD, \"X\"),\n        (0x6DE, \"V\"),\n        (0x70E, \"X\"),\n        (0x710, \"V\"),\n        (0x74B, \"X\"),\n        (0x74D, \"V\"),\n        (0x7B2, \"X\"),\n        (0x7C0, \"V\"),\n        (0x7FB, \"X\"),\n        (0x7FD, \"V\"),\n        (0x82E, \"X\"),\n        (0x830, \"V\"),\n        (0x83F, \"X\"),\n        (0x840, \"V\"),\n        (0x85C, \"X\"),\n        (0x85E, \"V\"),\n        (0x85F, \"X\"),\n        (0x860, \"V\"),\n        (0x86B, \"X\"),\n        (0x870, \"V\"),\n        (0x88F, \"X\"),\n        (0x897, \"V\"),\n        (0x8E2, \"X\"),\n        (0x8E3, \"V\"),\n        (0x958, \"M\", \"क़\"),\n        (0x959, \"M\", \"ख़\"),\n        (0x95A, \"M\", \"ग़\"),\n        (0x95B, \"M\", \"ज़\"),\n        (0x95C, \"M\", \"ड़\"),\n        (0x95D, \"M\", \"ढ़\"),\n        (0x95E, \"M\", \"फ़\"),\n        (0x95F, \"M\", \"य़\"),\n        (0x960, \"V\"),\n        (0x984, \"X\"),\n        (0x985, \"V\"),\n        (0x98D, \"X\"),\n        (0x98F, \"V\"),\n        (0x991, \"X\"),\n        (0x993, \"V\"),\n        (0x9A9, \"X\"),\n        (0x9AA, \"V\"),\n        (0x9B1, \"X\"),\n        (0x9B2, \"V\"),\n        (0x9B3, \"X\"),\n        (0x9B6, \"V\"),\n        (0x9BA, \"X\"),\n        (0x9BC, \"V\"),\n        (0x9C5, \"X\"),\n        (0x9C7, \"V\"),\n        (0x9C9, \"X\"),\n        (0x9CB, \"V\"),\n        (0x9CF, \"X\"),\n        (0x9D7, \"V\"),\n        (0x9D8, \"X\"),\n        (0x9DC, \"M\", \"ড়\"),\n        (0x9DD, \"M\", \"ঢ়\"),\n        (0x9DE, \"X\"),\n        (0x9DF, \"M\", \"য়\"),\n        (0x9E0, \"V\"),\n        (0x9E4, \"X\"),\n        (0x9E6, \"V\"),\n        (0x9FF, \"X\"),\n        (0xA01, \"V\"),\n        (0xA04, \"X\"),\n        (0xA05, \"V\"),\n        (0xA0B, \"X\"),\n        (0xA0F, \"V\"),\n        (0xA11, \"X\"),\n        (0xA13, \"V\"),\n        (0xA29, \"X\"),\n        (0xA2A, \"V\"),\n        (0xA31, \"X\"),\n        (0xA32, \"V\"),\n        (0xA33, \"M\", \"ਲ਼\"),\n        (0xA34, \"X\"),\n        (0xA35, \"V\"),\n        (0xA36, \"M\", \"ਸ਼\"),\n        (0xA37, \"X\"),\n        (0xA38, \"V\"),\n        (0xA3A, \"X\"),\n        (0xA3C, \"V\"),\n        (0xA3D, \"X\"),\n        (0xA3E, \"V\"),\n        (0xA43, \"X\"),\n        (0xA47, \"V\"),\n        (0xA49, \"X\"),\n        (0xA4B, \"V\"),\n        (0xA4E, \"X\"),\n        (0xA51, \"V\"),\n        (0xA52, \"X\"),\n        (0xA59, \"M\", \"ਖ਼\"),\n        (0xA5A, \"M\", \"ਗ਼\"),\n        (0xA5B, \"M\", \"ਜ਼\"),\n        (0xA5C, \"V\"),\n        (0xA5D, \"X\"),\n    ]\n\n\ndef _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xA5E, \"M\", \"ਫ਼\"),\n        (0xA5F, \"X\"),\n        (0xA66, \"V\"),\n        (0xA77, \"X\"),\n        (0xA81, \"V\"),\n        (0xA84, \"X\"),\n        (0xA85, \"V\"),\n        (0xA8E, \"X\"),\n        (0xA8F, \"V\"),\n        (0xA92, \"X\"),\n        (0xA93, \"V\"),\n        (0xAA9, \"X\"),\n        (0xAAA, \"V\"),\n        (0xAB1, \"X\"),\n        (0xAB2, \"V\"),\n        (0xAB4, \"X\"),\n        (0xAB5, \"V\"),\n        (0xABA, \"X\"),\n        (0xABC, \"V\"),\n        (0xAC6, \"X\"),\n        (0xAC7, \"V\"),\n        (0xACA, \"X\"),\n        (0xACB, \"V\"),\n        (0xACE, \"X\"),\n        (0xAD0, \"V\"),\n        (0xAD1, \"X\"),\n        (0xAE0, \"V\"),\n        (0xAE4, \"X\"),\n        (0xAE6, \"V\"),\n        (0xAF2, \"X\"),\n        (0xAF9, \"V\"),\n        (0xB00, \"X\"),\n        (0xB01, \"V\"),\n        (0xB04, \"X\"),\n        (0xB05, \"V\"),\n        (0xB0D, \"X\"),\n        (0xB0F, \"V\"),\n        (0xB11, \"X\"),\n        (0xB13, \"V\"),\n        (0xB29, \"X\"),\n        (0xB2A, \"V\"),\n        (0xB31, \"X\"),\n        (0xB32, \"V\"),\n        (0xB34, \"X\"),\n        (0xB35, \"V\"),\n        (0xB3A, \"X\"),\n        (0xB3C, \"V\"),\n        (0xB45, \"X\"),\n        (0xB47, \"V\"),\n        (0xB49, \"X\"),\n        (0xB4B, \"V\"),\n        (0xB4E, \"X\"),\n        (0xB55, \"V\"),\n        (0xB58, \"X\"),\n        (0xB5C, \"M\", \"ଡ଼\"),\n        (0xB5D, \"M\", \"ଢ଼\"),\n        (0xB5E, \"X\"),\n        (0xB5F, \"V\"),\n        (0xB64, \"X\"),\n        (0xB66, \"V\"),\n        (0xB78, \"X\"),\n        (0xB82, \"V\"),\n        (0xB84, \"X\"),\n        (0xB85, \"V\"),\n        (0xB8B, \"X\"),\n        (0xB8E, \"V\"),\n        (0xB91, \"X\"),\n        (0xB92, \"V\"),\n        (0xB96, \"X\"),\n        (0xB99, \"V\"),\n        (0xB9B, \"X\"),\n        (0xB9C, \"V\"),\n        (0xB9D, \"X\"),\n        (0xB9E, \"V\"),\n        (0xBA0, \"X\"),\n        (0xBA3, \"V\"),\n        (0xBA5, \"X\"),\n        (0xBA8, \"V\"),\n        (0xBAB, \"X\"),\n        (0xBAE, \"V\"),\n        (0xBBA, \"X\"),\n        (0xBBE, \"V\"),\n        (0xBC3, \"X\"),\n        (0xBC6, \"V\"),\n        (0xBC9, \"X\"),\n        (0xBCA, \"V\"),\n        (0xBCE, \"X\"),\n        (0xBD0, \"V\"),\n        (0xBD1, \"X\"),\n        (0xBD7, \"V\"),\n        (0xBD8, \"X\"),\n        (0xBE6, \"V\"),\n        (0xBFB, \"X\"),\n        (0xC00, \"V\"),\n        (0xC0D, \"X\"),\n        (0xC0E, \"V\"),\n        (0xC11, \"X\"),\n        (0xC12, \"V\"),\n        (0xC29, \"X\"),\n        (0xC2A, \"V\"),\n    ]\n\n\ndef _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xC3A, \"X\"),\n        (0xC3C, \"V\"),\n        (0xC45, \"X\"),\n        (0xC46, \"V\"),\n        (0xC49, \"X\"),\n        (0xC4A, \"V\"),\n        (0xC4E, \"X\"),\n        (0xC55, \"V\"),\n        (0xC57, \"X\"),\n        (0xC58, \"V\"),\n        (0xC5B, \"X\"),\n        (0xC5D, \"V\"),\n        (0xC5E, \"X\"),\n        (0xC60, \"V\"),\n        (0xC64, \"X\"),\n        (0xC66, \"V\"),\n        (0xC70, \"X\"),\n        (0xC77, \"V\"),\n        (0xC8D, \"X\"),\n        (0xC8E, \"V\"),\n        (0xC91, \"X\"),\n        (0xC92, \"V\"),\n        (0xCA9, \"X\"),\n        (0xCAA, \"V\"),\n        (0xCB4, \"X\"),\n        (0xCB5, \"V\"),\n        (0xCBA, \"X\"),\n        (0xCBC, \"V\"),\n        (0xCC5, \"X\"),\n        (0xCC6, \"V\"),\n        (0xCC9, \"X\"),\n        (0xCCA, \"V\"),\n        (0xCCE, \"X\"),\n        (0xCD5, \"V\"),\n        (0xCD7, \"X\"),\n        (0xCDD, \"V\"),\n        (0xCDF, \"X\"),\n        (0xCE0, \"V\"),\n        (0xCE4, \"X\"),\n        (0xCE6, \"V\"),\n        (0xCF0, \"X\"),\n        (0xCF1, \"V\"),\n        (0xCF4, \"X\"),\n        (0xD00, \"V\"),\n        (0xD0D, \"X\"),\n        (0xD0E, \"V\"),\n        (0xD11, \"X\"),\n        (0xD12, \"V\"),\n        (0xD45, \"X\"),\n        (0xD46, \"V\"),\n        (0xD49, \"X\"),\n        (0xD4A, \"V\"),\n        (0xD50, \"X\"),\n        (0xD54, \"V\"),\n        (0xD64, \"X\"),\n        (0xD66, \"V\"),\n        (0xD80, \"X\"),\n        (0xD81, \"V\"),\n        (0xD84, \"X\"),\n        (0xD85, \"V\"),\n        (0xD97, \"X\"),\n        (0xD9A, \"V\"),\n        (0xDB2, \"X\"),\n        (0xDB3, \"V\"),\n        (0xDBC, \"X\"),\n        (0xDBD, \"V\"),\n        (0xDBE, \"X\"),\n        (0xDC0, \"V\"),\n        (0xDC7, \"X\"),\n        (0xDCA, \"V\"),\n        (0xDCB, \"X\"),\n        (0xDCF, \"V\"),\n        (0xDD5, \"X\"),\n        (0xDD6, \"V\"),\n        (0xDD7, \"X\"),\n        (0xDD8, \"V\"),\n        (0xDE0, \"X\"),\n        (0xDE6, \"V\"),\n        (0xDF0, \"X\"),\n        (0xDF2, \"V\"),\n        (0xDF5, \"X\"),\n        (0xE01, \"V\"),\n        (0xE33, \"M\", \"ํา\"),\n        (0xE34, \"V\"),\n        (0xE3B, \"X\"),\n        (0xE3F, \"V\"),\n        (0xE5C, \"X\"),\n        (0xE81, \"V\"),\n        (0xE83, \"X\"),\n        (0xE84, \"V\"),\n        (0xE85, \"X\"),\n        (0xE86, \"V\"),\n        (0xE8B, \"X\"),\n        (0xE8C, \"V\"),\n        (0xEA4, \"X\"),\n        (0xEA5, \"V\"),\n        (0xEA6, \"X\"),\n        (0xEA7, \"V\"),\n        (0xEB3, \"M\", \"ໍາ\"),\n        (0xEB4, \"V\"),\n    ]\n\n\ndef _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xEBE, \"X\"),\n        (0xEC0, \"V\"),\n        (0xEC5, \"X\"),\n        (0xEC6, \"V\"),\n        (0xEC7, \"X\"),\n        (0xEC8, \"V\"),\n        (0xECF, \"X\"),\n        (0xED0, \"V\"),\n        (0xEDA, \"X\"),\n        (0xEDC, \"M\", \"ຫນ\"),\n        (0xEDD, \"M\", \"ຫມ\"),\n        (0xEDE, \"V\"),\n        (0xEE0, \"X\"),\n        (0xF00, \"V\"),\n        (0xF0C, \"M\", \"་\"),\n        (0xF0D, \"V\"),\n        (0xF43, \"M\", \"གྷ\"),\n        (0xF44, \"V\"),\n        (0xF48, \"X\"),\n        (0xF49, \"V\"),\n        (0xF4D, \"M\", \"ཌྷ\"),\n        (0xF4E, \"V\"),\n        (0xF52, \"M\", \"དྷ\"),\n        (0xF53, \"V\"),\n        (0xF57, \"M\", \"བྷ\"),\n        (0xF58, \"V\"),\n        (0xF5C, \"M\", \"ཛྷ\"),\n        (0xF5D, \"V\"),\n        (0xF69, \"M\", \"ཀྵ\"),\n        (0xF6A, \"V\"),\n        (0xF6D, \"X\"),\n        (0xF71, \"V\"),\n        (0xF73, \"M\", \"ཱི\"),\n        (0xF74, \"V\"),\n        (0xF75, \"M\", \"ཱུ\"),\n        (0xF76, \"M\", \"ྲྀ\"),\n        (0xF77, \"M\", \"ྲཱྀ\"),\n        (0xF78, \"M\", \"ླྀ\"),\n        (0xF79, \"M\", \"ླཱྀ\"),\n        (0xF7A, \"V\"),\n        (0xF81, \"M\", \"ཱྀ\"),\n        (0xF82, \"V\"),\n        (0xF93, \"M\", \"ྒྷ\"),\n        (0xF94, \"V\"),\n        (0xF98, \"X\"),\n        (0xF99, \"V\"),\n        (0xF9D, \"M\", \"ྜྷ\"),\n        (0xF9E, \"V\"),\n        (0xFA2, \"M\", \"ྡྷ\"),\n        (0xFA3, \"V\"),\n        (0xFA7, \"M\", \"ྦྷ\"),\n        (0xFA8, \"V\"),\n        (0xFAC, \"M\", \"ྫྷ\"),\n        (0xFAD, \"V\"),\n        (0xFB9, \"M\", \"ྐྵ\"),\n        (0xFBA, \"V\"),\n        (0xFBD, \"X\"),\n        (0xFBE, \"V\"),\n        (0xFCD, \"X\"),\n        (0xFCE, \"V\"),\n        (0xFDB, \"X\"),\n        (0x1000, \"V\"),\n        (0x10A0, \"M\", \"ⴀ\"),\n        (0x10A1, \"M\", \"ⴁ\"),\n        (0x10A2, \"M\", \"ⴂ\"),\n        (0x10A3, \"M\", \"ⴃ\"),\n        (0x10A4, \"M\", \"ⴄ\"),\n        (0x10A5, \"M\", \"ⴅ\"),\n        (0x10A6, \"M\", \"ⴆ\"),\n        (0x10A7, \"M\", \"ⴇ\"),\n        (0x10A8, \"M\", \"ⴈ\"),\n        (0x10A9, \"M\", \"ⴉ\"),\n        (0x10AA, \"M\", \"ⴊ\"),\n        (0x10AB, \"M\", \"ⴋ\"),\n        (0x10AC, \"M\", \"ⴌ\"),\n        (0x10AD, \"M\", \"ⴍ\"),\n        (0x10AE, \"M\", \"ⴎ\"),\n        (0x10AF, \"M\", \"ⴏ\"),\n        (0x10B0, \"M\", \"ⴐ\"),\n        (0x10B1, \"M\", \"ⴑ\"),\n        (0x10B2, \"M\", \"ⴒ\"),\n        (0x10B3, \"M\", \"ⴓ\"),\n        (0x10B4, \"M\", \"ⴔ\"),\n        (0x10B5, \"M\", \"ⴕ\"),\n        (0x10B6, \"M\", \"ⴖ\"),\n        (0x10B7, \"M\", \"ⴗ\"),\n        (0x10B8, \"M\", \"ⴘ\"),\n        (0x10B9, \"M\", \"ⴙ\"),\n        (0x10BA, \"M\", \"ⴚ\"),\n        (0x10BB, \"M\", \"ⴛ\"),\n        (0x10BC, \"M\", \"ⴜ\"),\n        (0x10BD, \"M\", \"ⴝ\"),\n        (0x10BE, \"M\", \"ⴞ\"),\n        (0x10BF, \"M\", \"ⴟ\"),\n        (0x10C0, \"M\", \"ⴠ\"),\n        (0x10C1, \"M\", \"ⴡ\"),\n        (0x10C2, \"M\", \"ⴢ\"),\n        (0x10C3, \"M\", \"ⴣ\"),\n        (0x10C4, \"M\", \"ⴤ\"),\n        (0x10C5, \"M\", \"ⴥ\"),\n    ]\n\n\ndef _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x10C6, \"X\"),\n        (0x10C7, \"M\", \"ⴧ\"),\n        (0x10C8, \"X\"),\n        (0x10CD, \"M\", \"ⴭ\"),\n        (0x10CE, \"X\"),\n        (0x10D0, \"V\"),\n        (0x10FC, \"M\", \"ნ\"),\n        (0x10FD, \"V\"),\n        (0x115F, \"I\"),\n        (0x1161, \"V\"),\n        (0x1249, \"X\"),\n        (0x124A, \"V\"),\n        (0x124E, \"X\"),\n        (0x1250, \"V\"),\n        (0x1257, \"X\"),\n        (0x1258, \"V\"),\n        (0x1259, \"X\"),\n        (0x125A, \"V\"),\n        (0x125E, \"X\"),\n        (0x1260, \"V\"),\n        (0x1289, \"X\"),\n        (0x128A, \"V\"),\n        (0x128E, \"X\"),\n        (0x1290, \"V\"),\n        (0x12B1, \"X\"),\n        (0x12B2, \"V\"),\n        (0x12B6, \"X\"),\n        (0x12B8, \"V\"),\n        (0x12BF, \"X\"),\n        (0x12C0, \"V\"),\n        (0x12C1, \"X\"),\n        (0x12C2, \"V\"),\n        (0x12C6, \"X\"),\n        (0x12C8, \"V\"),\n        (0x12D7, \"X\"),\n        (0x12D8, \"V\"),\n        (0x1311, \"X\"),\n        (0x1312, \"V\"),\n        (0x1316, \"X\"),\n        (0x1318, \"V\"),\n        (0x135B, \"X\"),\n        (0x135D, \"V\"),\n        (0x137D, \"X\"),\n        (0x1380, \"V\"),\n        (0x139A, \"X\"),\n        (0x13A0, \"V\"),\n        (0x13F6, \"X\"),\n        (0x13F8, \"M\", \"Ᏸ\"),\n        (0x13F9, \"M\", \"Ᏹ\"),\n        (0x13FA, \"M\", \"Ᏺ\"),\n        (0x13FB, \"M\", \"Ᏻ\"),\n        (0x13FC, \"M\", \"Ᏼ\"),\n        (0x13FD, \"M\", \"Ᏽ\"),\n        (0x13FE, \"X\"),\n        (0x1400, \"V\"),\n        (0x1680, \"X\"),\n        (0x1681, \"V\"),\n        (0x169D, \"X\"),\n        (0x16A0, \"V\"),\n        (0x16F9, \"X\"),\n        (0x1700, \"V\"),\n        (0x1716, \"X\"),\n        (0x171F, \"V\"),\n        (0x1737, \"X\"),\n        (0x1740, \"V\"),\n        (0x1754, \"X\"),\n        (0x1760, \"V\"),\n        (0x176D, \"X\"),\n        (0x176E, \"V\"),\n        (0x1771, \"X\"),\n        (0x1772, \"V\"),\n        (0x1774, \"X\"),\n        (0x1780, \"V\"),\n        (0x17B4, \"I\"),\n        (0x17B6, \"V\"),\n        (0x17DE, \"X\"),\n        (0x17E0, \"V\"),\n        (0x17EA, \"X\"),\n        (0x17F0, \"V\"),\n        (0x17FA, \"X\"),\n        (0x1800, \"V\"),\n        (0x180B, \"I\"),\n        (0x1810, \"V\"),\n        (0x181A, \"X\"),\n        (0x1820, \"V\"),\n        (0x1879, \"X\"),\n        (0x1880, \"V\"),\n        (0x18AB, \"X\"),\n        (0x18B0, \"V\"),\n        (0x18F6, \"X\"),\n        (0x1900, \"V\"),\n        (0x191F, \"X\"),\n        (0x1920, \"V\"),\n        (0x192C, \"X\"),\n        (0x1930, \"V\"),\n        (0x193C, \"X\"),\n        (0x1940, \"V\"),\n        (0x1941, \"X\"),\n        (0x1944, \"V\"),\n        (0x196E, \"X\"),\n    ]\n\n\ndef _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1970, \"V\"),\n        (0x1975, \"X\"),\n        (0x1980, \"V\"),\n        (0x19AC, \"X\"),\n        (0x19B0, \"V\"),\n        (0x19CA, \"X\"),\n        (0x19D0, \"V\"),\n        (0x19DB, \"X\"),\n        (0x19DE, \"V\"),\n        (0x1A1C, \"X\"),\n        (0x1A1E, \"V\"),\n        (0x1A5F, \"X\"),\n        (0x1A60, \"V\"),\n        (0x1A7D, \"X\"),\n        (0x1A7F, \"V\"),\n        (0x1A8A, \"X\"),\n        (0x1A90, \"V\"),\n        (0x1A9A, \"X\"),\n        (0x1AA0, \"V\"),\n        (0x1AAE, \"X\"),\n        (0x1AB0, \"V\"),\n        (0x1ACF, \"X\"),\n        (0x1B00, \"V\"),\n        (0x1B4D, \"X\"),\n        (0x1B4E, \"V\"),\n        (0x1BF4, \"X\"),\n        (0x1BFC, \"V\"),\n        (0x1C38, \"X\"),\n        (0x1C3B, \"V\"),\n        (0x1C4A, \"X\"),\n        (0x1C4D, \"V\"),\n        (0x1C80, \"M\", \"в\"),\n        (0x1C81, \"M\", \"д\"),\n        (0x1C82, \"M\", \"о\"),\n        (0x1C83, \"M\", \"с\"),\n        (0x1C84, \"M\", \"т\"),\n        (0x1C86, \"M\", \"ъ\"),\n        (0x1C87, \"M\", \"ѣ\"),\n        (0x1C88, \"M\", \"ꙋ\"),\n        (0x1C89, \"M\", \"ᲊ\"),\n        (0x1C8A, \"V\"),\n        (0x1C8B, \"X\"),\n        (0x1C90, \"M\", \"ა\"),\n        (0x1C91, \"M\", \"ბ\"),\n        (0x1C92, \"M\", \"გ\"),\n        (0x1C93, \"M\", \"დ\"),\n        (0x1C94, \"M\", \"ე\"),\n        (0x1C95, \"M\", \"ვ\"),\n        (0x1C96, \"M\", \"ზ\"),\n        (0x1C97, \"M\", \"თ\"),\n        (0x1C98, \"M\", \"ი\"),\n        (0x1C99, \"M\", \"კ\"),\n        (0x1C9A, \"M\", \"ლ\"),\n        (0x1C9B, \"M\", \"მ\"),\n        (0x1C9C, \"M\", \"ნ\"),\n        (0x1C9D, \"M\", \"ო\"),\n        (0x1C9E, \"M\", \"პ\"),\n        (0x1C9F, \"M\", \"ჟ\"),\n        (0x1CA0, \"M\", \"რ\"),\n        (0x1CA1, \"M\", \"ს\"),\n        (0x1CA2, \"M\", \"ტ\"),\n        (0x1CA3, \"M\", \"უ\"),\n        (0x1CA4, \"M\", \"ფ\"),\n        (0x1CA5, \"M\", \"ქ\"),\n        (0x1CA6, \"M\", \"ღ\"),\n        (0x1CA7, \"M\", \"ყ\"),\n        (0x1CA8, \"M\", \"შ\"),\n        (0x1CA9, \"M\", \"ჩ\"),\n        (0x1CAA, \"M\", \"ც\"),\n        (0x1CAB, \"M\", \"ძ\"),\n        (0x1CAC, \"M\", \"წ\"),\n        (0x1CAD, \"M\", \"ჭ\"),\n        (0x1CAE, \"M\", \"ხ\"),\n        (0x1CAF, \"M\", \"ჯ\"),\n        (0x1CB0, \"M\", \"ჰ\"),\n        (0x1CB1, \"M\", \"ჱ\"),\n        (0x1CB2, \"M\", \"ჲ\"),\n        (0x1CB3, \"M\", \"ჳ\"),\n        (0x1CB4, \"M\", \"ჴ\"),\n        (0x1CB5, \"M\", \"ჵ\"),\n        (0x1CB6, \"M\", \"ჶ\"),\n        (0x1CB7, \"M\", \"ჷ\"),\n        (0x1CB8, \"M\", \"ჸ\"),\n        (0x1CB9, \"M\", \"ჹ\"),\n        (0x1CBA, \"M\", \"ჺ\"),\n        (0x1CBB, \"X\"),\n        (0x1CBD, \"M\", \"ჽ\"),\n        (0x1CBE, \"M\", \"ჾ\"),\n        (0x1CBF, \"M\", \"ჿ\"),\n        (0x1CC0, \"V\"),\n        (0x1CC8, \"X\"),\n        (0x1CD0, \"V\"),\n        (0x1CFB, \"X\"),\n        (0x1D00, \"V\"),\n        (0x1D2C, \"M\", \"a\"),\n        (0x1D2D, \"M\", \"æ\"),\n        (0x1D2E, \"M\", \"b\"),\n        (0x1D2F, \"V\"),\n        (0x1D30, \"M\", \"d\"),\n        (0x1D31, \"M\", \"e\"),\n    ]\n\n\ndef _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D32, \"M\", \"ǝ\"),\n        (0x1D33, \"M\", \"g\"),\n        (0x1D34, \"M\", \"h\"),\n        (0x1D35, \"M\", \"i\"),\n        (0x1D36, \"M\", \"j\"),\n        (0x1D37, \"M\", \"k\"),\n        (0x1D38, \"M\", \"l\"),\n        (0x1D39, \"M\", \"m\"),\n        (0x1D3A, \"M\", \"n\"),\n        (0x1D3B, \"V\"),\n        (0x1D3C, \"M\", \"o\"),\n        (0x1D3D, \"M\", \"ȣ\"),\n        (0x1D3E, \"M\", \"p\"),\n        (0x1D3F, \"M\", \"r\"),\n        (0x1D40, \"M\", \"t\"),\n        (0x1D41, \"M\", \"u\"),\n        (0x1D42, \"M\", \"w\"),\n        (0x1D43, \"M\", \"a\"),\n        (0x1D44, \"M\", \"ɐ\"),\n        (0x1D45, \"M\", \"ɑ\"),\n        (0x1D46, \"M\", \"ᴂ\"),\n        (0x1D47, \"M\", \"b\"),\n        (0x1D48, \"M\", \"d\"),\n        (0x1D49, \"M\", \"e\"),\n        (0x1D4A, \"M\", \"ə\"),\n        (0x1D4B, \"M\", \"ɛ\"),\n        (0x1D4C, \"M\", \"ɜ\"),\n        (0x1D4D, \"M\", \"g\"),\n        (0x1D4E, \"V\"),\n        (0x1D4F, \"M\", \"k\"),\n        (0x1D50, \"M\", \"m\"),\n        (0x1D51, \"M\", \"ŋ\"),\n        (0x1D52, \"M\", \"o\"),\n        (0x1D53, \"M\", \"ɔ\"),\n        (0x1D54, \"M\", \"ᴖ\"),\n        (0x1D55, \"M\", \"ᴗ\"),\n        (0x1D56, \"M\", \"p\"),\n        (0x1D57, \"M\", \"t\"),\n        (0x1D58, \"M\", \"u\"),\n        (0x1D59, \"M\", \"ᴝ\"),\n        (0x1D5A, \"M\", \"ɯ\"),\n        (0x1D5B, \"M\", \"v\"),\n        (0x1D5C, \"M\", \"ᴥ\"),\n        (0x1D5D, \"M\", \"β\"),\n        (0x1D5E, \"M\", \"γ\"),\n        (0x1D5F, \"M\", \"δ\"),\n        (0x1D60, \"M\", \"φ\"),\n        (0x1D61, \"M\", \"χ\"),\n        (0x1D62, \"M\", \"i\"),\n        (0x1D63, \"M\", \"r\"),\n        (0x1D64, \"M\", \"u\"),\n        (0x1D65, \"M\", \"v\"),\n        (0x1D66, \"M\", \"β\"),\n        (0x1D67, \"M\", \"γ\"),\n        (0x1D68, \"M\", \"ρ\"),\n        (0x1D69, \"M\", \"φ\"),\n        (0x1D6A, \"M\", \"χ\"),\n        (0x1D6B, \"V\"),\n        (0x1D78, \"M\", \"н\"),\n        (0x1D79, \"V\"),\n        (0x1D9B, \"M\", \"ɒ\"),\n        (0x1D9C, \"M\", \"c\"),\n        (0x1D9D, \"M\", \"ɕ\"),\n        (0x1D9E, \"M\", \"ð\"),\n        (0x1D9F, \"M\", \"ɜ\"),\n        (0x1DA0, \"M\", \"f\"),\n        (0x1DA1, \"M\", \"ɟ\"),\n        (0x1DA2, \"M\", \"ɡ\"),\n        (0x1DA3, \"M\", \"ɥ\"),\n        (0x1DA4, \"M\", \"ɨ\"),\n        (0x1DA5, \"M\", \"ɩ\"),\n        (0x1DA6, \"M\", \"ɪ\"),\n        (0x1DA7, \"M\", \"ᵻ\"),\n        (0x1DA8, \"M\", \"ʝ\"),\n        (0x1DA9, \"M\", \"ɭ\"),\n        (0x1DAA, \"M\", \"ᶅ\"),\n        (0x1DAB, \"M\", \"ʟ\"),\n        (0x1DAC, \"M\", \"ɱ\"),\n        (0x1DAD, \"M\", \"ɰ\"),\n        (0x1DAE, \"M\", \"ɲ\"),\n        (0x1DAF, \"M\", \"ɳ\"),\n        (0x1DB0, \"M\", \"ɴ\"),\n        (0x1DB1, \"M\", \"ɵ\"),\n        (0x1DB2, \"M\", \"ɸ\"),\n        (0x1DB3, \"M\", \"ʂ\"),\n        (0x1DB4, \"M\", \"ʃ\"),\n        (0x1DB5, \"M\", \"ƫ\"),\n        (0x1DB6, \"M\", \"ʉ\"),\n        (0x1DB7, \"M\", \"ʊ\"),\n        (0x1DB8, \"M\", \"ᴜ\"),\n        (0x1DB9, \"M\", \"ʋ\"),\n        (0x1DBA, \"M\", \"ʌ\"),\n        (0x1DBB, \"M\", \"z\"),\n        (0x1DBC, \"M\", \"ʐ\"),\n        (0x1DBD, \"M\", \"ʑ\"),\n        (0x1DBE, \"M\", \"ʒ\"),\n        (0x1DBF, \"M\", \"θ\"),\n        (0x1DC0, \"V\"),\n        (0x1E00, \"M\", \"ḁ\"),\n        (0x1E01, \"V\"),\n    ]\n\n\ndef _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1E02, \"M\", \"ḃ\"),\n        (0x1E03, \"V\"),\n        (0x1E04, \"M\", \"ḅ\"),\n        (0x1E05, \"V\"),\n        (0x1E06, \"M\", \"ḇ\"),\n        (0x1E07, \"V\"),\n        (0x1E08, \"M\", \"ḉ\"),\n        (0x1E09, \"V\"),\n        (0x1E0A, \"M\", \"ḋ\"),\n        (0x1E0B, \"V\"),\n        (0x1E0C, \"M\", \"ḍ\"),\n        (0x1E0D, \"V\"),\n        (0x1E0E, \"M\", \"ḏ\"),\n        (0x1E0F, \"V\"),\n        (0x1E10, \"M\", \"ḑ\"),\n        (0x1E11, \"V\"),\n        (0x1E12, \"M\", \"ḓ\"),\n        (0x1E13, \"V\"),\n        (0x1E14, \"M\", \"ḕ\"),\n        (0x1E15, \"V\"),\n        (0x1E16, \"M\", \"ḗ\"),\n        (0x1E17, \"V\"),\n        (0x1E18, \"M\", \"ḙ\"),\n        (0x1E19, \"V\"),\n        (0x1E1A, \"M\", \"ḛ\"),\n        (0x1E1B, \"V\"),\n        (0x1E1C, \"M\", \"ḝ\"),\n        (0x1E1D, \"V\"),\n        (0x1E1E, \"M\", \"ḟ\"),\n        (0x1E1F, \"V\"),\n        (0x1E20, \"M\", \"ḡ\"),\n        (0x1E21, \"V\"),\n        (0x1E22, \"M\", \"ḣ\"),\n        (0x1E23, \"V\"),\n        (0x1E24, \"M\", \"ḥ\"),\n        (0x1E25, \"V\"),\n        (0x1E26, \"M\", \"ḧ\"),\n        (0x1E27, \"V\"),\n        (0x1E28, \"M\", \"ḩ\"),\n        (0x1E29, \"V\"),\n        (0x1E2A, \"M\", \"ḫ\"),\n        (0x1E2B, \"V\"),\n        (0x1E2C, \"M\", \"ḭ\"),\n        (0x1E2D, \"V\"),\n        (0x1E2E, \"M\", \"ḯ\"),\n        (0x1E2F, \"V\"),\n        (0x1E30, \"M\", \"ḱ\"),\n        (0x1E31, \"V\"),\n        (0x1E32, \"M\", \"ḳ\"),\n        (0x1E33, \"V\"),\n        (0x1E34, \"M\", \"ḵ\"),\n        (0x1E35, \"V\"),\n        (0x1E36, \"M\", \"ḷ\"),\n        (0x1E37, \"V\"),\n        (0x1E38, \"M\", \"ḹ\"),\n        (0x1E39, \"V\"),\n        (0x1E3A, \"M\", \"ḻ\"),\n        (0x1E3B, \"V\"),\n        (0x1E3C, \"M\", \"ḽ\"),\n        (0x1E3D, \"V\"),\n        (0x1E3E, \"M\", \"ḿ\"),\n        (0x1E3F, \"V\"),\n        (0x1E40, \"M\", \"ṁ\"),\n        (0x1E41, \"V\"),\n        (0x1E42, \"M\", \"ṃ\"),\n        (0x1E43, \"V\"),\n        (0x1E44, \"M\", \"ṅ\"),\n        (0x1E45, \"V\"),\n        (0x1E46, \"M\", \"ṇ\"),\n        (0x1E47, \"V\"),\n        (0x1E48, \"M\", \"ṉ\"),\n        (0x1E49, \"V\"),\n        (0x1E4A, \"M\", \"ṋ\"),\n        (0x1E4B, \"V\"),\n        (0x1E4C, \"M\", \"ṍ\"),\n        (0x1E4D, \"V\"),\n        (0x1E4E, \"M\", \"ṏ\"),\n        (0x1E4F, \"V\"),\n        (0x1E50, \"M\", \"ṑ\"),\n        (0x1E51, \"V\"),\n        (0x1E52, \"M\", \"ṓ\"),\n        (0x1E53, \"V\"),\n        (0x1E54, \"M\", \"ṕ\"),\n        (0x1E55, \"V\"),\n        (0x1E56, \"M\", \"ṗ\"),\n        (0x1E57, \"V\"),\n        (0x1E58, \"M\", \"ṙ\"),\n        (0x1E59, \"V\"),\n        (0x1E5A, \"M\", \"ṛ\"),\n        (0x1E5B, \"V\"),\n        (0x1E5C, \"M\", \"ṝ\"),\n        (0x1E5D, \"V\"),\n        (0x1E5E, \"M\", \"ṟ\"),\n        (0x1E5F, \"V\"),\n        (0x1E60, \"M\", \"ṡ\"),\n        (0x1E61, \"V\"),\n        (0x1E62, \"M\", \"ṣ\"),\n        (0x1E63, \"V\"),\n        (0x1E64, \"M\", \"ṥ\"),\n        (0x1E65, \"V\"),\n    ]\n\n\ndef _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1E66, \"M\", \"ṧ\"),\n        (0x1E67, \"V\"),\n        (0x1E68, \"M\", \"ṩ\"),\n        (0x1E69, \"V\"),\n        (0x1E6A, \"M\", \"ṫ\"),\n        (0x1E6B, \"V\"),\n        (0x1E6C, \"M\", \"ṭ\"),\n        (0x1E6D, \"V\"),\n        (0x1E6E, \"M\", \"ṯ\"),\n        (0x1E6F, \"V\"),\n        (0x1E70, \"M\", \"ṱ\"),\n        (0x1E71, \"V\"),\n        (0x1E72, \"M\", \"ṳ\"),\n        (0x1E73, \"V\"),\n        (0x1E74, \"M\", \"ṵ\"),\n        (0x1E75, \"V\"),\n        (0x1E76, \"M\", \"ṷ\"),\n        (0x1E77, \"V\"),\n        (0x1E78, \"M\", \"ṹ\"),\n        (0x1E79, \"V\"),\n        (0x1E7A, \"M\", \"ṻ\"),\n        (0x1E7B, \"V\"),\n        (0x1E7C, \"M\", \"ṽ\"),\n        (0x1E7D, \"V\"),\n        (0x1E7E, \"M\", \"ṿ\"),\n        (0x1E7F, \"V\"),\n        (0x1E80, \"M\", \"ẁ\"),\n        (0x1E81, \"V\"),\n        (0x1E82, \"M\", \"ẃ\"),\n        (0x1E83, \"V\"),\n        (0x1E84, \"M\", \"ẅ\"),\n        (0x1E85, \"V\"),\n        (0x1E86, \"M\", \"ẇ\"),\n        (0x1E87, \"V\"),\n        (0x1E88, \"M\", \"ẉ\"),\n        (0x1E89, \"V\"),\n        (0x1E8A, \"M\", \"ẋ\"),\n        (0x1E8B, \"V\"),\n        (0x1E8C, \"M\", \"ẍ\"),\n        (0x1E8D, \"V\"),\n        (0x1E8E, \"M\", \"ẏ\"),\n        (0x1E8F, \"V\"),\n        (0x1E90, \"M\", \"ẑ\"),\n        (0x1E91, \"V\"),\n        (0x1E92, \"M\", \"ẓ\"),\n        (0x1E93, \"V\"),\n        (0x1E94, \"M\", \"ẕ\"),\n        (0x1E95, \"V\"),\n        (0x1E9A, \"M\", \"aʾ\"),\n        (0x1E9B, \"M\", \"ṡ\"),\n        (0x1E9C, \"V\"),\n        (0x1E9E, \"M\", \"ß\"),\n        (0x1E9F, \"V\"),\n        (0x1EA0, \"M\", \"ạ\"),\n        (0x1EA1, \"V\"),\n        (0x1EA2, \"M\", \"ả\"),\n        (0x1EA3, \"V\"),\n        (0x1EA4, \"M\", \"ấ\"),\n        (0x1EA5, \"V\"),\n        (0x1EA6, \"M\", \"ầ\"),\n        (0x1EA7, \"V\"),\n        (0x1EA8, \"M\", \"ẩ\"),\n        (0x1EA9, \"V\"),\n        (0x1EAA, \"M\", \"ẫ\"),\n        (0x1EAB, \"V\"),\n        (0x1EAC, \"M\", \"ậ\"),\n        (0x1EAD, \"V\"),\n        (0x1EAE, \"M\", \"ắ\"),\n        (0x1EAF, \"V\"),\n        (0x1EB0, \"M\", \"ằ\"),\n        (0x1EB1, \"V\"),\n        (0x1EB2, \"M\", \"ẳ\"),\n        (0x1EB3, \"V\"),\n        (0x1EB4, \"M\", \"ẵ\"),\n        (0x1EB5, \"V\"),\n        (0x1EB6, \"M\", \"ặ\"),\n        (0x1EB7, \"V\"),\n        (0x1EB8, \"M\", \"ẹ\"),\n        (0x1EB9, \"V\"),\n        (0x1EBA, \"M\", \"ẻ\"),\n        (0x1EBB, \"V\"),\n        (0x1EBC, \"M\", \"ẽ\"),\n        (0x1EBD, \"V\"),\n        (0x1EBE, \"M\", \"ế\"),\n        (0x1EBF, \"V\"),\n        (0x1EC0, \"M\", \"ề\"),\n        (0x1EC1, \"V\"),\n        (0x1EC2, \"M\", \"ể\"),\n        (0x1EC3, \"V\"),\n        (0x1EC4, \"M\", \"ễ\"),\n        (0x1EC5, \"V\"),\n        (0x1EC6, \"M\", \"ệ\"),\n        (0x1EC7, \"V\"),\n        (0x1EC8, \"M\", \"ỉ\"),\n        (0x1EC9, \"V\"),\n        (0x1ECA, \"M\", \"ị\"),\n        (0x1ECB, \"V\"),\n        (0x1ECC, \"M\", \"ọ\"),\n        (0x1ECD, \"V\"),\n        (0x1ECE, \"M\", \"ỏ\"),\n    ]\n\n\ndef _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1ECF, \"V\"),\n        (0x1ED0, \"M\", \"ố\"),\n        (0x1ED1, \"V\"),\n        (0x1ED2, \"M\", \"ồ\"),\n        (0x1ED3, \"V\"),\n        (0x1ED4, \"M\", \"ổ\"),\n        (0x1ED5, \"V\"),\n        (0x1ED6, \"M\", \"ỗ\"),\n        (0x1ED7, \"V\"),\n        (0x1ED8, \"M\", \"ộ\"),\n        (0x1ED9, \"V\"),\n        (0x1EDA, \"M\", \"ớ\"),\n        (0x1EDB, \"V\"),\n        (0x1EDC, \"M\", \"ờ\"),\n        (0x1EDD, \"V\"),\n        (0x1EDE, \"M\", \"ở\"),\n        (0x1EDF, \"V\"),\n        (0x1EE0, \"M\", \"ỡ\"),\n        (0x1EE1, \"V\"),\n        (0x1EE2, \"M\", \"ợ\"),\n        (0x1EE3, \"V\"),\n        (0x1EE4, \"M\", \"ụ\"),\n        (0x1EE5, \"V\"),\n        (0x1EE6, \"M\", \"ủ\"),\n        (0x1EE7, \"V\"),\n        (0x1EE8, \"M\", \"ứ\"),\n        (0x1EE9, \"V\"),\n        (0x1EEA, \"M\", \"ừ\"),\n        (0x1EEB, \"V\"),\n        (0x1EEC, \"M\", \"ử\"),\n        (0x1EED, \"V\"),\n        (0x1EEE, \"M\", \"ữ\"),\n        (0x1EEF, \"V\"),\n        (0x1EF0, \"M\", \"ự\"),\n        (0x1EF1, \"V\"),\n        (0x1EF2, \"M\", \"ỳ\"),\n        (0x1EF3, \"V\"),\n        (0x1EF4, \"M\", \"ỵ\"),\n        (0x1EF5, \"V\"),\n        (0x1EF6, \"M\", \"ỷ\"),\n        (0x1EF7, \"V\"),\n        (0x1EF8, \"M\", \"ỹ\"),\n        (0x1EF9, \"V\"),\n        (0x1EFA, \"M\", \"ỻ\"),\n        (0x1EFB, \"V\"),\n        (0x1EFC, \"M\", \"ỽ\"),\n        (0x1EFD, \"V\"),\n        (0x1EFE, \"M\", \"ỿ\"),\n        (0x1EFF, \"V\"),\n        (0x1F08, \"M\", \"ἀ\"),\n        (0x1F09, \"M\", \"ἁ\"),\n        (0x1F0A, \"M\", \"ἂ\"),\n        (0x1F0B, \"M\", \"ἃ\"),\n        (0x1F0C, \"M\", \"ἄ\"),\n        (0x1F0D, \"M\", \"ἅ\"),\n        (0x1F0E, \"M\", \"ἆ\"),\n        (0x1F0F, \"M\", \"ἇ\"),\n        (0x1F10, \"V\"),\n        (0x1F16, \"X\"),\n        (0x1F18, \"M\", \"ἐ\"),\n        (0x1F19, \"M\", \"ἑ\"),\n        (0x1F1A, \"M\", \"ἒ\"),\n        (0x1F1B, \"M\", \"ἓ\"),\n        (0x1F1C, \"M\", \"ἔ\"),\n        (0x1F1D, \"M\", \"ἕ\"),\n        (0x1F1E, \"X\"),\n        (0x1F20, \"V\"),\n        (0x1F28, \"M\", \"ἠ\"),\n        (0x1F29, \"M\", \"ἡ\"),\n        (0x1F2A, \"M\", \"ἢ\"),\n        (0x1F2B, \"M\", \"ἣ\"),\n        (0x1F2C, \"M\", \"ἤ\"),\n        (0x1F2D, \"M\", \"ἥ\"),\n        (0x1F2E, \"M\", \"ἦ\"),\n        (0x1F2F, \"M\", \"ἧ\"),\n        (0x1F30, \"V\"),\n        (0x1F38, \"M\", \"ἰ\"),\n        (0x1F39, \"M\", \"ἱ\"),\n        (0x1F3A, \"M\", \"ἲ\"),\n        (0x1F3B, \"M\", \"ἳ\"),\n        (0x1F3C, \"M\", \"ἴ\"),\n        (0x1F3D, \"M\", \"ἵ\"),\n        (0x1F3E, \"M\", \"ἶ\"),\n        (0x1F3F, \"M\", \"ἷ\"),\n        (0x1F40, \"V\"),\n        (0x1F46, \"X\"),\n        (0x1F48, \"M\", \"ὀ\"),\n        (0x1F49, \"M\", \"ὁ\"),\n        (0x1F4A, \"M\", \"ὂ\"),\n        (0x1F4B, \"M\", \"ὃ\"),\n        (0x1F4C, \"M\", \"ὄ\"),\n        (0x1F4D, \"M\", \"ὅ\"),\n        (0x1F4E, \"X\"),\n        (0x1F50, \"V\"),\n        (0x1F58, \"X\"),\n        (0x1F59, \"M\", \"ὑ\"),\n        (0x1F5A, \"X\"),\n        (0x1F5B, \"M\", \"ὓ\"),\n        (0x1F5C, \"X\"),\n        (0x1F5D, \"M\", \"ὕ\"),\n    ]\n\n\ndef _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1F5E, \"X\"),\n        (0x1F5F, \"M\", \"ὗ\"),\n        (0x1F60, \"V\"),\n        (0x1F68, \"M\", \"ὠ\"),\n        (0x1F69, \"M\", \"ὡ\"),\n        (0x1F6A, \"M\", \"ὢ\"),\n        (0x1F6B, \"M\", \"ὣ\"),\n        (0x1F6C, \"M\", \"ὤ\"),\n        (0x1F6D, \"M\", \"ὥ\"),\n        (0x1F6E, \"M\", \"ὦ\"),\n        (0x1F6F, \"M\", \"ὧ\"),\n        (0x1F70, \"V\"),\n        (0x1F71, \"M\", \"ά\"),\n        (0x1F72, \"V\"),\n        (0x1F73, \"M\", \"έ\"),\n        (0x1F74, \"V\"),\n        (0x1F75, \"M\", \"ή\"),\n        (0x1F76, \"V\"),\n        (0x1F77, \"M\", \"ί\"),\n        (0x1F78, \"V\"),\n        (0x1F79, \"M\", \"ό\"),\n        (0x1F7A, \"V\"),\n        (0x1F7B, \"M\", \"ύ\"),\n        (0x1F7C, \"V\"),\n        (0x1F7D, \"M\", \"ώ\"),\n        (0x1F7E, \"X\"),\n        (0x1F80, \"M\", \"ἀι\"),\n        (0x1F81, \"M\", \"ἁι\"),\n        (0x1F82, \"M\", \"ἂι\"),\n        (0x1F83, \"M\", \"ἃι\"),\n        (0x1F84, \"M\", \"ἄι\"),\n        (0x1F85, \"M\", \"ἅι\"),\n        (0x1F86, \"M\", \"ἆι\"),\n        (0x1F87, \"M\", \"ἇι\"),\n        (0x1F88, \"M\", \"ἀι\"),\n        (0x1F89, \"M\", \"ἁι\"),\n        (0x1F8A, \"M\", \"ἂι\"),\n        (0x1F8B, \"M\", \"ἃι\"),\n        (0x1F8C, \"M\", \"ἄι\"),\n        (0x1F8D, \"M\", \"ἅι\"),\n        (0x1F8E, \"M\", \"ἆι\"),\n        (0x1F8F, \"M\", \"ἇι\"),\n        (0x1F90, \"M\", \"ἠι\"),\n        (0x1F91, \"M\", \"ἡι\"),\n        (0x1F92, \"M\", \"ἢι\"),\n        (0x1F93, \"M\", \"ἣι\"),\n        (0x1F94, \"M\", \"ἤι\"),\n        (0x1F95, \"M\", \"ἥι\"),\n        (0x1F96, \"M\", \"ἦι\"),\n        (0x1F97, \"M\", \"ἧι\"),\n        (0x1F98, \"M\", \"ἠι\"),\n        (0x1F99, \"M\", \"ἡι\"),\n        (0x1F9A, \"M\", \"ἢι\"),\n        (0x1F9B, \"M\", \"ἣι\"),\n        (0x1F9C, \"M\", \"ἤι\"),\n        (0x1F9D, \"M\", \"ἥι\"),\n        (0x1F9E, \"M\", \"ἦι\"),\n        (0x1F9F, \"M\", \"ἧι\"),\n        (0x1FA0, \"M\", \"ὠι\"),\n        (0x1FA1, \"M\", \"ὡι\"),\n        (0x1FA2, \"M\", \"ὢι\"),\n        (0x1FA3, \"M\", \"ὣι\"),\n        (0x1FA4, \"M\", \"ὤι\"),\n        (0x1FA5, \"M\", \"ὥι\"),\n        (0x1FA6, \"M\", \"ὦι\"),\n        (0x1FA7, \"M\", \"ὧι\"),\n        (0x1FA8, \"M\", \"ὠι\"),\n        (0x1FA9, \"M\", \"ὡι\"),\n        (0x1FAA, \"M\", \"ὢι\"),\n        (0x1FAB, \"M\", \"ὣι\"),\n        (0x1FAC, \"M\", \"ὤι\"),\n        (0x1FAD, \"M\", \"ὥι\"),\n        (0x1FAE, \"M\", \"ὦι\"),\n        (0x1FAF, \"M\", \"ὧι\"),\n        (0x1FB0, \"V\"),\n        (0x1FB2, \"M\", \"ὰι\"),\n        (0x1FB3, \"M\", \"αι\"),\n        (0x1FB4, \"M\", \"άι\"),\n        (0x1FB5, \"X\"),\n        (0x1FB6, \"V\"),\n        (0x1FB7, \"M\", \"ᾶι\"),\n        (0x1FB8, \"M\", \"ᾰ\"),\n        (0x1FB9, \"M\", \"ᾱ\"),\n        (0x1FBA, \"M\", \"ὰ\"),\n        (0x1FBB, \"M\", \"ά\"),\n        (0x1FBC, \"M\", \"αι\"),\n        (0x1FBD, \"M\", \" ̓\"),\n        (0x1FBE, \"M\", \"ι\"),\n        (0x1FBF, \"M\", \" ̓\"),\n        (0x1FC0, \"M\", \" ͂\"),\n        (0x1FC1, \"M\", \" ̈͂\"),\n        (0x1FC2, \"M\", \"ὴι\"),\n        (0x1FC3, \"M\", \"ηι\"),\n        (0x1FC4, \"M\", \"ήι\"),\n        (0x1FC5, \"X\"),\n        (0x1FC6, \"V\"),\n        (0x1FC7, \"M\", \"ῆι\"),\n        (0x1FC8, \"M\", \"ὲ\"),\n        (0x1FC9, \"M\", \"έ\"),\n        (0x1FCA, \"M\", \"ὴ\"),\n    ]\n\n\ndef _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1FCB, \"M\", \"ή\"),\n        (0x1FCC, \"M\", \"ηι\"),\n        (0x1FCD, \"M\", \" ̓̀\"),\n        (0x1FCE, \"M\", \" ̓́\"),\n        (0x1FCF, \"M\", \" ̓͂\"),\n        (0x1FD0, \"V\"),\n        (0x1FD3, \"M\", \"ΐ\"),\n        (0x1FD4, \"X\"),\n        (0x1FD6, \"V\"),\n        (0x1FD8, \"M\", \"ῐ\"),\n        (0x1FD9, \"M\", \"ῑ\"),\n        (0x1FDA, \"M\", \"ὶ\"),\n        (0x1FDB, \"M\", \"ί\"),\n        (0x1FDC, \"X\"),\n        (0x1FDD, \"M\", \" ̔̀\"),\n        (0x1FDE, \"M\", \" ̔́\"),\n        (0x1FDF, \"M\", \" ̔͂\"),\n        (0x1FE0, \"V\"),\n        (0x1FE3, \"M\", \"ΰ\"),\n        (0x1FE4, \"V\"),\n        (0x1FE8, \"M\", \"ῠ\"),\n        (0x1FE9, \"M\", \"ῡ\"),\n        (0x1FEA, \"M\", \"ὺ\"),\n        (0x1FEB, \"M\", \"ύ\"),\n        (0x1FEC, \"M\", \"ῥ\"),\n        (0x1FED, \"M\", \" ̈̀\"),\n        (0x1FEE, \"M\", \" ̈́\"),\n        (0x1FEF, \"M\", \"`\"),\n        (0x1FF0, \"X\"),\n        (0x1FF2, \"M\", \"ὼι\"),\n        (0x1FF3, \"M\", \"ωι\"),\n        (0x1FF4, \"M\", \"ώι\"),\n        (0x1FF5, \"X\"),\n        (0x1FF6, \"V\"),\n        (0x1FF7, \"M\", \"ῶι\"),\n        (0x1FF8, \"M\", \"ὸ\"),\n        (0x1FF9, \"M\", \"ό\"),\n        (0x1FFA, \"M\", \"ὼ\"),\n        (0x1FFB, \"M\", \"ώ\"),\n        (0x1FFC, \"M\", \"ωι\"),\n        (0x1FFD, \"M\", \" ́\"),\n        (0x1FFE, \"M\", \" ̔\"),\n        (0x1FFF, \"X\"),\n        (0x2000, \"M\", \" \"),\n        (0x200B, \"I\"),\n        (0x200C, \"D\", \"\"),\n        (0x200E, \"X\"),\n        (0x2010, \"V\"),\n        (0x2011, \"M\", \"‐\"),\n        (0x2012, \"V\"),\n        (0x2017, \"M\", \" ̳\"),\n        (0x2018, \"V\"),\n        (0x2024, \"X\"),\n        (0x2027, \"V\"),\n        (0x2028, \"X\"),\n        (0x202F, \"M\", \" \"),\n        (0x2030, \"V\"),\n        (0x2033, \"M\", \"′′\"),\n        (0x2034, \"M\", \"′′′\"),\n        (0x2035, \"V\"),\n        (0x2036, \"M\", \"‵‵\"),\n        (0x2037, \"M\", \"‵‵‵\"),\n        (0x2038, \"V\"),\n        (0x203C, \"M\", \"!!\"),\n        (0x203D, \"V\"),\n        (0x203E, \"M\", \" ̅\"),\n        (0x203F, \"V\"),\n        (0x2047, \"M\", \"??\"),\n        (0x2048, \"M\", \"?!\"),\n        (0x2049, \"M\", \"!?\"),\n        (0x204A, \"V\"),\n        (0x2057, \"M\", \"′′′′\"),\n        (0x2058, \"V\"),\n        (0x205F, \"M\", \" \"),\n        (0x2060, \"I\"),\n        (0x2065, \"X\"),\n        (0x206A, \"I\"),\n        (0x2070, \"M\", \"0\"),\n        (0x2071, \"M\", \"i\"),\n        (0x2072, \"X\"),\n        (0x2074, \"M\", \"4\"),\n        (0x2075, \"M\", \"5\"),\n        (0x2076, \"M\", \"6\"),\n        (0x2077, \"M\", \"7\"),\n        (0x2078, \"M\", \"8\"),\n        (0x2079, \"M\", \"9\"),\n        (0x207A, \"M\", \"+\"),\n        (0x207B, \"M\", \"−\"),\n        (0x207C, \"M\", \"=\"),\n        (0x207D, \"M\", \"(\"),\n        (0x207E, \"M\", \")\"),\n        (0x207F, \"M\", \"n\"),\n        (0x2080, \"M\", \"0\"),\n        (0x2081, \"M\", \"1\"),\n        (0x2082, \"M\", \"2\"),\n        (0x2083, \"M\", \"3\"),\n        (0x2084, \"M\", \"4\"),\n        (0x2085, \"M\", \"5\"),\n        (0x2086, \"M\", \"6\"),\n        (0x2087, \"M\", \"7\"),\n    ]\n\n\ndef _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2088, \"M\", \"8\"),\n        (0x2089, \"M\", \"9\"),\n        (0x208A, \"M\", \"+\"),\n        (0x208B, \"M\", \"−\"),\n        (0x208C, \"M\", \"=\"),\n        (0x208D, \"M\", \"(\"),\n        (0x208E, \"M\", \")\"),\n        (0x208F, \"X\"),\n        (0x2090, \"M\", \"a\"),\n        (0x2091, \"M\", \"e\"),\n        (0x2092, \"M\", \"o\"),\n        (0x2093, \"M\", \"x\"),\n        (0x2094, \"M\", \"ə\"),\n        (0x2095, \"M\", \"h\"),\n        (0x2096, \"M\", \"k\"),\n        (0x2097, \"M\", \"l\"),\n        (0x2098, \"M\", \"m\"),\n        (0x2099, \"M\", \"n\"),\n        (0x209A, \"M\", \"p\"),\n        (0x209B, \"M\", \"s\"),\n        (0x209C, \"M\", \"t\"),\n        (0x209D, \"X\"),\n        (0x20A0, \"V\"),\n        (0x20A8, \"M\", \"rs\"),\n        (0x20A9, \"V\"),\n        (0x20C1, \"X\"),\n        (0x20D0, \"V\"),\n        (0x20F1, \"X\"),\n        (0x2100, \"M\", \"a/c\"),\n        (0x2101, \"M\", \"a/s\"),\n        (0x2102, \"M\", \"c\"),\n        (0x2103, \"M\", \"°c\"),\n        (0x2104, \"V\"),\n        (0x2105, \"M\", \"c/o\"),\n        (0x2106, \"M\", \"c/u\"),\n        (0x2107, \"M\", \"ɛ\"),\n        (0x2108, \"V\"),\n        (0x2109, \"M\", \"°f\"),\n        (0x210A, \"M\", \"g\"),\n        (0x210B, \"M\", \"h\"),\n        (0x210F, \"M\", \"ħ\"),\n        (0x2110, \"M\", \"i\"),\n        (0x2112, \"M\", \"l\"),\n        (0x2114, \"V\"),\n        (0x2115, \"M\", \"n\"),\n        (0x2116, \"M\", \"no\"),\n        (0x2117, \"V\"),\n        (0x2119, \"M\", \"p\"),\n        (0x211A, \"M\", \"q\"),\n        (0x211B, \"M\", \"r\"),\n        (0x211E, \"V\"),\n        (0x2120, \"M\", \"sm\"),\n        (0x2121, \"M\", \"tel\"),\n        (0x2122, \"M\", \"tm\"),\n        (0x2123, \"V\"),\n        (0x2124, \"M\", \"z\"),\n        (0x2125, \"V\"),\n        (0x2126, \"M\", \"ω\"),\n        (0x2127, \"V\"),\n        (0x2128, \"M\", \"z\"),\n        (0x2129, \"V\"),\n        (0x212A, \"M\", \"k\"),\n        (0x212B, \"M\", \"å\"),\n        (0x212C, \"M\", \"b\"),\n        (0x212D, \"M\", \"c\"),\n        (0x212E, \"V\"),\n        (0x212F, \"M\", \"e\"),\n        (0x2131, \"M\", \"f\"),\n        (0x2132, \"M\", \"ⅎ\"),\n        (0x2133, \"M\", \"m\"),\n        (0x2134, \"M\", \"o\"),\n        (0x2135, \"M\", \"א\"),\n        (0x2136, \"M\", \"ב\"),\n        (0x2137, \"M\", \"ג\"),\n        (0x2138, \"M\", \"ד\"),\n        (0x2139, \"M\", \"i\"),\n        (0x213A, \"V\"),\n        (0x213B, \"M\", \"fax\"),\n        (0x213C, \"M\", \"π\"),\n        (0x213D, \"M\", \"γ\"),\n        (0x213F, \"M\", \"π\"),\n        (0x2140, \"M\", \"∑\"),\n        (0x2141, \"V\"),\n        (0x2145, \"M\", \"d\"),\n        (0x2147, \"M\", \"e\"),\n        (0x2148, \"M\", \"i\"),\n        (0x2149, \"M\", \"j\"),\n        (0x214A, \"V\"),\n        (0x2150, \"M\", \"1⁄7\"),\n        (0x2151, \"M\", \"1⁄9\"),\n        (0x2152, \"M\", \"1⁄10\"),\n        (0x2153, \"M\", \"1⁄3\"),\n        (0x2154, \"M\", \"2⁄3\"),\n        (0x2155, \"M\", \"1⁄5\"),\n        (0x2156, \"M\", \"2⁄5\"),\n        (0x2157, \"M\", \"3⁄5\"),\n        (0x2158, \"M\", \"4⁄5\"),\n        (0x2159, \"M\", \"1⁄6\"),\n        (0x215A, \"M\", \"5⁄6\"),\n        (0x215B, \"M\", \"1⁄8\"),\n    ]\n\n\ndef _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x215C, \"M\", \"3⁄8\"),\n        (0x215D, \"M\", \"5⁄8\"),\n        (0x215E, \"M\", \"7⁄8\"),\n        (0x215F, \"M\", \"1⁄\"),\n        (0x2160, \"M\", \"i\"),\n        (0x2161, \"M\", \"ii\"),\n        (0x2162, \"M\", \"iii\"),\n        (0x2163, \"M\", \"iv\"),\n        (0x2164, \"M\", \"v\"),\n        (0x2165, \"M\", \"vi\"),\n        (0x2166, \"M\", \"vii\"),\n        (0x2167, \"M\", \"viii\"),\n        (0x2168, \"M\", \"ix\"),\n        (0x2169, \"M\", \"x\"),\n        (0x216A, \"M\", \"xi\"),\n        (0x216B, \"M\", \"xii\"),\n        (0x216C, \"M\", \"l\"),\n        (0x216D, \"M\", \"c\"),\n        (0x216E, \"M\", \"d\"),\n        (0x216F, \"M\", \"m\"),\n        (0x2170, \"M\", \"i\"),\n        (0x2171, \"M\", \"ii\"),\n        (0x2172, \"M\", \"iii\"),\n        (0x2173, \"M\", \"iv\"),\n        (0x2174, \"M\", \"v\"),\n        (0x2175, \"M\", \"vi\"),\n        (0x2176, \"M\", \"vii\"),\n        (0x2177, \"M\", \"viii\"),\n        (0x2178, \"M\", \"ix\"),\n        (0x2179, \"M\", \"x\"),\n        (0x217A, \"M\", \"xi\"),\n        (0x217B, \"M\", \"xii\"),\n        (0x217C, \"M\", \"l\"),\n        (0x217D, \"M\", \"c\"),\n        (0x217E, \"M\", \"d\"),\n        (0x217F, \"M\", \"m\"),\n        (0x2180, \"V\"),\n        (0x2183, \"M\", \"ↄ\"),\n        (0x2184, \"V\"),\n        (0x2189, \"M\", \"0⁄3\"),\n        (0x218A, \"V\"),\n        (0x218C, \"X\"),\n        (0x2190, \"V\"),\n        (0x222C, \"M\", \"∫∫\"),\n        (0x222D, \"M\", \"∫∫∫\"),\n        (0x222E, \"V\"),\n        (0x222F, \"M\", \"∮∮\"),\n        (0x2230, \"M\", \"∮∮∮\"),\n        (0x2231, \"V\"),\n        (0x2329, \"M\", \"〈\"),\n        (0x232A, \"M\", \"〉\"),\n        (0x232B, \"V\"),\n        (0x242A, \"X\"),\n        (0x2440, \"V\"),\n        (0x244B, \"X\"),\n        (0x2460, \"M\", \"1\"),\n        (0x2461, \"M\", \"2\"),\n        (0x2462, \"M\", \"3\"),\n        (0x2463, \"M\", \"4\"),\n        (0x2464, \"M\", \"5\"),\n        (0x2465, \"M\", \"6\"),\n        (0x2466, \"M\", \"7\"),\n        (0x2467, \"M\", \"8\"),\n        (0x2468, \"M\", \"9\"),\n        (0x2469, \"M\", \"10\"),\n        (0x246A, \"M\", \"11\"),\n        (0x246B, \"M\", \"12\"),\n        (0x246C, \"M\", \"13\"),\n        (0x246D, \"M\", \"14\"),\n        (0x246E, \"M\", \"15\"),\n        (0x246F, \"M\", \"16\"),\n        (0x2470, \"M\", \"17\"),\n        (0x2471, \"M\", \"18\"),\n        (0x2472, \"M\", \"19\"),\n        (0x2473, \"M\", \"20\"),\n        (0x2474, \"M\", \"(1)\"),\n        (0x2475, \"M\", \"(2)\"),\n        (0x2476, \"M\", \"(3)\"),\n        (0x2477, \"M\", \"(4)\"),\n        (0x2478, \"M\", \"(5)\"),\n        (0x2479, \"M\", \"(6)\"),\n        (0x247A, \"M\", \"(7)\"),\n        (0x247B, \"M\", \"(8)\"),\n        (0x247C, \"M\", \"(9)\"),\n        (0x247D, \"M\", \"(10)\"),\n        (0x247E, \"M\", \"(11)\"),\n        (0x247F, \"M\", \"(12)\"),\n        (0x2480, \"M\", \"(13)\"),\n        (0x2481, \"M\", \"(14)\"),\n        (0x2482, \"M\", \"(15)\"),\n        (0x2483, \"M\", \"(16)\"),\n        (0x2484, \"M\", \"(17)\"),\n        (0x2485, \"M\", \"(18)\"),\n        (0x2486, \"M\", \"(19)\"),\n        (0x2487, \"M\", \"(20)\"),\n        (0x2488, \"X\"),\n        (0x249C, \"M\", \"(a)\"),\n        (0x249D, \"M\", \"(b)\"),\n        (0x249E, \"M\", \"(c)\"),\n        (0x249F, \"M\", \"(d)\"),\n    ]\n\n\ndef _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x24A0, \"M\", \"(e)\"),\n        (0x24A1, \"M\", \"(f)\"),\n        (0x24A2, \"M\", \"(g)\"),\n        (0x24A3, \"M\", \"(h)\"),\n        (0x24A4, \"M\", \"(i)\"),\n        (0x24A5, \"M\", \"(j)\"),\n        (0x24A6, \"M\", \"(k)\"),\n        (0x24A7, \"M\", \"(l)\"),\n        (0x24A8, \"M\", \"(m)\"),\n        (0x24A9, \"M\", \"(n)\"),\n        (0x24AA, \"M\", \"(o)\"),\n        (0x24AB, \"M\", \"(p)\"),\n        (0x24AC, \"M\", \"(q)\"),\n        (0x24AD, \"M\", \"(r)\"),\n        (0x24AE, \"M\", \"(s)\"),\n        (0x24AF, \"M\", \"(t)\"),\n        (0x24B0, \"M\", \"(u)\"),\n        (0x24B1, \"M\", \"(v)\"),\n        (0x24B2, \"M\", \"(w)\"),\n        (0x24B3, \"M\", \"(x)\"),\n        (0x24B4, \"M\", \"(y)\"),\n        (0x24B5, \"M\", \"(z)\"),\n        (0x24B6, \"M\", \"a\"),\n        (0x24B7, \"M\", \"b\"),\n        (0x24B8, \"M\", \"c\"),\n        (0x24B9, \"M\", \"d\"),\n        (0x24BA, \"M\", \"e\"),\n        (0x24BB, \"M\", \"f\"),\n        (0x24BC, \"M\", \"g\"),\n        (0x24BD, \"M\", \"h\"),\n        (0x24BE, \"M\", \"i\"),\n        (0x24BF, \"M\", \"j\"),\n        (0x24C0, \"M\", \"k\"),\n        (0x24C1, \"M\", \"l\"),\n        (0x24C2, \"M\", \"m\"),\n        (0x24C3, \"M\", \"n\"),\n        (0x24C4, \"M\", \"o\"),\n        (0x24C5, \"M\", \"p\"),\n        (0x24C6, \"M\", \"q\"),\n        (0x24C7, \"M\", \"r\"),\n        (0x24C8, \"M\", \"s\"),\n        (0x24C9, \"M\", \"t\"),\n        (0x24CA, \"M\", \"u\"),\n        (0x24CB, \"M\", \"v\"),\n        (0x24CC, \"M\", \"w\"),\n        (0x24CD, \"M\", \"x\"),\n        (0x24CE, \"M\", \"y\"),\n        (0x24CF, \"M\", \"z\"),\n        (0x24D0, \"M\", \"a\"),\n        (0x24D1, \"M\", \"b\"),\n        (0x24D2, \"M\", \"c\"),\n        (0x24D3, \"M\", \"d\"),\n        (0x24D4, \"M\", \"e\"),\n        (0x24D5, \"M\", \"f\"),\n        (0x24D6, \"M\", \"g\"),\n        (0x24D7, \"M\", \"h\"),\n        (0x24D8, \"M\", \"i\"),\n        (0x24D9, \"M\", \"j\"),\n        (0x24DA, \"M\", \"k\"),\n        (0x24DB, \"M\", \"l\"),\n        (0x24DC, \"M\", \"m\"),\n        (0x24DD, \"M\", \"n\"),\n        (0x24DE, \"M\", \"o\"),\n        (0x24DF, \"M\", \"p\"),\n        (0x24E0, \"M\", \"q\"),\n        (0x24E1, \"M\", \"r\"),\n        (0x24E2, \"M\", \"s\"),\n        (0x24E3, \"M\", \"t\"),\n        (0x24E4, \"M\", \"u\"),\n        (0x24E5, \"M\", \"v\"),\n        (0x24E6, \"M\", \"w\"),\n        (0x24E7, \"M\", \"x\"),\n        (0x24E8, \"M\", \"y\"),\n        (0x24E9, \"M\", \"z\"),\n        (0x24EA, \"M\", \"0\"),\n        (0x24EB, \"V\"),\n        (0x2A0C, \"M\", \"∫∫∫∫\"),\n        (0x2A0D, \"V\"),\n        (0x2A74, \"M\", \"::=\"),\n        (0x2A75, \"M\", \"==\"),\n        (0x2A76, \"M\", \"===\"),\n        (0x2A77, \"V\"),\n        (0x2ADC, \"M\", \"⫝̸\"),\n        (0x2ADD, \"V\"),\n        (0x2B74, \"X\"),\n        (0x2B76, \"V\"),\n        (0x2B96, \"X\"),\n        (0x2B97, \"V\"),\n        (0x2C00, \"M\", \"ⰰ\"),\n        (0x2C01, \"M\", \"ⰱ\"),\n        (0x2C02, \"M\", \"ⰲ\"),\n        (0x2C03, \"M\", \"ⰳ\"),\n        (0x2C04, \"M\", \"ⰴ\"),\n        (0x2C05, \"M\", \"ⰵ\"),\n        (0x2C06, \"M\", \"ⰶ\"),\n        (0x2C07, \"M\", \"ⰷ\"),\n        (0x2C08, \"M\", \"ⰸ\"),\n        (0x2C09, \"M\", \"ⰹ\"),\n        (0x2C0A, \"M\", \"ⰺ\"),\n        (0x2C0B, \"M\", \"ⰻ\"),\n    ]\n\n\ndef _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2C0C, \"M\", \"ⰼ\"),\n        (0x2C0D, \"M\", \"ⰽ\"),\n        (0x2C0E, \"M\", \"ⰾ\"),\n        (0x2C0F, \"M\", \"ⰿ\"),\n        (0x2C10, \"M\", \"ⱀ\"),\n        (0x2C11, \"M\", \"ⱁ\"),\n        (0x2C12, \"M\", \"ⱂ\"),\n        (0x2C13, \"M\", \"ⱃ\"),\n        (0x2C14, \"M\", \"ⱄ\"),\n        (0x2C15, \"M\", \"ⱅ\"),\n        (0x2C16, \"M\", \"ⱆ\"),\n        (0x2C17, \"M\", \"ⱇ\"),\n        (0x2C18, \"M\", \"ⱈ\"),\n        (0x2C19, \"M\", \"ⱉ\"),\n        (0x2C1A, \"M\", \"ⱊ\"),\n        (0x2C1B, \"M\", \"ⱋ\"),\n        (0x2C1C, \"M\", \"ⱌ\"),\n        (0x2C1D, \"M\", \"ⱍ\"),\n        (0x2C1E, \"M\", \"ⱎ\"),\n        (0x2C1F, \"M\", \"ⱏ\"),\n        (0x2C20, \"M\", \"ⱐ\"),\n        (0x2C21, \"M\", \"ⱑ\"),\n        (0x2C22, \"M\", \"ⱒ\"),\n        (0x2C23, \"M\", \"ⱓ\"),\n        (0x2C24, \"M\", \"ⱔ\"),\n        (0x2C25, \"M\", \"ⱕ\"),\n        (0x2C26, \"M\", \"ⱖ\"),\n        (0x2C27, \"M\", \"ⱗ\"),\n        (0x2C28, \"M\", \"ⱘ\"),\n        (0x2C29, \"M\", \"ⱙ\"),\n        (0x2C2A, \"M\", \"ⱚ\"),\n        (0x2C2B, \"M\", \"ⱛ\"),\n        (0x2C2C, \"M\", \"ⱜ\"),\n        (0x2C2D, \"M\", \"ⱝ\"),\n        (0x2C2E, \"M\", \"ⱞ\"),\n        (0x2C2F, \"M\", \"ⱟ\"),\n        (0x2C30, \"V\"),\n        (0x2C60, \"M\", \"ⱡ\"),\n        (0x2C61, \"V\"),\n        (0x2C62, \"M\", \"ɫ\"),\n        (0x2C63, \"M\", \"ᵽ\"),\n        (0x2C64, \"M\", \"ɽ\"),\n        (0x2C65, \"V\"),\n        (0x2C67, \"M\", \"ⱨ\"),\n        (0x2C68, \"V\"),\n        (0x2C69, \"M\", \"ⱪ\"),\n        (0x2C6A, \"V\"),\n        (0x2C6B, \"M\", \"ⱬ\"),\n        (0x2C6C, \"V\"),\n        (0x2C6D, \"M\", \"ɑ\"),\n        (0x2C6E, \"M\", \"ɱ\"),\n        (0x2C6F, \"M\", \"ɐ\"),\n        (0x2C70, \"M\", \"ɒ\"),\n        (0x2C71, \"V\"),\n        (0x2C72, \"M\", \"ⱳ\"),\n        (0x2C73, \"V\"),\n        (0x2C75, \"M\", \"ⱶ\"),\n        (0x2C76, \"V\"),\n        (0x2C7C, \"M\", \"j\"),\n        (0x2C7D, \"M\", \"v\"),\n        (0x2C7E, \"M\", \"ȿ\"),\n        (0x2C7F, \"M\", \"ɀ\"),\n        (0x2C80, \"M\", \"ⲁ\"),\n        (0x2C81, \"V\"),\n        (0x2C82, \"M\", \"ⲃ\"),\n        (0x2C83, \"V\"),\n        (0x2C84, \"M\", \"ⲅ\"),\n        (0x2C85, \"V\"),\n        (0x2C86, \"M\", \"ⲇ\"),\n        (0x2C87, \"V\"),\n        (0x2C88, \"M\", \"ⲉ\"),\n        (0x2C89, \"V\"),\n        (0x2C8A, \"M\", \"ⲋ\"),\n        (0x2C8B, \"V\"),\n        (0x2C8C, \"M\", \"ⲍ\"),\n        (0x2C8D, \"V\"),\n        (0x2C8E, \"M\", \"ⲏ\"),\n        (0x2C8F, \"V\"),\n        (0x2C90, \"M\", \"ⲑ\"),\n        (0x2C91, \"V\"),\n        (0x2C92, \"M\", \"ⲓ\"),\n        (0x2C93, \"V\"),\n        (0x2C94, \"M\", \"ⲕ\"),\n        (0x2C95, \"V\"),\n        (0x2C96, \"M\", \"ⲗ\"),\n        (0x2C97, \"V\"),\n        (0x2C98, \"M\", \"ⲙ\"),\n        (0x2C99, \"V\"),\n        (0x2C9A, \"M\", \"ⲛ\"),\n        (0x2C9B, \"V\"),\n        (0x2C9C, \"M\", \"ⲝ\"),\n        (0x2C9D, \"V\"),\n        (0x2C9E, \"M\", \"ⲟ\"),\n        (0x2C9F, \"V\"),\n        (0x2CA0, \"M\", \"ⲡ\"),\n        (0x2CA1, \"V\"),\n        (0x2CA2, \"M\", \"ⲣ\"),\n        (0x2CA3, \"V\"),\n        (0x2CA4, \"M\", \"ⲥ\"),\n        (0x2CA5, \"V\"),\n    ]\n\n\ndef _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2CA6, \"M\", \"ⲧ\"),\n        (0x2CA7, \"V\"),\n        (0x2CA8, \"M\", \"ⲩ\"),\n        (0x2CA9, \"V\"),\n        (0x2CAA, \"M\", \"ⲫ\"),\n        (0x2CAB, \"V\"),\n        (0x2CAC, \"M\", \"ⲭ\"),\n        (0x2CAD, \"V\"),\n        (0x2CAE, \"M\", \"ⲯ\"),\n        (0x2CAF, \"V\"),\n        (0x2CB0, \"M\", \"ⲱ\"),\n        (0x2CB1, \"V\"),\n        (0x2CB2, \"M\", \"ⲳ\"),\n        (0x2CB3, \"V\"),\n        (0x2CB4, \"M\", \"ⲵ\"),\n        (0x2CB5, \"V\"),\n        (0x2CB6, \"M\", \"ⲷ\"),\n        (0x2CB7, \"V\"),\n        (0x2CB8, \"M\", \"ⲹ\"),\n        (0x2CB9, \"V\"),\n        (0x2CBA, \"M\", \"ⲻ\"),\n        (0x2CBB, \"V\"),\n        (0x2CBC, \"M\", \"ⲽ\"),\n        (0x2CBD, \"V\"),\n        (0x2CBE, \"M\", \"ⲿ\"),\n        (0x2CBF, \"V\"),\n        (0x2CC0, \"M\", \"ⳁ\"),\n        (0x2CC1, \"V\"),\n        (0x2CC2, \"M\", \"ⳃ\"),\n        (0x2CC3, \"V\"),\n        (0x2CC4, \"M\", \"ⳅ\"),\n        (0x2CC5, \"V\"),\n        (0x2CC6, \"M\", \"ⳇ\"),\n        (0x2CC7, \"V\"),\n        (0x2CC8, \"M\", \"ⳉ\"),\n        (0x2CC9, \"V\"),\n        (0x2CCA, \"M\", \"ⳋ\"),\n        (0x2CCB, \"V\"),\n        (0x2CCC, \"M\", \"ⳍ\"),\n        (0x2CCD, \"V\"),\n        (0x2CCE, \"M\", \"ⳏ\"),\n        (0x2CCF, \"V\"),\n        (0x2CD0, \"M\", \"ⳑ\"),\n        (0x2CD1, \"V\"),\n        (0x2CD2, \"M\", \"ⳓ\"),\n        (0x2CD3, \"V\"),\n        (0x2CD4, \"M\", \"ⳕ\"),\n        (0x2CD5, \"V\"),\n        (0x2CD6, \"M\", \"ⳗ\"),\n        (0x2CD7, \"V\"),\n        (0x2CD8, \"M\", \"ⳙ\"),\n        (0x2CD9, \"V\"),\n        (0x2CDA, \"M\", \"ⳛ\"),\n        (0x2CDB, \"V\"),\n        (0x2CDC, \"M\", \"ⳝ\"),\n        (0x2CDD, \"V\"),\n        (0x2CDE, \"M\", \"ⳟ\"),\n        (0x2CDF, \"V\"),\n        (0x2CE0, \"M\", \"ⳡ\"),\n        (0x2CE1, \"V\"),\n        (0x2CE2, \"M\", \"ⳣ\"),\n        (0x2CE3, \"V\"),\n        (0x2CEB, \"M\", \"ⳬ\"),\n        (0x2CEC, \"V\"),\n        (0x2CED, \"M\", \"ⳮ\"),\n        (0x2CEE, \"V\"),\n        (0x2CF2, \"M\", \"ⳳ\"),\n        (0x2CF3, \"V\"),\n        (0x2CF4, \"X\"),\n        (0x2CF9, \"V\"),\n        (0x2D26, \"X\"),\n        (0x2D27, \"V\"),\n        (0x2D28, \"X\"),\n        (0x2D2D, \"V\"),\n        (0x2D2E, \"X\"),\n        (0x2D30, \"V\"),\n        (0x2D68, \"X\"),\n        (0x2D6F, \"M\", \"ⵡ\"),\n        (0x2D70, \"V\"),\n        (0x2D71, \"X\"),\n        (0x2D7F, \"V\"),\n        (0x2D97, \"X\"),\n        (0x2DA0, \"V\"),\n        (0x2DA7, \"X\"),\n        (0x2DA8, \"V\"),\n        (0x2DAF, \"X\"),\n        (0x2DB0, \"V\"),\n        (0x2DB7, \"X\"),\n        (0x2DB8, \"V\"),\n        (0x2DBF, \"X\"),\n        (0x2DC0, \"V\"),\n        (0x2DC7, \"X\"),\n        (0x2DC8, \"V\"),\n        (0x2DCF, \"X\"),\n        (0x2DD0, \"V\"),\n        (0x2DD7, \"X\"),\n        (0x2DD8, \"V\"),\n        (0x2DDF, \"X\"),\n        (0x2DE0, \"V\"),\n        (0x2E5E, \"X\"),\n    ]\n\n\ndef _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2E80, \"V\"),\n        (0x2E9A, \"X\"),\n        (0x2E9B, \"V\"),\n        (0x2E9F, \"M\", \"母\"),\n        (0x2EA0, \"V\"),\n        (0x2EF3, \"M\", \"龟\"),\n        (0x2EF4, \"X\"),\n        (0x2F00, \"M\", \"一\"),\n        (0x2F01, \"M\", \"丨\"),\n        (0x2F02, \"M\", \"丶\"),\n        (0x2F03, \"M\", \"丿\"),\n        (0x2F04, \"M\", \"乙\"),\n        (0x2F05, \"M\", \"亅\"),\n        (0x2F06, \"M\", \"二\"),\n        (0x2F07, \"M\", \"亠\"),\n        (0x2F08, \"M\", \"人\"),\n        (0x2F09, \"M\", \"儿\"),\n        (0x2F0A, \"M\", \"入\"),\n        (0x2F0B, \"M\", \"八\"),\n        (0x2F0C, \"M\", \"冂\"),\n        (0x2F0D, \"M\", \"冖\"),\n        (0x2F0E, \"M\", \"冫\"),\n        (0x2F0F, \"M\", \"几\"),\n        (0x2F10, \"M\", \"凵\"),\n        (0x2F11, \"M\", \"刀\"),\n        (0x2F12, \"M\", \"力\"),\n        (0x2F13, \"M\", \"勹\"),\n        (0x2F14, \"M\", \"匕\"),\n        (0x2F15, \"M\", \"匚\"),\n        (0x2F16, \"M\", \"匸\"),\n        (0x2F17, \"M\", \"十\"),\n        (0x2F18, \"M\", \"卜\"),\n        (0x2F19, \"M\", \"卩\"),\n        (0x2F1A, \"M\", \"厂\"),\n        (0x2F1B, \"M\", \"厶\"),\n        (0x2F1C, \"M\", \"又\"),\n        (0x2F1D, \"M\", \"口\"),\n        (0x2F1E, \"M\", \"囗\"),\n        (0x2F1F, \"M\", \"土\"),\n        (0x2F20, \"M\", \"士\"),\n        (0x2F21, \"M\", \"夂\"),\n        (0x2F22, \"M\", \"夊\"),\n        (0x2F23, \"M\", \"夕\"),\n        (0x2F24, \"M\", \"大\"),\n        (0x2F25, \"M\", \"女\"),\n        (0x2F26, \"M\", \"子\"),\n        (0x2F27, \"M\", \"宀\"),\n        (0x2F28, \"M\", \"寸\"),\n        (0x2F29, \"M\", \"小\"),\n        (0x2F2A, \"M\", \"尢\"),\n        (0x2F2B, \"M\", \"尸\"),\n        (0x2F2C, \"M\", \"屮\"),\n        (0x2F2D, \"M\", \"山\"),\n        (0x2F2E, \"M\", \"巛\"),\n        (0x2F2F, \"M\", \"工\"),\n        (0x2F30, \"M\", \"己\"),\n        (0x2F31, \"M\", \"巾\"),\n        (0x2F32, \"M\", \"干\"),\n        (0x2F33, \"M\", \"幺\"),\n        (0x2F34, \"M\", \"广\"),\n        (0x2F35, \"M\", \"廴\"),\n        (0x2F36, \"M\", \"廾\"),\n        (0x2F37, \"M\", \"弋\"),\n        (0x2F38, \"M\", \"弓\"),\n        (0x2F39, \"M\", \"彐\"),\n        (0x2F3A, \"M\", \"彡\"),\n        (0x2F3B, \"M\", \"彳\"),\n        (0x2F3C, \"M\", \"心\"),\n        (0x2F3D, \"M\", \"戈\"),\n        (0x2F3E, \"M\", \"戶\"),\n        (0x2F3F, \"M\", \"手\"),\n        (0x2F40, \"M\", \"支\"),\n        (0x2F41, \"M\", \"攴\"),\n        (0x2F42, \"M\", \"文\"),\n        (0x2F43, \"M\", \"斗\"),\n        (0x2F44, \"M\", \"斤\"),\n        (0x2F45, \"M\", \"方\"),\n        (0x2F46, \"M\", \"无\"),\n        (0x2F47, \"M\", \"日\"),\n        (0x2F48, \"M\", \"曰\"),\n        (0x2F49, \"M\", \"月\"),\n        (0x2F4A, \"M\", \"木\"),\n        (0x2F4B, \"M\", \"欠\"),\n        (0x2F4C, \"M\", \"止\"),\n        (0x2F4D, \"M\", \"歹\"),\n        (0x2F4E, \"M\", \"殳\"),\n        (0x2F4F, \"M\", \"毋\"),\n        (0x2F50, \"M\", \"比\"),\n        (0x2F51, \"M\", \"毛\"),\n        (0x2F52, \"M\", \"氏\"),\n        (0x2F53, \"M\", \"气\"),\n        (0x2F54, \"M\", \"水\"),\n        (0x2F55, \"M\", \"火\"),\n        (0x2F56, \"M\", \"爪\"),\n        (0x2F57, \"M\", \"父\"),\n        (0x2F58, \"M\", \"爻\"),\n        (0x2F59, \"M\", \"爿\"),\n        (0x2F5A, \"M\", \"片\"),\n        (0x2F5B, \"M\", \"牙\"),\n        (0x2F5C, \"M\", \"牛\"),\n    ]\n\n\ndef _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F5D, \"M\", \"犬\"),\n        (0x2F5E, \"M\", \"玄\"),\n        (0x2F5F, \"M\", \"玉\"),\n        (0x2F60, \"M\", \"瓜\"),\n        (0x2F61, \"M\", \"瓦\"),\n        (0x2F62, \"M\", \"甘\"),\n        (0x2F63, \"M\", \"生\"),\n        (0x2F64, \"M\", \"用\"),\n        (0x2F65, \"M\", \"田\"),\n        (0x2F66, \"M\", \"疋\"),\n        (0x2F67, \"M\", \"疒\"),\n        (0x2F68, \"M\", \"癶\"),\n        (0x2F69, \"M\", \"白\"),\n        (0x2F6A, \"M\", \"皮\"),\n        (0x2F6B, \"M\", \"皿\"),\n        (0x2F6C, \"M\", \"目\"),\n        (0x2F6D, \"M\", \"矛\"),\n        (0x2F6E, \"M\", \"矢\"),\n        (0x2F6F, \"M\", \"石\"),\n        (0x2F70, \"M\", \"示\"),\n        (0x2F71, \"M\", \"禸\"),\n        (0x2F72, \"M\", \"禾\"),\n        (0x2F73, \"M\", \"穴\"),\n        (0x2F74, \"M\", \"立\"),\n        (0x2F75, \"M\", \"竹\"),\n        (0x2F76, \"M\", \"米\"),\n        (0x2F77, \"M\", \"糸\"),\n        (0x2F78, \"M\", \"缶\"),\n        (0x2F79, \"M\", \"网\"),\n        (0x2F7A, \"M\", \"羊\"),\n        (0x2F7B, \"M\", \"羽\"),\n        (0x2F7C, \"M\", \"老\"),\n        (0x2F7D, \"M\", \"而\"),\n        (0x2F7E, \"M\", \"耒\"),\n        (0x2F7F, \"M\", \"耳\"),\n        (0x2F80, \"M\", \"聿\"),\n        (0x2F81, \"M\", \"肉\"),\n        (0x2F82, \"M\", \"臣\"),\n        (0x2F83, \"M\", \"自\"),\n        (0x2F84, \"M\", \"至\"),\n        (0x2F85, \"M\", \"臼\"),\n        (0x2F86, \"M\", \"舌\"),\n        (0x2F87, \"M\", \"舛\"),\n        (0x2F88, \"M\", \"舟\"),\n        (0x2F89, \"M\", \"艮\"),\n        (0x2F8A, \"M\", \"色\"),\n        (0x2F8B, \"M\", \"艸\"),\n        (0x2F8C, \"M\", \"虍\"),\n        (0x2F8D, \"M\", \"虫\"),\n        (0x2F8E, \"M\", \"血\"),\n        (0x2F8F, \"M\", \"行\"),\n        (0x2F90, \"M\", \"衣\"),\n        (0x2F91, \"M\", \"襾\"),\n        (0x2F92, \"M\", \"見\"),\n        (0x2F93, \"M\", \"角\"),\n        (0x2F94, \"M\", \"言\"),\n        (0x2F95, \"M\", \"谷\"),\n        (0x2F96, \"M\", \"豆\"),\n        (0x2F97, \"M\", \"豕\"),\n        (0x2F98, \"M\", \"豸\"),\n        (0x2F99, \"M\", \"貝\"),\n        (0x2F9A, \"M\", \"赤\"),\n        (0x2F9B, \"M\", \"走\"),\n        (0x2F9C, \"M\", \"足\"),\n        (0x2F9D, \"M\", \"身\"),\n        (0x2F9E, \"M\", \"車\"),\n        (0x2F9F, \"M\", \"辛\"),\n        (0x2FA0, \"M\", \"辰\"),\n        (0x2FA1, \"M\", \"辵\"),\n        (0x2FA2, \"M\", \"邑\"),\n        (0x2FA3, \"M\", \"酉\"),\n        (0x2FA4, \"M\", \"釆\"),\n        (0x2FA5, \"M\", \"里\"),\n        (0x2FA6, \"M\", \"金\"),\n        (0x2FA7, \"M\", \"長\"),\n        (0x2FA8, \"M\", \"門\"),\n        (0x2FA9, \"M\", \"阜\"),\n        (0x2FAA, \"M\", \"隶\"),\n        (0x2FAB, \"M\", \"隹\"),\n        (0x2FAC, \"M\", \"雨\"),\n        (0x2FAD, \"M\", \"靑\"),\n        (0x2FAE, \"M\", \"非\"),\n        (0x2FAF, \"M\", \"面\"),\n        (0x2FB0, \"M\", \"革\"),\n        (0x2FB1, \"M\", \"韋\"),\n        (0x2FB2, \"M\", \"韭\"),\n        (0x2FB3, \"M\", \"音\"),\n        (0x2FB4, \"M\", \"頁\"),\n        (0x2FB5, \"M\", \"風\"),\n        (0x2FB6, \"M\", \"飛\"),\n        (0x2FB7, \"M\", \"食\"),\n        (0x2FB8, \"M\", \"首\"),\n        (0x2FB9, \"M\", \"香\"),\n        (0x2FBA, \"M\", \"馬\"),\n        (0x2FBB, \"M\", \"骨\"),\n        (0x2FBC, \"M\", \"高\"),\n        (0x2FBD, \"M\", \"髟\"),\n        (0x2FBE, \"M\", \"鬥\"),\n        (0x2FBF, \"M\", \"鬯\"),\n        (0x2FC0, \"M\", \"鬲\"),\n    ]\n\n\ndef _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2FC1, \"M\", \"鬼\"),\n        (0x2FC2, \"M\", \"魚\"),\n        (0x2FC3, \"M\", \"鳥\"),\n        (0x2FC4, \"M\", \"鹵\"),\n        (0x2FC5, \"M\", \"鹿\"),\n        (0x2FC6, \"M\", \"麥\"),\n        (0x2FC7, \"M\", \"麻\"),\n        (0x2FC8, \"M\", \"黃\"),\n        (0x2FC9, \"M\", \"黍\"),\n        (0x2FCA, \"M\", \"黑\"),\n        (0x2FCB, \"M\", \"黹\"),\n        (0x2FCC, \"M\", \"黽\"),\n        (0x2FCD, \"M\", \"鼎\"),\n        (0x2FCE, \"M\", \"鼓\"),\n        (0x2FCF, \"M\", \"鼠\"),\n        (0x2FD0, \"M\", \"鼻\"),\n        (0x2FD1, \"M\", \"齊\"),\n        (0x2FD2, \"M\", \"齒\"),\n        (0x2FD3, \"M\", \"龍\"),\n        (0x2FD4, \"M\", \"龜\"),\n        (0x2FD5, \"M\", \"龠\"),\n        (0x2FD6, \"X\"),\n        (0x3000, \"M\", \" \"),\n        (0x3001, \"V\"),\n        (0x3002, \"M\", \".\"),\n        (0x3003, \"V\"),\n        (0x3036, \"M\", \"〒\"),\n        (0x3037, \"V\"),\n        (0x3038, \"M\", \"十\"),\n        (0x3039, \"M\", \"卄\"),\n        (0x303A, \"M\", \"卅\"),\n        (0x303B, \"V\"),\n        (0x3040, \"X\"),\n        (0x3041, \"V\"),\n        (0x3097, \"X\"),\n        (0x3099, \"V\"),\n        (0x309B, \"M\", \" ゙\"),\n        (0x309C, \"M\", \" ゚\"),\n        (0x309D, \"V\"),\n        (0x309F, \"M\", \"より\"),\n        (0x30A0, \"V\"),\n        (0x30FF, \"M\", \"コト\"),\n        (0x3100, \"X\"),\n        (0x3105, \"V\"),\n        (0x3130, \"X\"),\n        (0x3131, \"M\", \"ᄀ\"),\n        (0x3132, \"M\", \"ᄁ\"),\n        (0x3133, \"M\", \"ᆪ\"),\n        (0x3134, \"M\", \"ᄂ\"),\n        (0x3135, \"M\", \"ᆬ\"),\n        (0x3136, \"M\", \"ᆭ\"),\n        (0x3137, \"M\", \"ᄃ\"),\n        (0x3138, \"M\", \"ᄄ\"),\n        (0x3139, \"M\", \"ᄅ\"),\n        (0x313A, \"M\", \"ᆰ\"),\n        (0x313B, \"M\", \"ᆱ\"),\n        (0x313C, \"M\", \"ᆲ\"),\n        (0x313D, \"M\", \"ᆳ\"),\n        (0x313E, \"M\", \"ᆴ\"),\n        (0x313F, \"M\", \"ᆵ\"),\n        (0x3140, \"M\", \"ᄚ\"),\n        (0x3141, \"M\", \"ᄆ\"),\n        (0x3142, \"M\", \"ᄇ\"),\n        (0x3143, \"M\", \"ᄈ\"),\n        (0x3144, \"M\", \"ᄡ\"),\n        (0x3145, \"M\", \"ᄉ\"),\n        (0x3146, \"M\", \"ᄊ\"),\n        (0x3147, \"M\", \"ᄋ\"),\n        (0x3148, \"M\", \"ᄌ\"),\n        (0x3149, \"M\", \"ᄍ\"),\n        (0x314A, \"M\", \"ᄎ\"),\n        (0x314B, \"M\", \"ᄏ\"),\n        (0x314C, \"M\", \"ᄐ\"),\n        (0x314D, \"M\", \"ᄑ\"),\n        (0x314E, \"M\", \"ᄒ\"),\n        (0x314F, \"M\", \"ᅡ\"),\n        (0x3150, \"M\", \"ᅢ\"),\n        (0x3151, \"M\", \"ᅣ\"),\n        (0x3152, \"M\", \"ᅤ\"),\n        (0x3153, \"M\", \"ᅥ\"),\n        (0x3154, \"M\", \"ᅦ\"),\n        (0x3155, \"M\", \"ᅧ\"),\n        (0x3156, \"M\", \"ᅨ\"),\n        (0x3157, \"M\", \"ᅩ\"),\n        (0x3158, \"M\", \"ᅪ\"),\n        (0x3159, \"M\", \"ᅫ\"),\n        (0x315A, \"M\", \"ᅬ\"),\n        (0x315B, \"M\", \"ᅭ\"),\n        (0x315C, \"M\", \"ᅮ\"),\n        (0x315D, \"M\", \"ᅯ\"),\n        (0x315E, \"M\", \"ᅰ\"),\n        (0x315F, \"M\", \"ᅱ\"),\n        (0x3160, \"M\", \"ᅲ\"),\n        (0x3161, \"M\", \"ᅳ\"),\n        (0x3162, \"M\", \"ᅴ\"),\n        (0x3163, \"M\", \"ᅵ\"),\n        (0x3164, \"I\"),\n        (0x3165, \"M\", \"ᄔ\"),\n        (0x3166, \"M\", \"ᄕ\"),\n        (0x3167, \"M\", \"ᇇ\"),\n    ]\n\n\ndef _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x3168, \"M\", \"ᇈ\"),\n        (0x3169, \"M\", \"ᇌ\"),\n        (0x316A, \"M\", \"ᇎ\"),\n        (0x316B, \"M\", \"ᇓ\"),\n        (0x316C, \"M\", \"ᇗ\"),\n        (0x316D, \"M\", \"ᇙ\"),\n        (0x316E, \"M\", \"ᄜ\"),\n        (0x316F, \"M\", \"ᇝ\"),\n        (0x3170, \"M\", \"ᇟ\"),\n        (0x3171, \"M\", \"ᄝ\"),\n        (0x3172, \"M\", \"ᄞ\"),\n        (0x3173, \"M\", \"ᄠ\"),\n        (0x3174, \"M\", \"ᄢ\"),\n        (0x3175, \"M\", \"ᄣ\"),\n        (0x3176, \"M\", \"ᄧ\"),\n        (0x3177, \"M\", \"ᄩ\"),\n        (0x3178, \"M\", \"ᄫ\"),\n        (0x3179, \"M\", \"ᄬ\"),\n        (0x317A, \"M\", \"ᄭ\"),\n        (0x317B, \"M\", \"ᄮ\"),\n        (0x317C, \"M\", \"ᄯ\"),\n        (0x317D, \"M\", \"ᄲ\"),\n        (0x317E, \"M\", \"ᄶ\"),\n        (0x317F, \"M\", \"ᅀ\"),\n        (0x3180, \"M\", \"ᅇ\"),\n        (0x3181, \"M\", \"ᅌ\"),\n        (0x3182, \"M\", \"ᇱ\"),\n        (0x3183, \"M\", \"ᇲ\"),\n        (0x3184, \"M\", \"ᅗ\"),\n        (0x3185, \"M\", \"ᅘ\"),\n        (0x3186, \"M\", \"ᅙ\"),\n        (0x3187, \"M\", \"ᆄ\"),\n        (0x3188, \"M\", \"ᆅ\"),\n        (0x3189, \"M\", \"ᆈ\"),\n        (0x318A, \"M\", \"ᆑ\"),\n        (0x318B, \"M\", \"ᆒ\"),\n        (0x318C, \"M\", \"ᆔ\"),\n        (0x318D, \"M\", \"ᆞ\"),\n        (0x318E, \"M\", \"ᆡ\"),\n        (0x318F, \"X\"),\n        (0x3190, \"V\"),\n        (0x3192, \"M\", \"一\"),\n        (0x3193, \"M\", \"二\"),\n        (0x3194, \"M\", \"三\"),\n        (0x3195, \"M\", \"四\"),\n        (0x3196, \"M\", \"上\"),\n        (0x3197, \"M\", \"中\"),\n        (0x3198, \"M\", \"下\"),\n        (0x3199, \"M\", \"甲\"),\n        (0x319A, \"M\", \"乙\"),\n        (0x319B, \"M\", \"丙\"),\n        (0x319C, \"M\", \"丁\"),\n        (0x319D, \"M\", \"天\"),\n        (0x319E, \"M\", \"地\"),\n        (0x319F, \"M\", \"人\"),\n        (0x31A0, \"V\"),\n        (0x31E6, \"X\"),\n        (0x31F0, \"V\"),\n        (0x3200, \"M\", \"(ᄀ)\"),\n        (0x3201, \"M\", \"(ᄂ)\"),\n        (0x3202, \"M\", \"(ᄃ)\"),\n        (0x3203, \"M\", \"(ᄅ)\"),\n        (0x3204, \"M\", \"(ᄆ)\"),\n        (0x3205, \"M\", \"(ᄇ)\"),\n        (0x3206, \"M\", \"(ᄉ)\"),\n        (0x3207, \"M\", \"(ᄋ)\"),\n        (0x3208, \"M\", \"(ᄌ)\"),\n        (0x3209, \"M\", \"(ᄎ)\"),\n        (0x320A, \"M\", \"(ᄏ)\"),\n        (0x320B, \"M\", \"(ᄐ)\"),\n        (0x320C, \"M\", \"(ᄑ)\"),\n        (0x320D, \"M\", \"(ᄒ)\"),\n        (0x320E, \"M\", \"(가)\"),\n        (0x320F, \"M\", \"(나)\"),\n        (0x3210, \"M\", \"(다)\"),\n        (0x3211, \"M\", \"(라)\"),\n        (0x3212, \"M\", \"(마)\"),\n        (0x3213, \"M\", \"(바)\"),\n        (0x3214, \"M\", \"(사)\"),\n        (0x3215, \"M\", \"(아)\"),\n        (0x3216, \"M\", \"(자)\"),\n        (0x3217, \"M\", \"(차)\"),\n        (0x3218, \"M\", \"(카)\"),\n        (0x3219, \"M\", \"(타)\"),\n        (0x321A, \"M\", \"(파)\"),\n        (0x321B, \"M\", \"(하)\"),\n        (0x321C, \"M\", \"(주)\"),\n        (0x321D, \"M\", \"(오전)\"),\n        (0x321E, \"M\", \"(오후)\"),\n        (0x321F, \"X\"),\n        (0x3220, \"M\", \"(一)\"),\n        (0x3221, \"M\", \"(二)\"),\n        (0x3222, \"M\", \"(三)\"),\n        (0x3223, \"M\", \"(四)\"),\n        (0x3224, \"M\", \"(五)\"),\n        (0x3225, \"M\", \"(六)\"),\n        (0x3226, \"M\", \"(七)\"),\n        (0x3227, \"M\", \"(八)\"),\n        (0x3228, \"M\", \"(九)\"),\n        (0x3229, \"M\", \"(十)\"),\n    ]\n\n\ndef _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x322A, \"M\", \"(月)\"),\n        (0x322B, \"M\", \"(火)\"),\n        (0x322C, \"M\", \"(水)\"),\n        (0x322D, \"M\", \"(木)\"),\n        (0x322E, \"M\", \"(金)\"),\n        (0x322F, \"M\", \"(土)\"),\n        (0x3230, \"M\", \"(日)\"),\n        (0x3231, \"M\", \"(株)\"),\n        (0x3232, \"M\", \"(有)\"),\n        (0x3233, \"M\", \"(社)\"),\n        (0x3234, \"M\", \"(名)\"),\n        (0x3235, \"M\", \"(特)\"),\n        (0x3236, \"M\", \"(財)\"),\n        (0x3237, \"M\", \"(祝)\"),\n        (0x3238, \"M\", \"(労)\"),\n        (0x3239, \"M\", \"(代)\"),\n        (0x323A, \"M\", \"(呼)\"),\n        (0x323B, \"M\", \"(学)\"),\n        (0x323C, \"M\", \"(監)\"),\n        (0x323D, \"M\", \"(企)\"),\n        (0x323E, \"M\", \"(資)\"),\n        (0x323F, \"M\", \"(協)\"),\n        (0x3240, \"M\", \"(祭)\"),\n        (0x3241, \"M\", \"(休)\"),\n        (0x3242, \"M\", \"(自)\"),\n        (0x3243, \"M\", \"(至)\"),\n        (0x3244, \"M\", \"問\"),\n        (0x3245, \"M\", \"幼\"),\n        (0x3246, \"M\", \"文\"),\n        (0x3247, \"M\", \"箏\"),\n        (0x3248, \"V\"),\n        (0x3250, \"M\", \"pte\"),\n        (0x3251, \"M\", \"21\"),\n        (0x3252, \"M\", \"22\"),\n        (0x3253, \"M\", \"23\"),\n        (0x3254, \"M\", \"24\"),\n        (0x3255, \"M\", \"25\"),\n        (0x3256, \"M\", \"26\"),\n        (0x3257, \"M\", \"27\"),\n        (0x3258, \"M\", \"28\"),\n        (0x3259, \"M\", \"29\"),\n        (0x325A, \"M\", \"30\"),\n        (0x325B, \"M\", \"31\"),\n        (0x325C, \"M\", \"32\"),\n        (0x325D, \"M\", \"33\"),\n        (0x325E, \"M\", \"34\"),\n        (0x325F, \"M\", \"35\"),\n        (0x3260, \"M\", \"ᄀ\"),\n        (0x3261, \"M\", \"ᄂ\"),\n        (0x3262, \"M\", \"ᄃ\"),\n        (0x3263, \"M\", \"ᄅ\"),\n        (0x3264, \"M\", \"ᄆ\"),\n        (0x3265, \"M\", \"ᄇ\"),\n        (0x3266, \"M\", \"ᄉ\"),\n        (0x3267, \"M\", \"ᄋ\"),\n        (0x3268, \"M\", \"ᄌ\"),\n        (0x3269, \"M\", \"ᄎ\"),\n        (0x326A, \"M\", \"ᄏ\"),\n        (0x326B, \"M\", \"ᄐ\"),\n        (0x326C, \"M\", \"ᄑ\"),\n        (0x326D, \"M\", \"ᄒ\"),\n        (0x326E, \"M\", \"가\"),\n        (0x326F, \"M\", \"나\"),\n        (0x3270, \"M\", \"다\"),\n        (0x3271, \"M\", \"라\"),\n        (0x3272, \"M\", \"마\"),\n        (0x3273, \"M\", \"바\"),\n        (0x3274, \"M\", \"사\"),\n        (0x3275, \"M\", \"아\"),\n        (0x3276, \"M\", \"자\"),\n        (0x3277, \"M\", \"차\"),\n        (0x3278, \"M\", \"카\"),\n        (0x3279, \"M\", \"타\"),\n        (0x327A, \"M\", \"파\"),\n        (0x327B, \"M\", \"하\"),\n        (0x327C, \"M\", \"참고\"),\n        (0x327D, \"M\", \"주의\"),\n        (0x327E, \"M\", \"우\"),\n        (0x327F, \"V\"),\n        (0x3280, \"M\", \"一\"),\n        (0x3281, \"M\", \"二\"),\n        (0x3282, \"M\", \"三\"),\n        (0x3283, \"M\", \"四\"),\n        (0x3284, \"M\", \"五\"),\n        (0x3285, \"M\", \"六\"),\n        (0x3286, \"M\", \"七\"),\n        (0x3287, \"M\", \"八\"),\n        (0x3288, \"M\", \"九\"),\n        (0x3289, \"M\", \"十\"),\n        (0x328A, \"M\", \"月\"),\n        (0x328B, \"M\", \"火\"),\n        (0x328C, \"M\", \"水\"),\n        (0x328D, \"M\", \"木\"),\n        (0x328E, \"M\", \"金\"),\n        (0x328F, \"M\", \"土\"),\n        (0x3290, \"M\", \"日\"),\n        (0x3291, \"M\", \"株\"),\n        (0x3292, \"M\", \"有\"),\n        (0x3293, \"M\", \"社\"),\n        (0x3294, \"M\", \"名\"),\n    ]\n\n\ndef _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x3295, \"M\", \"特\"),\n        (0x3296, \"M\", \"財\"),\n        (0x3297, \"M\", \"祝\"),\n        (0x3298, \"M\", \"労\"),\n        (0x3299, \"M\", \"秘\"),\n        (0x329A, \"M\", \"男\"),\n        (0x329B, \"M\", \"女\"),\n        (0x329C, \"M\", \"適\"),\n        (0x329D, \"M\", \"優\"),\n        (0x329E, \"M\", \"印\"),\n        (0x329F, \"M\", \"注\"),\n        (0x32A0, \"M\", \"項\"),\n        (0x32A1, \"M\", \"休\"),\n        (0x32A2, \"M\", \"写\"),\n        (0x32A3, \"M\", \"正\"),\n        (0x32A4, \"M\", \"上\"),\n        (0x32A5, \"M\", \"中\"),\n        (0x32A6, \"M\", \"下\"),\n        (0x32A7, \"M\", \"左\"),\n        (0x32A8, \"M\", \"右\"),\n        (0x32A9, \"M\", \"医\"),\n        (0x32AA, \"M\", \"宗\"),\n        (0x32AB, \"M\", \"学\"),\n        (0x32AC, \"M\", \"監\"),\n        (0x32AD, \"M\", \"企\"),\n        (0x32AE, \"M\", \"資\"),\n        (0x32AF, \"M\", \"協\"),\n        (0x32B0, \"M\", \"夜\"),\n        (0x32B1, \"M\", \"36\"),\n        (0x32B2, \"M\", \"37\"),\n        (0x32B3, \"M\", \"38\"),\n        (0x32B4, \"M\", \"39\"),\n        (0x32B5, \"M\", \"40\"),\n        (0x32B6, \"M\", \"41\"),\n        (0x32B7, \"M\", \"42\"),\n        (0x32B8, \"M\", \"43\"),\n        (0x32B9, \"M\", \"44\"),\n        (0x32BA, \"M\", \"45\"),\n        (0x32BB, \"M\", \"46\"),\n        (0x32BC, \"M\", \"47\"),\n        (0x32BD, \"M\", \"48\"),\n        (0x32BE, \"M\", \"49\"),\n        (0x32BF, \"M\", \"50\"),\n        (0x32C0, \"M\", \"1月\"),\n        (0x32C1, \"M\", \"2月\"),\n        (0x32C2, \"M\", \"3月\"),\n        (0x32C3, \"M\", \"4月\"),\n        (0x32C4, \"M\", \"5月\"),\n        (0x32C5, \"M\", \"6月\"),\n        (0x32C6, \"M\", \"7月\"),\n        (0x32C7, \"M\", \"8月\"),\n        (0x32C8, \"M\", \"9月\"),\n        (0x32C9, \"M\", \"10月\"),\n        (0x32CA, \"M\", \"11月\"),\n        (0x32CB, \"M\", \"12月\"),\n        (0x32CC, \"M\", \"hg\"),\n        (0x32CD, \"M\", \"erg\"),\n        (0x32CE, \"M\", \"ev\"),\n        (0x32CF, \"M\", \"ltd\"),\n        (0x32D0, \"M\", \"ア\"),\n        (0x32D1, \"M\", \"イ\"),\n        (0x32D2, \"M\", \"ウ\"),\n        (0x32D3, \"M\", \"エ\"),\n        (0x32D4, \"M\", \"オ\"),\n        (0x32D5, \"M\", \"カ\"),\n        (0x32D6, \"M\", \"キ\"),\n        (0x32D7, \"M\", \"ク\"),\n        (0x32D8, \"M\", \"ケ\"),\n        (0x32D9, \"M\", \"コ\"),\n        (0x32DA, \"M\", \"サ\"),\n        (0x32DB, \"M\", \"シ\"),\n        (0x32DC, \"M\", \"ス\"),\n        (0x32DD, \"M\", \"セ\"),\n        (0x32DE, \"M\", \"ソ\"),\n        (0x32DF, \"M\", \"タ\"),\n        (0x32E0, \"M\", \"チ\"),\n        (0x32E1, \"M\", \"ツ\"),\n        (0x32E2, \"M\", \"テ\"),\n        (0x32E3, \"M\", \"ト\"),\n        (0x32E4, \"M\", \"ナ\"),\n        (0x32E5, \"M\", \"ニ\"),\n        (0x32E6, \"M\", \"ヌ\"),\n        (0x32E7, \"M\", \"ネ\"),\n        (0x32E8, \"M\", \"ノ\"),\n        (0x32E9, \"M\", \"ハ\"),\n        (0x32EA, \"M\", \"ヒ\"),\n        (0x32EB, \"M\", \"フ\"),\n        (0x32EC, \"M\", \"ヘ\"),\n        (0x32ED, \"M\", \"ホ\"),\n        (0x32EE, \"M\", \"マ\"),\n        (0x32EF, \"M\", \"ミ\"),\n        (0x32F0, \"M\", \"ム\"),\n        (0x32F1, \"M\", \"メ\"),\n        (0x32F2, \"M\", \"モ\"),\n        (0x32F3, \"M\", \"ヤ\"),\n        (0x32F4, \"M\", \"ユ\"),\n        (0x32F5, \"M\", \"ヨ\"),\n        (0x32F6, \"M\", \"ラ\"),\n        (0x32F7, \"M\", \"リ\"),\n        (0x32F8, \"M\", \"ル\"),\n    ]\n\n\ndef _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x32F9, \"M\", \"レ\"),\n        (0x32FA, \"M\", \"ロ\"),\n        (0x32FB, \"M\", \"ワ\"),\n        (0x32FC, \"M\", \"ヰ\"),\n        (0x32FD, \"M\", \"ヱ\"),\n        (0x32FE, \"M\", \"ヲ\"),\n        (0x32FF, \"M\", \"令和\"),\n        (0x3300, \"M\", \"アパート\"),\n        (0x3301, \"M\", \"アルファ\"),\n        (0x3302, \"M\", \"アンペア\"),\n        (0x3303, \"M\", \"アール\"),\n        (0x3304, \"M\", \"イニング\"),\n        (0x3305, \"M\", \"インチ\"),\n        (0x3306, \"M\", \"ウォン\"),\n        (0x3307, \"M\", \"エスクード\"),\n        (0x3308, \"M\", \"エーカー\"),\n        (0x3309, \"M\", \"オンス\"),\n        (0x330A, \"M\", \"オーム\"),\n        (0x330B, \"M\", \"カイリ\"),\n        (0x330C, \"M\", \"カラット\"),\n        (0x330D, \"M\", \"カロリー\"),\n        (0x330E, \"M\", \"ガロン\"),\n        (0x330F, \"M\", \"ガンマ\"),\n        (0x3310, \"M\", \"ギガ\"),\n        (0x3311, \"M\", \"ギニー\"),\n        (0x3312, \"M\", \"キュリー\"),\n        (0x3313, \"M\", \"ギルダー\"),\n        (0x3314, \"M\", \"キロ\"),\n        (0x3315, \"M\", \"キログラム\"),\n        (0x3316, \"M\", \"キロメートル\"),\n        (0x3317, \"M\", \"キロワット\"),\n        (0x3318, \"M\", \"グラム\"),\n        (0x3319, \"M\", \"グラムトン\"),\n        (0x331A, \"M\", \"クルゼイロ\"),\n        (0x331B, \"M\", \"クローネ\"),\n        (0x331C, \"M\", \"ケース\"),\n        (0x331D, \"M\", \"コルナ\"),\n        (0x331E, \"M\", \"コーポ\"),\n        (0x331F, \"M\", \"サイクル\"),\n        (0x3320, \"M\", \"サンチーム\"),\n        (0x3321, \"M\", \"シリング\"),\n        (0x3322, \"M\", \"センチ\"),\n        (0x3323, \"M\", \"セント\"),\n        (0x3324, \"M\", \"ダース\"),\n        (0x3325, \"M\", \"デシ\"),\n        (0x3326, \"M\", \"ドル\"),\n        (0x3327, \"M\", \"トン\"),\n        (0x3328, \"M\", \"ナノ\"),\n        (0x3329, \"M\", \"ノット\"),\n        (0x332A, \"M\", \"ハイツ\"),\n        (0x332B, \"M\", \"パーセント\"),\n        (0x332C, \"M\", \"パーツ\"),\n        (0x332D, \"M\", \"バーレル\"),\n        (0x332E, \"M\", \"ピアストル\"),\n        (0x332F, \"M\", \"ピクル\"),\n        (0x3330, \"M\", \"ピコ\"),\n        (0x3331, \"M\", \"ビル\"),\n        (0x3332, \"M\", \"ファラッド\"),\n        (0x3333, \"M\", \"フィート\"),\n        (0x3334, \"M\", \"ブッシェル\"),\n        (0x3335, \"M\", \"フラン\"),\n        (0x3336, \"M\", \"ヘクタール\"),\n        (0x3337, \"M\", \"ペソ\"),\n        (0x3338, \"M\", \"ペニヒ\"),\n        (0x3339, \"M\", \"ヘルツ\"),\n        (0x333A, \"M\", \"ペンス\"),\n        (0x333B, \"M\", \"ページ\"),\n        (0x333C, \"M\", \"ベータ\"),\n        (0x333D, \"M\", \"ポイント\"),\n        (0x333E, \"M\", \"ボルト\"),\n        (0x333F, \"M\", \"ホン\"),\n        (0x3340, \"M\", \"ポンド\"),\n        (0x3341, \"M\", \"ホール\"),\n        (0x3342, \"M\", \"ホーン\"),\n        (0x3343, \"M\", \"マイクロ\"),\n        (0x3344, \"M\", \"マイル\"),\n        (0x3345, \"M\", \"マッハ\"),\n        (0x3346, \"M\", \"マルク\"),\n        (0x3347, \"M\", \"マンション\"),\n        (0x3348, \"M\", \"ミクロン\"),\n        (0x3349, \"M\", \"ミリ\"),\n        (0x334A, \"M\", \"ミリバール\"),\n        (0x334B, \"M\", \"メガ\"),\n        (0x334C, \"M\", \"メガトン\"),\n        (0x334D, \"M\", \"メートル\"),\n        (0x334E, \"M\", \"ヤード\"),\n        (0x334F, \"M\", \"ヤール\"),\n        (0x3350, \"M\", \"ユアン\"),\n        (0x3351, \"M\", \"リットル\"),\n        (0x3352, \"M\", \"リラ\"),\n        (0x3353, \"M\", \"ルピー\"),\n        (0x3354, \"M\", \"ルーブル\"),\n        (0x3355, \"M\", \"レム\"),\n        (0x3356, \"M\", \"レントゲン\"),\n        (0x3357, \"M\", \"ワット\"),\n        (0x3358, \"M\", \"0点\"),\n        (0x3359, \"M\", \"1点\"),\n        (0x335A, \"M\", \"2点\"),\n        (0x335B, \"M\", \"3点\"),\n        (0x335C, \"M\", \"4点\"),\n    ]\n\n\ndef _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x335D, \"M\", \"5点\"),\n        (0x335E, \"M\", \"6点\"),\n        (0x335F, \"M\", \"7点\"),\n        (0x3360, \"M\", \"8点\"),\n        (0x3361, \"M\", \"9点\"),\n        (0x3362, \"M\", \"10点\"),\n        (0x3363, \"M\", \"11点\"),\n        (0x3364, \"M\", \"12点\"),\n        (0x3365, \"M\", \"13点\"),\n        (0x3366, \"M\", \"14点\"),\n        (0x3367, \"M\", \"15点\"),\n        (0x3368, \"M\", \"16点\"),\n        (0x3369, \"M\", \"17点\"),\n        (0x336A, \"M\", \"18点\"),\n        (0x336B, \"M\", \"19点\"),\n        (0x336C, \"M\", \"20点\"),\n        (0x336D, \"M\", \"21点\"),\n        (0x336E, \"M\", \"22点\"),\n        (0x336F, \"M\", \"23点\"),\n        (0x3370, \"M\", \"24点\"),\n        (0x3371, \"M\", \"hpa\"),\n        (0x3372, \"M\", \"da\"),\n        (0x3373, \"M\", \"au\"),\n        (0x3374, \"M\", \"bar\"),\n        (0x3375, \"M\", \"ov\"),\n        (0x3376, \"M\", \"pc\"),\n        (0x3377, \"M\", \"dm\"),\n        (0x3378, \"M\", \"dm2\"),\n        (0x3379, \"M\", \"dm3\"),\n        (0x337A, \"M\", \"iu\"),\n        (0x337B, \"M\", \"平成\"),\n        (0x337C, \"M\", \"昭和\"),\n        (0x337D, \"M\", \"大正\"),\n        (0x337E, \"M\", \"明治\"),\n        (0x337F, \"M\", \"株式会社\"),\n        (0x3380, \"M\", \"pa\"),\n        (0x3381, \"M\", \"na\"),\n        (0x3382, \"M\", \"μa\"),\n        (0x3383, \"M\", \"ma\"),\n        (0x3384, \"M\", \"ka\"),\n        (0x3385, \"M\", \"kb\"),\n        (0x3386, \"M\", \"mb\"),\n        (0x3387, \"M\", \"gb\"),\n        (0x3388, \"M\", \"cal\"),\n        (0x3389, \"M\", \"kcal\"),\n        (0x338A, \"M\", \"pf\"),\n        (0x338B, \"M\", \"nf\"),\n        (0x338C, \"M\", \"μf\"),\n        (0x338D, \"M\", \"μg\"),\n        (0x338E, \"M\", \"mg\"),\n        (0x338F, \"M\", \"kg\"),\n        (0x3390, \"M\", \"hz\"),\n        (0x3391, \"M\", \"khz\"),\n        (0x3392, \"M\", \"mhz\"),\n        (0x3393, \"M\", \"ghz\"),\n        (0x3394, \"M\", \"thz\"),\n        (0x3395, \"M\", \"μl\"),\n        (0x3396, \"M\", \"ml\"),\n        (0x3397, \"M\", \"dl\"),\n        (0x3398, \"M\", \"kl\"),\n        (0x3399, \"M\", \"fm\"),\n        (0x339A, \"M\", \"nm\"),\n        (0x339B, \"M\", \"μm\"),\n        (0x339C, \"M\", \"mm\"),\n        (0x339D, \"M\", \"cm\"),\n        (0x339E, \"M\", \"km\"),\n        (0x339F, \"M\", \"mm2\"),\n        (0x33A0, \"M\", \"cm2\"),\n        (0x33A1, \"M\", \"m2\"),\n        (0x33A2, \"M\", \"km2\"),\n        (0x33A3, \"M\", \"mm3\"),\n        (0x33A4, \"M\", \"cm3\"),\n        (0x33A5, \"M\", \"m3\"),\n        (0x33A6, \"M\", \"km3\"),\n        (0x33A7, \"M\", \"m∕s\"),\n        (0x33A8, \"M\", \"m∕s2\"),\n        (0x33A9, \"M\", \"pa\"),\n        (0x33AA, \"M\", \"kpa\"),\n        (0x33AB, \"M\", \"mpa\"),\n        (0x33AC, \"M\", \"gpa\"),\n        (0x33AD, \"M\", \"rad\"),\n        (0x33AE, \"M\", \"rad∕s\"),\n        (0x33AF, \"M\", \"rad∕s2\"),\n        (0x33B0, \"M\", \"ps\"),\n        (0x33B1, \"M\", \"ns\"),\n        (0x33B2, \"M\", \"μs\"),\n        (0x33B3, \"M\", \"ms\"),\n        (0x33B4, \"M\", \"pv\"),\n        (0x33B5, \"M\", \"nv\"),\n        (0x33B6, \"M\", \"μv\"),\n        (0x33B7, \"M\", \"mv\"),\n        (0x33B8, \"M\", \"kv\"),\n        (0x33B9, \"M\", \"mv\"),\n        (0x33BA, \"M\", \"pw\"),\n        (0x33BB, \"M\", \"nw\"),\n        (0x33BC, \"M\", \"μw\"),\n        (0x33BD, \"M\", \"mw\"),\n        (0x33BE, \"M\", \"kw\"),\n        (0x33BF, \"M\", \"mw\"),\n        (0x33C0, \"M\", \"kω\"),\n    ]\n\n\ndef _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x33C1, \"M\", \"mω\"),\n        (0x33C2, \"X\"),\n        (0x33C3, \"M\", \"bq\"),\n        (0x33C4, \"M\", \"cc\"),\n        (0x33C5, \"M\", \"cd\"),\n        (0x33C6, \"M\", \"c∕kg\"),\n        (0x33C7, \"X\"),\n        (0x33C8, \"M\", \"db\"),\n        (0x33C9, \"M\", \"gy\"),\n        (0x33CA, \"M\", \"ha\"),\n        (0x33CB, \"M\", \"hp\"),\n        (0x33CC, \"M\", \"in\"),\n        (0x33CD, \"M\", \"kk\"),\n        (0x33CE, \"M\", \"km\"),\n        (0x33CF, \"M\", \"kt\"),\n        (0x33D0, \"M\", \"lm\"),\n        (0x33D1, \"M\", \"ln\"),\n        (0x33D2, \"M\", \"log\"),\n        (0x33D3, \"M\", \"lx\"),\n        (0x33D4, \"M\", \"mb\"),\n        (0x33D5, \"M\", \"mil\"),\n        (0x33D6, \"M\", \"mol\"),\n        (0x33D7, \"M\", \"ph\"),\n        (0x33D8, \"X\"),\n        (0x33D9, \"M\", \"ppm\"),\n        (0x33DA, \"M\", \"pr\"),\n        (0x33DB, \"M\", \"sr\"),\n        (0x33DC, \"M\", \"sv\"),\n        (0x33DD, \"M\", \"wb\"),\n        (0x33DE, \"M\", \"v∕m\"),\n        (0x33DF, \"M\", \"a∕m\"),\n        (0x33E0, \"M\", \"1日\"),\n        (0x33E1, \"M\", \"2日\"),\n        (0x33E2, \"M\", \"3日\"),\n        (0x33E3, \"M\", \"4日\"),\n        (0x33E4, \"M\", \"5日\"),\n        (0x33E5, \"M\", \"6日\"),\n        (0x33E6, \"M\", \"7日\"),\n        (0x33E7, \"M\", \"8日\"),\n        (0x33E8, \"M\", \"9日\"),\n        (0x33E9, \"M\", \"10日\"),\n        (0x33EA, \"M\", \"11日\"),\n        (0x33EB, \"M\", \"12日\"),\n        (0x33EC, \"M\", \"13日\"),\n        (0x33ED, \"M\", \"14日\"),\n        (0x33EE, \"M\", \"15日\"),\n        (0x33EF, \"M\", \"16日\"),\n        (0x33F0, \"M\", \"17日\"),\n        (0x33F1, \"M\", \"18日\"),\n        (0x33F2, \"M\", \"19日\"),\n        (0x33F3, \"M\", \"20日\"),\n        (0x33F4, \"M\", \"21日\"),\n        (0x33F5, \"M\", \"22日\"),\n        (0x33F6, \"M\", \"23日\"),\n        (0x33F7, \"M\", \"24日\"),\n        (0x33F8, \"M\", \"25日\"),\n        (0x33F9, \"M\", \"26日\"),\n        (0x33FA, \"M\", \"27日\"),\n        (0x33FB, \"M\", \"28日\"),\n        (0x33FC, \"M\", \"29日\"),\n        (0x33FD, \"M\", \"30日\"),\n        (0x33FE, \"M\", \"31日\"),\n        (0x33FF, \"M\", \"gal\"),\n        (0x3400, \"V\"),\n        (0xA48D, \"X\"),\n        (0xA490, \"V\"),\n        (0xA4C7, \"X\"),\n        (0xA4D0, \"V\"),\n        (0xA62C, \"X\"),\n        (0xA640, \"M\", \"ꙁ\"),\n        (0xA641, \"V\"),\n        (0xA642, \"M\", \"ꙃ\"),\n        (0xA643, \"V\"),\n        (0xA644, \"M\", \"ꙅ\"),\n        (0xA645, \"V\"),\n        (0xA646, \"M\", \"ꙇ\"),\n        (0xA647, \"V\"),\n        (0xA648, \"M\", \"ꙉ\"),\n        (0xA649, \"V\"),\n        (0xA64A, \"M\", \"ꙋ\"),\n        (0xA64B, \"V\"),\n        (0xA64C, \"M\", \"ꙍ\"),\n        (0xA64D, \"V\"),\n        (0xA64E, \"M\", \"ꙏ\"),\n        (0xA64F, \"V\"),\n        (0xA650, \"M\", \"ꙑ\"),\n        (0xA651, \"V\"),\n        (0xA652, \"M\", \"ꙓ\"),\n        (0xA653, \"V\"),\n        (0xA654, \"M\", \"ꙕ\"),\n        (0xA655, \"V\"),\n        (0xA656, \"M\", \"ꙗ\"),\n        (0xA657, \"V\"),\n        (0xA658, \"M\", \"ꙙ\"),\n        (0xA659, \"V\"),\n        (0xA65A, \"M\", \"ꙛ\"),\n        (0xA65B, \"V\"),\n        (0xA65C, \"M\", \"ꙝ\"),\n        (0xA65D, \"V\"),\n        (0xA65E, \"M\", \"ꙟ\"),\n    ]\n\n\ndef _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xA65F, \"V\"),\n        (0xA660, \"M\", \"ꙡ\"),\n        (0xA661, \"V\"),\n        (0xA662, \"M\", \"ꙣ\"),\n        (0xA663, \"V\"),\n        (0xA664, \"M\", \"ꙥ\"),\n        (0xA665, \"V\"),\n        (0xA666, \"M\", \"ꙧ\"),\n        (0xA667, \"V\"),\n        (0xA668, \"M\", \"ꙩ\"),\n        (0xA669, \"V\"),\n        (0xA66A, \"M\", \"ꙫ\"),\n        (0xA66B, \"V\"),\n        (0xA66C, \"M\", \"ꙭ\"),\n        (0xA66D, \"V\"),\n        (0xA680, \"M\", \"ꚁ\"),\n        (0xA681, \"V\"),\n        (0xA682, \"M\", \"ꚃ\"),\n        (0xA683, \"V\"),\n        (0xA684, \"M\", \"ꚅ\"),\n        (0xA685, \"V\"),\n        (0xA686, \"M\", \"ꚇ\"),\n        (0xA687, \"V\"),\n        (0xA688, \"M\", \"ꚉ\"),\n        (0xA689, \"V\"),\n        (0xA68A, \"M\", \"ꚋ\"),\n        (0xA68B, \"V\"),\n        (0xA68C, \"M\", \"ꚍ\"),\n        (0xA68D, \"V\"),\n        (0xA68E, \"M\", \"ꚏ\"),\n        (0xA68F, \"V\"),\n        (0xA690, \"M\", \"ꚑ\"),\n        (0xA691, \"V\"),\n        (0xA692, \"M\", \"ꚓ\"),\n        (0xA693, \"V\"),\n        (0xA694, \"M\", \"ꚕ\"),\n        (0xA695, \"V\"),\n        (0xA696, \"M\", \"ꚗ\"),\n        (0xA697, \"V\"),\n        (0xA698, \"M\", \"ꚙ\"),\n        (0xA699, \"V\"),\n        (0xA69A, \"M\", \"ꚛ\"),\n        (0xA69B, \"V\"),\n        (0xA69C, \"M\", \"ъ\"),\n        (0xA69D, \"M\", \"ь\"),\n        (0xA69E, \"V\"),\n        (0xA6F8, \"X\"),\n        (0xA700, \"V\"),\n        (0xA722, \"M\", \"ꜣ\"),\n        (0xA723, \"V\"),\n        (0xA724, \"M\", \"ꜥ\"),\n        (0xA725, \"V\"),\n        (0xA726, \"M\", \"ꜧ\"),\n        (0xA727, \"V\"),\n        (0xA728, \"M\", \"ꜩ\"),\n        (0xA729, \"V\"),\n        (0xA72A, \"M\", \"ꜫ\"),\n        (0xA72B, \"V\"),\n        (0xA72C, \"M\", \"ꜭ\"),\n        (0xA72D, \"V\"),\n        (0xA72E, \"M\", \"ꜯ\"),\n        (0xA72F, \"V\"),\n        (0xA732, \"M\", \"ꜳ\"),\n        (0xA733, \"V\"),\n        (0xA734, \"M\", \"ꜵ\"),\n        (0xA735, \"V\"),\n        (0xA736, \"M\", \"ꜷ\"),\n        (0xA737, \"V\"),\n        (0xA738, \"M\", \"ꜹ\"),\n        (0xA739, \"V\"),\n        (0xA73A, \"M\", \"ꜻ\"),\n        (0xA73B, \"V\"),\n        (0xA73C, \"M\", \"ꜽ\"),\n        (0xA73D, \"V\"),\n        (0xA73E, \"M\", \"ꜿ\"),\n        (0xA73F, \"V\"),\n        (0xA740, \"M\", \"ꝁ\"),\n        (0xA741, \"V\"),\n        (0xA742, \"M\", \"ꝃ\"),\n        (0xA743, \"V\"),\n        (0xA744, \"M\", \"ꝅ\"),\n        (0xA745, \"V\"),\n        (0xA746, \"M\", \"ꝇ\"),\n        (0xA747, \"V\"),\n        (0xA748, \"M\", \"ꝉ\"),\n        (0xA749, \"V\"),\n        (0xA74A, \"M\", \"ꝋ\"),\n        (0xA74B, \"V\"),\n        (0xA74C, \"M\", \"ꝍ\"),\n        (0xA74D, \"V\"),\n        (0xA74E, \"M\", \"ꝏ\"),\n        (0xA74F, \"V\"),\n        (0xA750, \"M\", \"ꝑ\"),\n        (0xA751, \"V\"),\n        (0xA752, \"M\", \"ꝓ\"),\n        (0xA753, \"V\"),\n        (0xA754, \"M\", \"ꝕ\"),\n        (0xA755, \"V\"),\n        (0xA756, \"M\", \"ꝗ\"),\n        (0xA757, \"V\"),\n    ]\n\n\ndef _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xA758, \"M\", \"ꝙ\"),\n        (0xA759, \"V\"),\n        (0xA75A, \"M\", \"ꝛ\"),\n        (0xA75B, \"V\"),\n        (0xA75C, \"M\", \"ꝝ\"),\n        (0xA75D, \"V\"),\n        (0xA75E, \"M\", \"ꝟ\"),\n        (0xA75F, \"V\"),\n        (0xA760, \"M\", \"ꝡ\"),\n        (0xA761, \"V\"),\n        (0xA762, \"M\", \"ꝣ\"),\n        (0xA763, \"V\"),\n        (0xA764, \"M\", \"ꝥ\"),\n        (0xA765, \"V\"),\n        (0xA766, \"M\", \"ꝧ\"),\n        (0xA767, \"V\"),\n        (0xA768, \"M\", \"ꝩ\"),\n        (0xA769, \"V\"),\n        (0xA76A, \"M\", \"ꝫ\"),\n        (0xA76B, \"V\"),\n        (0xA76C, \"M\", \"ꝭ\"),\n        (0xA76D, \"V\"),\n        (0xA76E, \"M\", \"ꝯ\"),\n        (0xA76F, \"V\"),\n        (0xA770, \"M\", \"ꝯ\"),\n        (0xA771, \"V\"),\n        (0xA779, \"M\", \"ꝺ\"),\n        (0xA77A, \"V\"),\n        (0xA77B, \"M\", \"ꝼ\"),\n        (0xA77C, \"V\"),\n        (0xA77D, \"M\", \"ᵹ\"),\n        (0xA77E, \"M\", \"ꝿ\"),\n        (0xA77F, \"V\"),\n        (0xA780, \"M\", \"ꞁ\"),\n        (0xA781, \"V\"),\n        (0xA782, \"M\", \"ꞃ\"),\n        (0xA783, \"V\"),\n        (0xA784, \"M\", \"ꞅ\"),\n        (0xA785, \"V\"),\n        (0xA786, \"M\", \"ꞇ\"),\n        (0xA787, \"V\"),\n        (0xA78B, \"M\", \"ꞌ\"),\n        (0xA78C, \"V\"),\n        (0xA78D, \"M\", \"ɥ\"),\n        (0xA78E, \"V\"),\n        (0xA790, \"M\", \"ꞑ\"),\n        (0xA791, \"V\"),\n        (0xA792, \"M\", \"ꞓ\"),\n        (0xA793, \"V\"),\n        (0xA796, \"M\", \"ꞗ\"),\n        (0xA797, \"V\"),\n        (0xA798, \"M\", \"ꞙ\"),\n        (0xA799, \"V\"),\n        (0xA79A, \"M\", \"ꞛ\"),\n        (0xA79B, \"V\"),\n        (0xA79C, \"M\", \"ꞝ\"),\n        (0xA79D, \"V\"),\n        (0xA79E, \"M\", \"ꞟ\"),\n        (0xA79F, \"V\"),\n        (0xA7A0, \"M\", \"ꞡ\"),\n        (0xA7A1, \"V\"),\n        (0xA7A2, \"M\", \"ꞣ\"),\n        (0xA7A3, \"V\"),\n        (0xA7A4, \"M\", \"ꞥ\"),\n        (0xA7A5, \"V\"),\n        (0xA7A6, \"M\", \"ꞧ\"),\n        (0xA7A7, \"V\"),\n        (0xA7A8, \"M\", \"ꞩ\"),\n        (0xA7A9, \"V\"),\n        (0xA7AA, \"M\", \"ɦ\"),\n        (0xA7AB, \"M\", \"ɜ\"),\n        (0xA7AC, \"M\", \"ɡ\"),\n        (0xA7AD, \"M\", \"ɬ\"),\n        (0xA7AE, \"M\", \"ɪ\"),\n        (0xA7AF, \"V\"),\n        (0xA7B0, \"M\", \"ʞ\"),\n        (0xA7B1, \"M\", \"ʇ\"),\n        (0xA7B2, \"M\", \"ʝ\"),\n        (0xA7B3, \"M\", \"ꭓ\"),\n        (0xA7B4, \"M\", \"ꞵ\"),\n        (0xA7B5, \"V\"),\n        (0xA7B6, \"M\", \"ꞷ\"),\n        (0xA7B7, \"V\"),\n        (0xA7B8, \"M\", \"ꞹ\"),\n        (0xA7B9, \"V\"),\n        (0xA7BA, \"M\", \"ꞻ\"),\n        (0xA7BB, \"V\"),\n        (0xA7BC, \"M\", \"ꞽ\"),\n        (0xA7BD, \"V\"),\n        (0xA7BE, \"M\", \"ꞿ\"),\n        (0xA7BF, \"V\"),\n        (0xA7C0, \"M\", \"ꟁ\"),\n        (0xA7C1, \"V\"),\n        (0xA7C2, \"M\", \"ꟃ\"),\n        (0xA7C3, \"V\"),\n        (0xA7C4, \"M\", \"ꞔ\"),\n        (0xA7C5, \"M\", \"ʂ\"),\n        (0xA7C6, \"M\", \"ᶎ\"),\n        (0xA7C7, \"M\", \"ꟈ\"),\n        (0xA7C8, \"V\"),\n    ]\n\n\ndef _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xA7C9, \"M\", \"ꟊ\"),\n        (0xA7CA, \"V\"),\n        (0xA7CB, \"M\", \"ɤ\"),\n        (0xA7CC, \"M\", \"ꟍ\"),\n        (0xA7CD, \"V\"),\n        (0xA7CE, \"X\"),\n        (0xA7D0, \"M\", \"ꟑ\"),\n        (0xA7D1, \"V\"),\n        (0xA7D2, \"X\"),\n        (0xA7D3, \"V\"),\n        (0xA7D4, \"X\"),\n        (0xA7D5, \"V\"),\n        (0xA7D6, \"M\", \"ꟗ\"),\n        (0xA7D7, \"V\"),\n        (0xA7D8, \"M\", \"ꟙ\"),\n        (0xA7D9, \"V\"),\n        (0xA7DA, \"M\", \"ꟛ\"),\n        (0xA7DB, \"V\"),\n        (0xA7DC, \"M\", \"ƛ\"),\n        (0xA7DD, \"X\"),\n        (0xA7F2, \"M\", \"c\"),\n        (0xA7F3, \"M\", \"f\"),\n        (0xA7F4, \"M\", \"q\"),\n        (0xA7F5, \"M\", \"ꟶ\"),\n        (0xA7F6, \"V\"),\n        (0xA7F8, \"M\", \"ħ\"),\n        (0xA7F9, \"M\", \"œ\"),\n        (0xA7FA, \"V\"),\n        (0xA82D, \"X\"),\n        (0xA830, \"V\"),\n        (0xA83A, \"X\"),\n        (0xA840, \"V\"),\n        (0xA878, \"X\"),\n        (0xA880, \"V\"),\n        (0xA8C6, \"X\"),\n        (0xA8CE, \"V\"),\n        (0xA8DA, \"X\"),\n        (0xA8E0, \"V\"),\n        (0xA954, \"X\"),\n        (0xA95F, \"V\"),\n        (0xA97D, \"X\"),\n        (0xA980, \"V\"),\n        (0xA9CE, \"X\"),\n        (0xA9CF, \"V\"),\n        (0xA9DA, \"X\"),\n        (0xA9DE, \"V\"),\n        (0xA9FF, \"X\"),\n        (0xAA00, \"V\"),\n        (0xAA37, \"X\"),\n        (0xAA40, \"V\"),\n        (0xAA4E, \"X\"),\n        (0xAA50, \"V\"),\n        (0xAA5A, \"X\"),\n        (0xAA5C, \"V\"),\n        (0xAAC3, \"X\"),\n        (0xAADB, \"V\"),\n        (0xAAF7, \"X\"),\n        (0xAB01, \"V\"),\n        (0xAB07, \"X\"),\n        (0xAB09, \"V\"),\n        (0xAB0F, \"X\"),\n        (0xAB11, \"V\"),\n        (0xAB17, \"X\"),\n        (0xAB20, \"V\"),\n        (0xAB27, \"X\"),\n        (0xAB28, \"V\"),\n        (0xAB2F, \"X\"),\n        (0xAB30, \"V\"),\n        (0xAB5C, \"M\", \"ꜧ\"),\n        (0xAB5D, \"M\", \"ꬷ\"),\n        (0xAB5E, \"M\", \"ɫ\"),\n        (0xAB5F, \"M\", \"ꭒ\"),\n        (0xAB60, \"V\"),\n        (0xAB69, \"M\", \"ʍ\"),\n        (0xAB6A, \"V\"),\n        (0xAB6C, \"X\"),\n        (0xAB70, \"M\", \"Ꭰ\"),\n        (0xAB71, \"M\", \"Ꭱ\"),\n        (0xAB72, \"M\", \"Ꭲ\"),\n        (0xAB73, \"M\", \"Ꭳ\"),\n        (0xAB74, \"M\", \"Ꭴ\"),\n        (0xAB75, \"M\", \"Ꭵ\"),\n        (0xAB76, \"M\", \"Ꭶ\"),\n        (0xAB77, \"M\", \"Ꭷ\"),\n        (0xAB78, \"M\", \"Ꭸ\"),\n        (0xAB79, \"M\", \"Ꭹ\"),\n        (0xAB7A, \"M\", \"Ꭺ\"),\n        (0xAB7B, \"M\", \"Ꭻ\"),\n        (0xAB7C, \"M\", \"Ꭼ\"),\n        (0xAB7D, \"M\", \"Ꭽ\"),\n        (0xAB7E, \"M\", \"Ꭾ\"),\n        (0xAB7F, \"M\", \"Ꭿ\"),\n        (0xAB80, \"M\", \"Ꮀ\"),\n        (0xAB81, \"M\", \"Ꮁ\"),\n        (0xAB82, \"M\", \"Ꮂ\"),\n        (0xAB83, \"M\", \"Ꮃ\"),\n        (0xAB84, \"M\", \"Ꮄ\"),\n        (0xAB85, \"M\", \"Ꮅ\"),\n        (0xAB86, \"M\", \"Ꮆ\"),\n        (0xAB87, \"M\", \"Ꮇ\"),\n    ]\n\n\ndef _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xAB88, \"M\", \"Ꮈ\"),\n        (0xAB89, \"M\", \"Ꮉ\"),\n        (0xAB8A, \"M\", \"Ꮊ\"),\n        (0xAB8B, \"M\", \"Ꮋ\"),\n        (0xAB8C, \"M\", \"Ꮌ\"),\n        (0xAB8D, \"M\", \"Ꮍ\"),\n        (0xAB8E, \"M\", \"Ꮎ\"),\n        (0xAB8F, \"M\", \"Ꮏ\"),\n        (0xAB90, \"M\", \"Ꮐ\"),\n        (0xAB91, \"M\", \"Ꮑ\"),\n        (0xAB92, \"M\", \"Ꮒ\"),\n        (0xAB93, \"M\", \"Ꮓ\"),\n        (0xAB94, \"M\", \"Ꮔ\"),\n        (0xAB95, \"M\", \"Ꮕ\"),\n        (0xAB96, \"M\", \"Ꮖ\"),\n        (0xAB97, \"M\", \"Ꮗ\"),\n        (0xAB98, \"M\", \"Ꮘ\"),\n        (0xAB99, \"M\", \"Ꮙ\"),\n        (0xAB9A, \"M\", \"Ꮚ\"),\n        (0xAB9B, \"M\", \"Ꮛ\"),\n        (0xAB9C, \"M\", \"Ꮜ\"),\n        (0xAB9D, \"M\", \"Ꮝ\"),\n        (0xAB9E, \"M\", \"Ꮞ\"),\n        (0xAB9F, \"M\", \"Ꮟ\"),\n        (0xABA0, \"M\", \"Ꮠ\"),\n        (0xABA1, \"M\", \"Ꮡ\"),\n        (0xABA2, \"M\", \"Ꮢ\"),\n        (0xABA3, \"M\", \"Ꮣ\"),\n        (0xABA4, \"M\", \"Ꮤ\"),\n        (0xABA5, \"M\", \"Ꮥ\"),\n        (0xABA6, \"M\", \"Ꮦ\"),\n        (0xABA7, \"M\", \"Ꮧ\"),\n        (0xABA8, \"M\", \"Ꮨ\"),\n        (0xABA9, \"M\", \"Ꮩ\"),\n        (0xABAA, \"M\", \"Ꮪ\"),\n        (0xABAB, \"M\", \"Ꮫ\"),\n        (0xABAC, \"M\", \"Ꮬ\"),\n        (0xABAD, \"M\", \"Ꮭ\"),\n        (0xABAE, \"M\", \"Ꮮ\"),\n        (0xABAF, \"M\", \"Ꮯ\"),\n        (0xABB0, \"M\", \"Ꮰ\"),\n        (0xABB1, \"M\", \"Ꮱ\"),\n        (0xABB2, \"M\", \"Ꮲ\"),\n        (0xABB3, \"M\", \"Ꮳ\"),\n        (0xABB4, \"M\", \"Ꮴ\"),\n        (0xABB5, \"M\", \"Ꮵ\"),\n        (0xABB6, \"M\", \"Ꮶ\"),\n        (0xABB7, \"M\", \"Ꮷ\"),\n        (0xABB8, \"M\", \"Ꮸ\"),\n        (0xABB9, \"M\", \"Ꮹ\"),\n        (0xABBA, \"M\", \"Ꮺ\"),\n        (0xABBB, \"M\", \"Ꮻ\"),\n        (0xABBC, \"M\", \"Ꮼ\"),\n        (0xABBD, \"M\", \"Ꮽ\"),\n        (0xABBE, \"M\", \"Ꮾ\"),\n        (0xABBF, \"M\", \"Ꮿ\"),\n        (0xABC0, \"V\"),\n        (0xABEE, \"X\"),\n        (0xABF0, \"V\"),\n        (0xABFA, \"X\"),\n        (0xAC00, \"V\"),\n        (0xD7A4, \"X\"),\n        (0xD7B0, \"V\"),\n        (0xD7C7, \"X\"),\n        (0xD7CB, \"V\"),\n        (0xD7FC, \"X\"),\n        (0xF900, \"M\", \"豈\"),\n        (0xF901, \"M\", \"更\"),\n        (0xF902, \"M\", \"車\"),\n        (0xF903, \"M\", \"賈\"),\n        (0xF904, \"M\", \"滑\"),\n        (0xF905, \"M\", \"串\"),\n        (0xF906, \"M\", \"句\"),\n        (0xF907, \"M\", \"龜\"),\n        (0xF909, \"M\", \"契\"),\n        (0xF90A, \"M\", \"金\"),\n        (0xF90B, \"M\", \"喇\"),\n        (0xF90C, \"M\", \"奈\"),\n        (0xF90D, \"M\", \"懶\"),\n        (0xF90E, \"M\", \"癩\"),\n        (0xF90F, \"M\", \"羅\"),\n        (0xF910, \"M\", \"蘿\"),\n        (0xF911, \"M\", \"螺\"),\n        (0xF912, \"M\", \"裸\"),\n        (0xF913, \"M\", \"邏\"),\n        (0xF914, \"M\", \"樂\"),\n        (0xF915, \"M\", \"洛\"),\n        (0xF916, \"M\", \"烙\"),\n        (0xF917, \"M\", \"珞\"),\n        (0xF918, \"M\", \"落\"),\n        (0xF919, \"M\", \"酪\"),\n        (0xF91A, \"M\", \"駱\"),\n        (0xF91B, \"M\", \"亂\"),\n        (0xF91C, \"M\", \"卵\"),\n        (0xF91D, \"M\", \"欄\"),\n        (0xF91E, \"M\", \"爛\"),\n        (0xF91F, \"M\", \"蘭\"),\n        (0xF920, \"M\", \"鸞\"),\n        (0xF921, \"M\", \"嵐\"),\n        (0xF922, \"M\", \"濫\"),\n    ]\n\n\ndef _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xF923, \"M\", \"藍\"),\n        (0xF924, \"M\", \"襤\"),\n        (0xF925, \"M\", \"拉\"),\n        (0xF926, \"M\", \"臘\"),\n        (0xF927, \"M\", \"蠟\"),\n        (0xF928, \"M\", \"廊\"),\n        (0xF929, \"M\", \"朗\"),\n        (0xF92A, \"M\", \"浪\"),\n        (0xF92B, \"M\", \"狼\"),\n        (0xF92C, \"M\", \"郎\"),\n        (0xF92D, \"M\", \"來\"),\n        (0xF92E, \"M\", \"冷\"),\n        (0xF92F, \"M\", \"勞\"),\n        (0xF930, \"M\", \"擄\"),\n        (0xF931, \"M\", \"櫓\"),\n        (0xF932, \"M\", \"爐\"),\n        (0xF933, \"M\", \"盧\"),\n        (0xF934, \"M\", \"老\"),\n        (0xF935, \"M\", \"蘆\"),\n        (0xF936, \"M\", \"虜\"),\n        (0xF937, \"M\", \"路\"),\n        (0xF938, \"M\", \"露\"),\n        (0xF939, \"M\", \"魯\"),\n        (0xF93A, \"M\", \"鷺\"),\n        (0xF93B, \"M\", \"碌\"),\n        (0xF93C, \"M\", \"祿\"),\n        (0xF93D, \"M\", \"綠\"),\n        (0xF93E, \"M\", \"菉\"),\n        (0xF93F, \"M\", \"錄\"),\n        (0xF940, \"M\", \"鹿\"),\n        (0xF941, \"M\", \"論\"),\n        (0xF942, \"M\", \"壟\"),\n        (0xF943, \"M\", \"弄\"),\n        (0xF944, \"M\", \"籠\"),\n        (0xF945, \"M\", \"聾\"),\n        (0xF946, \"M\", \"牢\"),\n        (0xF947, \"M\", \"磊\"),\n        (0xF948, \"M\", \"賂\"),\n        (0xF949, \"M\", \"雷\"),\n        (0xF94A, \"M\", \"壘\"),\n        (0xF94B, \"M\", \"屢\"),\n        (0xF94C, \"M\", \"樓\"),\n        (0xF94D, \"M\", \"淚\"),\n        (0xF94E, \"M\", \"漏\"),\n        (0xF94F, \"M\", \"累\"),\n        (0xF950, \"M\", \"縷\"),\n        (0xF951, \"M\", \"陋\"),\n        (0xF952, \"M\", \"勒\"),\n        (0xF953, \"M\", \"肋\"),\n        (0xF954, \"M\", \"凜\"),\n        (0xF955, \"M\", \"凌\"),\n        (0xF956, \"M\", \"稜\"),\n        (0xF957, \"M\", \"綾\"),\n        (0xF958, \"M\", \"菱\"),\n        (0xF959, \"M\", \"陵\"),\n        (0xF95A, \"M\", \"讀\"),\n        (0xF95B, \"M\", \"拏\"),\n        (0xF95C, \"M\", \"樂\"),\n        (0xF95D, \"M\", \"諾\"),\n        (0xF95E, \"M\", \"丹\"),\n        (0xF95F, \"M\", \"寧\"),\n        (0xF960, \"M\", \"怒\"),\n        (0xF961, \"M\", \"率\"),\n        (0xF962, \"M\", \"異\"),\n        (0xF963, \"M\", \"北\"),\n        (0xF964, \"M\", \"磻\"),\n        (0xF965, \"M\", \"便\"),\n        (0xF966, \"M\", \"復\"),\n        (0xF967, \"M\", \"不\"),\n        (0xF968, \"M\", \"泌\"),\n        (0xF969, \"M\", \"數\"),\n        (0xF96A, \"M\", \"索\"),\n        (0xF96B, \"M\", \"參\"),\n        (0xF96C, \"M\", \"塞\"),\n        (0xF96D, \"M\", \"省\"),\n        (0xF96E, \"M\", \"葉\"),\n        (0xF96F, \"M\", \"說\"),\n        (0xF970, \"M\", \"殺\"),\n        (0xF971, \"M\", \"辰\"),\n        (0xF972, \"M\", \"沈\"),\n        (0xF973, \"M\", \"拾\"),\n        (0xF974, \"M\", \"若\"),\n        (0xF975, \"M\", \"掠\"),\n        (0xF976, \"M\", \"略\"),\n        (0xF977, \"M\", \"亮\"),\n        (0xF978, \"M\", \"兩\"),\n        (0xF979, \"M\", \"凉\"),\n        (0xF97A, \"M\", \"梁\"),\n        (0xF97B, \"M\", \"糧\"),\n        (0xF97C, \"M\", \"良\"),\n        (0xF97D, \"M\", \"諒\"),\n        (0xF97E, \"M\", \"量\"),\n        (0xF97F, \"M\", \"勵\"),\n        (0xF980, \"M\", \"呂\"),\n        (0xF981, \"M\", \"女\"),\n        (0xF982, \"M\", \"廬\"),\n        (0xF983, \"M\", \"旅\"),\n        (0xF984, \"M\", \"濾\"),\n        (0xF985, \"M\", \"礪\"),\n        (0xF986, \"M\", \"閭\"),\n    ]\n\n\ndef _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xF987, \"M\", \"驪\"),\n        (0xF988, \"M\", \"麗\"),\n        (0xF989, \"M\", \"黎\"),\n        (0xF98A, \"M\", \"力\"),\n        (0xF98B, \"M\", \"曆\"),\n        (0xF98C, \"M\", \"歷\"),\n        (0xF98D, \"M\", \"轢\"),\n        (0xF98E, \"M\", \"年\"),\n        (0xF98F, \"M\", \"憐\"),\n        (0xF990, \"M\", \"戀\"),\n        (0xF991, \"M\", \"撚\"),\n        (0xF992, \"M\", \"漣\"),\n        (0xF993, \"M\", \"煉\"),\n        (0xF994, \"M\", \"璉\"),\n        (0xF995, \"M\", \"秊\"),\n        (0xF996, \"M\", \"練\"),\n        (0xF997, \"M\", \"聯\"),\n        (0xF998, \"M\", \"輦\"),\n        (0xF999, \"M\", \"蓮\"),\n        (0xF99A, \"M\", \"連\"),\n        (0xF99B, \"M\", \"鍊\"),\n        (0xF99C, \"M\", \"列\"),\n        (0xF99D, \"M\", \"劣\"),\n        (0xF99E, \"M\", \"咽\"),\n        (0xF99F, \"M\", \"烈\"),\n        (0xF9A0, \"M\", \"裂\"),\n        (0xF9A1, \"M\", \"說\"),\n        (0xF9A2, \"M\", \"廉\"),\n        (0xF9A3, \"M\", \"念\"),\n        (0xF9A4, \"M\", \"捻\"),\n        (0xF9A5, \"M\", \"殮\"),\n        (0xF9A6, \"M\", \"簾\"),\n        (0xF9A7, \"M\", \"獵\"),\n        (0xF9A8, \"M\", \"令\"),\n        (0xF9A9, \"M\", \"囹\"),\n        (0xF9AA, \"M\", \"寧\"),\n        (0xF9AB, \"M\", \"嶺\"),\n        (0xF9AC, \"M\", \"怜\"),\n        (0xF9AD, \"M\", \"玲\"),\n        (0xF9AE, \"M\", \"瑩\"),\n        (0xF9AF, \"M\", \"羚\"),\n        (0xF9B0, \"M\", \"聆\"),\n        (0xF9B1, \"M\", \"鈴\"),\n        (0xF9B2, \"M\", \"零\"),\n        (0xF9B3, \"M\", \"靈\"),\n        (0xF9B4, \"M\", \"領\"),\n        (0xF9B5, \"M\", \"例\"),\n        (0xF9B6, \"M\", \"禮\"),\n        (0xF9B7, \"M\", \"醴\"),\n        (0xF9B8, \"M\", \"隸\"),\n        (0xF9B9, \"M\", \"惡\"),\n        (0xF9BA, \"M\", \"了\"),\n        (0xF9BB, \"M\", \"僚\"),\n        (0xF9BC, \"M\", \"寮\"),\n        (0xF9BD, \"M\", \"尿\"),\n        (0xF9BE, \"M\", \"料\"),\n        (0xF9BF, \"M\", \"樂\"),\n        (0xF9C0, \"M\", \"燎\"),\n        (0xF9C1, \"M\", \"療\"),\n        (0xF9C2, \"M\", \"蓼\"),\n        (0xF9C3, \"M\", \"遼\"),\n        (0xF9C4, \"M\", \"龍\"),\n        (0xF9C5, \"M\", \"暈\"),\n        (0xF9C6, \"M\", \"阮\"),\n        (0xF9C7, \"M\", \"劉\"),\n        (0xF9C8, \"M\", \"杻\"),\n        (0xF9C9, \"M\", \"柳\"),\n        (0xF9CA, \"M\", \"流\"),\n        (0xF9CB, \"M\", \"溜\"),\n        (0xF9CC, \"M\", \"琉\"),\n        (0xF9CD, \"M\", \"留\"),\n        (0xF9CE, \"M\", \"硫\"),\n        (0xF9CF, \"M\", \"紐\"),\n        (0xF9D0, \"M\", \"類\"),\n        (0xF9D1, \"M\", \"六\"),\n        (0xF9D2, \"M\", \"戮\"),\n        (0xF9D3, \"M\", \"陸\"),\n        (0xF9D4, \"M\", \"倫\"),\n        (0xF9D5, \"M\", \"崙\"),\n        (0xF9D6, \"M\", \"淪\"),\n        (0xF9D7, \"M\", \"輪\"),\n        (0xF9D8, \"M\", \"律\"),\n        (0xF9D9, \"M\", \"慄\"),\n        (0xF9DA, \"M\", \"栗\"),\n        (0xF9DB, \"M\", \"率\"),\n        (0xF9DC, \"M\", \"隆\"),\n        (0xF9DD, \"M\", \"利\"),\n        (0xF9DE, \"M\", \"吏\"),\n        (0xF9DF, \"M\", \"履\"),\n        (0xF9E0, \"M\", \"易\"),\n        (0xF9E1, \"M\", \"李\"),\n        (0xF9E2, \"M\", \"梨\"),\n        (0xF9E3, \"M\", \"泥\"),\n        (0xF9E4, \"M\", \"理\"),\n        (0xF9E5, \"M\", \"痢\"),\n        (0xF9E6, \"M\", \"罹\"),\n        (0xF9E7, \"M\", \"裏\"),\n        (0xF9E8, \"M\", \"裡\"),\n        (0xF9E9, \"M\", \"里\"),\n        (0xF9EA, \"M\", \"離\"),\n    ]\n\n\ndef _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xF9EB, \"M\", \"匿\"),\n        (0xF9EC, \"M\", \"溺\"),\n        (0xF9ED, \"M\", \"吝\"),\n        (0xF9EE, \"M\", \"燐\"),\n        (0xF9EF, \"M\", \"璘\"),\n        (0xF9F0, \"M\", \"藺\"),\n        (0xF9F1, \"M\", \"隣\"),\n        (0xF9F2, \"M\", \"鱗\"),\n        (0xF9F3, \"M\", \"麟\"),\n        (0xF9F4, \"M\", \"林\"),\n        (0xF9F5, \"M\", \"淋\"),\n        (0xF9F6, \"M\", \"臨\"),\n        (0xF9F7, \"M\", \"立\"),\n        (0xF9F8, \"M\", \"笠\"),\n        (0xF9F9, \"M\", \"粒\"),\n        (0xF9FA, \"M\", \"狀\"),\n        (0xF9FB, \"M\", \"炙\"),\n        (0xF9FC, \"M\", \"識\"),\n        (0xF9FD, \"M\", \"什\"),\n        (0xF9FE, \"M\", \"茶\"),\n        (0xF9FF, \"M\", \"刺\"),\n        (0xFA00, \"M\", \"切\"),\n        (0xFA01, \"M\", \"度\"),\n        (0xFA02, \"M\", \"拓\"),\n        (0xFA03, \"M\", \"糖\"),\n        (0xFA04, \"M\", \"宅\"),\n        (0xFA05, \"M\", \"洞\"),\n        (0xFA06, \"M\", \"暴\"),\n        (0xFA07, \"M\", \"輻\"),\n        (0xFA08, \"M\", \"行\"),\n        (0xFA09, \"M\", \"降\"),\n        (0xFA0A, \"M\", \"見\"),\n        (0xFA0B, \"M\", \"廓\"),\n        (0xFA0C, \"M\", \"兀\"),\n        (0xFA0D, \"M\", \"嗀\"),\n        (0xFA0E, \"V\"),\n        (0xFA10, \"M\", \"塚\"),\n        (0xFA11, \"V\"),\n        (0xFA12, \"M\", \"晴\"),\n        (0xFA13, \"V\"),\n        (0xFA15, \"M\", \"凞\"),\n        (0xFA16, \"M\", \"猪\"),\n        (0xFA17, \"M\", \"益\"),\n        (0xFA18, \"M\", \"礼\"),\n        (0xFA19, \"M\", \"神\"),\n        (0xFA1A, \"M\", \"祥\"),\n        (0xFA1B, \"M\", \"福\"),\n        (0xFA1C, \"M\", \"靖\"),\n        (0xFA1D, \"M\", \"精\"),\n        (0xFA1E, \"M\", \"羽\"),\n        (0xFA1F, \"V\"),\n        (0xFA20, \"M\", \"蘒\"),\n        (0xFA21, \"V\"),\n        (0xFA22, \"M\", \"諸\"),\n        (0xFA23, \"V\"),\n        (0xFA25, \"M\", \"逸\"),\n        (0xFA26, \"M\", \"都\"),\n        (0xFA27, \"V\"),\n        (0xFA2A, \"M\", \"飯\"),\n        (0xFA2B, \"M\", \"飼\"),\n        (0xFA2C, \"M\", \"館\"),\n        (0xFA2D, \"M\", \"鶴\"),\n        (0xFA2E, \"M\", \"郞\"),\n        (0xFA2F, \"M\", \"隷\"),\n        (0xFA30, \"M\", \"侮\"),\n        (0xFA31, \"M\", \"僧\"),\n        (0xFA32, \"M\", \"免\"),\n        (0xFA33, \"M\", \"勉\"),\n        (0xFA34, \"M\", \"勤\"),\n        (0xFA35, \"M\", \"卑\"),\n        (0xFA36, \"M\", \"喝\"),\n        (0xFA37, \"M\", \"嘆\"),\n        (0xFA38, \"M\", \"器\"),\n        (0xFA39, \"M\", \"塀\"),\n        (0xFA3A, \"M\", \"墨\"),\n        (0xFA3B, \"M\", \"層\"),\n        (0xFA3C, \"M\", \"屮\"),\n        (0xFA3D, \"M\", \"悔\"),\n        (0xFA3E, \"M\", \"慨\"),\n        (0xFA3F, \"M\", \"憎\"),\n        (0xFA40, \"M\", \"懲\"),\n        (0xFA41, \"M\", \"敏\"),\n        (0xFA42, \"M\", \"既\"),\n        (0xFA43, \"M\", \"暑\"),\n        (0xFA44, \"M\", \"梅\"),\n        (0xFA45, \"M\", \"海\"),\n        (0xFA46, \"M\", \"渚\"),\n        (0xFA47, \"M\", \"漢\"),\n        (0xFA48, \"M\", \"煮\"),\n        (0xFA49, \"M\", \"爫\"),\n        (0xFA4A, \"M\", \"琢\"),\n        (0xFA4B, \"M\", \"碑\"),\n        (0xFA4C, \"M\", \"社\"),\n        (0xFA4D, \"M\", \"祉\"),\n        (0xFA4E, \"M\", \"祈\"),\n        (0xFA4F, \"M\", \"祐\"),\n        (0xFA50, \"M\", \"祖\"),\n        (0xFA51, \"M\", \"祝\"),\n        (0xFA52, \"M\", \"禍\"),\n        (0xFA53, \"M\", \"禎\"),\n    ]\n\n\ndef _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFA54, \"M\", \"穀\"),\n        (0xFA55, \"M\", \"突\"),\n        (0xFA56, \"M\", \"節\"),\n        (0xFA57, \"M\", \"練\"),\n        (0xFA58, \"M\", \"縉\"),\n        (0xFA59, \"M\", \"繁\"),\n        (0xFA5A, \"M\", \"署\"),\n        (0xFA5B, \"M\", \"者\"),\n        (0xFA5C, \"M\", \"臭\"),\n        (0xFA5D, \"M\", \"艹\"),\n        (0xFA5F, \"M\", \"著\"),\n        (0xFA60, \"M\", \"褐\"),\n        (0xFA61, \"M\", \"視\"),\n        (0xFA62, \"M\", \"謁\"),\n        (0xFA63, \"M\", \"謹\"),\n        (0xFA64, \"M\", \"賓\"),\n        (0xFA65, \"M\", \"贈\"),\n        (0xFA66, \"M\", \"辶\"),\n        (0xFA67, \"M\", \"逸\"),\n        (0xFA68, \"M\", \"難\"),\n        (0xFA69, \"M\", \"響\"),\n        (0xFA6A, \"M\", \"頻\"),\n        (0xFA6B, \"M\", \"恵\"),\n        (0xFA6C, \"M\", \"𤋮\"),\n        (0xFA6D, \"M\", \"舘\"),\n        (0xFA6E, \"X\"),\n        (0xFA70, \"M\", \"並\"),\n        (0xFA71, \"M\", \"况\"),\n        (0xFA72, \"M\", \"全\"),\n        (0xFA73, \"M\", \"侀\"),\n        (0xFA74, \"M\", \"充\"),\n        (0xFA75, \"M\", \"冀\"),\n        (0xFA76, \"M\", \"勇\"),\n        (0xFA77, \"M\", \"勺\"),\n        (0xFA78, \"M\", \"喝\"),\n        (0xFA79, \"M\", \"啕\"),\n        (0xFA7A, \"M\", \"喙\"),\n        (0xFA7B, \"M\", \"嗢\"),\n        (0xFA7C, \"M\", \"塚\"),\n        (0xFA7D, \"M\", \"墳\"),\n        (0xFA7E, \"M\", \"奄\"),\n        (0xFA7F, \"M\", \"奔\"),\n        (0xFA80, \"M\", \"婢\"),\n        (0xFA81, \"M\", \"嬨\"),\n        (0xFA82, \"M\", \"廒\"),\n        (0xFA83, \"M\", \"廙\"),\n        (0xFA84, \"M\", \"彩\"),\n        (0xFA85, \"M\", \"徭\"),\n        (0xFA86, \"M\", \"惘\"),\n        (0xFA87, \"M\", \"慎\"),\n        (0xFA88, \"M\", \"愈\"),\n        (0xFA89, \"M\", \"憎\"),\n        (0xFA8A, \"M\", \"慠\"),\n        (0xFA8B, \"M\", \"懲\"),\n        (0xFA8C, \"M\", \"戴\"),\n        (0xFA8D, \"M\", \"揄\"),\n        (0xFA8E, \"M\", \"搜\"),\n        (0xFA8F, \"M\", \"摒\"),\n        (0xFA90, \"M\", \"敖\"),\n        (0xFA91, \"M\", \"晴\"),\n        (0xFA92, \"M\", \"朗\"),\n        (0xFA93, \"M\", \"望\"),\n        (0xFA94, \"M\", \"杖\"),\n        (0xFA95, \"M\", \"歹\"),\n        (0xFA96, \"M\", \"殺\"),\n        (0xFA97, \"M\", \"流\"),\n        (0xFA98, \"M\", \"滛\"),\n        (0xFA99, \"M\", \"滋\"),\n        (0xFA9A, \"M\", \"漢\"),\n        (0xFA9B, \"M\", \"瀞\"),\n        (0xFA9C, \"M\", \"煮\"),\n        (0xFA9D, \"M\", \"瞧\"),\n        (0xFA9E, \"M\", \"爵\"),\n        (0xFA9F, \"M\", \"犯\"),\n        (0xFAA0, \"M\", \"猪\"),\n        (0xFAA1, \"M\", \"瑱\"),\n        (0xFAA2, \"M\", \"甆\"),\n        (0xFAA3, \"M\", \"画\"),\n        (0xFAA4, \"M\", \"瘝\"),\n        (0xFAA5, \"M\", \"瘟\"),\n        (0xFAA6, \"M\", \"益\"),\n        (0xFAA7, \"M\", \"盛\"),\n        (0xFAA8, \"M\", \"直\"),\n        (0xFAA9, \"M\", \"睊\"),\n        (0xFAAA, \"M\", \"着\"),\n        (0xFAAB, \"M\", \"磌\"),\n        (0xFAAC, \"M\", \"窱\"),\n        (0xFAAD, \"M\", \"節\"),\n        (0xFAAE, \"M\", \"类\"),\n        (0xFAAF, \"M\", \"絛\"),\n        (0xFAB0, \"M\", \"練\"),\n        (0xFAB1, \"M\", \"缾\"),\n        (0xFAB2, \"M\", \"者\"),\n        (0xFAB3, \"M\", \"荒\"),\n        (0xFAB4, \"M\", \"華\"),\n        (0xFAB5, \"M\", \"蝹\"),\n        (0xFAB6, \"M\", \"襁\"),\n        (0xFAB7, \"M\", \"覆\"),\n        (0xFAB8, \"M\", \"視\"),\n        (0xFAB9, \"M\", \"調\"),\n    ]\n\n\ndef _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFABA, \"M\", \"諸\"),\n        (0xFABB, \"M\", \"請\"),\n        (0xFABC, \"M\", \"謁\"),\n        (0xFABD, \"M\", \"諾\"),\n        (0xFABE, \"M\", \"諭\"),\n        (0xFABF, \"M\", \"謹\"),\n        (0xFAC0, \"M\", \"變\"),\n        (0xFAC1, \"M\", \"贈\"),\n        (0xFAC2, \"M\", \"輸\"),\n        (0xFAC3, \"M\", \"遲\"),\n        (0xFAC4, \"M\", \"醙\"),\n        (0xFAC5, \"M\", \"鉶\"),\n        (0xFAC6, \"M\", \"陼\"),\n        (0xFAC7, \"M\", \"難\"),\n        (0xFAC8, \"M\", \"靖\"),\n        (0xFAC9, \"M\", \"韛\"),\n        (0xFACA, \"M\", \"響\"),\n        (0xFACB, \"M\", \"頋\"),\n        (0xFACC, \"M\", \"頻\"),\n        (0xFACD, \"M\", \"鬒\"),\n        (0xFACE, \"M\", \"龜\"),\n        (0xFACF, \"M\", \"𢡊\"),\n        (0xFAD0, \"M\", \"𢡄\"),\n        (0xFAD1, \"M\", \"𣏕\"),\n        (0xFAD2, \"M\", \"㮝\"),\n        (0xFAD3, \"M\", \"䀘\"),\n        (0xFAD4, \"M\", \"䀹\"),\n        (0xFAD5, \"M\", \"𥉉\"),\n        (0xFAD6, \"M\", \"𥳐\"),\n        (0xFAD7, \"M\", \"𧻓\"),\n        (0xFAD8, \"M\", \"齃\"),\n        (0xFAD9, \"M\", \"龎\"),\n        (0xFADA, \"X\"),\n        (0xFB00, \"M\", \"ff\"),\n        (0xFB01, \"M\", \"fi\"),\n        (0xFB02, \"M\", \"fl\"),\n        (0xFB03, \"M\", \"ffi\"),\n        (0xFB04, \"M\", \"ffl\"),\n        (0xFB05, \"M\", \"st\"),\n        (0xFB07, \"X\"),\n        (0xFB13, \"M\", \"մն\"),\n        (0xFB14, \"M\", \"մե\"),\n        (0xFB15, \"M\", \"մի\"),\n        (0xFB16, \"M\", \"վն\"),\n        (0xFB17, \"M\", \"մխ\"),\n        (0xFB18, \"X\"),\n        (0xFB1D, \"M\", \"יִ\"),\n        (0xFB1E, \"V\"),\n        (0xFB1F, \"M\", \"ײַ\"),\n        (0xFB20, \"M\", \"ע\"),\n        (0xFB21, \"M\", \"א\"),\n        (0xFB22, \"M\", \"ד\"),\n        (0xFB23, \"M\", \"ה\"),\n        (0xFB24, \"M\", \"כ\"),\n        (0xFB25, \"M\", \"ל\"),\n        (0xFB26, \"M\", \"ם\"),\n        (0xFB27, \"M\", \"ר\"),\n        (0xFB28, \"M\", \"ת\"),\n        (0xFB29, \"M\", \"+\"),\n        (0xFB2A, \"M\", \"שׁ\"),\n        (0xFB2B, \"M\", \"שׂ\"),\n        (0xFB2C, \"M\", \"שּׁ\"),\n        (0xFB2D, \"M\", \"שּׂ\"),\n        (0xFB2E, \"M\", \"אַ\"),\n        (0xFB2F, \"M\", \"אָ\"),\n        (0xFB30, \"M\", \"אּ\"),\n        (0xFB31, \"M\", \"בּ\"),\n        (0xFB32, \"M\", \"גּ\"),\n        (0xFB33, \"M\", \"דּ\"),\n        (0xFB34, \"M\", \"הּ\"),\n        (0xFB35, \"M\", \"וּ\"),\n        (0xFB36, \"M\", \"זּ\"),\n        (0xFB37, \"X\"),\n        (0xFB38, \"M\", \"טּ\"),\n        (0xFB39, \"M\", \"יּ\"),\n        (0xFB3A, \"M\", \"ךּ\"),\n        (0xFB3B, \"M\", \"כּ\"),\n        (0xFB3C, \"M\", \"לּ\"),\n        (0xFB3D, \"X\"),\n        (0xFB3E, \"M\", \"מּ\"),\n        (0xFB3F, \"X\"),\n        (0xFB40, \"M\", \"נּ\"),\n        (0xFB41, \"M\", \"סּ\"),\n        (0xFB42, \"X\"),\n        (0xFB43, \"M\", \"ףּ\"),\n        (0xFB44, \"M\", \"פּ\"),\n        (0xFB45, \"X\"),\n        (0xFB46, \"M\", \"צּ\"),\n        (0xFB47, \"M\", \"קּ\"),\n        (0xFB48, \"M\", \"רּ\"),\n        (0xFB49, \"M\", \"שּ\"),\n        (0xFB4A, \"M\", \"תּ\"),\n        (0xFB4B, \"M\", \"וֹ\"),\n        (0xFB4C, \"M\", \"בֿ\"),\n        (0xFB4D, \"M\", \"כֿ\"),\n        (0xFB4E, \"M\", \"פֿ\"),\n        (0xFB4F, \"M\", \"אל\"),\n        (0xFB50, \"M\", \"ٱ\"),\n        (0xFB52, \"M\", \"ٻ\"),\n        (0xFB56, \"M\", \"پ\"),\n    ]\n\n\ndef _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFB5A, \"M\", \"ڀ\"),\n        (0xFB5E, \"M\", \"ٺ\"),\n        (0xFB62, \"M\", \"ٿ\"),\n        (0xFB66, \"M\", \"ٹ\"),\n        (0xFB6A, \"M\", \"ڤ\"),\n        (0xFB6E, \"M\", \"ڦ\"),\n        (0xFB72, \"M\", \"ڄ\"),\n        (0xFB76, \"M\", \"ڃ\"),\n        (0xFB7A, \"M\", \"چ\"),\n        (0xFB7E, \"M\", \"ڇ\"),\n        (0xFB82, \"M\", \"ڍ\"),\n        (0xFB84, \"M\", \"ڌ\"),\n        (0xFB86, \"M\", \"ڎ\"),\n        (0xFB88, \"M\", \"ڈ\"),\n        (0xFB8A, \"M\", \"ژ\"),\n        (0xFB8C, \"M\", \"ڑ\"),\n        (0xFB8E, \"M\", \"ک\"),\n        (0xFB92, \"M\", \"گ\"),\n        (0xFB96, \"M\", \"ڳ\"),\n        (0xFB9A, \"M\", \"ڱ\"),\n        (0xFB9E, \"M\", \"ں\"),\n        (0xFBA0, \"M\", \"ڻ\"),\n        (0xFBA4, \"M\", \"ۀ\"),\n        (0xFBA6, \"M\", \"ہ\"),\n        (0xFBAA, \"M\", \"ھ\"),\n        (0xFBAE, \"M\", \"ے\"),\n        (0xFBB0, \"M\", \"ۓ\"),\n        (0xFBB2, \"V\"),\n        (0xFBC3, \"X\"),\n        (0xFBD3, \"M\", \"ڭ\"),\n        (0xFBD7, \"M\", \"ۇ\"),\n        (0xFBD9, \"M\", \"ۆ\"),\n        (0xFBDB, \"M\", \"ۈ\"),\n        (0xFBDD, \"M\", \"ۇٴ\"),\n        (0xFBDE, \"M\", \"ۋ\"),\n        (0xFBE0, \"M\", \"ۅ\"),\n        (0xFBE2, \"M\", \"ۉ\"),\n        (0xFBE4, \"M\", \"ې\"),\n        (0xFBE8, \"M\", \"ى\"),\n        (0xFBEA, \"M\", \"ئا\"),\n        (0xFBEC, \"M\", \"ئە\"),\n        (0xFBEE, \"M\", \"ئو\"),\n        (0xFBF0, \"M\", \"ئۇ\"),\n        (0xFBF2, \"M\", \"ئۆ\"),\n        (0xFBF4, \"M\", \"ئۈ\"),\n        (0xFBF6, \"M\", \"ئې\"),\n        (0xFBF9, \"M\", \"ئى\"),\n        (0xFBFC, \"M\", \"ی\"),\n        (0xFC00, \"M\", \"ئج\"),\n        (0xFC01, \"M\", \"ئح\"),\n        (0xFC02, \"M\", \"ئم\"),\n        (0xFC03, \"M\", \"ئى\"),\n        (0xFC04, \"M\", \"ئي\"),\n        (0xFC05, \"M\", \"بج\"),\n        (0xFC06, \"M\", \"بح\"),\n        (0xFC07, \"M\", \"بخ\"),\n        (0xFC08, \"M\", \"بم\"),\n        (0xFC09, \"M\", \"بى\"),\n        (0xFC0A, \"M\", \"بي\"),\n        (0xFC0B, \"M\", \"تج\"),\n        (0xFC0C, \"M\", \"تح\"),\n        (0xFC0D, \"M\", \"تخ\"),\n        (0xFC0E, \"M\", \"تم\"),\n        (0xFC0F, \"M\", \"تى\"),\n        (0xFC10, \"M\", \"تي\"),\n        (0xFC11, \"M\", \"ثج\"),\n        (0xFC12, \"M\", \"ثم\"),\n        (0xFC13, \"M\", \"ثى\"),\n        (0xFC14, \"M\", \"ثي\"),\n        (0xFC15, \"M\", \"جح\"),\n        (0xFC16, \"M\", \"جم\"),\n        (0xFC17, \"M\", \"حج\"),\n        (0xFC18, \"M\", \"حم\"),\n        (0xFC19, \"M\", \"خج\"),\n        (0xFC1A, \"M\", \"خح\"),\n        (0xFC1B, \"M\", \"خم\"),\n        (0xFC1C, \"M\", \"سج\"),\n        (0xFC1D, \"M\", \"سح\"),\n        (0xFC1E, \"M\", \"سخ\"),\n        (0xFC1F, \"M\", \"سم\"),\n        (0xFC20, \"M\", \"صح\"),\n        (0xFC21, \"M\", \"صم\"),\n        (0xFC22, \"M\", \"ضج\"),\n        (0xFC23, \"M\", \"ضح\"),\n        (0xFC24, \"M\", \"ضخ\"),\n        (0xFC25, \"M\", \"ضم\"),\n        (0xFC26, \"M\", \"طح\"),\n        (0xFC27, \"M\", \"طم\"),\n        (0xFC28, \"M\", \"ظم\"),\n        (0xFC29, \"M\", \"عج\"),\n        (0xFC2A, \"M\", \"عم\"),\n        (0xFC2B, \"M\", \"غج\"),\n        (0xFC2C, \"M\", \"غم\"),\n        (0xFC2D, \"M\", \"فج\"),\n        (0xFC2E, \"M\", \"فح\"),\n        (0xFC2F, \"M\", \"فخ\"),\n        (0xFC30, \"M\", \"فم\"),\n        (0xFC31, \"M\", \"فى\"),\n        (0xFC32, \"M\", \"في\"),\n        (0xFC33, \"M\", \"قح\"),\n    ]\n\n\ndef _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFC34, \"M\", \"قم\"),\n        (0xFC35, \"M\", \"قى\"),\n        (0xFC36, \"M\", \"قي\"),\n        (0xFC37, \"M\", \"كا\"),\n        (0xFC38, \"M\", \"كج\"),\n        (0xFC39, \"M\", \"كح\"),\n        (0xFC3A, \"M\", \"كخ\"),\n        (0xFC3B, \"M\", \"كل\"),\n        (0xFC3C, \"M\", \"كم\"),\n        (0xFC3D, \"M\", \"كى\"),\n        (0xFC3E, \"M\", \"كي\"),\n        (0xFC3F, \"M\", \"لج\"),\n        (0xFC40, \"M\", \"لح\"),\n        (0xFC41, \"M\", \"لخ\"),\n        (0xFC42, \"M\", \"لم\"),\n        (0xFC43, \"M\", \"لى\"),\n        (0xFC44, \"M\", \"لي\"),\n        (0xFC45, \"M\", \"مج\"),\n        (0xFC46, \"M\", \"مح\"),\n        (0xFC47, \"M\", \"مخ\"),\n        (0xFC48, \"M\", \"مم\"),\n        (0xFC49, \"M\", \"مى\"),\n        (0xFC4A, \"M\", \"مي\"),\n        (0xFC4B, \"M\", \"نج\"),\n        (0xFC4C, \"M\", \"نح\"),\n        (0xFC4D, \"M\", \"نخ\"),\n        (0xFC4E, \"M\", \"نم\"),\n        (0xFC4F, \"M\", \"نى\"),\n        (0xFC50, \"M\", \"ني\"),\n        (0xFC51, \"M\", \"هج\"),\n        (0xFC52, \"M\", \"هم\"),\n        (0xFC53, \"M\", \"هى\"),\n        (0xFC54, \"M\", \"هي\"),\n        (0xFC55, \"M\", \"يج\"),\n        (0xFC56, \"M\", \"يح\"),\n        (0xFC57, \"M\", \"يخ\"),\n        (0xFC58, \"M\", \"يم\"),\n        (0xFC59, \"M\", \"يى\"),\n        (0xFC5A, \"M\", \"يي\"),\n        (0xFC5B, \"M\", \"ذٰ\"),\n        (0xFC5C, \"M\", \"رٰ\"),\n        (0xFC5D, \"M\", \"ىٰ\"),\n        (0xFC5E, \"M\", \" ٌّ\"),\n        (0xFC5F, \"M\", \" ٍّ\"),\n        (0xFC60, \"M\", \" َّ\"),\n        (0xFC61, \"M\", \" ُّ\"),\n        (0xFC62, \"M\", \" ِّ\"),\n        (0xFC63, \"M\", \" ّٰ\"),\n        (0xFC64, \"M\", \"ئر\"),\n        (0xFC65, \"M\", \"ئز\"),\n        (0xFC66, \"M\", \"ئم\"),\n        (0xFC67, \"M\", \"ئن\"),\n        (0xFC68, \"M\", \"ئى\"),\n        (0xFC69, \"M\", \"ئي\"),\n        (0xFC6A, \"M\", \"بر\"),\n        (0xFC6B, \"M\", \"بز\"),\n        (0xFC6C, \"M\", \"بم\"),\n        (0xFC6D, \"M\", \"بن\"),\n        (0xFC6E, \"M\", \"بى\"),\n        (0xFC6F, \"M\", \"بي\"),\n        (0xFC70, \"M\", \"تر\"),\n        (0xFC71, \"M\", \"تز\"),\n        (0xFC72, \"M\", \"تم\"),\n        (0xFC73, \"M\", \"تن\"),\n        (0xFC74, \"M\", \"تى\"),\n        (0xFC75, \"M\", \"تي\"),\n        (0xFC76, \"M\", \"ثر\"),\n        (0xFC77, \"M\", \"ثز\"),\n        (0xFC78, \"M\", \"ثم\"),\n        (0xFC79, \"M\", \"ثن\"),\n        (0xFC7A, \"M\", \"ثى\"),\n        (0xFC7B, \"M\", \"ثي\"),\n        (0xFC7C, \"M\", \"فى\"),\n        (0xFC7D, \"M\", \"في\"),\n        (0xFC7E, \"M\", \"قى\"),\n        (0xFC7F, \"M\", \"قي\"),\n        (0xFC80, \"M\", \"كا\"),\n        (0xFC81, \"M\", \"كل\"),\n        (0xFC82, \"M\", \"كم\"),\n        (0xFC83, \"M\", \"كى\"),\n        (0xFC84, \"M\", \"كي\"),\n        (0xFC85, \"M\", \"لم\"),\n        (0xFC86, \"M\", \"لى\"),\n        (0xFC87, \"M\", \"لي\"),\n        (0xFC88, \"M\", \"ما\"),\n        (0xFC89, \"M\", \"مم\"),\n        (0xFC8A, \"M\", \"نر\"),\n        (0xFC8B, \"M\", \"نز\"),\n        (0xFC8C, \"M\", \"نم\"),\n        (0xFC8D, \"M\", \"نن\"),\n        (0xFC8E, \"M\", \"نى\"),\n        (0xFC8F, \"M\", \"ني\"),\n        (0xFC90, \"M\", \"ىٰ\"),\n        (0xFC91, \"M\", \"ير\"),\n        (0xFC92, \"M\", \"يز\"),\n        (0xFC93, \"M\", \"يم\"),\n        (0xFC94, \"M\", \"ين\"),\n        (0xFC95, \"M\", \"يى\"),\n        (0xFC96, \"M\", \"يي\"),\n        (0xFC97, \"M\", \"ئج\"),\n    ]\n\n\ndef _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFC98, \"M\", \"ئح\"),\n        (0xFC99, \"M\", \"ئخ\"),\n        (0xFC9A, \"M\", \"ئم\"),\n        (0xFC9B, \"M\", \"ئه\"),\n        (0xFC9C, \"M\", \"بج\"),\n        (0xFC9D, \"M\", \"بح\"),\n        (0xFC9E, \"M\", \"بخ\"),\n        (0xFC9F, \"M\", \"بم\"),\n        (0xFCA0, \"M\", \"به\"),\n        (0xFCA1, \"M\", \"تج\"),\n        (0xFCA2, \"M\", \"تح\"),\n        (0xFCA3, \"M\", \"تخ\"),\n        (0xFCA4, \"M\", \"تم\"),\n        (0xFCA5, \"M\", \"ته\"),\n        (0xFCA6, \"M\", \"ثم\"),\n        (0xFCA7, \"M\", \"جح\"),\n        (0xFCA8, \"M\", \"جم\"),\n        (0xFCA9, \"M\", \"حج\"),\n        (0xFCAA, \"M\", \"حم\"),\n        (0xFCAB, \"M\", \"خج\"),\n        (0xFCAC, \"M\", \"خم\"),\n        (0xFCAD, \"M\", \"سج\"),\n        (0xFCAE, \"M\", \"سح\"),\n        (0xFCAF, \"M\", \"سخ\"),\n        (0xFCB0, \"M\", \"سم\"),\n        (0xFCB1, \"M\", \"صح\"),\n        (0xFCB2, \"M\", \"صخ\"),\n        (0xFCB3, \"M\", \"صم\"),\n        (0xFCB4, \"M\", \"ضج\"),\n        (0xFCB5, \"M\", \"ضح\"),\n        (0xFCB6, \"M\", \"ضخ\"),\n        (0xFCB7, \"M\", \"ضم\"),\n        (0xFCB8, \"M\", \"طح\"),\n        (0xFCB9, \"M\", \"ظم\"),\n        (0xFCBA, \"M\", \"عج\"),\n        (0xFCBB, \"M\", \"عم\"),\n        (0xFCBC, \"M\", \"غج\"),\n        (0xFCBD, \"M\", \"غم\"),\n        (0xFCBE, \"M\", \"فج\"),\n        (0xFCBF, \"M\", \"فح\"),\n        (0xFCC0, \"M\", \"فخ\"),\n        (0xFCC1, \"M\", \"فم\"),\n        (0xFCC2, \"M\", \"قح\"),\n        (0xFCC3, \"M\", \"قم\"),\n        (0xFCC4, \"M\", \"كج\"),\n        (0xFCC5, \"M\", \"كح\"),\n        (0xFCC6, \"M\", \"كخ\"),\n        (0xFCC7, \"M\", \"كل\"),\n        (0xFCC8, \"M\", \"كم\"),\n        (0xFCC9, \"M\", \"لج\"),\n        (0xFCCA, \"M\", \"لح\"),\n        (0xFCCB, \"M\", \"لخ\"),\n        (0xFCCC, \"M\", \"لم\"),\n        (0xFCCD, \"M\", \"له\"),\n        (0xFCCE, \"M\", \"مج\"),\n        (0xFCCF, \"M\", \"مح\"),\n        (0xFCD0, \"M\", \"مخ\"),\n        (0xFCD1, \"M\", \"مم\"),\n        (0xFCD2, \"M\", \"نج\"),\n        (0xFCD3, \"M\", \"نح\"),\n        (0xFCD4, \"M\", \"نخ\"),\n        (0xFCD5, \"M\", \"نم\"),\n        (0xFCD6, \"M\", \"نه\"),\n        (0xFCD7, \"M\", \"هج\"),\n        (0xFCD8, \"M\", \"هم\"),\n        (0xFCD9, \"M\", \"هٰ\"),\n        (0xFCDA, \"M\", \"يج\"),\n        (0xFCDB, \"M\", \"يح\"),\n        (0xFCDC, \"M\", \"يخ\"),\n        (0xFCDD, \"M\", \"يم\"),\n        (0xFCDE, \"M\", \"يه\"),\n        (0xFCDF, \"M\", \"ئم\"),\n        (0xFCE0, \"M\", \"ئه\"),\n        (0xFCE1, \"M\", \"بم\"),\n        (0xFCE2, \"M\", \"به\"),\n        (0xFCE3, \"M\", \"تم\"),\n        (0xFCE4, \"M\", \"ته\"),\n        (0xFCE5, \"M\", \"ثم\"),\n        (0xFCE6, \"M\", \"ثه\"),\n        (0xFCE7, \"M\", \"سم\"),\n        (0xFCE8, \"M\", \"سه\"),\n        (0xFCE9, \"M\", \"شم\"),\n        (0xFCEA, \"M\", \"شه\"),\n        (0xFCEB, \"M\", \"كل\"),\n        (0xFCEC, \"M\", \"كم\"),\n        (0xFCED, \"M\", \"لم\"),\n        (0xFCEE, \"M\", \"نم\"),\n        (0xFCEF, \"M\", \"نه\"),\n        (0xFCF0, \"M\", \"يم\"),\n        (0xFCF1, \"M\", \"يه\"),\n        (0xFCF2, \"M\", \"ـَّ\"),\n        (0xFCF3, \"M\", \"ـُّ\"),\n        (0xFCF4, \"M\", \"ـِّ\"),\n        (0xFCF5, \"M\", \"طى\"),\n        (0xFCF6, \"M\", \"طي\"),\n        (0xFCF7, \"M\", \"عى\"),\n        (0xFCF8, \"M\", \"عي\"),\n        (0xFCF9, \"M\", \"غى\"),\n        (0xFCFA, \"M\", \"غي\"),\n        (0xFCFB, \"M\", \"سى\"),\n    ]\n\n\ndef _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFCFC, \"M\", \"سي\"),\n        (0xFCFD, \"M\", \"شى\"),\n        (0xFCFE, \"M\", \"شي\"),\n        (0xFCFF, \"M\", \"حى\"),\n        (0xFD00, \"M\", \"حي\"),\n        (0xFD01, \"M\", \"جى\"),\n        (0xFD02, \"M\", \"جي\"),\n        (0xFD03, \"M\", \"خى\"),\n        (0xFD04, \"M\", \"خي\"),\n        (0xFD05, \"M\", \"صى\"),\n        (0xFD06, \"M\", \"صي\"),\n        (0xFD07, \"M\", \"ضى\"),\n        (0xFD08, \"M\", \"ضي\"),\n        (0xFD09, \"M\", \"شج\"),\n        (0xFD0A, \"M\", \"شح\"),\n        (0xFD0B, \"M\", \"شخ\"),\n        (0xFD0C, \"M\", \"شم\"),\n        (0xFD0D, \"M\", \"شر\"),\n        (0xFD0E, \"M\", \"سر\"),\n        (0xFD0F, \"M\", \"صر\"),\n        (0xFD10, \"M\", \"ضر\"),\n        (0xFD11, \"M\", \"طى\"),\n        (0xFD12, \"M\", \"طي\"),\n        (0xFD13, \"M\", \"عى\"),\n        (0xFD14, \"M\", \"عي\"),\n        (0xFD15, \"M\", \"غى\"),\n        (0xFD16, \"M\", \"غي\"),\n        (0xFD17, \"M\", \"سى\"),\n        (0xFD18, \"M\", \"سي\"),\n        (0xFD19, \"M\", \"شى\"),\n        (0xFD1A, \"M\", \"شي\"),\n        (0xFD1B, \"M\", \"حى\"),\n        (0xFD1C, \"M\", \"حي\"),\n        (0xFD1D, \"M\", \"جى\"),\n        (0xFD1E, \"M\", \"جي\"),\n        (0xFD1F, \"M\", \"خى\"),\n        (0xFD20, \"M\", \"خي\"),\n        (0xFD21, \"M\", \"صى\"),\n        (0xFD22, \"M\", \"صي\"),\n        (0xFD23, \"M\", \"ضى\"),\n        (0xFD24, \"M\", \"ضي\"),\n        (0xFD25, \"M\", \"شج\"),\n        (0xFD26, \"M\", \"شح\"),\n        (0xFD27, \"M\", \"شخ\"),\n        (0xFD28, \"M\", \"شم\"),\n        (0xFD29, \"M\", \"شر\"),\n        (0xFD2A, \"M\", \"سر\"),\n        (0xFD2B, \"M\", \"صر\"),\n        (0xFD2C, \"M\", \"ضر\"),\n        (0xFD2D, \"M\", \"شج\"),\n        (0xFD2E, \"M\", \"شح\"),\n        (0xFD2F, \"M\", \"شخ\"),\n        (0xFD30, \"M\", \"شم\"),\n        (0xFD31, \"M\", \"سه\"),\n        (0xFD32, \"M\", \"شه\"),\n        (0xFD33, \"M\", \"طم\"),\n        (0xFD34, \"M\", \"سج\"),\n        (0xFD35, \"M\", \"سح\"),\n        (0xFD36, \"M\", \"سخ\"),\n        (0xFD37, \"M\", \"شج\"),\n        (0xFD38, \"M\", \"شح\"),\n        (0xFD39, \"M\", \"شخ\"),\n        (0xFD3A, \"M\", \"طم\"),\n        (0xFD3B, \"M\", \"ظم\"),\n        (0xFD3C, \"M\", \"اً\"),\n        (0xFD3E, \"V\"),\n        (0xFD50, \"M\", \"تجم\"),\n        (0xFD51, \"M\", \"تحج\"),\n        (0xFD53, \"M\", \"تحم\"),\n        (0xFD54, \"M\", \"تخم\"),\n        (0xFD55, \"M\", \"تمج\"),\n        (0xFD56, \"M\", \"تمح\"),\n        (0xFD57, \"M\", \"تمخ\"),\n        (0xFD58, \"M\", \"جمح\"),\n        (0xFD5A, \"M\", \"حمي\"),\n        (0xFD5B, \"M\", \"حمى\"),\n        (0xFD5C, \"M\", \"سحج\"),\n        (0xFD5D, \"M\", \"سجح\"),\n        (0xFD5E, \"M\", \"سجى\"),\n        (0xFD5F, \"M\", \"سمح\"),\n        (0xFD61, \"M\", \"سمج\"),\n        (0xFD62, \"M\", \"سمم\"),\n        (0xFD64, \"M\", \"صحح\"),\n        (0xFD66, \"M\", \"صمم\"),\n        (0xFD67, \"M\", \"شحم\"),\n        (0xFD69, \"M\", \"شجي\"),\n        (0xFD6A, \"M\", \"شمخ\"),\n        (0xFD6C, \"M\", \"شمم\"),\n        (0xFD6E, \"M\", \"ضحى\"),\n        (0xFD6F, \"M\", \"ضخم\"),\n        (0xFD71, \"M\", \"طمح\"),\n        (0xFD73, \"M\", \"طمم\"),\n        (0xFD74, \"M\", \"طمي\"),\n        (0xFD75, \"M\", \"عجم\"),\n        (0xFD76, \"M\", \"عمم\"),\n        (0xFD78, \"M\", \"عمى\"),\n        (0xFD79, \"M\", \"غمم\"),\n        (0xFD7A, \"M\", \"غمي\"),\n        (0xFD7B, \"M\", \"غمى\"),\n        (0xFD7C, \"M\", \"فخم\"),\n    ]\n\n\ndef _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFD7E, \"M\", \"قمح\"),\n        (0xFD7F, \"M\", \"قمم\"),\n        (0xFD80, \"M\", \"لحم\"),\n        (0xFD81, \"M\", \"لحي\"),\n        (0xFD82, \"M\", \"لحى\"),\n        (0xFD83, \"M\", \"لجج\"),\n        (0xFD85, \"M\", \"لخم\"),\n        (0xFD87, \"M\", \"لمح\"),\n        (0xFD89, \"M\", \"محج\"),\n        (0xFD8A, \"M\", \"محم\"),\n        (0xFD8B, \"M\", \"محي\"),\n        (0xFD8C, \"M\", \"مجح\"),\n        (0xFD8D, \"M\", \"مجم\"),\n        (0xFD8E, \"M\", \"مخج\"),\n        (0xFD8F, \"M\", \"مخم\"),\n        (0xFD90, \"X\"),\n        (0xFD92, \"M\", \"مجخ\"),\n        (0xFD93, \"M\", \"همج\"),\n        (0xFD94, \"M\", \"همم\"),\n        (0xFD95, \"M\", \"نحم\"),\n        (0xFD96, \"M\", \"نحى\"),\n        (0xFD97, \"M\", \"نجم\"),\n        (0xFD99, \"M\", \"نجى\"),\n        (0xFD9A, \"M\", \"نمي\"),\n        (0xFD9B, \"M\", \"نمى\"),\n        (0xFD9C, \"M\", \"يمم\"),\n        (0xFD9E, \"M\", \"بخي\"),\n        (0xFD9F, \"M\", \"تجي\"),\n        (0xFDA0, \"M\", \"تجى\"),\n        (0xFDA1, \"M\", \"تخي\"),\n        (0xFDA2, \"M\", \"تخى\"),\n        (0xFDA3, \"M\", \"تمي\"),\n        (0xFDA4, \"M\", \"تمى\"),\n        (0xFDA5, \"M\", \"جمي\"),\n        (0xFDA6, \"M\", \"جحى\"),\n        (0xFDA7, \"M\", \"جمى\"),\n        (0xFDA8, \"M\", \"سخى\"),\n        (0xFDA9, \"M\", \"صحي\"),\n        (0xFDAA, \"M\", \"شحي\"),\n        (0xFDAB, \"M\", \"ضحي\"),\n        (0xFDAC, \"M\", \"لجي\"),\n        (0xFDAD, \"M\", \"لمي\"),\n        (0xFDAE, \"M\", \"يحي\"),\n        (0xFDAF, \"M\", \"يجي\"),\n        (0xFDB0, \"M\", \"يمي\"),\n        (0xFDB1, \"M\", \"ممي\"),\n        (0xFDB2, \"M\", \"قمي\"),\n        (0xFDB3, \"M\", \"نحي\"),\n        (0xFDB4, \"M\", \"قمح\"),\n        (0xFDB5, \"M\", \"لحم\"),\n        (0xFDB6, \"M\", \"عمي\"),\n        (0xFDB7, \"M\", \"كمي\"),\n        (0xFDB8, \"M\", \"نجح\"),\n        (0xFDB9, \"M\", \"مخي\"),\n        (0xFDBA, \"M\", \"لجم\"),\n        (0xFDBB, \"M\", \"كمم\"),\n        (0xFDBC, \"M\", \"لجم\"),\n        (0xFDBD, \"M\", \"نجح\"),\n        (0xFDBE, \"M\", \"جحي\"),\n        (0xFDBF, \"M\", \"حجي\"),\n        (0xFDC0, \"M\", \"مجي\"),\n        (0xFDC1, \"M\", \"فمي\"),\n        (0xFDC2, \"M\", \"بحي\"),\n        (0xFDC3, \"M\", \"كمم\"),\n        (0xFDC4, \"M\", \"عجم\"),\n        (0xFDC5, \"M\", \"صمم\"),\n        (0xFDC6, \"M\", \"سخي\"),\n        (0xFDC7, \"M\", \"نجي\"),\n        (0xFDC8, \"X\"),\n        (0xFDCF, \"V\"),\n        (0xFDD0, \"X\"),\n        (0xFDF0, \"M\", \"صلے\"),\n        (0xFDF1, \"M\", \"قلے\"),\n        (0xFDF2, \"M\", \"الله\"),\n        (0xFDF3, \"M\", \"اكبر\"),\n        (0xFDF4, \"M\", \"محمد\"),\n        (0xFDF5, \"M\", \"صلعم\"),\n        (0xFDF6, \"M\", \"رسول\"),\n        (0xFDF7, \"M\", \"عليه\"),\n        (0xFDF8, \"M\", \"وسلم\"),\n        (0xFDF9, \"M\", \"صلى\"),\n        (0xFDFA, \"M\", \"صلى الله عليه وسلم\"),\n        (0xFDFB, \"M\", \"جل جلاله\"),\n        (0xFDFC, \"M\", \"ریال\"),\n        (0xFDFD, \"V\"),\n        (0xFE00, \"I\"),\n        (0xFE10, \"M\", \",\"),\n        (0xFE11, \"M\", \"、\"),\n        (0xFE12, \"X\"),\n        (0xFE13, \"M\", \":\"),\n        (0xFE14, \"M\", \";\"),\n        (0xFE15, \"M\", \"!\"),\n        (0xFE16, \"M\", \"?\"),\n        (0xFE17, \"M\", \"〖\"),\n        (0xFE18, \"M\", \"〗\"),\n        (0xFE19, \"X\"),\n        (0xFE20, \"V\"),\n        (0xFE30, \"X\"),\n        (0xFE31, \"M\", \"—\"),\n        (0xFE32, \"M\", \"–\"),\n    ]\n\n\ndef _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFE33, \"M\", \"_\"),\n        (0xFE35, \"M\", \"(\"),\n        (0xFE36, \"M\", \")\"),\n        (0xFE37, \"M\", \"{\"),\n        (0xFE38, \"M\", \"}\"),\n        (0xFE39, \"M\", \"〔\"),\n        (0xFE3A, \"M\", \"〕\"),\n        (0xFE3B, \"M\", \"【\"),\n        (0xFE3C, \"M\", \"】\"),\n        (0xFE3D, \"M\", \"《\"),\n        (0xFE3E, \"M\", \"》\"),\n        (0xFE3F, \"M\", \"〈\"),\n        (0xFE40, \"M\", \"〉\"),\n        (0xFE41, \"M\", \"「\"),\n        (0xFE42, \"M\", \"」\"),\n        (0xFE43, \"M\", \"『\"),\n        (0xFE44, \"M\", \"』\"),\n        (0xFE45, \"V\"),\n        (0xFE47, \"M\", \"[\"),\n        (0xFE48, \"M\", \"]\"),\n        (0xFE49, \"M\", \" ̅\"),\n        (0xFE4D, \"M\", \"_\"),\n        (0xFE50, \"M\", \",\"),\n        (0xFE51, \"M\", \"、\"),\n        (0xFE52, \"X\"),\n        (0xFE54, \"M\", \";\"),\n        (0xFE55, \"M\", \":\"),\n        (0xFE56, \"M\", \"?\"),\n        (0xFE57, \"M\", \"!\"),\n        (0xFE58, \"M\", \"—\"),\n        (0xFE59, \"M\", \"(\"),\n        (0xFE5A, \"M\", \")\"),\n        (0xFE5B, \"M\", \"{\"),\n        (0xFE5C, \"M\", \"}\"),\n        (0xFE5D, \"M\", \"〔\"),\n        (0xFE5E, \"M\", \"〕\"),\n        (0xFE5F, \"M\", \"#\"),\n        (0xFE60, \"M\", \"&\"),\n        (0xFE61, \"M\", \"*\"),\n        (0xFE62, \"M\", \"+\"),\n        (0xFE63, \"M\", \"-\"),\n        (0xFE64, \"M\", \"<\"),\n        (0xFE65, \"M\", \">\"),\n        (0xFE66, \"M\", \"=\"),\n        (0xFE67, \"X\"),\n        (0xFE68, \"M\", \"\\\\\"),\n        (0xFE69, \"M\", \"$\"),\n        (0xFE6A, \"M\", \"%\"),\n        (0xFE6B, \"M\", \"@\"),\n        (0xFE6C, \"X\"),\n        (0xFE70, \"M\", \" ً\"),\n        (0xFE71, \"M\", \"ـً\"),\n        (0xFE72, \"M\", \" ٌ\"),\n        (0xFE73, \"V\"),\n        (0xFE74, \"M\", \" ٍ\"),\n        (0xFE75, \"X\"),\n        (0xFE76, \"M\", \" َ\"),\n        (0xFE77, \"M\", \"ـَ\"),\n        (0xFE78, \"M\", \" ُ\"),\n        (0xFE79, \"M\", \"ـُ\"),\n        (0xFE7A, \"M\", \" ِ\"),\n        (0xFE7B, \"M\", \"ـِ\"),\n        (0xFE7C, \"M\", \" ّ\"),\n        (0xFE7D, \"M\", \"ـّ\"),\n        (0xFE7E, \"M\", \" ْ\"),\n        (0xFE7F, \"M\", \"ـْ\"),\n        (0xFE80, \"M\", \"ء\"),\n        (0xFE81, \"M\", \"آ\"),\n        (0xFE83, \"M\", \"أ\"),\n        (0xFE85, \"M\", \"ؤ\"),\n        (0xFE87, \"M\", \"إ\"),\n        (0xFE89, \"M\", \"ئ\"),\n        (0xFE8D, \"M\", \"ا\"),\n        (0xFE8F, \"M\", \"ب\"),\n        (0xFE93, \"M\", \"ة\"),\n        (0xFE95, \"M\", \"ت\"),\n        (0xFE99, \"M\", \"ث\"),\n        (0xFE9D, \"M\", \"ج\"),\n        (0xFEA1, \"M\", \"ح\"),\n        (0xFEA5, \"M\", \"خ\"),\n        (0xFEA9, \"M\", \"د\"),\n        (0xFEAB, \"M\", \"ذ\"),\n        (0xFEAD, \"M\", \"ر\"),\n        (0xFEAF, \"M\", \"ز\"),\n        (0xFEB1, \"M\", \"س\"),\n        (0xFEB5, \"M\", \"ش\"),\n        (0xFEB9, \"M\", \"ص\"),\n        (0xFEBD, \"M\", \"ض\"),\n        (0xFEC1, \"M\", \"ط\"),\n        (0xFEC5, \"M\", \"ظ\"),\n        (0xFEC9, \"M\", \"ع\"),\n        (0xFECD, \"M\", \"غ\"),\n        (0xFED1, \"M\", \"ف\"),\n        (0xFED5, \"M\", \"ق\"),\n        (0xFED9, \"M\", \"ك\"),\n        (0xFEDD, \"M\", \"ل\"),\n        (0xFEE1, \"M\", \"م\"),\n        (0xFEE5, \"M\", \"ن\"),\n        (0xFEE9, \"M\", \"ه\"),\n        (0xFEED, \"M\", \"و\"),\n    ]\n\n\ndef _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFEEF, \"M\", \"ى\"),\n        (0xFEF1, \"M\", \"ي\"),\n        (0xFEF5, \"M\", \"لآ\"),\n        (0xFEF7, \"M\", \"لأ\"),\n        (0xFEF9, \"M\", \"لإ\"),\n        (0xFEFB, \"M\", \"لا\"),\n        (0xFEFD, \"X\"),\n        (0xFEFF, \"I\"),\n        (0xFF00, \"X\"),\n        (0xFF01, \"M\", \"!\"),\n        (0xFF02, \"M\", '\"'),\n        (0xFF03, \"M\", \"#\"),\n        (0xFF04, \"M\", \"$\"),\n        (0xFF05, \"M\", \"%\"),\n        (0xFF06, \"M\", \"&\"),\n        (0xFF07, \"M\", \"'\"),\n        (0xFF08, \"M\", \"(\"),\n        (0xFF09, \"M\", \")\"),\n        (0xFF0A, \"M\", \"*\"),\n        (0xFF0B, \"M\", \"+\"),\n        (0xFF0C, \"M\", \",\"),\n        (0xFF0D, \"M\", \"-\"),\n        (0xFF0E, \"M\", \".\"),\n        (0xFF0F, \"M\", \"/\"),\n        (0xFF10, \"M\", \"0\"),\n        (0xFF11, \"M\", \"1\"),\n        (0xFF12, \"M\", \"2\"),\n        (0xFF13, \"M\", \"3\"),\n        (0xFF14, \"M\", \"4\"),\n        (0xFF15, \"M\", \"5\"),\n        (0xFF16, \"M\", \"6\"),\n        (0xFF17, \"M\", \"7\"),\n        (0xFF18, \"M\", \"8\"),\n        (0xFF19, \"M\", \"9\"),\n        (0xFF1A, \"M\", \":\"),\n        (0xFF1B, \"M\", \";\"),\n        (0xFF1C, \"M\", \"<\"),\n        (0xFF1D, \"M\", \"=\"),\n        (0xFF1E, \"M\", \">\"),\n        (0xFF1F, \"M\", \"?\"),\n        (0xFF20, \"M\", \"@\"),\n        (0xFF21, \"M\", \"a\"),\n        (0xFF22, \"M\", \"b\"),\n        (0xFF23, \"M\", \"c\"),\n        (0xFF24, \"M\", \"d\"),\n        (0xFF25, \"M\", \"e\"),\n        (0xFF26, \"M\", \"f\"),\n        (0xFF27, \"M\", \"g\"),\n        (0xFF28, \"M\", \"h\"),\n        (0xFF29, \"M\", \"i\"),\n        (0xFF2A, \"M\", \"j\"),\n        (0xFF2B, \"M\", \"k\"),\n        (0xFF2C, \"M\", \"l\"),\n        (0xFF2D, \"M\", \"m\"),\n        (0xFF2E, \"M\", \"n\"),\n        (0xFF2F, \"M\", \"o\"),\n        (0xFF30, \"M\", \"p\"),\n        (0xFF31, \"M\", \"q\"),\n        (0xFF32, \"M\", \"r\"),\n        (0xFF33, \"M\", \"s\"),\n        (0xFF34, \"M\", \"t\"),\n        (0xFF35, \"M\", \"u\"),\n        (0xFF36, \"M\", \"v\"),\n        (0xFF37, \"M\", \"w\"),\n        (0xFF38, \"M\", \"x\"),\n        (0xFF39, \"M\", \"y\"),\n        (0xFF3A, \"M\", \"z\"),\n        (0xFF3B, \"M\", \"[\"),\n        (0xFF3C, \"M\", \"\\\\\"),\n        (0xFF3D, \"M\", \"]\"),\n        (0xFF3E, \"M\", \"^\"),\n        (0xFF3F, \"M\", \"_\"),\n        (0xFF40, \"M\", \"`\"),\n        (0xFF41, \"M\", \"a\"),\n        (0xFF42, \"M\", \"b\"),\n        (0xFF43, \"M\", \"c\"),\n        (0xFF44, \"M\", \"d\"),\n        (0xFF45, \"M\", \"e\"),\n        (0xFF46, \"M\", \"f\"),\n        (0xFF47, \"M\", \"g\"),\n        (0xFF48, \"M\", \"h\"),\n        (0xFF49, \"M\", \"i\"),\n        (0xFF4A, \"M\", \"j\"),\n        (0xFF4B, \"M\", \"k\"),\n        (0xFF4C, \"M\", \"l\"),\n        (0xFF4D, \"M\", \"m\"),\n        (0xFF4E, \"M\", \"n\"),\n        (0xFF4F, \"M\", \"o\"),\n        (0xFF50, \"M\", \"p\"),\n        (0xFF51, \"M\", \"q\"),\n        (0xFF52, \"M\", \"r\"),\n        (0xFF53, \"M\", \"s\"),\n        (0xFF54, \"M\", \"t\"),\n        (0xFF55, \"M\", \"u\"),\n        (0xFF56, \"M\", \"v\"),\n        (0xFF57, \"M\", \"w\"),\n        (0xFF58, \"M\", \"x\"),\n        (0xFF59, \"M\", \"y\"),\n        (0xFF5A, \"M\", \"z\"),\n        (0xFF5B, \"M\", \"{\"),\n    ]\n\n\ndef _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFF5C, \"M\", \"|\"),\n        (0xFF5D, \"M\", \"}\"),\n        (0xFF5E, \"M\", \"~\"),\n        (0xFF5F, \"M\", \"⦅\"),\n        (0xFF60, \"M\", \"⦆\"),\n        (0xFF61, \"M\", \".\"),\n        (0xFF62, \"M\", \"「\"),\n        (0xFF63, \"M\", \"」\"),\n        (0xFF64, \"M\", \"、\"),\n        (0xFF65, \"M\", \"・\"),\n        (0xFF66, \"M\", \"ヲ\"),\n        (0xFF67, \"M\", \"ァ\"),\n        (0xFF68, \"M\", \"ィ\"),\n        (0xFF69, \"M\", \"ゥ\"),\n        (0xFF6A, \"M\", \"ェ\"),\n        (0xFF6B, \"M\", \"ォ\"),\n        (0xFF6C, \"M\", \"ャ\"),\n        (0xFF6D, \"M\", \"ュ\"),\n        (0xFF6E, \"M\", \"ョ\"),\n        (0xFF6F, \"M\", \"ッ\"),\n        (0xFF70, \"M\", \"ー\"),\n        (0xFF71, \"M\", \"ア\"),\n        (0xFF72, \"M\", \"イ\"),\n        (0xFF73, \"M\", \"ウ\"),\n        (0xFF74, \"M\", \"エ\"),\n        (0xFF75, \"M\", \"オ\"),\n        (0xFF76, \"M\", \"カ\"),\n        (0xFF77, \"M\", \"キ\"),\n        (0xFF78, \"M\", \"ク\"),\n        (0xFF79, \"M\", \"ケ\"),\n        (0xFF7A, \"M\", \"コ\"),\n        (0xFF7B, \"M\", \"サ\"),\n        (0xFF7C, \"M\", \"シ\"),\n        (0xFF7D, \"M\", \"ス\"),\n        (0xFF7E, \"M\", \"セ\"),\n        (0xFF7F, \"M\", \"ソ\"),\n        (0xFF80, \"M\", \"タ\"),\n        (0xFF81, \"M\", \"チ\"),\n        (0xFF82, \"M\", \"ツ\"),\n        (0xFF83, \"M\", \"テ\"),\n        (0xFF84, \"M\", \"ト\"),\n        (0xFF85, \"M\", \"ナ\"),\n        (0xFF86, \"M\", \"ニ\"),\n        (0xFF87, \"M\", \"ヌ\"),\n        (0xFF88, \"M\", \"ネ\"),\n        (0xFF89, \"M\", \"ノ\"),\n        (0xFF8A, \"M\", \"ハ\"),\n        (0xFF8B, \"M\", \"ヒ\"),\n        (0xFF8C, \"M\", \"フ\"),\n        (0xFF8D, \"M\", \"ヘ\"),\n        (0xFF8E, \"M\", \"ホ\"),\n        (0xFF8F, \"M\", \"マ\"),\n        (0xFF90, \"M\", \"ミ\"),\n        (0xFF91, \"M\", \"ム\"),\n        (0xFF92, \"M\", \"メ\"),\n        (0xFF93, \"M\", \"モ\"),\n        (0xFF94, \"M\", \"ヤ\"),\n        (0xFF95, \"M\", \"ユ\"),\n        (0xFF96, \"M\", \"ヨ\"),\n        (0xFF97, \"M\", \"ラ\"),\n        (0xFF98, \"M\", \"リ\"),\n        (0xFF99, \"M\", \"ル\"),\n        (0xFF9A, \"M\", \"レ\"),\n        (0xFF9B, \"M\", \"ロ\"),\n        (0xFF9C, \"M\", \"ワ\"),\n        (0xFF9D, \"M\", \"ン\"),\n        (0xFF9E, \"M\", \"゙\"),\n        (0xFF9F, \"M\", \"゚\"),\n        (0xFFA0, \"I\"),\n        (0xFFA1, \"M\", \"ᄀ\"),\n        (0xFFA2, \"M\", \"ᄁ\"),\n        (0xFFA3, \"M\", \"ᆪ\"),\n        (0xFFA4, \"M\", \"ᄂ\"),\n        (0xFFA5, \"M\", \"ᆬ\"),\n        (0xFFA6, \"M\", \"ᆭ\"),\n        (0xFFA7, \"M\", \"ᄃ\"),\n        (0xFFA8, \"M\", \"ᄄ\"),\n        (0xFFA9, \"M\", \"ᄅ\"),\n        (0xFFAA, \"M\", \"ᆰ\"),\n        (0xFFAB, \"M\", \"ᆱ\"),\n        (0xFFAC, \"M\", \"ᆲ\"),\n        (0xFFAD, \"M\", \"ᆳ\"),\n        (0xFFAE, \"M\", \"ᆴ\"),\n        (0xFFAF, \"M\", \"ᆵ\"),\n        (0xFFB0, \"M\", \"ᄚ\"),\n        (0xFFB1, \"M\", \"ᄆ\"),\n        (0xFFB2, \"M\", \"ᄇ\"),\n        (0xFFB3, \"M\", \"ᄈ\"),\n        (0xFFB4, \"M\", \"ᄡ\"),\n        (0xFFB5, \"M\", \"ᄉ\"),\n        (0xFFB6, \"M\", \"ᄊ\"),\n        (0xFFB7, \"M\", \"ᄋ\"),\n        (0xFFB8, \"M\", \"ᄌ\"),\n        (0xFFB9, \"M\", \"ᄍ\"),\n        (0xFFBA, \"M\", \"ᄎ\"),\n        (0xFFBB, \"M\", \"ᄏ\"),\n        (0xFFBC, \"M\", \"ᄐ\"),\n        (0xFFBD, \"M\", \"ᄑ\"),\n        (0xFFBE, \"M\", \"ᄒ\"),\n        (0xFFBF, \"X\"),\n    ]\n\n\ndef _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0xFFC2, \"M\", \"ᅡ\"),\n        (0xFFC3, \"M\", \"ᅢ\"),\n        (0xFFC4, \"M\", \"ᅣ\"),\n        (0xFFC5, \"M\", \"ᅤ\"),\n        (0xFFC6, \"M\", \"ᅥ\"),\n        (0xFFC7, \"M\", \"ᅦ\"),\n        (0xFFC8, \"X\"),\n        (0xFFCA, \"M\", \"ᅧ\"),\n        (0xFFCB, \"M\", \"ᅨ\"),\n        (0xFFCC, \"M\", \"ᅩ\"),\n        (0xFFCD, \"M\", \"ᅪ\"),\n        (0xFFCE, \"M\", \"ᅫ\"),\n        (0xFFCF, \"M\", \"ᅬ\"),\n        (0xFFD0, \"X\"),\n        (0xFFD2, \"M\", \"ᅭ\"),\n        (0xFFD3, \"M\", \"ᅮ\"),\n        (0xFFD4, \"M\", \"ᅯ\"),\n        (0xFFD5, \"M\", \"ᅰ\"),\n        (0xFFD6, \"M\", \"ᅱ\"),\n        (0xFFD7, \"M\", \"ᅲ\"),\n        (0xFFD8, \"X\"),\n        (0xFFDA, \"M\", \"ᅳ\"),\n        (0xFFDB, \"M\", \"ᅴ\"),\n        (0xFFDC, \"M\", \"ᅵ\"),\n        (0xFFDD, \"X\"),\n        (0xFFE0, \"M\", \"¢\"),\n        (0xFFE1, \"M\", \"£\"),\n        (0xFFE2, \"M\", \"¬\"),\n        (0xFFE3, \"M\", \" ̄\"),\n        (0xFFE4, \"M\", \"¦\"),\n        (0xFFE5, \"M\", \"¥\"),\n        (0xFFE6, \"M\", \"₩\"),\n        (0xFFE7, \"X\"),\n        (0xFFE8, \"M\", \"│\"),\n        (0xFFE9, \"M\", \"←\"),\n        (0xFFEA, \"M\", \"↑\"),\n        (0xFFEB, \"M\", \"→\"),\n        (0xFFEC, \"M\", \"↓\"),\n        (0xFFED, \"M\", \"■\"),\n        (0xFFEE, \"M\", \"○\"),\n        (0xFFEF, \"X\"),\n        (0x10000, \"V\"),\n        (0x1000C, \"X\"),\n        (0x1000D, \"V\"),\n        (0x10027, \"X\"),\n        (0x10028, \"V\"),\n        (0x1003B, \"X\"),\n        (0x1003C, \"V\"),\n        (0x1003E, \"X\"),\n        (0x1003F, \"V\"),\n        (0x1004E, \"X\"),\n        (0x10050, \"V\"),\n        (0x1005E, \"X\"),\n        (0x10080, \"V\"),\n        (0x100FB, \"X\"),\n        (0x10100, \"V\"),\n        (0x10103, \"X\"),\n        (0x10107, \"V\"),\n        (0x10134, \"X\"),\n        (0x10137, \"V\"),\n        (0x1018F, \"X\"),\n        (0x10190, \"V\"),\n        (0x1019D, \"X\"),\n        (0x101A0, \"V\"),\n        (0x101A1, \"X\"),\n        (0x101D0, \"V\"),\n        (0x101FE, \"X\"),\n        (0x10280, \"V\"),\n        (0x1029D, \"X\"),\n        (0x102A0, \"V\"),\n        (0x102D1, \"X\"),\n        (0x102E0, \"V\"),\n        (0x102FC, \"X\"),\n        (0x10300, \"V\"),\n        (0x10324, \"X\"),\n        (0x1032D, \"V\"),\n        (0x1034B, \"X\"),\n        (0x10350, \"V\"),\n        (0x1037B, \"X\"),\n        (0x10380, \"V\"),\n        (0x1039E, \"X\"),\n        (0x1039F, \"V\"),\n        (0x103C4, \"X\"),\n        (0x103C8, \"V\"),\n        (0x103D6, \"X\"),\n        (0x10400, \"M\", \"𐐨\"),\n        (0x10401, \"M\", \"𐐩\"),\n        (0x10402, \"M\", \"𐐪\"),\n        (0x10403, \"M\", \"𐐫\"),\n        (0x10404, \"M\", \"𐐬\"),\n        (0x10405, \"M\", \"𐐭\"),\n        (0x10406, \"M\", \"𐐮\"),\n        (0x10407, \"M\", \"𐐯\"),\n        (0x10408, \"M\", \"𐐰\"),\n        (0x10409, \"M\", \"𐐱\"),\n        (0x1040A, \"M\", \"𐐲\"),\n        (0x1040B, \"M\", \"𐐳\"),\n        (0x1040C, \"M\", \"𐐴\"),\n        (0x1040D, \"M\", \"𐐵\"),\n        (0x1040E, \"M\", \"𐐶\"),\n    ]\n\n\ndef _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1040F, \"M\", \"𐐷\"),\n        (0x10410, \"M\", \"𐐸\"),\n        (0x10411, \"M\", \"𐐹\"),\n        (0x10412, \"M\", \"𐐺\"),\n        (0x10413, \"M\", \"𐐻\"),\n        (0x10414, \"M\", \"𐐼\"),\n        (0x10415, \"M\", \"𐐽\"),\n        (0x10416, \"M\", \"𐐾\"),\n        (0x10417, \"M\", \"𐐿\"),\n        (0x10418, \"M\", \"𐑀\"),\n        (0x10419, \"M\", \"𐑁\"),\n        (0x1041A, \"M\", \"𐑂\"),\n        (0x1041B, \"M\", \"𐑃\"),\n        (0x1041C, \"M\", \"𐑄\"),\n        (0x1041D, \"M\", \"𐑅\"),\n        (0x1041E, \"M\", \"𐑆\"),\n        (0x1041F, \"M\", \"𐑇\"),\n        (0x10420, \"M\", \"𐑈\"),\n        (0x10421, \"M\", \"𐑉\"),\n        (0x10422, \"M\", \"𐑊\"),\n        (0x10423, \"M\", \"𐑋\"),\n        (0x10424, \"M\", \"𐑌\"),\n        (0x10425, \"M\", \"𐑍\"),\n        (0x10426, \"M\", \"𐑎\"),\n        (0x10427, \"M\", \"𐑏\"),\n        (0x10428, \"V\"),\n        (0x1049E, \"X\"),\n        (0x104A0, \"V\"),\n        (0x104AA, \"X\"),\n        (0x104B0, \"M\", \"𐓘\"),\n        (0x104B1, \"M\", \"𐓙\"),\n        (0x104B2, \"M\", \"𐓚\"),\n        (0x104B3, \"M\", \"𐓛\"),\n        (0x104B4, \"M\", \"𐓜\"),\n        (0x104B5, \"M\", \"𐓝\"),\n        (0x104B6, \"M\", \"𐓞\"),\n        (0x104B7, \"M\", \"𐓟\"),\n        (0x104B8, \"M\", \"𐓠\"),\n        (0x104B9, \"M\", \"𐓡\"),\n        (0x104BA, \"M\", \"𐓢\"),\n        (0x104BB, \"M\", \"𐓣\"),\n        (0x104BC, \"M\", \"𐓤\"),\n        (0x104BD, \"M\", \"𐓥\"),\n        (0x104BE, \"M\", \"𐓦\"),\n        (0x104BF, \"M\", \"𐓧\"),\n        (0x104C0, \"M\", \"𐓨\"),\n        (0x104C1, \"M\", \"𐓩\"),\n        (0x104C2, \"M\", \"𐓪\"),\n        (0x104C3, \"M\", \"𐓫\"),\n        (0x104C4, \"M\", \"𐓬\"),\n        (0x104C5, \"M\", \"𐓭\"),\n        (0x104C6, \"M\", \"𐓮\"),\n        (0x104C7, \"M\", \"𐓯\"),\n        (0x104C8, \"M\", \"𐓰\"),\n        (0x104C9, \"M\", \"𐓱\"),\n        (0x104CA, \"M\", \"𐓲\"),\n        (0x104CB, \"M\", \"𐓳\"),\n        (0x104CC, \"M\", \"𐓴\"),\n        (0x104CD, \"M\", \"𐓵\"),\n        (0x104CE, \"M\", \"𐓶\"),\n        (0x104CF, \"M\", \"𐓷\"),\n        (0x104D0, \"M\", \"𐓸\"),\n        (0x104D1, \"M\", \"𐓹\"),\n        (0x104D2, \"M\", \"𐓺\"),\n        (0x104D3, \"M\", \"𐓻\"),\n        (0x104D4, \"X\"),\n        (0x104D8, \"V\"),\n        (0x104FC, \"X\"),\n        (0x10500, \"V\"),\n        (0x10528, \"X\"),\n        (0x10530, \"V\"),\n        (0x10564, \"X\"),\n        (0x1056F, \"V\"),\n        (0x10570, \"M\", \"𐖗\"),\n        (0x10571, \"M\", \"𐖘\"),\n        (0x10572, \"M\", \"𐖙\"),\n        (0x10573, \"M\", \"𐖚\"),\n        (0x10574, \"M\", \"𐖛\"),\n        (0x10575, \"M\", \"𐖜\"),\n        (0x10576, \"M\", \"𐖝\"),\n        (0x10577, \"M\", \"𐖞\"),\n        (0x10578, \"M\", \"𐖟\"),\n        (0x10579, \"M\", \"𐖠\"),\n        (0x1057A, \"M\", \"𐖡\"),\n        (0x1057B, \"X\"),\n        (0x1057C, \"M\", \"𐖣\"),\n        (0x1057D, \"M\", \"𐖤\"),\n        (0x1057E, \"M\", \"𐖥\"),\n        (0x1057F, \"M\", \"𐖦\"),\n        (0x10580, \"M\", \"𐖧\"),\n        (0x10581, \"M\", \"𐖨\"),\n        (0x10582, \"M\", \"𐖩\"),\n        (0x10583, \"M\", \"𐖪\"),\n        (0x10584, \"M\", \"𐖫\"),\n        (0x10585, \"M\", \"𐖬\"),\n        (0x10586, \"M\", \"𐖭\"),\n        (0x10587, \"M\", \"𐖮\"),\n        (0x10588, \"M\", \"𐖯\"),\n        (0x10589, \"M\", \"𐖰\"),\n        (0x1058A, \"M\", \"𐖱\"),\n    ]\n\n\ndef _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1058B, \"X\"),\n        (0x1058C, \"M\", \"𐖳\"),\n        (0x1058D, \"M\", \"𐖴\"),\n        (0x1058E, \"M\", \"𐖵\"),\n        (0x1058F, \"M\", \"𐖶\"),\n        (0x10590, \"M\", \"𐖷\"),\n        (0x10591, \"M\", \"𐖸\"),\n        (0x10592, \"M\", \"𐖹\"),\n        (0x10593, \"X\"),\n        (0x10594, \"M\", \"𐖻\"),\n        (0x10595, \"M\", \"𐖼\"),\n        (0x10596, \"X\"),\n        (0x10597, \"V\"),\n        (0x105A2, \"X\"),\n        (0x105A3, \"V\"),\n        (0x105B2, \"X\"),\n        (0x105B3, \"V\"),\n        (0x105BA, \"X\"),\n        (0x105BB, \"V\"),\n        (0x105BD, \"X\"),\n        (0x105C0, \"V\"),\n        (0x105F4, \"X\"),\n        (0x10600, \"V\"),\n        (0x10737, \"X\"),\n        (0x10740, \"V\"),\n        (0x10756, \"X\"),\n        (0x10760, \"V\"),\n        (0x10768, \"X\"),\n        (0x10780, \"V\"),\n        (0x10781, \"M\", \"ː\"),\n        (0x10782, \"M\", \"ˑ\"),\n        (0x10783, \"M\", \"æ\"),\n        (0x10784, \"M\", \"ʙ\"),\n        (0x10785, \"M\", \"ɓ\"),\n        (0x10786, \"X\"),\n        (0x10787, \"M\", \"ʣ\"),\n        (0x10788, \"M\", \"ꭦ\"),\n        (0x10789, \"M\", \"ʥ\"),\n        (0x1078A, \"M\", \"ʤ\"),\n        (0x1078B, \"M\", \"ɖ\"),\n        (0x1078C, \"M\", \"ɗ\"),\n        (0x1078D, \"M\", \"ᶑ\"),\n        (0x1078E, \"M\", \"ɘ\"),\n        (0x1078F, \"M\", \"ɞ\"),\n        (0x10790, \"M\", \"ʩ\"),\n        (0x10791, \"M\", \"ɤ\"),\n        (0x10792, \"M\", \"ɢ\"),\n        (0x10793, \"M\", \"ɠ\"),\n        (0x10794, \"M\", \"ʛ\"),\n        (0x10795, \"M\", \"ħ\"),\n        (0x10796, \"M\", \"ʜ\"),\n        (0x10797, \"M\", \"ɧ\"),\n        (0x10798, \"M\", \"ʄ\"),\n        (0x10799, \"M\", \"ʪ\"),\n        (0x1079A, \"M\", \"ʫ\"),\n        (0x1079B, \"M\", \"ɬ\"),\n        (0x1079C, \"M\", \"𝼄\"),\n        (0x1079D, \"M\", \"ꞎ\"),\n        (0x1079E, \"M\", \"ɮ\"),\n        (0x1079F, \"M\", \"𝼅\"),\n        (0x107A0, \"M\", \"ʎ\"),\n        (0x107A1, \"M\", \"𝼆\"),\n        (0x107A2, \"M\", \"ø\"),\n        (0x107A3, \"M\", \"ɶ\"),\n        (0x107A4, \"M\", \"ɷ\"),\n        (0x107A5, \"M\", \"q\"),\n        (0x107A6, \"M\", \"ɺ\"),\n        (0x107A7, \"M\", \"𝼈\"),\n        (0x107A8, \"M\", \"ɽ\"),\n        (0x107A9, \"M\", \"ɾ\"),\n        (0x107AA, \"M\", \"ʀ\"),\n        (0x107AB, \"M\", \"ʨ\"),\n        (0x107AC, \"M\", \"ʦ\"),\n        (0x107AD, \"M\", \"ꭧ\"),\n        (0x107AE, \"M\", \"ʧ\"),\n        (0x107AF, \"M\", \"ʈ\"),\n        (0x107B0, \"M\", \"ⱱ\"),\n        (0x107B1, \"X\"),\n        (0x107B2, \"M\", \"ʏ\"),\n        (0x107B3, \"M\", \"ʡ\"),\n        (0x107B4, \"M\", \"ʢ\"),\n        (0x107B5, \"M\", \"ʘ\"),\n        (0x107B6, \"M\", \"ǀ\"),\n        (0x107B7, \"M\", \"ǁ\"),\n        (0x107B8, \"M\", \"ǂ\"),\n        (0x107B9, \"M\", \"𝼊\"),\n        (0x107BA, \"M\", \"𝼞\"),\n        (0x107BB, \"X\"),\n        (0x10800, \"V\"),\n        (0x10806, \"X\"),\n        (0x10808, \"V\"),\n        (0x10809, \"X\"),\n        (0x1080A, \"V\"),\n        (0x10836, \"X\"),\n        (0x10837, \"V\"),\n        (0x10839, \"X\"),\n        (0x1083C, \"V\"),\n        (0x1083D, \"X\"),\n        (0x1083F, \"V\"),\n        (0x10856, \"X\"),\n    ]\n\n\ndef _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x10857, \"V\"),\n        (0x1089F, \"X\"),\n        (0x108A7, \"V\"),\n        (0x108B0, \"X\"),\n        (0x108E0, \"V\"),\n        (0x108F3, \"X\"),\n        (0x108F4, \"V\"),\n        (0x108F6, \"X\"),\n        (0x108FB, \"V\"),\n        (0x1091C, \"X\"),\n        (0x1091F, \"V\"),\n        (0x1093A, \"X\"),\n        (0x1093F, \"V\"),\n        (0x10940, \"X\"),\n        (0x10980, \"V\"),\n        (0x109B8, \"X\"),\n        (0x109BC, \"V\"),\n        (0x109D0, \"X\"),\n        (0x109D2, \"V\"),\n        (0x10A04, \"X\"),\n        (0x10A05, \"V\"),\n        (0x10A07, \"X\"),\n        (0x10A0C, \"V\"),\n        (0x10A14, \"X\"),\n        (0x10A15, \"V\"),\n        (0x10A18, \"X\"),\n        (0x10A19, \"V\"),\n        (0x10A36, \"X\"),\n        (0x10A38, \"V\"),\n        (0x10A3B, \"X\"),\n        (0x10A3F, \"V\"),\n        (0x10A49, \"X\"),\n        (0x10A50, \"V\"),\n        (0x10A59, \"X\"),\n        (0x10A60, \"V\"),\n        (0x10AA0, \"X\"),\n        (0x10AC0, \"V\"),\n        (0x10AE7, \"X\"),\n        (0x10AEB, \"V\"),\n        (0x10AF7, \"X\"),\n        (0x10B00, \"V\"),\n        (0x10B36, \"X\"),\n        (0x10B39, \"V\"),\n        (0x10B56, \"X\"),\n        (0x10B58, \"V\"),\n        (0x10B73, \"X\"),\n        (0x10B78, \"V\"),\n        (0x10B92, \"X\"),\n        (0x10B99, \"V\"),\n        (0x10B9D, \"X\"),\n        (0x10BA9, \"V\"),\n        (0x10BB0, \"X\"),\n        (0x10C00, \"V\"),\n        (0x10C49, \"X\"),\n        (0x10C80, \"M\", \"𐳀\"),\n        (0x10C81, \"M\", \"𐳁\"),\n        (0x10C82, \"M\", \"𐳂\"),\n        (0x10C83, \"M\", \"𐳃\"),\n        (0x10C84, \"M\", \"𐳄\"),\n        (0x10C85, \"M\", \"𐳅\"),\n        (0x10C86, \"M\", \"𐳆\"),\n        (0x10C87, \"M\", \"𐳇\"),\n        (0x10C88, \"M\", \"𐳈\"),\n        (0x10C89, \"M\", \"𐳉\"),\n        (0x10C8A, \"M\", \"𐳊\"),\n        (0x10C8B, \"M\", \"𐳋\"),\n        (0x10C8C, \"M\", \"𐳌\"),\n        (0x10C8D, \"M\", \"𐳍\"),\n        (0x10C8E, \"M\", \"𐳎\"),\n        (0x10C8F, \"M\", \"𐳏\"),\n        (0x10C90, \"M\", \"𐳐\"),\n        (0x10C91, \"M\", \"𐳑\"),\n        (0x10C92, \"M\", \"𐳒\"),\n        (0x10C93, \"M\", \"𐳓\"),\n        (0x10C94, \"M\", \"𐳔\"),\n        (0x10C95, \"M\", \"𐳕\"),\n        (0x10C96, \"M\", \"𐳖\"),\n        (0x10C97, \"M\", \"𐳗\"),\n        (0x10C98, \"M\", \"𐳘\"),\n        (0x10C99, \"M\", \"𐳙\"),\n        (0x10C9A, \"M\", \"𐳚\"),\n        (0x10C9B, \"M\", \"𐳛\"),\n        (0x10C9C, \"M\", \"𐳜\"),\n        (0x10C9D, \"M\", \"𐳝\"),\n        (0x10C9E, \"M\", \"𐳞\"),\n        (0x10C9F, \"M\", \"𐳟\"),\n        (0x10CA0, \"M\", \"𐳠\"),\n        (0x10CA1, \"M\", \"𐳡\"),\n        (0x10CA2, \"M\", \"𐳢\"),\n        (0x10CA3, \"M\", \"𐳣\"),\n        (0x10CA4, \"M\", \"𐳤\"),\n        (0x10CA5, \"M\", \"𐳥\"),\n        (0x10CA6, \"M\", \"𐳦\"),\n        (0x10CA7, \"M\", \"𐳧\"),\n        (0x10CA8, \"M\", \"𐳨\"),\n        (0x10CA9, \"M\", \"𐳩\"),\n        (0x10CAA, \"M\", \"𐳪\"),\n        (0x10CAB, \"M\", \"𐳫\"),\n        (0x10CAC, \"M\", \"𐳬\"),\n        (0x10CAD, \"M\", \"𐳭\"),\n    ]\n\n\ndef _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x10CAE, \"M\", \"𐳮\"),\n        (0x10CAF, \"M\", \"𐳯\"),\n        (0x10CB0, \"M\", \"𐳰\"),\n        (0x10CB1, \"M\", \"𐳱\"),\n        (0x10CB2, \"M\", \"𐳲\"),\n        (0x10CB3, \"X\"),\n        (0x10CC0, \"V\"),\n        (0x10CF3, \"X\"),\n        (0x10CFA, \"V\"),\n        (0x10D28, \"X\"),\n        (0x10D30, \"V\"),\n        (0x10D3A, \"X\"),\n        (0x10D40, \"V\"),\n        (0x10D50, \"M\", \"𐵰\"),\n        (0x10D51, \"M\", \"𐵱\"),\n        (0x10D52, \"M\", \"𐵲\"),\n        (0x10D53, \"M\", \"𐵳\"),\n        (0x10D54, \"M\", \"𐵴\"),\n        (0x10D55, \"M\", \"𐵵\"),\n        (0x10D56, \"M\", \"𐵶\"),\n        (0x10D57, \"M\", \"𐵷\"),\n        (0x10D58, \"M\", \"𐵸\"),\n        (0x10D59, \"M\", \"𐵹\"),\n        (0x10D5A, \"M\", \"𐵺\"),\n        (0x10D5B, \"M\", \"𐵻\"),\n        (0x10D5C, \"M\", \"𐵼\"),\n        (0x10D5D, \"M\", \"𐵽\"),\n        (0x10D5E, \"M\", \"𐵾\"),\n        (0x10D5F, \"M\", \"𐵿\"),\n        (0x10D60, \"M\", \"𐶀\"),\n        (0x10D61, \"M\", \"𐶁\"),\n        (0x10D62, \"M\", \"𐶂\"),\n        (0x10D63, \"M\", \"𐶃\"),\n        (0x10D64, \"M\", \"𐶄\"),\n        (0x10D65, \"M\", \"𐶅\"),\n        (0x10D66, \"X\"),\n        (0x10D69, \"V\"),\n        (0x10D86, \"X\"),\n        (0x10D8E, \"V\"),\n        (0x10D90, \"X\"),\n        (0x10E60, \"V\"),\n        (0x10E7F, \"X\"),\n        (0x10E80, \"V\"),\n        (0x10EAA, \"X\"),\n        (0x10EAB, \"V\"),\n        (0x10EAE, \"X\"),\n        (0x10EB0, \"V\"),\n        (0x10EB2, \"X\"),\n        (0x10EC2, \"V\"),\n        (0x10EC5, \"X\"),\n        (0x10EFC, \"V\"),\n        (0x10F28, \"X\"),\n        (0x10F30, \"V\"),\n        (0x10F5A, \"X\"),\n        (0x10F70, \"V\"),\n        (0x10F8A, \"X\"),\n        (0x10FB0, \"V\"),\n        (0x10FCC, \"X\"),\n        (0x10FE0, \"V\"),\n        (0x10FF7, \"X\"),\n        (0x11000, \"V\"),\n        (0x1104E, \"X\"),\n        (0x11052, \"V\"),\n        (0x11076, \"X\"),\n        (0x1107F, \"V\"),\n        (0x110BD, \"X\"),\n        (0x110BE, \"V\"),\n        (0x110C3, \"X\"),\n        (0x110D0, \"V\"),\n        (0x110E9, \"X\"),\n        (0x110F0, \"V\"),\n        (0x110FA, \"X\"),\n        (0x11100, \"V\"),\n        (0x11135, \"X\"),\n        (0x11136, \"V\"),\n        (0x11148, \"X\"),\n        (0x11150, \"V\"),\n        (0x11177, \"X\"),\n        (0x11180, \"V\"),\n        (0x111E0, \"X\"),\n        (0x111E1, \"V\"),\n        (0x111F5, \"X\"),\n        (0x11200, \"V\"),\n        (0x11212, \"X\"),\n        (0x11213, \"V\"),\n        (0x11242, \"X\"),\n        (0x11280, \"V\"),\n        (0x11287, \"X\"),\n        (0x11288, \"V\"),\n        (0x11289, \"X\"),\n        (0x1128A, \"V\"),\n        (0x1128E, \"X\"),\n        (0x1128F, \"V\"),\n        (0x1129E, \"X\"),\n        (0x1129F, \"V\"),\n        (0x112AA, \"X\"),\n        (0x112B0, \"V\"),\n        (0x112EB, \"X\"),\n        (0x112F0, \"V\"),\n        (0x112FA, \"X\"),\n    ]\n\n\ndef _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x11300, \"V\"),\n        (0x11304, \"X\"),\n        (0x11305, \"V\"),\n        (0x1130D, \"X\"),\n        (0x1130F, \"V\"),\n        (0x11311, \"X\"),\n        (0x11313, \"V\"),\n        (0x11329, \"X\"),\n        (0x1132A, \"V\"),\n        (0x11331, \"X\"),\n        (0x11332, \"V\"),\n        (0x11334, \"X\"),\n        (0x11335, \"V\"),\n        (0x1133A, \"X\"),\n        (0x1133B, \"V\"),\n        (0x11345, \"X\"),\n        (0x11347, \"V\"),\n        (0x11349, \"X\"),\n        (0x1134B, \"V\"),\n        (0x1134E, \"X\"),\n        (0x11350, \"V\"),\n        (0x11351, \"X\"),\n        (0x11357, \"V\"),\n        (0x11358, \"X\"),\n        (0x1135D, \"V\"),\n        (0x11364, \"X\"),\n        (0x11366, \"V\"),\n        (0x1136D, \"X\"),\n        (0x11370, \"V\"),\n        (0x11375, \"X\"),\n        (0x11380, \"V\"),\n        (0x1138A, \"X\"),\n        (0x1138B, \"V\"),\n        (0x1138C, \"X\"),\n        (0x1138E, \"V\"),\n        (0x1138F, \"X\"),\n        (0x11390, \"V\"),\n        (0x113B6, \"X\"),\n        (0x113B7, \"V\"),\n        (0x113C1, \"X\"),\n        (0x113C2, \"V\"),\n        (0x113C3, \"X\"),\n        (0x113C5, \"V\"),\n        (0x113C6, \"X\"),\n        (0x113C7, \"V\"),\n        (0x113CB, \"X\"),\n        (0x113CC, \"V\"),\n        (0x113D6, \"X\"),\n        (0x113D7, \"V\"),\n        (0x113D9, \"X\"),\n        (0x113E1, \"V\"),\n        (0x113E3, \"X\"),\n        (0x11400, \"V\"),\n        (0x1145C, \"X\"),\n        (0x1145D, \"V\"),\n        (0x11462, \"X\"),\n        (0x11480, \"V\"),\n        (0x114C8, \"X\"),\n        (0x114D0, \"V\"),\n        (0x114DA, \"X\"),\n        (0x11580, \"V\"),\n        (0x115B6, \"X\"),\n        (0x115B8, \"V\"),\n        (0x115DE, \"X\"),\n        (0x11600, \"V\"),\n        (0x11645, \"X\"),\n        (0x11650, \"V\"),\n        (0x1165A, \"X\"),\n        (0x11660, \"V\"),\n        (0x1166D, \"X\"),\n        (0x11680, \"V\"),\n        (0x116BA, \"X\"),\n        (0x116C0, \"V\"),\n        (0x116CA, \"X\"),\n        (0x116D0, \"V\"),\n        (0x116E4, \"X\"),\n        (0x11700, \"V\"),\n        (0x1171B, \"X\"),\n        (0x1171D, \"V\"),\n        (0x1172C, \"X\"),\n        (0x11730, \"V\"),\n        (0x11747, \"X\"),\n        (0x11800, \"V\"),\n        (0x1183C, \"X\"),\n        (0x118A0, \"M\", \"𑣀\"),\n        (0x118A1, \"M\", \"𑣁\"),\n        (0x118A2, \"M\", \"𑣂\"),\n        (0x118A3, \"M\", \"𑣃\"),\n        (0x118A4, \"M\", \"𑣄\"),\n        (0x118A5, \"M\", \"𑣅\"),\n        (0x118A6, \"M\", \"𑣆\"),\n        (0x118A7, \"M\", \"𑣇\"),\n        (0x118A8, \"M\", \"𑣈\"),\n        (0x118A9, \"M\", \"𑣉\"),\n        (0x118AA, \"M\", \"𑣊\"),\n        (0x118AB, \"M\", \"𑣋\"),\n        (0x118AC, \"M\", \"𑣌\"),\n        (0x118AD, \"M\", \"𑣍\"),\n        (0x118AE, \"M\", \"𑣎\"),\n        (0x118AF, \"M\", \"𑣏\"),\n    ]\n\n\ndef _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x118B0, \"M\", \"𑣐\"),\n        (0x118B1, \"M\", \"𑣑\"),\n        (0x118B2, \"M\", \"𑣒\"),\n        (0x118B3, \"M\", \"𑣓\"),\n        (0x118B4, \"M\", \"𑣔\"),\n        (0x118B5, \"M\", \"𑣕\"),\n        (0x118B6, \"M\", \"𑣖\"),\n        (0x118B7, \"M\", \"𑣗\"),\n        (0x118B8, \"M\", \"𑣘\"),\n        (0x118B9, \"M\", \"𑣙\"),\n        (0x118BA, \"M\", \"𑣚\"),\n        (0x118BB, \"M\", \"𑣛\"),\n        (0x118BC, \"M\", \"𑣜\"),\n        (0x118BD, \"M\", \"𑣝\"),\n        (0x118BE, \"M\", \"𑣞\"),\n        (0x118BF, \"M\", \"𑣟\"),\n        (0x118C0, \"V\"),\n        (0x118F3, \"X\"),\n        (0x118FF, \"V\"),\n        (0x11907, \"X\"),\n        (0x11909, \"V\"),\n        (0x1190A, \"X\"),\n        (0x1190C, \"V\"),\n        (0x11914, \"X\"),\n        (0x11915, \"V\"),\n        (0x11917, \"X\"),\n        (0x11918, \"V\"),\n        (0x11936, \"X\"),\n        (0x11937, \"V\"),\n        (0x11939, \"X\"),\n        (0x1193B, \"V\"),\n        (0x11947, \"X\"),\n        (0x11950, \"V\"),\n        (0x1195A, \"X\"),\n        (0x119A0, \"V\"),\n        (0x119A8, \"X\"),\n        (0x119AA, \"V\"),\n        (0x119D8, \"X\"),\n        (0x119DA, \"V\"),\n        (0x119E5, \"X\"),\n        (0x11A00, \"V\"),\n        (0x11A48, \"X\"),\n        (0x11A50, \"V\"),\n        (0x11AA3, \"X\"),\n        (0x11AB0, \"V\"),\n        (0x11AF9, \"X\"),\n        (0x11B00, \"V\"),\n        (0x11B0A, \"X\"),\n        (0x11BC0, \"V\"),\n        (0x11BE2, \"X\"),\n        (0x11BF0, \"V\"),\n        (0x11BFA, \"X\"),\n        (0x11C00, \"V\"),\n        (0x11C09, \"X\"),\n        (0x11C0A, \"V\"),\n        (0x11C37, \"X\"),\n        (0x11C38, \"V\"),\n        (0x11C46, \"X\"),\n        (0x11C50, \"V\"),\n        (0x11C6D, \"X\"),\n        (0x11C70, \"V\"),\n        (0x11C90, \"X\"),\n        (0x11C92, \"V\"),\n        (0x11CA8, \"X\"),\n        (0x11CA9, \"V\"),\n        (0x11CB7, \"X\"),\n        (0x11D00, \"V\"),\n        (0x11D07, \"X\"),\n        (0x11D08, \"V\"),\n        (0x11D0A, \"X\"),\n        (0x11D0B, \"V\"),\n        (0x11D37, \"X\"),\n        (0x11D3A, \"V\"),\n        (0x11D3B, \"X\"),\n        (0x11D3C, \"V\"),\n        (0x11D3E, \"X\"),\n        (0x11D3F, \"V\"),\n        (0x11D48, \"X\"),\n        (0x11D50, \"V\"),\n        (0x11D5A, \"X\"),\n        (0x11D60, \"V\"),\n        (0x11D66, \"X\"),\n        (0x11D67, \"V\"),\n        (0x11D69, \"X\"),\n        (0x11D6A, \"V\"),\n        (0x11D8F, \"X\"),\n        (0x11D90, \"V\"),\n        (0x11D92, \"X\"),\n        (0x11D93, \"V\"),\n        (0x11D99, \"X\"),\n        (0x11DA0, \"V\"),\n        (0x11DAA, \"X\"),\n        (0x11EE0, \"V\"),\n        (0x11EF9, \"X\"),\n        (0x11F00, \"V\"),\n        (0x11F11, \"X\"),\n        (0x11F12, \"V\"),\n        (0x11F3B, \"X\"),\n        (0x11F3E, \"V\"),\n        (0x11F5B, \"X\"),\n    ]\n\n\ndef _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x11FB0, \"V\"),\n        (0x11FB1, \"X\"),\n        (0x11FC0, \"V\"),\n        (0x11FF2, \"X\"),\n        (0x11FFF, \"V\"),\n        (0x1239A, \"X\"),\n        (0x12400, \"V\"),\n        (0x1246F, \"X\"),\n        (0x12470, \"V\"),\n        (0x12475, \"X\"),\n        (0x12480, \"V\"),\n        (0x12544, \"X\"),\n        (0x12F90, \"V\"),\n        (0x12FF3, \"X\"),\n        (0x13000, \"V\"),\n        (0x13430, \"X\"),\n        (0x13440, \"V\"),\n        (0x13456, \"X\"),\n        (0x13460, \"V\"),\n        (0x143FB, \"X\"),\n        (0x14400, \"V\"),\n        (0x14647, \"X\"),\n        (0x16100, \"V\"),\n        (0x1613A, \"X\"),\n        (0x16800, \"V\"),\n        (0x16A39, \"X\"),\n        (0x16A40, \"V\"),\n        (0x16A5F, \"X\"),\n        (0x16A60, \"V\"),\n        (0x16A6A, \"X\"),\n        (0x16A6E, \"V\"),\n        (0x16ABF, \"X\"),\n        (0x16AC0, \"V\"),\n        (0x16ACA, \"X\"),\n        (0x16AD0, \"V\"),\n        (0x16AEE, \"X\"),\n        (0x16AF0, \"V\"),\n        (0x16AF6, \"X\"),\n        (0x16B00, \"V\"),\n        (0x16B46, \"X\"),\n        (0x16B50, \"V\"),\n        (0x16B5A, \"X\"),\n        (0x16B5B, \"V\"),\n        (0x16B62, \"X\"),\n        (0x16B63, \"V\"),\n        (0x16B78, \"X\"),\n        (0x16B7D, \"V\"),\n        (0x16B90, \"X\"),\n        (0x16D40, \"V\"),\n        (0x16D7A, \"X\"),\n        (0x16E40, \"M\", \"𖹠\"),\n        (0x16E41, \"M\", \"𖹡\"),\n        (0x16E42, \"M\", \"𖹢\"),\n        (0x16E43, \"M\", \"𖹣\"),\n        (0x16E44, \"M\", \"𖹤\"),\n        (0x16E45, \"M\", \"𖹥\"),\n        (0x16E46, \"M\", \"𖹦\"),\n        (0x16E47, \"M\", \"𖹧\"),\n        (0x16E48, \"M\", \"𖹨\"),\n        (0x16E49, \"M\", \"𖹩\"),\n        (0x16E4A, \"M\", \"𖹪\"),\n        (0x16E4B, \"M\", \"𖹫\"),\n        (0x16E4C, \"M\", \"𖹬\"),\n        (0x16E4D, \"M\", \"𖹭\"),\n        (0x16E4E, \"M\", \"𖹮\"),\n        (0x16E4F, \"M\", \"𖹯\"),\n        (0x16E50, \"M\", \"𖹰\"),\n        (0x16E51, \"M\", \"𖹱\"),\n        (0x16E52, \"M\", \"𖹲\"),\n        (0x16E53, \"M\", \"𖹳\"),\n        (0x16E54, \"M\", \"𖹴\"),\n        (0x16E55, \"M\", \"𖹵\"),\n        (0x16E56, \"M\", \"𖹶\"),\n        (0x16E57, \"M\", \"𖹷\"),\n        (0x16E58, \"M\", \"𖹸\"),\n        (0x16E59, \"M\", \"𖹹\"),\n        (0x16E5A, \"M\", \"𖹺\"),\n        (0x16E5B, \"M\", \"𖹻\"),\n        (0x16E5C, \"M\", \"𖹼\"),\n        (0x16E5D, \"M\", \"𖹽\"),\n        (0x16E5E, \"M\", \"𖹾\"),\n        (0x16E5F, \"M\", \"𖹿\"),\n        (0x16E60, \"V\"),\n        (0x16E9B, \"X\"),\n        (0x16F00, \"V\"),\n        (0x16F4B, \"X\"),\n        (0x16F4F, \"V\"),\n        (0x16F88, \"X\"),\n        (0x16F8F, \"V\"),\n        (0x16FA0, \"X\"),\n        (0x16FE0, \"V\"),\n        (0x16FE5, \"X\"),\n        (0x16FF0, \"V\"),\n        (0x16FF2, \"X\"),\n        (0x17000, \"V\"),\n        (0x187F8, \"X\"),\n        (0x18800, \"V\"),\n        (0x18CD6, \"X\"),\n        (0x18CFF, \"V\"),\n        (0x18D09, \"X\"),\n    ]\n\n\ndef _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1AFF0, \"V\"),\n        (0x1AFF4, \"X\"),\n        (0x1AFF5, \"V\"),\n        (0x1AFFC, \"X\"),\n        (0x1AFFD, \"V\"),\n        (0x1AFFF, \"X\"),\n        (0x1B000, \"V\"),\n        (0x1B123, \"X\"),\n        (0x1B132, \"V\"),\n        (0x1B133, \"X\"),\n        (0x1B150, \"V\"),\n        (0x1B153, \"X\"),\n        (0x1B155, \"V\"),\n        (0x1B156, \"X\"),\n        (0x1B164, \"V\"),\n        (0x1B168, \"X\"),\n        (0x1B170, \"V\"),\n        (0x1B2FC, \"X\"),\n        (0x1BC00, \"V\"),\n        (0x1BC6B, \"X\"),\n        (0x1BC70, \"V\"),\n        (0x1BC7D, \"X\"),\n        (0x1BC80, \"V\"),\n        (0x1BC89, \"X\"),\n        (0x1BC90, \"V\"),\n        (0x1BC9A, \"X\"),\n        (0x1BC9C, \"V\"),\n        (0x1BCA0, \"I\"),\n        (0x1BCA4, \"X\"),\n        (0x1CC00, \"V\"),\n        (0x1CCD6, \"M\", \"a\"),\n        (0x1CCD7, \"M\", \"b\"),\n        (0x1CCD8, \"M\", \"c\"),\n        (0x1CCD9, \"M\", \"d\"),\n        (0x1CCDA, \"M\", \"e\"),\n        (0x1CCDB, \"M\", \"f\"),\n        (0x1CCDC, \"M\", \"g\"),\n        (0x1CCDD, \"M\", \"h\"),\n        (0x1CCDE, \"M\", \"i\"),\n        (0x1CCDF, \"M\", \"j\"),\n        (0x1CCE0, \"M\", \"k\"),\n        (0x1CCE1, \"M\", \"l\"),\n        (0x1CCE2, \"M\", \"m\"),\n        (0x1CCE3, \"M\", \"n\"),\n        (0x1CCE4, \"M\", \"o\"),\n        (0x1CCE5, \"M\", \"p\"),\n        (0x1CCE6, \"M\", \"q\"),\n        (0x1CCE7, \"M\", \"r\"),\n        (0x1CCE8, \"M\", \"s\"),\n        (0x1CCE9, \"M\", \"t\"),\n        (0x1CCEA, \"M\", \"u\"),\n        (0x1CCEB, \"M\", \"v\"),\n        (0x1CCEC, \"M\", \"w\"),\n        (0x1CCED, \"M\", \"x\"),\n        (0x1CCEE, \"M\", \"y\"),\n        (0x1CCEF, \"M\", \"z\"),\n        (0x1CCF0, \"M\", \"0\"),\n        (0x1CCF1, \"M\", \"1\"),\n        (0x1CCF2, \"M\", \"2\"),\n        (0x1CCF3, \"M\", \"3\"),\n        (0x1CCF4, \"M\", \"4\"),\n        (0x1CCF5, \"M\", \"5\"),\n        (0x1CCF6, \"M\", \"6\"),\n        (0x1CCF7, \"M\", \"7\"),\n        (0x1CCF8, \"M\", \"8\"),\n        (0x1CCF9, \"M\", \"9\"),\n        (0x1CCFA, \"X\"),\n        (0x1CD00, \"V\"),\n        (0x1CEB4, \"X\"),\n        (0x1CF00, \"V\"),\n        (0x1CF2E, \"X\"),\n        (0x1CF30, \"V\"),\n        (0x1CF47, \"X\"),\n        (0x1CF50, \"V\"),\n        (0x1CFC4, \"X\"),\n        (0x1D000, \"V\"),\n        (0x1D0F6, \"X\"),\n        (0x1D100, \"V\"),\n        (0x1D127, \"X\"),\n        (0x1D129, \"V\"),\n        (0x1D15E, \"M\", \"𝅗𝅥\"),\n        (0x1D15F, \"M\", \"𝅘𝅥\"),\n        (0x1D160, \"M\", \"𝅘𝅥𝅮\"),\n        (0x1D161, \"M\", \"𝅘𝅥𝅯\"),\n        (0x1D162, \"M\", \"𝅘𝅥𝅰\"),\n        (0x1D163, \"M\", \"𝅘𝅥𝅱\"),\n        (0x1D164, \"M\", \"𝅘𝅥𝅲\"),\n        (0x1D165, \"V\"),\n        (0x1D173, \"I\"),\n        (0x1D17B, \"V\"),\n        (0x1D1BB, \"M\", \"𝆹𝅥\"),\n        (0x1D1BC, \"M\", \"𝆺𝅥\"),\n        (0x1D1BD, \"M\", \"𝆹𝅥𝅮\"),\n        (0x1D1BE, \"M\", \"𝆺𝅥𝅮\"),\n        (0x1D1BF, \"M\", \"𝆹𝅥𝅯\"),\n        (0x1D1C0, \"M\", \"𝆺𝅥𝅯\"),\n        (0x1D1C1, \"V\"),\n        (0x1D1EB, \"X\"),\n        (0x1D200, \"V\"),\n        (0x1D246, \"X\"),\n    ]\n\n\ndef _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D2C0, \"V\"),\n        (0x1D2D4, \"X\"),\n        (0x1D2E0, \"V\"),\n        (0x1D2F4, \"X\"),\n        (0x1D300, \"V\"),\n        (0x1D357, \"X\"),\n        (0x1D360, \"V\"),\n        (0x1D379, \"X\"),\n        (0x1D400, \"M\", \"a\"),\n        (0x1D401, \"M\", \"b\"),\n        (0x1D402, \"M\", \"c\"),\n        (0x1D403, \"M\", \"d\"),\n        (0x1D404, \"M\", \"e\"),\n        (0x1D405, \"M\", \"f\"),\n        (0x1D406, \"M\", \"g\"),\n        (0x1D407, \"M\", \"h\"),\n        (0x1D408, \"M\", \"i\"),\n        (0x1D409, \"M\", \"j\"),\n        (0x1D40A, \"M\", \"k\"),\n        (0x1D40B, \"M\", \"l\"),\n        (0x1D40C, \"M\", \"m\"),\n        (0x1D40D, \"M\", \"n\"),\n        (0x1D40E, \"M\", \"o\"),\n        (0x1D40F, \"M\", \"p\"),\n        (0x1D410, \"M\", \"q\"),\n        (0x1D411, \"M\", \"r\"),\n        (0x1D412, \"M\", \"s\"),\n        (0x1D413, \"M\", \"t\"),\n        (0x1D414, \"M\", \"u\"),\n        (0x1D415, \"M\", \"v\"),\n        (0x1D416, \"M\", \"w\"),\n        (0x1D417, \"M\", \"x\"),\n        (0x1D418, \"M\", \"y\"),\n        (0x1D419, \"M\", \"z\"),\n        (0x1D41A, \"M\", \"a\"),\n        (0x1D41B, \"M\", \"b\"),\n        (0x1D41C, \"M\", \"c\"),\n        (0x1D41D, \"M\", \"d\"),\n        (0x1D41E, \"M\", \"e\"),\n        (0x1D41F, \"M\", \"f\"),\n        (0x1D420, \"M\", \"g\"),\n        (0x1D421, \"M\", \"h\"),\n        (0x1D422, \"M\", \"i\"),\n        (0x1D423, \"M\", \"j\"),\n        (0x1D424, \"M\", \"k\"),\n        (0x1D425, \"M\", \"l\"),\n        (0x1D426, \"M\", \"m\"),\n        (0x1D427, \"M\", \"n\"),\n        (0x1D428, \"M\", \"o\"),\n        (0x1D429, \"M\", \"p\"),\n        (0x1D42A, \"M\", \"q\"),\n        (0x1D42B, \"M\", \"r\"),\n        (0x1D42C, \"M\", \"s\"),\n        (0x1D42D, \"M\", \"t\"),\n        (0x1D42E, \"M\", \"u\"),\n        (0x1D42F, \"M\", \"v\"),\n        (0x1D430, \"M\", \"w\"),\n        (0x1D431, \"M\", \"x\"),\n        (0x1D432, \"M\", \"y\"),\n        (0x1D433, \"M\", \"z\"),\n        (0x1D434, \"M\", \"a\"),\n        (0x1D435, \"M\", \"b\"),\n        (0x1D436, \"M\", \"c\"),\n        (0x1D437, \"M\", \"d\"),\n        (0x1D438, \"M\", \"e\"),\n        (0x1D439, \"M\", \"f\"),\n        (0x1D43A, \"M\", \"g\"),\n        (0x1D43B, \"M\", \"h\"),\n        (0x1D43C, \"M\", \"i\"),\n        (0x1D43D, \"M\", \"j\"),\n        (0x1D43E, \"M\", \"k\"),\n        (0x1D43F, \"M\", \"l\"),\n        (0x1D440, \"M\", \"m\"),\n        (0x1D441, \"M\", \"n\"),\n        (0x1D442, \"M\", \"o\"),\n        (0x1D443, \"M\", \"p\"),\n        (0x1D444, \"M\", \"q\"),\n        (0x1D445, \"M\", \"r\"),\n        (0x1D446, \"M\", \"s\"),\n        (0x1D447, \"M\", \"t\"),\n        (0x1D448, \"M\", \"u\"),\n        (0x1D449, \"M\", \"v\"),\n        (0x1D44A, \"M\", \"w\"),\n        (0x1D44B, \"M\", \"x\"),\n        (0x1D44C, \"M\", \"y\"),\n        (0x1D44D, \"M\", \"z\"),\n        (0x1D44E, \"M\", \"a\"),\n        (0x1D44F, \"M\", \"b\"),\n        (0x1D450, \"M\", \"c\"),\n        (0x1D451, \"M\", \"d\"),\n        (0x1D452, \"M\", \"e\"),\n        (0x1D453, \"M\", \"f\"),\n        (0x1D454, \"M\", \"g\"),\n        (0x1D455, \"X\"),\n        (0x1D456, \"M\", \"i\"),\n        (0x1D457, \"M\", \"j\"),\n        (0x1D458, \"M\", \"k\"),\n        (0x1D459, \"M\", \"l\"),\n        (0x1D45A, \"M\", \"m\"),\n        (0x1D45B, \"M\", \"n\"),\n    ]\n\n\ndef _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D45C, \"M\", \"o\"),\n        (0x1D45D, \"M\", \"p\"),\n        (0x1D45E, \"M\", \"q\"),\n        (0x1D45F, \"M\", \"r\"),\n        (0x1D460, \"M\", \"s\"),\n        (0x1D461, \"M\", \"t\"),\n        (0x1D462, \"M\", \"u\"),\n        (0x1D463, \"M\", \"v\"),\n        (0x1D464, \"M\", \"w\"),\n        (0x1D465, \"M\", \"x\"),\n        (0x1D466, \"M\", \"y\"),\n        (0x1D467, \"M\", \"z\"),\n        (0x1D468, \"M\", \"a\"),\n        (0x1D469, \"M\", \"b\"),\n        (0x1D46A, \"M\", \"c\"),\n        (0x1D46B, \"M\", \"d\"),\n        (0x1D46C, \"M\", \"e\"),\n        (0x1D46D, \"M\", \"f\"),\n        (0x1D46E, \"M\", \"g\"),\n        (0x1D46F, \"M\", \"h\"),\n        (0x1D470, \"M\", \"i\"),\n        (0x1D471, \"M\", \"j\"),\n        (0x1D472, \"M\", \"k\"),\n        (0x1D473, \"M\", \"l\"),\n        (0x1D474, \"M\", \"m\"),\n        (0x1D475, \"M\", \"n\"),\n        (0x1D476, \"M\", \"o\"),\n        (0x1D477, \"M\", \"p\"),\n        (0x1D478, \"M\", \"q\"),\n        (0x1D479, \"M\", \"r\"),\n        (0x1D47A, \"M\", \"s\"),\n        (0x1D47B, \"M\", \"t\"),\n        (0x1D47C, \"M\", \"u\"),\n        (0x1D47D, \"M\", \"v\"),\n        (0x1D47E, \"M\", \"w\"),\n        (0x1D47F, \"M\", \"x\"),\n        (0x1D480, \"M\", \"y\"),\n        (0x1D481, \"M\", \"z\"),\n        (0x1D482, \"M\", \"a\"),\n        (0x1D483, \"M\", \"b\"),\n        (0x1D484, \"M\", \"c\"),\n        (0x1D485, \"M\", \"d\"),\n        (0x1D486, \"M\", \"e\"),\n        (0x1D487, \"M\", \"f\"),\n        (0x1D488, \"M\", \"g\"),\n        (0x1D489, \"M\", \"h\"),\n        (0x1D48A, \"M\", \"i\"),\n        (0x1D48B, \"M\", \"j\"),\n        (0x1D48C, \"M\", \"k\"),\n        (0x1D48D, \"M\", \"l\"),\n        (0x1D48E, \"M\", \"m\"),\n        (0x1D48F, \"M\", \"n\"),\n        (0x1D490, \"M\", \"o\"),\n        (0x1D491, \"M\", \"p\"),\n        (0x1D492, \"M\", \"q\"),\n        (0x1D493, \"M\", \"r\"),\n        (0x1D494, \"M\", \"s\"),\n        (0x1D495, \"M\", \"t\"),\n        (0x1D496, \"M\", \"u\"),\n        (0x1D497, \"M\", \"v\"),\n        (0x1D498, \"M\", \"w\"),\n        (0x1D499, \"M\", \"x\"),\n        (0x1D49A, \"M\", \"y\"),\n        (0x1D49B, \"M\", \"z\"),\n        (0x1D49C, \"M\", \"a\"),\n        (0x1D49D, \"X\"),\n        (0x1D49E, \"M\", \"c\"),\n        (0x1D49F, \"M\", \"d\"),\n        (0x1D4A0, \"X\"),\n        (0x1D4A2, \"M\", \"g\"),\n        (0x1D4A3, \"X\"),\n        (0x1D4A5, \"M\", \"j\"),\n        (0x1D4A6, \"M\", \"k\"),\n        (0x1D4A7, \"X\"),\n        (0x1D4A9, \"M\", \"n\"),\n        (0x1D4AA, \"M\", \"o\"),\n        (0x1D4AB, \"M\", \"p\"),\n        (0x1D4AC, \"M\", \"q\"),\n        (0x1D4AD, \"X\"),\n        (0x1D4AE, \"M\", \"s\"),\n        (0x1D4AF, \"M\", \"t\"),\n        (0x1D4B0, \"M\", \"u\"),\n        (0x1D4B1, \"M\", \"v\"),\n        (0x1D4B2, \"M\", \"w\"),\n        (0x1D4B3, \"M\", \"x\"),\n        (0x1D4B4, \"M\", \"y\"),\n        (0x1D4B5, \"M\", \"z\"),\n        (0x1D4B6, \"M\", \"a\"),\n        (0x1D4B7, \"M\", \"b\"),\n        (0x1D4B8, \"M\", \"c\"),\n        (0x1D4B9, \"M\", \"d\"),\n        (0x1D4BA, \"X\"),\n        (0x1D4BB, \"M\", \"f\"),\n        (0x1D4BC, \"X\"),\n        (0x1D4BD, \"M\", \"h\"),\n        (0x1D4BE, \"M\", \"i\"),\n        (0x1D4BF, \"M\", \"j\"),\n        (0x1D4C0, \"M\", \"k\"),\n        (0x1D4C1, \"M\", \"l\"),\n        (0x1D4C2, \"M\", \"m\"),\n    ]\n\n\ndef _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D4C3, \"M\", \"n\"),\n        (0x1D4C4, \"X\"),\n        (0x1D4C5, \"M\", \"p\"),\n        (0x1D4C6, \"M\", \"q\"),\n        (0x1D4C7, \"M\", \"r\"),\n        (0x1D4C8, \"M\", \"s\"),\n        (0x1D4C9, \"M\", \"t\"),\n        (0x1D4CA, \"M\", \"u\"),\n        (0x1D4CB, \"M\", \"v\"),\n        (0x1D4CC, \"M\", \"w\"),\n        (0x1D4CD, \"M\", \"x\"),\n        (0x1D4CE, \"M\", \"y\"),\n        (0x1D4CF, \"M\", \"z\"),\n        (0x1D4D0, \"M\", \"a\"),\n        (0x1D4D1, \"M\", \"b\"),\n        (0x1D4D2, \"M\", \"c\"),\n        (0x1D4D3, \"M\", \"d\"),\n        (0x1D4D4, \"M\", \"e\"),\n        (0x1D4D5, \"M\", \"f\"),\n        (0x1D4D6, \"M\", \"g\"),\n        (0x1D4D7, \"M\", \"h\"),\n        (0x1D4D8, \"M\", \"i\"),\n        (0x1D4D9, \"M\", \"j\"),\n        (0x1D4DA, \"M\", \"k\"),\n        (0x1D4DB, \"M\", \"l\"),\n        (0x1D4DC, \"M\", \"m\"),\n        (0x1D4DD, \"M\", \"n\"),\n        (0x1D4DE, \"M\", \"o\"),\n        (0x1D4DF, \"M\", \"p\"),\n        (0x1D4E0, \"M\", \"q\"),\n        (0x1D4E1, \"M\", \"r\"),\n        (0x1D4E2, \"M\", \"s\"),\n        (0x1D4E3, \"M\", \"t\"),\n        (0x1D4E4, \"M\", \"u\"),\n        (0x1D4E5, \"M\", \"v\"),\n        (0x1D4E6, \"M\", \"w\"),\n        (0x1D4E7, \"M\", \"x\"),\n        (0x1D4E8, \"M\", \"y\"),\n        (0x1D4E9, \"M\", \"z\"),\n        (0x1D4EA, \"M\", \"a\"),\n        (0x1D4EB, \"M\", \"b\"),\n        (0x1D4EC, \"M\", \"c\"),\n        (0x1D4ED, \"M\", \"d\"),\n        (0x1D4EE, \"M\", \"e\"),\n        (0x1D4EF, \"M\", \"f\"),\n        (0x1D4F0, \"M\", \"g\"),\n        (0x1D4F1, \"M\", \"h\"),\n        (0x1D4F2, \"M\", \"i\"),\n        (0x1D4F3, \"M\", \"j\"),\n        (0x1D4F4, \"M\", \"k\"),\n        (0x1D4F5, \"M\", \"l\"),\n        (0x1D4F6, \"M\", \"m\"),\n        (0x1D4F7, \"M\", \"n\"),\n        (0x1D4F8, \"M\", \"o\"),\n        (0x1D4F9, \"M\", \"p\"),\n        (0x1D4FA, \"M\", \"q\"),\n        (0x1D4FB, \"M\", \"r\"),\n        (0x1D4FC, \"M\", \"s\"),\n        (0x1D4FD, \"M\", \"t\"),\n        (0x1D4FE, \"M\", \"u\"),\n        (0x1D4FF, \"M\", \"v\"),\n        (0x1D500, \"M\", \"w\"),\n        (0x1D501, \"M\", \"x\"),\n        (0x1D502, \"M\", \"y\"),\n        (0x1D503, \"M\", \"z\"),\n        (0x1D504, \"M\", \"a\"),\n        (0x1D505, \"M\", \"b\"),\n        (0x1D506, \"X\"),\n        (0x1D507, \"M\", \"d\"),\n        (0x1D508, \"M\", \"e\"),\n        (0x1D509, \"M\", \"f\"),\n        (0x1D50A, \"M\", \"g\"),\n        (0x1D50B, \"X\"),\n        (0x1D50D, \"M\", \"j\"),\n        (0x1D50E, \"M\", \"k\"),\n        (0x1D50F, \"M\", \"l\"),\n        (0x1D510, \"M\", \"m\"),\n        (0x1D511, \"M\", \"n\"),\n        (0x1D512, \"M\", \"o\"),\n        (0x1D513, \"M\", \"p\"),\n        (0x1D514, \"M\", \"q\"),\n        (0x1D515, \"X\"),\n        (0x1D516, \"M\", \"s\"),\n        (0x1D517, \"M\", \"t\"),\n        (0x1D518, \"M\", \"u\"),\n        (0x1D519, \"M\", \"v\"),\n        (0x1D51A, \"M\", \"w\"),\n        (0x1D51B, \"M\", \"x\"),\n        (0x1D51C, \"M\", \"y\"),\n        (0x1D51D, \"X\"),\n        (0x1D51E, \"M\", \"a\"),\n        (0x1D51F, \"M\", \"b\"),\n        (0x1D520, \"M\", \"c\"),\n        (0x1D521, \"M\", \"d\"),\n        (0x1D522, \"M\", \"e\"),\n        (0x1D523, \"M\", \"f\"),\n        (0x1D524, \"M\", \"g\"),\n        (0x1D525, \"M\", \"h\"),\n        (0x1D526, \"M\", \"i\"),\n        (0x1D527, \"M\", \"j\"),\n    ]\n\n\ndef _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D528, \"M\", \"k\"),\n        (0x1D529, \"M\", \"l\"),\n        (0x1D52A, \"M\", \"m\"),\n        (0x1D52B, \"M\", \"n\"),\n        (0x1D52C, \"M\", \"o\"),\n        (0x1D52D, \"M\", \"p\"),\n        (0x1D52E, \"M\", \"q\"),\n        (0x1D52F, \"M\", \"r\"),\n        (0x1D530, \"M\", \"s\"),\n        (0x1D531, \"M\", \"t\"),\n        (0x1D532, \"M\", \"u\"),\n        (0x1D533, \"M\", \"v\"),\n        (0x1D534, \"M\", \"w\"),\n        (0x1D535, \"M\", \"x\"),\n        (0x1D536, \"M\", \"y\"),\n        (0x1D537, \"M\", \"z\"),\n        (0x1D538, \"M\", \"a\"),\n        (0x1D539, \"M\", \"b\"),\n        (0x1D53A, \"X\"),\n        (0x1D53B, \"M\", \"d\"),\n        (0x1D53C, \"M\", \"e\"),\n        (0x1D53D, \"M\", \"f\"),\n        (0x1D53E, \"M\", \"g\"),\n        (0x1D53F, \"X\"),\n        (0x1D540, \"M\", \"i\"),\n        (0x1D541, \"M\", \"j\"),\n        (0x1D542, \"M\", \"k\"),\n        (0x1D543, \"M\", \"l\"),\n        (0x1D544, \"M\", \"m\"),\n        (0x1D545, \"X\"),\n        (0x1D546, \"M\", \"o\"),\n        (0x1D547, \"X\"),\n        (0x1D54A, \"M\", \"s\"),\n        (0x1D54B, \"M\", \"t\"),\n        (0x1D54C, \"M\", \"u\"),\n        (0x1D54D, \"M\", \"v\"),\n        (0x1D54E, \"M\", \"w\"),\n        (0x1D54F, \"M\", \"x\"),\n        (0x1D550, \"M\", \"y\"),\n        (0x1D551, \"X\"),\n        (0x1D552, \"M\", \"a\"),\n        (0x1D553, \"M\", \"b\"),\n        (0x1D554, \"M\", \"c\"),\n        (0x1D555, \"M\", \"d\"),\n        (0x1D556, \"M\", \"e\"),\n        (0x1D557, \"M\", \"f\"),\n        (0x1D558, \"M\", \"g\"),\n        (0x1D559, \"M\", \"h\"),\n        (0x1D55A, \"M\", \"i\"),\n        (0x1D55B, \"M\", \"j\"),\n        (0x1D55C, \"M\", \"k\"),\n        (0x1D55D, \"M\", \"l\"),\n        (0x1D55E, \"M\", \"m\"),\n        (0x1D55F, \"M\", \"n\"),\n        (0x1D560, \"M\", \"o\"),\n        (0x1D561, \"M\", \"p\"),\n        (0x1D562, \"M\", \"q\"),\n        (0x1D563, \"M\", \"r\"),\n        (0x1D564, \"M\", \"s\"),\n        (0x1D565, \"M\", \"t\"),\n        (0x1D566, \"M\", \"u\"),\n        (0x1D567, \"M\", \"v\"),\n        (0x1D568, \"M\", \"w\"),\n        (0x1D569, \"M\", \"x\"),\n        (0x1D56A, \"M\", \"y\"),\n        (0x1D56B, \"M\", \"z\"),\n        (0x1D56C, \"M\", \"a\"),\n        (0x1D56D, \"M\", \"b\"),\n        (0x1D56E, \"M\", \"c\"),\n        (0x1D56F, \"M\", \"d\"),\n        (0x1D570, \"M\", \"e\"),\n        (0x1D571, \"M\", \"f\"),\n        (0x1D572, \"M\", \"g\"),\n        (0x1D573, \"M\", \"h\"),\n        (0x1D574, \"M\", \"i\"),\n        (0x1D575, \"M\", \"j\"),\n        (0x1D576, \"M\", \"k\"),\n        (0x1D577, \"M\", \"l\"),\n        (0x1D578, \"M\", \"m\"),\n        (0x1D579, \"M\", \"n\"),\n        (0x1D57A, \"M\", \"o\"),\n        (0x1D57B, \"M\", \"p\"),\n        (0x1D57C, \"M\", \"q\"),\n        (0x1D57D, \"M\", \"r\"),\n        (0x1D57E, \"M\", \"s\"),\n        (0x1D57F, \"M\", \"t\"),\n        (0x1D580, \"M\", \"u\"),\n        (0x1D581, \"M\", \"v\"),\n        (0x1D582, \"M\", \"w\"),\n        (0x1D583, \"M\", \"x\"),\n        (0x1D584, \"M\", \"y\"),\n        (0x1D585, \"M\", \"z\"),\n        (0x1D586, \"M\", \"a\"),\n        (0x1D587, \"M\", \"b\"),\n        (0x1D588, \"M\", \"c\"),\n        (0x1D589, \"M\", \"d\"),\n        (0x1D58A, \"M\", \"e\"),\n        (0x1D58B, \"M\", \"f\"),\n        (0x1D58C, \"M\", \"g\"),\n        (0x1D58D, \"M\", \"h\"),\n    ]\n\n\ndef _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D58E, \"M\", \"i\"),\n        (0x1D58F, \"M\", \"j\"),\n        (0x1D590, \"M\", \"k\"),\n        (0x1D591, \"M\", \"l\"),\n        (0x1D592, \"M\", \"m\"),\n        (0x1D593, \"M\", \"n\"),\n        (0x1D594, \"M\", \"o\"),\n        (0x1D595, \"M\", \"p\"),\n        (0x1D596, \"M\", \"q\"),\n        (0x1D597, \"M\", \"r\"),\n        (0x1D598, \"M\", \"s\"),\n        (0x1D599, \"M\", \"t\"),\n        (0x1D59A, \"M\", \"u\"),\n        (0x1D59B, \"M\", \"v\"),\n        (0x1D59C, \"M\", \"w\"),\n        (0x1D59D, \"M\", \"x\"),\n        (0x1D59E, \"M\", \"y\"),\n        (0x1D59F, \"M\", \"z\"),\n        (0x1D5A0, \"M\", \"a\"),\n        (0x1D5A1, \"M\", \"b\"),\n        (0x1D5A2, \"M\", \"c\"),\n        (0x1D5A3, \"M\", \"d\"),\n        (0x1D5A4, \"M\", \"e\"),\n        (0x1D5A5, \"M\", \"f\"),\n        (0x1D5A6, \"M\", \"g\"),\n        (0x1D5A7, \"M\", \"h\"),\n        (0x1D5A8, \"M\", \"i\"),\n        (0x1D5A9, \"M\", \"j\"),\n        (0x1D5AA, \"M\", \"k\"),\n        (0x1D5AB, \"M\", \"l\"),\n        (0x1D5AC, \"M\", \"m\"),\n        (0x1D5AD, \"M\", \"n\"),\n        (0x1D5AE, \"M\", \"o\"),\n        (0x1D5AF, \"M\", \"p\"),\n        (0x1D5B0, \"M\", \"q\"),\n        (0x1D5B1, \"M\", \"r\"),\n        (0x1D5B2, \"M\", \"s\"),\n        (0x1D5B3, \"M\", \"t\"),\n        (0x1D5B4, \"M\", \"u\"),\n        (0x1D5B5, \"M\", \"v\"),\n        (0x1D5B6, \"M\", \"w\"),\n        (0x1D5B7, \"M\", \"x\"),\n        (0x1D5B8, \"M\", \"y\"),\n        (0x1D5B9, \"M\", \"z\"),\n        (0x1D5BA, \"M\", \"a\"),\n        (0x1D5BB, \"M\", \"b\"),\n        (0x1D5BC, \"M\", \"c\"),\n        (0x1D5BD, \"M\", \"d\"),\n        (0x1D5BE, \"M\", \"e\"),\n        (0x1D5BF, \"M\", \"f\"),\n        (0x1D5C0, \"M\", \"g\"),\n        (0x1D5C1, \"M\", \"h\"),\n        (0x1D5C2, \"M\", \"i\"),\n        (0x1D5C3, \"M\", \"j\"),\n        (0x1D5C4, \"M\", \"k\"),\n        (0x1D5C5, \"M\", \"l\"),\n        (0x1D5C6, \"M\", \"m\"),\n        (0x1D5C7, \"M\", \"n\"),\n        (0x1D5C8, \"M\", \"o\"),\n        (0x1D5C9, \"M\", \"p\"),\n        (0x1D5CA, \"M\", \"q\"),\n        (0x1D5CB, \"M\", \"r\"),\n        (0x1D5CC, \"M\", \"s\"),\n        (0x1D5CD, \"M\", \"t\"),\n        (0x1D5CE, \"M\", \"u\"),\n        (0x1D5CF, \"M\", \"v\"),\n        (0x1D5D0, \"M\", \"w\"),\n        (0x1D5D1, \"M\", \"x\"),\n        (0x1D5D2, \"M\", \"y\"),\n        (0x1D5D3, \"M\", \"z\"),\n        (0x1D5D4, \"M\", \"a\"),\n        (0x1D5D5, \"M\", \"b\"),\n        (0x1D5D6, \"M\", \"c\"),\n        (0x1D5D7, \"M\", \"d\"),\n        (0x1D5D8, \"M\", \"e\"),\n        (0x1D5D9, \"M\", \"f\"),\n        (0x1D5DA, \"M\", \"g\"),\n        (0x1D5DB, \"M\", \"h\"),\n        (0x1D5DC, \"M\", \"i\"),\n        (0x1D5DD, \"M\", \"j\"),\n        (0x1D5DE, \"M\", \"k\"),\n        (0x1D5DF, \"M\", \"l\"),\n        (0x1D5E0, \"M\", \"m\"),\n        (0x1D5E1, \"M\", \"n\"),\n        (0x1D5E2, \"M\", \"o\"),\n        (0x1D5E3, \"M\", \"p\"),\n        (0x1D5E4, \"M\", \"q\"),\n        (0x1D5E5, \"M\", \"r\"),\n        (0x1D5E6, \"M\", \"s\"),\n        (0x1D5E7, \"M\", \"t\"),\n        (0x1D5E8, \"M\", \"u\"),\n        (0x1D5E9, \"M\", \"v\"),\n        (0x1D5EA, \"M\", \"w\"),\n        (0x1D5EB, \"M\", \"x\"),\n        (0x1D5EC, \"M\", \"y\"),\n        (0x1D5ED, \"M\", \"z\"),\n        (0x1D5EE, \"M\", \"a\"),\n        (0x1D5EF, \"M\", \"b\"),\n        (0x1D5F0, \"M\", \"c\"),\n        (0x1D5F1, \"M\", \"d\"),\n    ]\n\n\ndef _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D5F2, \"M\", \"e\"),\n        (0x1D5F3, \"M\", \"f\"),\n        (0x1D5F4, \"M\", \"g\"),\n        (0x1D5F5, \"M\", \"h\"),\n        (0x1D5F6, \"M\", \"i\"),\n        (0x1D5F7, \"M\", \"j\"),\n        (0x1D5F8, \"M\", \"k\"),\n        (0x1D5F9, \"M\", \"l\"),\n        (0x1D5FA, \"M\", \"m\"),\n        (0x1D5FB, \"M\", \"n\"),\n        (0x1D5FC, \"M\", \"o\"),\n        (0x1D5FD, \"M\", \"p\"),\n        (0x1D5FE, \"M\", \"q\"),\n        (0x1D5FF, \"M\", \"r\"),\n        (0x1D600, \"M\", \"s\"),\n        (0x1D601, \"M\", \"t\"),\n        (0x1D602, \"M\", \"u\"),\n        (0x1D603, \"M\", \"v\"),\n        (0x1D604, \"M\", \"w\"),\n        (0x1D605, \"M\", \"x\"),\n        (0x1D606, \"M\", \"y\"),\n        (0x1D607, \"M\", \"z\"),\n        (0x1D608, \"M\", \"a\"),\n        (0x1D609, \"M\", \"b\"),\n        (0x1D60A, \"M\", \"c\"),\n        (0x1D60B, \"M\", \"d\"),\n        (0x1D60C, \"M\", \"e\"),\n        (0x1D60D, \"M\", \"f\"),\n        (0x1D60E, \"M\", \"g\"),\n        (0x1D60F, \"M\", \"h\"),\n        (0x1D610, \"M\", \"i\"),\n        (0x1D611, \"M\", \"j\"),\n        (0x1D612, \"M\", \"k\"),\n        (0x1D613, \"M\", \"l\"),\n        (0x1D614, \"M\", \"m\"),\n        (0x1D615, \"M\", \"n\"),\n        (0x1D616, \"M\", \"o\"),\n        (0x1D617, \"M\", \"p\"),\n        (0x1D618, \"M\", \"q\"),\n        (0x1D619, \"M\", \"r\"),\n        (0x1D61A, \"M\", \"s\"),\n        (0x1D61B, \"M\", \"t\"),\n        (0x1D61C, \"M\", \"u\"),\n        (0x1D61D, \"M\", \"v\"),\n        (0x1D61E, \"M\", \"w\"),\n        (0x1D61F, \"M\", \"x\"),\n        (0x1D620, \"M\", \"y\"),\n        (0x1D621, \"M\", \"z\"),\n        (0x1D622, \"M\", \"a\"),\n        (0x1D623, \"M\", \"b\"),\n        (0x1D624, \"M\", \"c\"),\n        (0x1D625, \"M\", \"d\"),\n        (0x1D626, \"M\", \"e\"),\n        (0x1D627, \"M\", \"f\"),\n        (0x1D628, \"M\", \"g\"),\n        (0x1D629, \"M\", \"h\"),\n        (0x1D62A, \"M\", \"i\"),\n        (0x1D62B, \"M\", \"j\"),\n        (0x1D62C, \"M\", \"k\"),\n        (0x1D62D, \"M\", \"l\"),\n        (0x1D62E, \"M\", \"m\"),\n        (0x1D62F, \"M\", \"n\"),\n        (0x1D630, \"M\", \"o\"),\n        (0x1D631, \"M\", \"p\"),\n        (0x1D632, \"M\", \"q\"),\n        (0x1D633, \"M\", \"r\"),\n        (0x1D634, \"M\", \"s\"),\n        (0x1D635, \"M\", \"t\"),\n        (0x1D636, \"M\", \"u\"),\n        (0x1D637, \"M\", \"v\"),\n        (0x1D638, \"M\", \"w\"),\n        (0x1D639, \"M\", \"x\"),\n        (0x1D63A, \"M\", \"y\"),\n        (0x1D63B, \"M\", \"z\"),\n        (0x1D63C, \"M\", \"a\"),\n        (0x1D63D, \"M\", \"b\"),\n        (0x1D63E, \"M\", \"c\"),\n        (0x1D63F, \"M\", \"d\"),\n        (0x1D640, \"M\", \"e\"),\n        (0x1D641, \"M\", \"f\"),\n        (0x1D642, \"M\", \"g\"),\n        (0x1D643, \"M\", \"h\"),\n        (0x1D644, \"M\", \"i\"),\n        (0x1D645, \"M\", \"j\"),\n        (0x1D646, \"M\", \"k\"),\n        (0x1D647, \"M\", \"l\"),\n        (0x1D648, \"M\", \"m\"),\n        (0x1D649, \"M\", \"n\"),\n        (0x1D64A, \"M\", \"o\"),\n        (0x1D64B, \"M\", \"p\"),\n        (0x1D64C, \"M\", \"q\"),\n        (0x1D64D, \"M\", \"r\"),\n        (0x1D64E, \"M\", \"s\"),\n        (0x1D64F, \"M\", \"t\"),\n        (0x1D650, \"M\", \"u\"),\n        (0x1D651, \"M\", \"v\"),\n        (0x1D652, \"M\", \"w\"),\n        (0x1D653, \"M\", \"x\"),\n        (0x1D654, \"M\", \"y\"),\n        (0x1D655, \"M\", \"z\"),\n    ]\n\n\ndef _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D656, \"M\", \"a\"),\n        (0x1D657, \"M\", \"b\"),\n        (0x1D658, \"M\", \"c\"),\n        (0x1D659, \"M\", \"d\"),\n        (0x1D65A, \"M\", \"e\"),\n        (0x1D65B, \"M\", \"f\"),\n        (0x1D65C, \"M\", \"g\"),\n        (0x1D65D, \"M\", \"h\"),\n        (0x1D65E, \"M\", \"i\"),\n        (0x1D65F, \"M\", \"j\"),\n        (0x1D660, \"M\", \"k\"),\n        (0x1D661, \"M\", \"l\"),\n        (0x1D662, \"M\", \"m\"),\n        (0x1D663, \"M\", \"n\"),\n        (0x1D664, \"M\", \"o\"),\n        (0x1D665, \"M\", \"p\"),\n        (0x1D666, \"M\", \"q\"),\n        (0x1D667, \"M\", \"r\"),\n        (0x1D668, \"M\", \"s\"),\n        (0x1D669, \"M\", \"t\"),\n        (0x1D66A, \"M\", \"u\"),\n        (0x1D66B, \"M\", \"v\"),\n        (0x1D66C, \"M\", \"w\"),\n        (0x1D66D, \"M\", \"x\"),\n        (0x1D66E, \"M\", \"y\"),\n        (0x1D66F, \"M\", \"z\"),\n        (0x1D670, \"M\", \"a\"),\n        (0x1D671, \"M\", \"b\"),\n        (0x1D672, \"M\", \"c\"),\n        (0x1D673, \"M\", \"d\"),\n        (0x1D674, \"M\", \"e\"),\n        (0x1D675, \"M\", \"f\"),\n        (0x1D676, \"M\", \"g\"),\n        (0x1D677, \"M\", \"h\"),\n        (0x1D678, \"M\", \"i\"),\n        (0x1D679, \"M\", \"j\"),\n        (0x1D67A, \"M\", \"k\"),\n        (0x1D67B, \"M\", \"l\"),\n        (0x1D67C, \"M\", \"m\"),\n        (0x1D67D, \"M\", \"n\"),\n        (0x1D67E, \"M\", \"o\"),\n        (0x1D67F, \"M\", \"p\"),\n        (0x1D680, \"M\", \"q\"),\n        (0x1D681, \"M\", \"r\"),\n        (0x1D682, \"M\", \"s\"),\n        (0x1D683, \"M\", \"t\"),\n        (0x1D684, \"M\", \"u\"),\n        (0x1D685, \"M\", \"v\"),\n        (0x1D686, \"M\", \"w\"),\n        (0x1D687, \"M\", \"x\"),\n        (0x1D688, \"M\", \"y\"),\n        (0x1D689, \"M\", \"z\"),\n        (0x1D68A, \"M\", \"a\"),\n        (0x1D68B, \"M\", \"b\"),\n        (0x1D68C, \"M\", \"c\"),\n        (0x1D68D, \"M\", \"d\"),\n        (0x1D68E, \"M\", \"e\"),\n        (0x1D68F, \"M\", \"f\"),\n        (0x1D690, \"M\", \"g\"),\n        (0x1D691, \"M\", \"h\"),\n        (0x1D692, \"M\", \"i\"),\n        (0x1D693, \"M\", \"j\"),\n        (0x1D694, \"M\", \"k\"),\n        (0x1D695, \"M\", \"l\"),\n        (0x1D696, \"M\", \"m\"),\n        (0x1D697, \"M\", \"n\"),\n        (0x1D698, \"M\", \"o\"),\n        (0x1D699, \"M\", \"p\"),\n        (0x1D69A, \"M\", \"q\"),\n        (0x1D69B, \"M\", \"r\"),\n        (0x1D69C, \"M\", \"s\"),\n        (0x1D69D, \"M\", \"t\"),\n        (0x1D69E, \"M\", \"u\"),\n        (0x1D69F, \"M\", \"v\"),\n        (0x1D6A0, \"M\", \"w\"),\n        (0x1D6A1, \"M\", \"x\"),\n        (0x1D6A2, \"M\", \"y\"),\n        (0x1D6A3, \"M\", \"z\"),\n        (0x1D6A4, \"M\", \"ı\"),\n        (0x1D6A5, \"M\", \"ȷ\"),\n        (0x1D6A6, \"X\"),\n        (0x1D6A8, \"M\", \"α\"),\n        (0x1D6A9, \"M\", \"β\"),\n        (0x1D6AA, \"M\", \"γ\"),\n        (0x1D6AB, \"M\", \"δ\"),\n        (0x1D6AC, \"M\", \"ε\"),\n        (0x1D6AD, \"M\", \"ζ\"),\n        (0x1D6AE, \"M\", \"η\"),\n        (0x1D6AF, \"M\", \"θ\"),\n        (0x1D6B0, \"M\", \"ι\"),\n        (0x1D6B1, \"M\", \"κ\"),\n        (0x1D6B2, \"M\", \"λ\"),\n        (0x1D6B3, \"M\", \"μ\"),\n        (0x1D6B4, \"M\", \"ν\"),\n        (0x1D6B5, \"M\", \"ξ\"),\n        (0x1D6B6, \"M\", \"ο\"),\n        (0x1D6B7, \"M\", \"π\"),\n        (0x1D6B8, \"M\", \"ρ\"),\n        (0x1D6B9, \"M\", \"θ\"),\n        (0x1D6BA, \"M\", \"σ\"),\n    ]\n\n\ndef _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D6BB, \"M\", \"τ\"),\n        (0x1D6BC, \"M\", \"υ\"),\n        (0x1D6BD, \"M\", \"φ\"),\n        (0x1D6BE, \"M\", \"χ\"),\n        (0x1D6BF, \"M\", \"ψ\"),\n        (0x1D6C0, \"M\", \"ω\"),\n        (0x1D6C1, \"M\", \"∇\"),\n        (0x1D6C2, \"M\", \"α\"),\n        (0x1D6C3, \"M\", \"β\"),\n        (0x1D6C4, \"M\", \"γ\"),\n        (0x1D6C5, \"M\", \"δ\"),\n        (0x1D6C6, \"M\", \"ε\"),\n        (0x1D6C7, \"M\", \"ζ\"),\n        (0x1D6C8, \"M\", \"η\"),\n        (0x1D6C9, \"M\", \"θ\"),\n        (0x1D6CA, \"M\", \"ι\"),\n        (0x1D6CB, \"M\", \"κ\"),\n        (0x1D6CC, \"M\", \"λ\"),\n        (0x1D6CD, \"M\", \"μ\"),\n        (0x1D6CE, \"M\", \"ν\"),\n        (0x1D6CF, \"M\", \"ξ\"),\n        (0x1D6D0, \"M\", \"ο\"),\n        (0x1D6D1, \"M\", \"π\"),\n        (0x1D6D2, \"M\", \"ρ\"),\n        (0x1D6D3, \"M\", \"σ\"),\n        (0x1D6D5, \"M\", \"τ\"),\n        (0x1D6D6, \"M\", \"υ\"),\n        (0x1D6D7, \"M\", \"φ\"),\n        (0x1D6D8, \"M\", \"χ\"),\n        (0x1D6D9, \"M\", \"ψ\"),\n        (0x1D6DA, \"M\", \"ω\"),\n        (0x1D6DB, \"M\", \"∂\"),\n        (0x1D6DC, \"M\", \"ε\"),\n        (0x1D6DD, \"M\", \"θ\"),\n        (0x1D6DE, \"M\", \"κ\"),\n        (0x1D6DF, \"M\", \"φ\"),\n        (0x1D6E0, \"M\", \"ρ\"),\n        (0x1D6E1, \"M\", \"π\"),\n        (0x1D6E2, \"M\", \"α\"),\n        (0x1D6E3, \"M\", \"β\"),\n        (0x1D6E4, \"M\", \"γ\"),\n        (0x1D6E5, \"M\", \"δ\"),\n        (0x1D6E6, \"M\", \"ε\"),\n        (0x1D6E7, \"M\", \"ζ\"),\n        (0x1D6E8, \"M\", \"η\"),\n        (0x1D6E9, \"M\", \"θ\"),\n        (0x1D6EA, \"M\", \"ι\"),\n        (0x1D6EB, \"M\", \"κ\"),\n        (0x1D6EC, \"M\", \"λ\"),\n        (0x1D6ED, \"M\", \"μ\"),\n        (0x1D6EE, \"M\", \"ν\"),\n        (0x1D6EF, \"M\", \"ξ\"),\n        (0x1D6F0, \"M\", \"ο\"),\n        (0x1D6F1, \"M\", \"π\"),\n        (0x1D6F2, \"M\", \"ρ\"),\n        (0x1D6F3, \"M\", \"θ\"),\n        (0x1D6F4, \"M\", \"σ\"),\n        (0x1D6F5, \"M\", \"τ\"),\n        (0x1D6F6, \"M\", \"υ\"),\n        (0x1D6F7, \"M\", \"φ\"),\n        (0x1D6F8, \"M\", \"χ\"),\n        (0x1D6F9, \"M\", \"ψ\"),\n        (0x1D6FA, \"M\", \"ω\"),\n        (0x1D6FB, \"M\", \"∇\"),\n        (0x1D6FC, \"M\", \"α\"),\n        (0x1D6FD, \"M\", \"β\"),\n        (0x1D6FE, \"M\", \"γ\"),\n        (0x1D6FF, \"M\", \"δ\"),\n        (0x1D700, \"M\", \"ε\"),\n        (0x1D701, \"M\", \"ζ\"),\n        (0x1D702, \"M\", \"η\"),\n        (0x1D703, \"M\", \"θ\"),\n        (0x1D704, \"M\", \"ι\"),\n        (0x1D705, \"M\", \"κ\"),\n        (0x1D706, \"M\", \"λ\"),\n        (0x1D707, \"M\", \"μ\"),\n        (0x1D708, \"M\", \"ν\"),\n        (0x1D709, \"M\", \"ξ\"),\n        (0x1D70A, \"M\", \"ο\"),\n        (0x1D70B, \"M\", \"π\"),\n        (0x1D70C, \"M\", \"ρ\"),\n        (0x1D70D, \"M\", \"σ\"),\n        (0x1D70F, \"M\", \"τ\"),\n        (0x1D710, \"M\", \"υ\"),\n        (0x1D711, \"M\", \"φ\"),\n        (0x1D712, \"M\", \"χ\"),\n        (0x1D713, \"M\", \"ψ\"),\n        (0x1D714, \"M\", \"ω\"),\n        (0x1D715, \"M\", \"∂\"),\n        (0x1D716, \"M\", \"ε\"),\n        (0x1D717, \"M\", \"θ\"),\n        (0x1D718, \"M\", \"κ\"),\n        (0x1D719, \"M\", \"φ\"),\n        (0x1D71A, \"M\", \"ρ\"),\n        (0x1D71B, \"M\", \"π\"),\n        (0x1D71C, \"M\", \"α\"),\n        (0x1D71D, \"M\", \"β\"),\n        (0x1D71E, \"M\", \"γ\"),\n        (0x1D71F, \"M\", \"δ\"),\n        (0x1D720, \"M\", \"ε\"),\n    ]\n\n\ndef _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D721, \"M\", \"ζ\"),\n        (0x1D722, \"M\", \"η\"),\n        (0x1D723, \"M\", \"θ\"),\n        (0x1D724, \"M\", \"ι\"),\n        (0x1D725, \"M\", \"κ\"),\n        (0x1D726, \"M\", \"λ\"),\n        (0x1D727, \"M\", \"μ\"),\n        (0x1D728, \"M\", \"ν\"),\n        (0x1D729, \"M\", \"ξ\"),\n        (0x1D72A, \"M\", \"ο\"),\n        (0x1D72B, \"M\", \"π\"),\n        (0x1D72C, \"M\", \"ρ\"),\n        (0x1D72D, \"M\", \"θ\"),\n        (0x1D72E, \"M\", \"σ\"),\n        (0x1D72F, \"M\", \"τ\"),\n        (0x1D730, \"M\", \"υ\"),\n        (0x1D731, \"M\", \"φ\"),\n        (0x1D732, \"M\", \"χ\"),\n        (0x1D733, \"M\", \"ψ\"),\n        (0x1D734, \"M\", \"ω\"),\n        (0x1D735, \"M\", \"∇\"),\n        (0x1D736, \"M\", \"α\"),\n        (0x1D737, \"M\", \"β\"),\n        (0x1D738, \"M\", \"γ\"),\n        (0x1D739, \"M\", \"δ\"),\n        (0x1D73A, \"M\", \"ε\"),\n        (0x1D73B, \"M\", \"ζ\"),\n        (0x1D73C, \"M\", \"η\"),\n        (0x1D73D, \"M\", \"θ\"),\n        (0x1D73E, \"M\", \"ι\"),\n        (0x1D73F, \"M\", \"κ\"),\n        (0x1D740, \"M\", \"λ\"),\n        (0x1D741, \"M\", \"μ\"),\n        (0x1D742, \"M\", \"ν\"),\n        (0x1D743, \"M\", \"ξ\"),\n        (0x1D744, \"M\", \"ο\"),\n        (0x1D745, \"M\", \"π\"),\n        (0x1D746, \"M\", \"ρ\"),\n        (0x1D747, \"M\", \"σ\"),\n        (0x1D749, \"M\", \"τ\"),\n        (0x1D74A, \"M\", \"υ\"),\n        (0x1D74B, \"M\", \"φ\"),\n        (0x1D74C, \"M\", \"χ\"),\n        (0x1D74D, \"M\", \"ψ\"),\n        (0x1D74E, \"M\", \"ω\"),\n        (0x1D74F, \"M\", \"∂\"),\n        (0x1D750, \"M\", \"ε\"),\n        (0x1D751, \"M\", \"θ\"),\n        (0x1D752, \"M\", \"κ\"),\n        (0x1D753, \"M\", \"φ\"),\n        (0x1D754, \"M\", \"ρ\"),\n        (0x1D755, \"M\", \"π\"),\n        (0x1D756, \"M\", \"α\"),\n        (0x1D757, \"M\", \"β\"),\n        (0x1D758, \"M\", \"γ\"),\n        (0x1D759, \"M\", \"δ\"),\n        (0x1D75A, \"M\", \"ε\"),\n        (0x1D75B, \"M\", \"ζ\"),\n        (0x1D75C, \"M\", \"η\"),\n        (0x1D75D, \"M\", \"θ\"),\n        (0x1D75E, \"M\", \"ι\"),\n        (0x1D75F, \"M\", \"κ\"),\n        (0x1D760, \"M\", \"λ\"),\n        (0x1D761, \"M\", \"μ\"),\n        (0x1D762, \"M\", \"ν\"),\n        (0x1D763, \"M\", \"ξ\"),\n        (0x1D764, \"M\", \"ο\"),\n        (0x1D765, \"M\", \"π\"),\n        (0x1D766, \"M\", \"ρ\"),\n        (0x1D767, \"M\", \"θ\"),\n        (0x1D768, \"M\", \"σ\"),\n        (0x1D769, \"M\", \"τ\"),\n        (0x1D76A, \"M\", \"υ\"),\n        (0x1D76B, \"M\", \"φ\"),\n        (0x1D76C, \"M\", \"χ\"),\n        (0x1D76D, \"M\", \"ψ\"),\n        (0x1D76E, \"M\", \"ω\"),\n        (0x1D76F, \"M\", \"∇\"),\n        (0x1D770, \"M\", \"α\"),\n        (0x1D771, \"M\", \"β\"),\n        (0x1D772, \"M\", \"γ\"),\n        (0x1D773, \"M\", \"δ\"),\n        (0x1D774, \"M\", \"ε\"),\n        (0x1D775, \"M\", \"ζ\"),\n        (0x1D776, \"M\", \"η\"),\n        (0x1D777, \"M\", \"θ\"),\n        (0x1D778, \"M\", \"ι\"),\n        (0x1D779, \"M\", \"κ\"),\n        (0x1D77A, \"M\", \"λ\"),\n        (0x1D77B, \"M\", \"μ\"),\n        (0x1D77C, \"M\", \"ν\"),\n        (0x1D77D, \"M\", \"ξ\"),\n        (0x1D77E, \"M\", \"ο\"),\n        (0x1D77F, \"M\", \"π\"),\n        (0x1D780, \"M\", \"ρ\"),\n        (0x1D781, \"M\", \"σ\"),\n        (0x1D783, \"M\", \"τ\"),\n        (0x1D784, \"M\", \"υ\"),\n        (0x1D785, \"M\", \"φ\"),\n        (0x1D786, \"M\", \"χ\"),\n    ]\n\n\ndef _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D787, \"M\", \"ψ\"),\n        (0x1D788, \"M\", \"ω\"),\n        (0x1D789, \"M\", \"∂\"),\n        (0x1D78A, \"M\", \"ε\"),\n        (0x1D78B, \"M\", \"θ\"),\n        (0x1D78C, \"M\", \"κ\"),\n        (0x1D78D, \"M\", \"φ\"),\n        (0x1D78E, \"M\", \"ρ\"),\n        (0x1D78F, \"M\", \"π\"),\n        (0x1D790, \"M\", \"α\"),\n        (0x1D791, \"M\", \"β\"),\n        (0x1D792, \"M\", \"γ\"),\n        (0x1D793, \"M\", \"δ\"),\n        (0x1D794, \"M\", \"ε\"),\n        (0x1D795, \"M\", \"ζ\"),\n        (0x1D796, \"M\", \"η\"),\n        (0x1D797, \"M\", \"θ\"),\n        (0x1D798, \"M\", \"ι\"),\n        (0x1D799, \"M\", \"κ\"),\n        (0x1D79A, \"M\", \"λ\"),\n        (0x1D79B, \"M\", \"μ\"),\n        (0x1D79C, \"M\", \"ν\"),\n        (0x1D79D, \"M\", \"ξ\"),\n        (0x1D79E, \"M\", \"ο\"),\n        (0x1D79F, \"M\", \"π\"),\n        (0x1D7A0, \"M\", \"ρ\"),\n        (0x1D7A1, \"M\", \"θ\"),\n        (0x1D7A2, \"M\", \"σ\"),\n        (0x1D7A3, \"M\", \"τ\"),\n        (0x1D7A4, \"M\", \"υ\"),\n        (0x1D7A5, \"M\", \"φ\"),\n        (0x1D7A6, \"M\", \"χ\"),\n        (0x1D7A7, \"M\", \"ψ\"),\n        (0x1D7A8, \"M\", \"ω\"),\n        (0x1D7A9, \"M\", \"∇\"),\n        (0x1D7AA, \"M\", \"α\"),\n        (0x1D7AB, \"M\", \"β\"),\n        (0x1D7AC, \"M\", \"γ\"),\n        (0x1D7AD, \"M\", \"δ\"),\n        (0x1D7AE, \"M\", \"ε\"),\n        (0x1D7AF, \"M\", \"ζ\"),\n        (0x1D7B0, \"M\", \"η\"),\n        (0x1D7B1, \"M\", \"θ\"),\n        (0x1D7B2, \"M\", \"ι\"),\n        (0x1D7B3, \"M\", \"κ\"),\n        (0x1D7B4, \"M\", \"λ\"),\n        (0x1D7B5, \"M\", \"μ\"),\n        (0x1D7B6, \"M\", \"ν\"),\n        (0x1D7B7, \"M\", \"ξ\"),\n        (0x1D7B8, \"M\", \"ο\"),\n        (0x1D7B9, \"M\", \"π\"),\n        (0x1D7BA, \"M\", \"ρ\"),\n        (0x1D7BB, \"M\", \"σ\"),\n        (0x1D7BD, \"M\", \"τ\"),\n        (0x1D7BE, \"M\", \"υ\"),\n        (0x1D7BF, \"M\", \"φ\"),\n        (0x1D7C0, \"M\", \"χ\"),\n        (0x1D7C1, \"M\", \"ψ\"),\n        (0x1D7C2, \"M\", \"ω\"),\n        (0x1D7C3, \"M\", \"∂\"),\n        (0x1D7C4, \"M\", \"ε\"),\n        (0x1D7C5, \"M\", \"θ\"),\n        (0x1D7C6, \"M\", \"κ\"),\n        (0x1D7C7, \"M\", \"φ\"),\n        (0x1D7C8, \"M\", \"ρ\"),\n        (0x1D7C9, \"M\", \"π\"),\n        (0x1D7CA, \"M\", \"ϝ\"),\n        (0x1D7CC, \"X\"),\n        (0x1D7CE, \"M\", \"0\"),\n        (0x1D7CF, \"M\", \"1\"),\n        (0x1D7D0, \"M\", \"2\"),\n        (0x1D7D1, \"M\", \"3\"),\n        (0x1D7D2, \"M\", \"4\"),\n        (0x1D7D3, \"M\", \"5\"),\n        (0x1D7D4, \"M\", \"6\"),\n        (0x1D7D5, \"M\", \"7\"),\n        (0x1D7D6, \"M\", \"8\"),\n        (0x1D7D7, \"M\", \"9\"),\n        (0x1D7D8, \"M\", \"0\"),\n        (0x1D7D9, \"M\", \"1\"),\n        (0x1D7DA, \"M\", \"2\"),\n        (0x1D7DB, \"M\", \"3\"),\n        (0x1D7DC, \"M\", \"4\"),\n        (0x1D7DD, \"M\", \"5\"),\n        (0x1D7DE, \"M\", \"6\"),\n        (0x1D7DF, \"M\", \"7\"),\n        (0x1D7E0, \"M\", \"8\"),\n        (0x1D7E1, \"M\", \"9\"),\n        (0x1D7E2, \"M\", \"0\"),\n        (0x1D7E3, \"M\", \"1\"),\n        (0x1D7E4, \"M\", \"2\"),\n        (0x1D7E5, \"M\", \"3\"),\n        (0x1D7E6, \"M\", \"4\"),\n        (0x1D7E7, \"M\", \"5\"),\n        (0x1D7E8, \"M\", \"6\"),\n        (0x1D7E9, \"M\", \"7\"),\n        (0x1D7EA, \"M\", \"8\"),\n        (0x1D7EB, \"M\", \"9\"),\n        (0x1D7EC, \"M\", \"0\"),\n        (0x1D7ED, \"M\", \"1\"),\n    ]\n\n\ndef _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1D7EE, \"M\", \"2\"),\n        (0x1D7EF, \"M\", \"3\"),\n        (0x1D7F0, \"M\", \"4\"),\n        (0x1D7F1, \"M\", \"5\"),\n        (0x1D7F2, \"M\", \"6\"),\n        (0x1D7F3, \"M\", \"7\"),\n        (0x1D7F4, \"M\", \"8\"),\n        (0x1D7F5, \"M\", \"9\"),\n        (0x1D7F6, \"M\", \"0\"),\n        (0x1D7F7, \"M\", \"1\"),\n        (0x1D7F8, \"M\", \"2\"),\n        (0x1D7F9, \"M\", \"3\"),\n        (0x1D7FA, \"M\", \"4\"),\n        (0x1D7FB, \"M\", \"5\"),\n        (0x1D7FC, \"M\", \"6\"),\n        (0x1D7FD, \"M\", \"7\"),\n        (0x1D7FE, \"M\", \"8\"),\n        (0x1D7FF, \"M\", \"9\"),\n        (0x1D800, \"V\"),\n        (0x1DA8C, \"X\"),\n        (0x1DA9B, \"V\"),\n        (0x1DAA0, \"X\"),\n        (0x1DAA1, \"V\"),\n        (0x1DAB0, \"X\"),\n        (0x1DF00, \"V\"),\n        (0x1DF1F, \"X\"),\n        (0x1DF25, \"V\"),\n        (0x1DF2B, \"X\"),\n        (0x1E000, \"V\"),\n        (0x1E007, \"X\"),\n        (0x1E008, \"V\"),\n        (0x1E019, \"X\"),\n        (0x1E01B, \"V\"),\n        (0x1E022, \"X\"),\n        (0x1E023, \"V\"),\n        (0x1E025, \"X\"),\n        (0x1E026, \"V\"),\n        (0x1E02B, \"X\"),\n        (0x1E030, \"M\", \"а\"),\n        (0x1E031, \"M\", \"б\"),\n        (0x1E032, \"M\", \"в\"),\n        (0x1E033, \"M\", \"г\"),\n        (0x1E034, \"M\", \"д\"),\n        (0x1E035, \"M\", \"е\"),\n        (0x1E036, \"M\", \"ж\"),\n        (0x1E037, \"M\", \"з\"),\n        (0x1E038, \"M\", \"и\"),\n        (0x1E039, \"M\", \"к\"),\n        (0x1E03A, \"M\", \"л\"),\n        (0x1E03B, \"M\", \"м\"),\n        (0x1E03C, \"M\", \"о\"),\n        (0x1E03D, \"M\", \"п\"),\n        (0x1E03E, \"M\", \"р\"),\n        (0x1E03F, \"M\", \"с\"),\n        (0x1E040, \"M\", \"т\"),\n        (0x1E041, \"M\", \"у\"),\n        (0x1E042, \"M\", \"ф\"),\n        (0x1E043, \"M\", \"х\"),\n        (0x1E044, \"M\", \"ц\"),\n        (0x1E045, \"M\", \"ч\"),\n        (0x1E046, \"M\", \"ш\"),\n        (0x1E047, \"M\", \"ы\"),\n        (0x1E048, \"M\", \"э\"),\n        (0x1E049, \"M\", \"ю\"),\n        (0x1E04A, \"M\", \"ꚉ\"),\n        (0x1E04B, \"M\", \"ә\"),\n        (0x1E04C, \"M\", \"і\"),\n        (0x1E04D, \"M\", \"ј\"),\n        (0x1E04E, \"M\", \"ө\"),\n        (0x1E04F, \"M\", \"ү\"),\n        (0x1E050, \"M\", \"ӏ\"),\n        (0x1E051, \"M\", \"а\"),\n        (0x1E052, \"M\", \"б\"),\n        (0x1E053, \"M\", \"в\"),\n        (0x1E054, \"M\", \"г\"),\n        (0x1E055, \"M\", \"д\"),\n        (0x1E056, \"M\", \"е\"),\n        (0x1E057, \"M\", \"ж\"),\n        (0x1E058, \"M\", \"з\"),\n        (0x1E059, \"M\", \"и\"),\n        (0x1E05A, \"M\", \"к\"),\n        (0x1E05B, \"M\", \"л\"),\n        (0x1E05C, \"M\", \"о\"),\n        (0x1E05D, \"M\", \"п\"),\n        (0x1E05E, \"M\", \"с\"),\n        (0x1E05F, \"M\", \"у\"),\n        (0x1E060, \"M\", \"ф\"),\n        (0x1E061, \"M\", \"х\"),\n        (0x1E062, \"M\", \"ц\"),\n        (0x1E063, \"M\", \"ч\"),\n        (0x1E064, \"M\", \"ш\"),\n        (0x1E065, \"M\", \"ъ\"),\n        (0x1E066, \"M\", \"ы\"),\n        (0x1E067, \"M\", \"ґ\"),\n        (0x1E068, \"M\", \"і\"),\n        (0x1E069, \"M\", \"ѕ\"),\n        (0x1E06A, \"M\", \"џ\"),\n        (0x1E06B, \"M\", \"ҫ\"),\n        (0x1E06C, \"M\", \"ꙑ\"),\n        (0x1E06D, \"M\", \"ұ\"),\n    ]\n\n\ndef _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1E06E, \"X\"),\n        (0x1E08F, \"V\"),\n        (0x1E090, \"X\"),\n        (0x1E100, \"V\"),\n        (0x1E12D, \"X\"),\n        (0x1E130, \"V\"),\n        (0x1E13E, \"X\"),\n        (0x1E140, \"V\"),\n        (0x1E14A, \"X\"),\n        (0x1E14E, \"V\"),\n        (0x1E150, \"X\"),\n        (0x1E290, \"V\"),\n        (0x1E2AF, \"X\"),\n        (0x1E2C0, \"V\"),\n        (0x1E2FA, \"X\"),\n        (0x1E2FF, \"V\"),\n        (0x1E300, \"X\"),\n        (0x1E4D0, \"V\"),\n        (0x1E4FA, \"X\"),\n        (0x1E5D0, \"V\"),\n        (0x1E5FB, \"X\"),\n        (0x1E5FF, \"V\"),\n        (0x1E600, \"X\"),\n        (0x1E7E0, \"V\"),\n        (0x1E7E7, \"X\"),\n        (0x1E7E8, \"V\"),\n        (0x1E7EC, \"X\"),\n        (0x1E7ED, \"V\"),\n        (0x1E7EF, \"X\"),\n        (0x1E7F0, \"V\"),\n        (0x1E7FF, \"X\"),\n        (0x1E800, \"V\"),\n        (0x1E8C5, \"X\"),\n        (0x1E8C7, \"V\"),\n        (0x1E8D7, \"X\"),\n        (0x1E900, \"M\", \"𞤢\"),\n        (0x1E901, \"M\", \"𞤣\"),\n        (0x1E902, \"M\", \"𞤤\"),\n        (0x1E903, \"M\", \"𞤥\"),\n        (0x1E904, \"M\", \"𞤦\"),\n        (0x1E905, \"M\", \"𞤧\"),\n        (0x1E906, \"M\", \"𞤨\"),\n        (0x1E907, \"M\", \"𞤩\"),\n        (0x1E908, \"M\", \"𞤪\"),\n        (0x1E909, \"M\", \"𞤫\"),\n        (0x1E90A, \"M\", \"𞤬\"),\n        (0x1E90B, \"M\", \"𞤭\"),\n        (0x1E90C, \"M\", \"𞤮\"),\n        (0x1E90D, \"M\", \"𞤯\"),\n        (0x1E90E, \"M\", \"𞤰\"),\n        (0x1E90F, \"M\", \"𞤱\"),\n        (0x1E910, \"M\", \"𞤲\"),\n        (0x1E911, \"M\", \"𞤳\"),\n        (0x1E912, \"M\", \"𞤴\"),\n        (0x1E913, \"M\", \"𞤵\"),\n        (0x1E914, \"M\", \"𞤶\"),\n        (0x1E915, \"M\", \"𞤷\"),\n        (0x1E916, \"M\", \"𞤸\"),\n        (0x1E917, \"M\", \"𞤹\"),\n        (0x1E918, \"M\", \"𞤺\"),\n        (0x1E919, \"M\", \"𞤻\"),\n        (0x1E91A, \"M\", \"𞤼\"),\n        (0x1E91B, \"M\", \"𞤽\"),\n        (0x1E91C, \"M\", \"𞤾\"),\n        (0x1E91D, \"M\", \"𞤿\"),\n        (0x1E91E, \"M\", \"𞥀\"),\n        (0x1E91F, \"M\", \"𞥁\"),\n        (0x1E920, \"M\", \"𞥂\"),\n        (0x1E921, \"M\", \"𞥃\"),\n        (0x1E922, \"V\"),\n        (0x1E94C, \"X\"),\n        (0x1E950, \"V\"),\n        (0x1E95A, \"X\"),\n        (0x1E95E, \"V\"),\n        (0x1E960, \"X\"),\n        (0x1EC71, \"V\"),\n        (0x1ECB5, \"X\"),\n        (0x1ED01, \"V\"),\n        (0x1ED3E, \"X\"),\n        (0x1EE00, \"M\", \"ا\"),\n        (0x1EE01, \"M\", \"ب\"),\n        (0x1EE02, \"M\", \"ج\"),\n        (0x1EE03, \"M\", \"د\"),\n        (0x1EE04, \"X\"),\n        (0x1EE05, \"M\", \"و\"),\n        (0x1EE06, \"M\", \"ز\"),\n        (0x1EE07, \"M\", \"ح\"),\n        (0x1EE08, \"M\", \"ط\"),\n        (0x1EE09, \"M\", \"ي\"),\n        (0x1EE0A, \"M\", \"ك\"),\n        (0x1EE0B, \"M\", \"ل\"),\n        (0x1EE0C, \"M\", \"م\"),\n        (0x1EE0D, \"M\", \"ن\"),\n        (0x1EE0E, \"M\", \"س\"),\n        (0x1EE0F, \"M\", \"ع\"),\n        (0x1EE10, \"M\", \"ف\"),\n        (0x1EE11, \"M\", \"ص\"),\n        (0x1EE12, \"M\", \"ق\"),\n        (0x1EE13, \"M\", \"ر\"),\n        (0x1EE14, \"M\", \"ش\"),\n    ]\n\n\ndef _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1EE15, \"M\", \"ت\"),\n        (0x1EE16, \"M\", \"ث\"),\n        (0x1EE17, \"M\", \"خ\"),\n        (0x1EE18, \"M\", \"ذ\"),\n        (0x1EE19, \"M\", \"ض\"),\n        (0x1EE1A, \"M\", \"ظ\"),\n        (0x1EE1B, \"M\", \"غ\"),\n        (0x1EE1C, \"M\", \"ٮ\"),\n        (0x1EE1D, \"M\", \"ں\"),\n        (0x1EE1E, \"M\", \"ڡ\"),\n        (0x1EE1F, \"M\", \"ٯ\"),\n        (0x1EE20, \"X\"),\n        (0x1EE21, \"M\", \"ب\"),\n        (0x1EE22, \"M\", \"ج\"),\n        (0x1EE23, \"X\"),\n        (0x1EE24, \"M\", \"ه\"),\n        (0x1EE25, \"X\"),\n        (0x1EE27, \"M\", \"ح\"),\n        (0x1EE28, \"X\"),\n        (0x1EE29, \"M\", \"ي\"),\n        (0x1EE2A, \"M\", \"ك\"),\n        (0x1EE2B, \"M\", \"ل\"),\n        (0x1EE2C, \"M\", \"م\"),\n        (0x1EE2D, \"M\", \"ن\"),\n        (0x1EE2E, \"M\", \"س\"),\n        (0x1EE2F, \"M\", \"ع\"),\n        (0x1EE30, \"M\", \"ف\"),\n        (0x1EE31, \"M\", \"ص\"),\n        (0x1EE32, \"M\", \"ق\"),\n        (0x1EE33, \"X\"),\n        (0x1EE34, \"M\", \"ش\"),\n        (0x1EE35, \"M\", \"ت\"),\n        (0x1EE36, \"M\", \"ث\"),\n        (0x1EE37, \"M\", \"خ\"),\n        (0x1EE38, \"X\"),\n        (0x1EE39, \"M\", \"ض\"),\n        (0x1EE3A, \"X\"),\n        (0x1EE3B, \"M\", \"غ\"),\n        (0x1EE3C, \"X\"),\n        (0x1EE42, \"M\", \"ج\"),\n        (0x1EE43, \"X\"),\n        (0x1EE47, \"M\", \"ح\"),\n        (0x1EE48, \"X\"),\n        (0x1EE49, \"M\", \"ي\"),\n        (0x1EE4A, \"X\"),\n        (0x1EE4B, \"M\", \"ل\"),\n        (0x1EE4C, \"X\"),\n        (0x1EE4D, \"M\", \"ن\"),\n        (0x1EE4E, \"M\", \"س\"),\n        (0x1EE4F, \"M\", \"ع\"),\n        (0x1EE50, \"X\"),\n        (0x1EE51, \"M\", \"ص\"),\n        (0x1EE52, \"M\", \"ق\"),\n        (0x1EE53, \"X\"),\n        (0x1EE54, \"M\", \"ش\"),\n        (0x1EE55, \"X\"),\n        (0x1EE57, \"M\", \"خ\"),\n        (0x1EE58, \"X\"),\n        (0x1EE59, \"M\", \"ض\"),\n        (0x1EE5A, \"X\"),\n        (0x1EE5B, \"M\", \"غ\"),\n        (0x1EE5C, \"X\"),\n        (0x1EE5D, \"M\", \"ں\"),\n        (0x1EE5E, \"X\"),\n        (0x1EE5F, \"M\", \"ٯ\"),\n        (0x1EE60, \"X\"),\n        (0x1EE61, \"M\", \"ب\"),\n        (0x1EE62, \"M\", \"ج\"),\n        (0x1EE63, \"X\"),\n        (0x1EE64, \"M\", \"ه\"),\n        (0x1EE65, \"X\"),\n        (0x1EE67, \"M\", \"ح\"),\n        (0x1EE68, \"M\", \"ط\"),\n        (0x1EE69, \"M\", \"ي\"),\n        (0x1EE6A, \"M\", \"ك\"),\n        (0x1EE6B, \"X\"),\n        (0x1EE6C, \"M\", \"م\"),\n        (0x1EE6D, \"M\", \"ن\"),\n        (0x1EE6E, \"M\", \"س\"),\n        (0x1EE6F, \"M\", \"ع\"),\n        (0x1EE70, \"M\", \"ف\"),\n        (0x1EE71, \"M\", \"ص\"),\n        (0x1EE72, \"M\", \"ق\"),\n        (0x1EE73, \"X\"),\n        (0x1EE74, \"M\", \"ش\"),\n        (0x1EE75, \"M\", \"ت\"),\n        (0x1EE76, \"M\", \"ث\"),\n        (0x1EE77, \"M\", \"خ\"),\n        (0x1EE78, \"X\"),\n        (0x1EE79, \"M\", \"ض\"),\n        (0x1EE7A, \"M\", \"ظ\"),\n        (0x1EE7B, \"M\", \"غ\"),\n        (0x1EE7C, \"M\", \"ٮ\"),\n        (0x1EE7D, \"X\"),\n        (0x1EE7E, \"M\", \"ڡ\"),\n        (0x1EE7F, \"X\"),\n        (0x1EE80, \"M\", \"ا\"),\n        (0x1EE81, \"M\", \"ب\"),\n        (0x1EE82, \"M\", \"ج\"),\n        (0x1EE83, \"M\", \"د\"),\n    ]\n\n\ndef _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1EE84, \"M\", \"ه\"),\n        (0x1EE85, \"M\", \"و\"),\n        (0x1EE86, \"M\", \"ز\"),\n        (0x1EE87, \"M\", \"ح\"),\n        (0x1EE88, \"M\", \"ط\"),\n        (0x1EE89, \"M\", \"ي\"),\n        (0x1EE8A, \"X\"),\n        (0x1EE8B, \"M\", \"ل\"),\n        (0x1EE8C, \"M\", \"م\"),\n        (0x1EE8D, \"M\", \"ن\"),\n        (0x1EE8E, \"M\", \"س\"),\n        (0x1EE8F, \"M\", \"ع\"),\n        (0x1EE90, \"M\", \"ف\"),\n        (0x1EE91, \"M\", \"ص\"),\n        (0x1EE92, \"M\", \"ق\"),\n        (0x1EE93, \"M\", \"ر\"),\n        (0x1EE94, \"M\", \"ش\"),\n        (0x1EE95, \"M\", \"ت\"),\n        (0x1EE96, \"M\", \"ث\"),\n        (0x1EE97, \"M\", \"خ\"),\n        (0x1EE98, \"M\", \"ذ\"),\n        (0x1EE99, \"M\", \"ض\"),\n        (0x1EE9A, \"M\", \"ظ\"),\n        (0x1EE9B, \"M\", \"غ\"),\n        (0x1EE9C, \"X\"),\n        (0x1EEA1, \"M\", \"ب\"),\n        (0x1EEA2, \"M\", \"ج\"),\n        (0x1EEA3, \"M\", \"د\"),\n        (0x1EEA4, \"X\"),\n        (0x1EEA5, \"M\", \"و\"),\n        (0x1EEA6, \"M\", \"ز\"),\n        (0x1EEA7, \"M\", \"ح\"),\n        (0x1EEA8, \"M\", \"ط\"),\n        (0x1EEA9, \"M\", \"ي\"),\n        (0x1EEAA, \"X\"),\n        (0x1EEAB, \"M\", \"ل\"),\n        (0x1EEAC, \"M\", \"م\"),\n        (0x1EEAD, \"M\", \"ن\"),\n        (0x1EEAE, \"M\", \"س\"),\n        (0x1EEAF, \"M\", \"ع\"),\n        (0x1EEB0, \"M\", \"ف\"),\n        (0x1EEB1, \"M\", \"ص\"),\n        (0x1EEB2, \"M\", \"ق\"),\n        (0x1EEB3, \"M\", \"ر\"),\n        (0x1EEB4, \"M\", \"ش\"),\n        (0x1EEB5, \"M\", \"ت\"),\n        (0x1EEB6, \"M\", \"ث\"),\n        (0x1EEB7, \"M\", \"خ\"),\n        (0x1EEB8, \"M\", \"ذ\"),\n        (0x1EEB9, \"M\", \"ض\"),\n        (0x1EEBA, \"M\", \"ظ\"),\n        (0x1EEBB, \"M\", \"غ\"),\n        (0x1EEBC, \"X\"),\n        (0x1EEF0, \"V\"),\n        (0x1EEF2, \"X\"),\n        (0x1F000, \"V\"),\n        (0x1F02C, \"X\"),\n        (0x1F030, \"V\"),\n        (0x1F094, \"X\"),\n        (0x1F0A0, \"V\"),\n        (0x1F0AF, \"X\"),\n        (0x1F0B1, \"V\"),\n        (0x1F0C0, \"X\"),\n        (0x1F0C1, \"V\"),\n        (0x1F0D0, \"X\"),\n        (0x1F0D1, \"V\"),\n        (0x1F0F6, \"X\"),\n        (0x1F101, \"M\", \"0,\"),\n        (0x1F102, \"M\", \"1,\"),\n        (0x1F103, \"M\", \"2,\"),\n        (0x1F104, \"M\", \"3,\"),\n        (0x1F105, \"M\", \"4,\"),\n        (0x1F106, \"M\", \"5,\"),\n        (0x1F107, \"M\", \"6,\"),\n        (0x1F108, \"M\", \"7,\"),\n        (0x1F109, \"M\", \"8,\"),\n        (0x1F10A, \"M\", \"9,\"),\n        (0x1F10B, \"V\"),\n        (0x1F110, \"M\", \"(a)\"),\n        (0x1F111, \"M\", \"(b)\"),\n        (0x1F112, \"M\", \"(c)\"),\n        (0x1F113, \"M\", \"(d)\"),\n        (0x1F114, \"M\", \"(e)\"),\n        (0x1F115, \"M\", \"(f)\"),\n        (0x1F116, \"M\", \"(g)\"),\n        (0x1F117, \"M\", \"(h)\"),\n        (0x1F118, \"M\", \"(i)\"),\n        (0x1F119, \"M\", \"(j)\"),\n        (0x1F11A, \"M\", \"(k)\"),\n        (0x1F11B, \"M\", \"(l)\"),\n        (0x1F11C, \"M\", \"(m)\"),\n        (0x1F11D, \"M\", \"(n)\"),\n        (0x1F11E, \"M\", \"(o)\"),\n        (0x1F11F, \"M\", \"(p)\"),\n        (0x1F120, \"M\", \"(q)\"),\n        (0x1F121, \"M\", \"(r)\"),\n        (0x1F122, \"M\", \"(s)\"),\n        (0x1F123, \"M\", \"(t)\"),\n        (0x1F124, \"M\", \"(u)\"),\n        (0x1F125, \"M\", \"(v)\"),\n    ]\n\n\ndef _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1F126, \"M\", \"(w)\"),\n        (0x1F127, \"M\", \"(x)\"),\n        (0x1F128, \"M\", \"(y)\"),\n        (0x1F129, \"M\", \"(z)\"),\n        (0x1F12A, \"M\", \"〔s〕\"),\n        (0x1F12B, \"M\", \"c\"),\n        (0x1F12C, \"M\", \"r\"),\n        (0x1F12D, \"M\", \"cd\"),\n        (0x1F12E, \"M\", \"wz\"),\n        (0x1F12F, \"V\"),\n        (0x1F130, \"M\", \"a\"),\n        (0x1F131, \"M\", \"b\"),\n        (0x1F132, \"M\", \"c\"),\n        (0x1F133, \"M\", \"d\"),\n        (0x1F134, \"M\", \"e\"),\n        (0x1F135, \"M\", \"f\"),\n        (0x1F136, \"M\", \"g\"),\n        (0x1F137, \"M\", \"h\"),\n        (0x1F138, \"M\", \"i\"),\n        (0x1F139, \"M\", \"j\"),\n        (0x1F13A, \"M\", \"k\"),\n        (0x1F13B, \"M\", \"l\"),\n        (0x1F13C, \"M\", \"m\"),\n        (0x1F13D, \"M\", \"n\"),\n        (0x1F13E, \"M\", \"o\"),\n        (0x1F13F, \"M\", \"p\"),\n        (0x1F140, \"M\", \"q\"),\n        (0x1F141, \"M\", \"r\"),\n        (0x1F142, \"M\", \"s\"),\n        (0x1F143, \"M\", \"t\"),\n        (0x1F144, \"M\", \"u\"),\n        (0x1F145, \"M\", \"v\"),\n        (0x1F146, \"M\", \"w\"),\n        (0x1F147, \"M\", \"x\"),\n        (0x1F148, \"M\", \"y\"),\n        (0x1F149, \"M\", \"z\"),\n        (0x1F14A, \"M\", \"hv\"),\n        (0x1F14B, \"M\", \"mv\"),\n        (0x1F14C, \"M\", \"sd\"),\n        (0x1F14D, \"M\", \"ss\"),\n        (0x1F14E, \"M\", \"ppv\"),\n        (0x1F14F, \"M\", \"wc\"),\n        (0x1F150, \"V\"),\n        (0x1F16A, \"M\", \"mc\"),\n        (0x1F16B, \"M\", \"md\"),\n        (0x1F16C, \"M\", \"mr\"),\n        (0x1F16D, \"V\"),\n        (0x1F190, \"M\", \"dj\"),\n        (0x1F191, \"V\"),\n        (0x1F1AE, \"X\"),\n        (0x1F1E6, \"V\"),\n        (0x1F200, \"M\", \"ほか\"),\n        (0x1F201, \"M\", \"ココ\"),\n        (0x1F202, \"M\", \"サ\"),\n        (0x1F203, \"X\"),\n        (0x1F210, \"M\", \"手\"),\n        (0x1F211, \"M\", \"字\"),\n        (0x1F212, \"M\", \"双\"),\n        (0x1F213, \"M\", \"デ\"),\n        (0x1F214, \"M\", \"二\"),\n        (0x1F215, \"M\", \"多\"),\n        (0x1F216, \"M\", \"解\"),\n        (0x1F217, \"M\", \"天\"),\n        (0x1F218, \"M\", \"交\"),\n        (0x1F219, \"M\", \"映\"),\n        (0x1F21A, \"M\", \"無\"),\n        (0x1F21B, \"M\", \"料\"),\n        (0x1F21C, \"M\", \"前\"),\n        (0x1F21D, \"M\", \"後\"),\n        (0x1F21E, \"M\", \"再\"),\n        (0x1F21F, \"M\", \"新\"),\n        (0x1F220, \"M\", \"初\"),\n        (0x1F221, \"M\", \"終\"),\n        (0x1F222, \"M\", \"生\"),\n        (0x1F223, \"M\", \"販\"),\n        (0x1F224, \"M\", \"声\"),\n        (0x1F225, \"M\", \"吹\"),\n        (0x1F226, \"M\", \"演\"),\n        (0x1F227, \"M\", \"投\"),\n        (0x1F228, \"M\", \"捕\"),\n        (0x1F229, \"M\", \"一\"),\n        (0x1F22A, \"M\", \"三\"),\n        (0x1F22B, \"M\", \"遊\"),\n        (0x1F22C, \"M\", \"左\"),\n        (0x1F22D, \"M\", \"中\"),\n        (0x1F22E, \"M\", \"右\"),\n        (0x1F22F, \"M\", \"指\"),\n        (0x1F230, \"M\", \"走\"),\n        (0x1F231, \"M\", \"打\"),\n        (0x1F232, \"M\", \"禁\"),\n        (0x1F233, \"M\", \"空\"),\n        (0x1F234, \"M\", \"合\"),\n        (0x1F235, \"M\", \"満\"),\n        (0x1F236, \"M\", \"有\"),\n        (0x1F237, \"M\", \"月\"),\n        (0x1F238, \"M\", \"申\"),\n        (0x1F239, \"M\", \"割\"),\n        (0x1F23A, \"M\", \"営\"),\n        (0x1F23B, \"M\", \"配\"),\n        (0x1F23C, \"X\"),\n    ]\n\n\ndef _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x1F240, \"M\", \"〔本〕\"),\n        (0x1F241, \"M\", \"〔三〕\"),\n        (0x1F242, \"M\", \"〔二〕\"),\n        (0x1F243, \"M\", \"〔安〕\"),\n        (0x1F244, \"M\", \"〔点〕\"),\n        (0x1F245, \"M\", \"〔打〕\"),\n        (0x1F246, \"M\", \"〔盗〕\"),\n        (0x1F247, \"M\", \"〔勝〕\"),\n        (0x1F248, \"M\", \"〔敗〕\"),\n        (0x1F249, \"X\"),\n        (0x1F250, \"M\", \"得\"),\n        (0x1F251, \"M\", \"可\"),\n        (0x1F252, \"X\"),\n        (0x1F260, \"V\"),\n        (0x1F266, \"X\"),\n        (0x1F300, \"V\"),\n        (0x1F6D8, \"X\"),\n        (0x1F6DC, \"V\"),\n        (0x1F6ED, \"X\"),\n        (0x1F6F0, \"V\"),\n        (0x1F6FD, \"X\"),\n        (0x1F700, \"V\"),\n        (0x1F777, \"X\"),\n        (0x1F77B, \"V\"),\n        (0x1F7DA, \"X\"),\n        (0x1F7E0, \"V\"),\n        (0x1F7EC, \"X\"),\n        (0x1F7F0, \"V\"),\n        (0x1F7F1, \"X\"),\n        (0x1F800, \"V\"),\n        (0x1F80C, \"X\"),\n        (0x1F810, \"V\"),\n        (0x1F848, \"X\"),\n        (0x1F850, \"V\"),\n        (0x1F85A, \"X\"),\n        (0x1F860, \"V\"),\n        (0x1F888, \"X\"),\n        (0x1F890, \"V\"),\n        (0x1F8AE, \"X\"),\n        (0x1F8B0, \"V\"),\n        (0x1F8BC, \"X\"),\n        (0x1F8C0, \"V\"),\n        (0x1F8C2, \"X\"),\n        (0x1F900, \"V\"),\n        (0x1FA54, \"X\"),\n        (0x1FA60, \"V\"),\n        (0x1FA6E, \"X\"),\n        (0x1FA70, \"V\"),\n        (0x1FA7D, \"X\"),\n        (0x1FA80, \"V\"),\n        (0x1FA8A, \"X\"),\n        (0x1FA8F, \"V\"),\n        (0x1FAC7, \"X\"),\n        (0x1FACE, \"V\"),\n        (0x1FADD, \"X\"),\n        (0x1FADF, \"V\"),\n        (0x1FAEA, \"X\"),\n        (0x1FAF0, \"V\"),\n        (0x1FAF9, \"X\"),\n        (0x1FB00, \"V\"),\n        (0x1FB93, \"X\"),\n        (0x1FB94, \"V\"),\n        (0x1FBF0, \"M\", \"0\"),\n        (0x1FBF1, \"M\", \"1\"),\n        (0x1FBF2, \"M\", \"2\"),\n        (0x1FBF3, \"M\", \"3\"),\n        (0x1FBF4, \"M\", \"4\"),\n        (0x1FBF5, \"M\", \"5\"),\n        (0x1FBF6, \"M\", \"6\"),\n        (0x1FBF7, \"M\", \"7\"),\n        (0x1FBF8, \"M\", \"8\"),\n        (0x1FBF9, \"M\", \"9\"),\n        (0x1FBFA, \"X\"),\n        (0x20000, \"V\"),\n        (0x2A6E0, \"X\"),\n        (0x2A700, \"V\"),\n        (0x2B73A, \"X\"),\n        (0x2B740, \"V\"),\n        (0x2B81E, \"X\"),\n        (0x2B820, \"V\"),\n        (0x2CEA2, \"X\"),\n        (0x2CEB0, \"V\"),\n        (0x2EBE1, \"X\"),\n        (0x2EBF0, \"V\"),\n        (0x2EE5E, \"X\"),\n        (0x2F800, \"M\", \"丽\"),\n        (0x2F801, \"M\", \"丸\"),\n        (0x2F802, \"M\", \"乁\"),\n        (0x2F803, \"M\", \"𠄢\"),\n        (0x2F804, \"M\", \"你\"),\n        (0x2F805, \"M\", \"侮\"),\n        (0x2F806, \"M\", \"侻\"),\n        (0x2F807, \"M\", \"倂\"),\n        (0x2F808, \"M\", \"偺\"),\n        (0x2F809, \"M\", \"備\"),\n        (0x2F80A, \"M\", \"僧\"),\n        (0x2F80B, \"M\", \"像\"),\n        (0x2F80C, \"M\", \"㒞\"),\n        (0x2F80D, \"M\", \"𠘺\"),\n        (0x2F80E, \"M\", \"免\"),\n    ]\n\n\ndef _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F80F, \"M\", \"兔\"),\n        (0x2F810, \"M\", \"兤\"),\n        (0x2F811, \"M\", \"具\"),\n        (0x2F812, \"M\", \"𠔜\"),\n        (0x2F813, \"M\", \"㒹\"),\n        (0x2F814, \"M\", \"內\"),\n        (0x2F815, \"M\", \"再\"),\n        (0x2F816, \"M\", \"𠕋\"),\n        (0x2F817, \"M\", \"冗\"),\n        (0x2F818, \"M\", \"冤\"),\n        (0x2F819, \"M\", \"仌\"),\n        (0x2F81A, \"M\", \"冬\"),\n        (0x2F81B, \"M\", \"况\"),\n        (0x2F81C, \"M\", \"𩇟\"),\n        (0x2F81D, \"M\", \"凵\"),\n        (0x2F81E, \"M\", \"刃\"),\n        (0x2F81F, \"M\", \"㓟\"),\n        (0x2F820, \"M\", \"刻\"),\n        (0x2F821, \"M\", \"剆\"),\n        (0x2F822, \"M\", \"割\"),\n        (0x2F823, \"M\", \"剷\"),\n        (0x2F824, \"M\", \"㔕\"),\n        (0x2F825, \"M\", \"勇\"),\n        (0x2F826, \"M\", \"勉\"),\n        (0x2F827, \"M\", \"勤\"),\n        (0x2F828, \"M\", \"勺\"),\n        (0x2F829, \"M\", \"包\"),\n        (0x2F82A, \"M\", \"匆\"),\n        (0x2F82B, \"M\", \"北\"),\n        (0x2F82C, \"M\", \"卉\"),\n        (0x2F82D, \"M\", \"卑\"),\n        (0x2F82E, \"M\", \"博\"),\n        (0x2F82F, \"M\", \"即\"),\n        (0x2F830, \"M\", \"卽\"),\n        (0x2F831, \"M\", \"卿\"),\n        (0x2F834, \"M\", \"𠨬\"),\n        (0x2F835, \"M\", \"灰\"),\n        (0x2F836, \"M\", \"及\"),\n        (0x2F837, \"M\", \"叟\"),\n        (0x2F838, \"M\", \"𠭣\"),\n        (0x2F839, \"M\", \"叫\"),\n        (0x2F83A, \"M\", \"叱\"),\n        (0x2F83B, \"M\", \"吆\"),\n        (0x2F83C, \"M\", \"咞\"),\n        (0x2F83D, \"M\", \"吸\"),\n        (0x2F83E, \"M\", \"呈\"),\n        (0x2F83F, \"M\", \"周\"),\n        (0x2F840, \"M\", \"咢\"),\n        (0x2F841, \"M\", \"哶\"),\n        (0x2F842, \"M\", \"唐\"),\n        (0x2F843, \"M\", \"啓\"),\n        (0x2F844, \"M\", \"啣\"),\n        (0x2F845, \"M\", \"善\"),\n        (0x2F847, \"M\", \"喙\"),\n        (0x2F848, \"M\", \"喫\"),\n        (0x2F849, \"M\", \"喳\"),\n        (0x2F84A, \"M\", \"嗂\"),\n        (0x2F84B, \"M\", \"圖\"),\n        (0x2F84C, \"M\", \"嘆\"),\n        (0x2F84D, \"M\", \"圗\"),\n        (0x2F84E, \"M\", \"噑\"),\n        (0x2F84F, \"M\", \"噴\"),\n        (0x2F850, \"M\", \"切\"),\n        (0x2F851, \"M\", \"壮\"),\n        (0x2F852, \"M\", \"城\"),\n        (0x2F853, \"M\", \"埴\"),\n        (0x2F854, \"M\", \"堍\"),\n        (0x2F855, \"M\", \"型\"),\n        (0x2F856, \"M\", \"堲\"),\n        (0x2F857, \"M\", \"報\"),\n        (0x2F858, \"M\", \"墬\"),\n        (0x2F859, \"M\", \"𡓤\"),\n        (0x2F85A, \"M\", \"売\"),\n        (0x2F85B, \"M\", \"壷\"),\n        (0x2F85C, \"M\", \"夆\"),\n        (0x2F85D, \"M\", \"多\"),\n        (0x2F85E, \"M\", \"夢\"),\n        (0x2F85F, \"M\", \"奢\"),\n        (0x2F860, \"M\", \"𡚨\"),\n        (0x2F861, \"M\", \"𡛪\"),\n        (0x2F862, \"M\", \"姬\"),\n        (0x2F863, \"M\", \"娛\"),\n        (0x2F864, \"M\", \"娧\"),\n        (0x2F865, \"M\", \"姘\"),\n        (0x2F866, \"M\", \"婦\"),\n        (0x2F867, \"M\", \"㛮\"),\n        (0x2F868, \"M\", \"㛼\"),\n        (0x2F869, \"M\", \"嬈\"),\n        (0x2F86A, \"M\", \"嬾\"),\n        (0x2F86C, \"M\", \"𡧈\"),\n        (0x2F86D, \"M\", \"寃\"),\n        (0x2F86E, \"M\", \"寘\"),\n        (0x2F86F, \"M\", \"寧\"),\n        (0x2F870, \"M\", \"寳\"),\n        (0x2F871, \"M\", \"𡬘\"),\n        (0x2F872, \"M\", \"寿\"),\n        (0x2F873, \"M\", \"将\"),\n        (0x2F874, \"M\", \"当\"),\n        (0x2F875, \"M\", \"尢\"),\n        (0x2F876, \"M\", \"㞁\"),\n    ]\n\n\ndef _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F877, \"M\", \"屠\"),\n        (0x2F878, \"M\", \"屮\"),\n        (0x2F879, \"M\", \"峀\"),\n        (0x2F87A, \"M\", \"岍\"),\n        (0x2F87B, \"M\", \"𡷤\"),\n        (0x2F87C, \"M\", \"嵃\"),\n        (0x2F87D, \"M\", \"𡷦\"),\n        (0x2F87E, \"M\", \"嵮\"),\n        (0x2F87F, \"M\", \"嵫\"),\n        (0x2F880, \"M\", \"嵼\"),\n        (0x2F881, \"M\", \"巡\"),\n        (0x2F882, \"M\", \"巢\"),\n        (0x2F883, \"M\", \"㠯\"),\n        (0x2F884, \"M\", \"巽\"),\n        (0x2F885, \"M\", \"帨\"),\n        (0x2F886, \"M\", \"帽\"),\n        (0x2F887, \"M\", \"幩\"),\n        (0x2F888, \"M\", \"㡢\"),\n        (0x2F889, \"M\", \"𢆃\"),\n        (0x2F88A, \"M\", \"㡼\"),\n        (0x2F88B, \"M\", \"庰\"),\n        (0x2F88C, \"M\", \"庳\"),\n        (0x2F88D, \"M\", \"庶\"),\n        (0x2F88E, \"M\", \"廊\"),\n        (0x2F88F, \"M\", \"𪎒\"),\n        (0x2F890, \"M\", \"廾\"),\n        (0x2F891, \"M\", \"𢌱\"),\n        (0x2F893, \"M\", \"舁\"),\n        (0x2F894, \"M\", \"弢\"),\n        (0x2F896, \"M\", \"㣇\"),\n        (0x2F897, \"M\", \"𣊸\"),\n        (0x2F898, \"M\", \"𦇚\"),\n        (0x2F899, \"M\", \"形\"),\n        (0x2F89A, \"M\", \"彫\"),\n        (0x2F89B, \"M\", \"㣣\"),\n        (0x2F89C, \"M\", \"徚\"),\n        (0x2F89D, \"M\", \"忍\"),\n        (0x2F89E, \"M\", \"志\"),\n        (0x2F89F, \"M\", \"忹\"),\n        (0x2F8A0, \"M\", \"悁\"),\n        (0x2F8A1, \"M\", \"㤺\"),\n        (0x2F8A2, \"M\", \"㤜\"),\n        (0x2F8A3, \"M\", \"悔\"),\n        (0x2F8A4, \"M\", \"𢛔\"),\n        (0x2F8A5, \"M\", \"惇\"),\n        (0x2F8A6, \"M\", \"慈\"),\n        (0x2F8A7, \"M\", \"慌\"),\n        (0x2F8A8, \"M\", \"慎\"),\n        (0x2F8A9, \"M\", \"慌\"),\n        (0x2F8AA, \"M\", \"慺\"),\n        (0x2F8AB, \"M\", \"憎\"),\n        (0x2F8AC, \"M\", \"憲\"),\n        (0x2F8AD, \"M\", \"憤\"),\n        (0x2F8AE, \"M\", \"憯\"),\n        (0x2F8AF, \"M\", \"懞\"),\n        (0x2F8B0, \"M\", \"懲\"),\n        (0x2F8B1, \"M\", \"懶\"),\n        (0x2F8B2, \"M\", \"成\"),\n        (0x2F8B3, \"M\", \"戛\"),\n        (0x2F8B4, \"M\", \"扝\"),\n        (0x2F8B5, \"M\", \"抱\"),\n        (0x2F8B6, \"M\", \"拔\"),\n        (0x2F8B7, \"M\", \"捐\"),\n        (0x2F8B8, \"M\", \"𢬌\"),\n        (0x2F8B9, \"M\", \"挽\"),\n        (0x2F8BA, \"M\", \"拼\"),\n        (0x2F8BB, \"M\", \"捨\"),\n        (0x2F8BC, \"M\", \"掃\"),\n        (0x2F8BD, \"M\", \"揤\"),\n        (0x2F8BE, \"M\", \"𢯱\"),\n        (0x2F8BF, \"M\", \"搢\"),\n        (0x2F8C0, \"M\", \"揅\"),\n        (0x2F8C1, \"M\", \"掩\"),\n        (0x2F8C2, \"M\", \"㨮\"),\n        (0x2F8C3, \"M\", \"摩\"),\n        (0x2F8C4, \"M\", \"摾\"),\n        (0x2F8C5, \"M\", \"撝\"),\n        (0x2F8C6, \"M\", \"摷\"),\n        (0x2F8C7, \"M\", \"㩬\"),\n        (0x2F8C8, \"M\", \"敏\"),\n        (0x2F8C9, \"M\", \"敬\"),\n        (0x2F8CA, \"M\", \"𣀊\"),\n        (0x2F8CB, \"M\", \"旣\"),\n        (0x2F8CC, \"M\", \"書\"),\n        (0x2F8CD, \"M\", \"晉\"),\n        (0x2F8CE, \"M\", \"㬙\"),\n        (0x2F8CF, \"M\", \"暑\"),\n        (0x2F8D0, \"M\", \"㬈\"),\n        (0x2F8D1, \"M\", \"㫤\"),\n        (0x2F8D2, \"M\", \"冒\"),\n        (0x2F8D3, \"M\", \"冕\"),\n        (0x2F8D4, \"M\", \"最\"),\n        (0x2F8D5, \"M\", \"暜\"),\n        (0x2F8D6, \"M\", \"肭\"),\n        (0x2F8D7, \"M\", \"䏙\"),\n        (0x2F8D8, \"M\", \"朗\"),\n        (0x2F8D9, \"M\", \"望\"),\n        (0x2F8DA, \"M\", \"朡\"),\n        (0x2F8DB, \"M\", \"杞\"),\n        (0x2F8DC, \"M\", \"杓\"),\n    ]\n\n\ndef _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F8DD, \"M\", \"𣏃\"),\n        (0x2F8DE, \"M\", \"㭉\"),\n        (0x2F8DF, \"M\", \"柺\"),\n        (0x2F8E0, \"M\", \"枅\"),\n        (0x2F8E1, \"M\", \"桒\"),\n        (0x2F8E2, \"M\", \"梅\"),\n        (0x2F8E3, \"M\", \"𣑭\"),\n        (0x2F8E4, \"M\", \"梎\"),\n        (0x2F8E5, \"M\", \"栟\"),\n        (0x2F8E6, \"M\", \"椔\"),\n        (0x2F8E7, \"M\", \"㮝\"),\n        (0x2F8E8, \"M\", \"楂\"),\n        (0x2F8E9, \"M\", \"榣\"),\n        (0x2F8EA, \"M\", \"槪\"),\n        (0x2F8EB, \"M\", \"檨\"),\n        (0x2F8EC, \"M\", \"𣚣\"),\n        (0x2F8ED, \"M\", \"櫛\"),\n        (0x2F8EE, \"M\", \"㰘\"),\n        (0x2F8EF, \"M\", \"次\"),\n        (0x2F8F0, \"M\", \"𣢧\"),\n        (0x2F8F1, \"M\", \"歔\"),\n        (0x2F8F2, \"M\", \"㱎\"),\n        (0x2F8F3, \"M\", \"歲\"),\n        (0x2F8F4, \"M\", \"殟\"),\n        (0x2F8F5, \"M\", \"殺\"),\n        (0x2F8F6, \"M\", \"殻\"),\n        (0x2F8F7, \"M\", \"𣪍\"),\n        (0x2F8F8, \"M\", \"𡴋\"),\n        (0x2F8F9, \"M\", \"𣫺\"),\n        (0x2F8FA, \"M\", \"汎\"),\n        (0x2F8FB, \"M\", \"𣲼\"),\n        (0x2F8FC, \"M\", \"沿\"),\n        (0x2F8FD, \"M\", \"泍\"),\n        (0x2F8FE, \"M\", \"汧\"),\n        (0x2F8FF, \"M\", \"洖\"),\n        (0x2F900, \"M\", \"派\"),\n        (0x2F901, \"M\", \"海\"),\n        (0x2F902, \"M\", \"流\"),\n        (0x2F903, \"M\", \"浩\"),\n        (0x2F904, \"M\", \"浸\"),\n        (0x2F905, \"M\", \"涅\"),\n        (0x2F906, \"M\", \"𣴞\"),\n        (0x2F907, \"M\", \"洴\"),\n        (0x2F908, \"M\", \"港\"),\n        (0x2F909, \"M\", \"湮\"),\n        (0x2F90A, \"M\", \"㴳\"),\n        (0x2F90B, \"M\", \"滋\"),\n        (0x2F90C, \"M\", \"滇\"),\n        (0x2F90D, \"M\", \"𣻑\"),\n        (0x2F90E, \"M\", \"淹\"),\n        (0x2F90F, \"M\", \"潮\"),\n        (0x2F910, \"M\", \"𣽞\"),\n        (0x2F911, \"M\", \"𣾎\"),\n        (0x2F912, \"M\", \"濆\"),\n        (0x2F913, \"M\", \"瀹\"),\n        (0x2F914, \"M\", \"瀞\"),\n        (0x2F915, \"M\", \"瀛\"),\n        (0x2F916, \"M\", \"㶖\"),\n        (0x2F917, \"M\", \"灊\"),\n        (0x2F918, \"M\", \"災\"),\n        (0x2F919, \"M\", \"灷\"),\n        (0x2F91A, \"M\", \"炭\"),\n        (0x2F91B, \"M\", \"𠔥\"),\n        (0x2F91C, \"M\", \"煅\"),\n        (0x2F91D, \"M\", \"𤉣\"),\n        (0x2F91E, \"M\", \"熜\"),\n        (0x2F91F, \"M\", \"𤎫\"),\n        (0x2F920, \"M\", \"爨\"),\n        (0x2F921, \"M\", \"爵\"),\n        (0x2F922, \"M\", \"牐\"),\n        (0x2F923, \"M\", \"𤘈\"),\n        (0x2F924, \"M\", \"犀\"),\n        (0x2F925, \"M\", \"犕\"),\n        (0x2F926, \"M\", \"𤜵\"),\n        (0x2F927, \"M\", \"𤠔\"),\n        (0x2F928, \"M\", \"獺\"),\n        (0x2F929, \"M\", \"王\"),\n        (0x2F92A, \"M\", \"㺬\"),\n        (0x2F92B, \"M\", \"玥\"),\n        (0x2F92C, \"M\", \"㺸\"),\n        (0x2F92E, \"M\", \"瑇\"),\n        (0x2F92F, \"M\", \"瑜\"),\n        (0x2F930, \"M\", \"瑱\"),\n        (0x2F931, \"M\", \"璅\"),\n        (0x2F932, \"M\", \"瓊\"),\n        (0x2F933, \"M\", \"㼛\"),\n        (0x2F934, \"M\", \"甤\"),\n        (0x2F935, \"M\", \"𤰶\"),\n        (0x2F936, \"M\", \"甾\"),\n        (0x2F937, \"M\", \"𤲒\"),\n        (0x2F938, \"M\", \"異\"),\n        (0x2F939, \"M\", \"𢆟\"),\n        (0x2F93A, \"M\", \"瘐\"),\n        (0x2F93B, \"M\", \"𤾡\"),\n        (0x2F93C, \"M\", \"𤾸\"),\n        (0x2F93D, \"M\", \"𥁄\"),\n        (0x2F93E, \"M\", \"㿼\"),\n        (0x2F93F, \"M\", \"䀈\"),\n        (0x2F940, \"M\", \"直\"),\n        (0x2F941, \"M\", \"𥃳\"),\n    ]\n\n\ndef _seg_81() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F942, \"M\", \"𥃲\"),\n        (0x2F943, \"M\", \"𥄙\"),\n        (0x2F944, \"M\", \"𥄳\"),\n        (0x2F945, \"M\", \"眞\"),\n        (0x2F946, \"M\", \"真\"),\n        (0x2F948, \"M\", \"睊\"),\n        (0x2F949, \"M\", \"䀹\"),\n        (0x2F94A, \"M\", \"瞋\"),\n        (0x2F94B, \"M\", \"䁆\"),\n        (0x2F94C, \"M\", \"䂖\"),\n        (0x2F94D, \"M\", \"𥐝\"),\n        (0x2F94E, \"M\", \"硎\"),\n        (0x2F94F, \"M\", \"碌\"),\n        (0x2F950, \"M\", \"磌\"),\n        (0x2F951, \"M\", \"䃣\"),\n        (0x2F952, \"M\", \"𥘦\"),\n        (0x2F953, \"M\", \"祖\"),\n        (0x2F954, \"M\", \"𥚚\"),\n        (0x2F955, \"M\", \"𥛅\"),\n        (0x2F956, \"M\", \"福\"),\n        (0x2F957, \"M\", \"秫\"),\n        (0x2F958, \"M\", \"䄯\"),\n        (0x2F959, \"M\", \"穀\"),\n        (0x2F95A, \"M\", \"穊\"),\n        (0x2F95B, \"M\", \"穏\"),\n        (0x2F95C, \"M\", \"𥥼\"),\n        (0x2F95D, \"M\", \"𥪧\"),\n        (0x2F95F, \"M\", \"竮\"),\n        (0x2F960, \"M\", \"䈂\"),\n        (0x2F961, \"M\", \"𥮫\"),\n        (0x2F962, \"M\", \"篆\"),\n        (0x2F963, \"M\", \"築\"),\n        (0x2F964, \"M\", \"䈧\"),\n        (0x2F965, \"M\", \"𥲀\"),\n        (0x2F966, \"M\", \"糒\"),\n        (0x2F967, \"M\", \"䊠\"),\n        (0x2F968, \"M\", \"糨\"),\n        (0x2F969, \"M\", \"糣\"),\n        (0x2F96A, \"M\", \"紀\"),\n        (0x2F96B, \"M\", \"𥾆\"),\n        (0x2F96C, \"M\", \"絣\"),\n        (0x2F96D, \"M\", \"䌁\"),\n        (0x2F96E, \"M\", \"緇\"),\n        (0x2F96F, \"M\", \"縂\"),\n        (0x2F970, \"M\", \"繅\"),\n        (0x2F971, \"M\", \"䌴\"),\n        (0x2F972, \"M\", \"𦈨\"),\n        (0x2F973, \"M\", \"𦉇\"),\n        (0x2F974, \"M\", \"䍙\"),\n        (0x2F975, \"M\", \"𦋙\"),\n        (0x2F976, \"M\", \"罺\"),\n        (0x2F977, \"M\", \"𦌾\"),\n        (0x2F978, \"M\", \"羕\"),\n        (0x2F979, \"M\", \"翺\"),\n        (0x2F97A, \"M\", \"者\"),\n        (0x2F97B, \"M\", \"𦓚\"),\n        (0x2F97C, \"M\", \"𦔣\"),\n        (0x2F97D, \"M\", \"聠\"),\n        (0x2F97E, \"M\", \"𦖨\"),\n        (0x2F97F, \"M\", \"聰\"),\n        (0x2F980, \"M\", \"𣍟\"),\n        (0x2F981, \"M\", \"䏕\"),\n        (0x2F982, \"M\", \"育\"),\n        (0x2F983, \"M\", \"脃\"),\n        (0x2F984, \"M\", \"䐋\"),\n        (0x2F985, \"M\", \"脾\"),\n        (0x2F986, \"M\", \"媵\"),\n        (0x2F987, \"M\", \"𦞧\"),\n        (0x2F988, \"M\", \"𦞵\"),\n        (0x2F989, \"M\", \"𣎓\"),\n        (0x2F98A, \"M\", \"𣎜\"),\n        (0x2F98B, \"M\", \"舁\"),\n        (0x2F98C, \"M\", \"舄\"),\n        (0x2F98D, \"M\", \"辞\"),\n        (0x2F98E, \"M\", \"䑫\"),\n        (0x2F98F, \"M\", \"芑\"),\n        (0x2F990, \"M\", \"芋\"),\n        (0x2F991, \"M\", \"芝\"),\n        (0x2F992, \"M\", \"劳\"),\n        (0x2F993, \"M\", \"花\"),\n        (0x2F994, \"M\", \"芳\"),\n        (0x2F995, \"M\", \"芽\"),\n        (0x2F996, \"M\", \"苦\"),\n        (0x2F997, \"M\", \"𦬼\"),\n        (0x2F998, \"M\", \"若\"),\n        (0x2F999, \"M\", \"茝\"),\n        (0x2F99A, \"M\", \"荣\"),\n        (0x2F99B, \"M\", \"莭\"),\n        (0x2F99C, \"M\", \"茣\"),\n        (0x2F99D, \"M\", \"莽\"),\n        (0x2F99E, \"M\", \"菧\"),\n        (0x2F99F, \"M\", \"著\"),\n        (0x2F9A0, \"M\", \"荓\"),\n        (0x2F9A1, \"M\", \"菊\"),\n        (0x2F9A2, \"M\", \"菌\"),\n        (0x2F9A3, \"M\", \"菜\"),\n        (0x2F9A4, \"M\", \"𦰶\"),\n        (0x2F9A5, \"M\", \"𦵫\"),\n        (0x2F9A6, \"M\", \"𦳕\"),\n        (0x2F9A7, \"M\", \"䔫\"),\n    ]\n\n\ndef _seg_82() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2F9A8, \"M\", \"蓱\"),\n        (0x2F9A9, \"M\", \"蓳\"),\n        (0x2F9AA, \"M\", \"蔖\"),\n        (0x2F9AB, \"M\", \"𧏊\"),\n        (0x2F9AC, \"M\", \"蕤\"),\n        (0x2F9AD, \"M\", \"𦼬\"),\n        (0x2F9AE, \"M\", \"䕝\"),\n        (0x2F9AF, \"M\", \"䕡\"),\n        (0x2F9B0, \"M\", \"𦾱\"),\n        (0x2F9B1, \"M\", \"𧃒\"),\n        (0x2F9B2, \"M\", \"䕫\"),\n        (0x2F9B3, \"M\", \"虐\"),\n        (0x2F9B4, \"M\", \"虜\"),\n        (0x2F9B5, \"M\", \"虧\"),\n        (0x2F9B6, \"M\", \"虩\"),\n        (0x2F9B7, \"M\", \"蚩\"),\n        (0x2F9B8, \"M\", \"蚈\"),\n        (0x2F9B9, \"M\", \"蜎\"),\n        (0x2F9BA, \"M\", \"蛢\"),\n        (0x2F9BB, \"M\", \"蝹\"),\n        (0x2F9BC, \"M\", \"蜨\"),\n        (0x2F9BD, \"M\", \"蝫\"),\n        (0x2F9BE, \"M\", \"螆\"),\n        (0x2F9BF, \"M\", \"䗗\"),\n        (0x2F9C0, \"M\", \"蟡\"),\n        (0x2F9C1, \"M\", \"蠁\"),\n        (0x2F9C2, \"M\", \"䗹\"),\n        (0x2F9C3, \"M\", \"衠\"),\n        (0x2F9C4, \"M\", \"衣\"),\n        (0x2F9C5, \"M\", \"𧙧\"),\n        (0x2F9C6, \"M\", \"裗\"),\n        (0x2F9C7, \"M\", \"裞\"),\n        (0x2F9C8, \"M\", \"䘵\"),\n        (0x2F9C9, \"M\", \"裺\"),\n        (0x2F9CA, \"M\", \"㒻\"),\n        (0x2F9CB, \"M\", \"𧢮\"),\n        (0x2F9CC, \"M\", \"𧥦\"),\n        (0x2F9CD, \"M\", \"䚾\"),\n        (0x2F9CE, \"M\", \"䛇\"),\n        (0x2F9CF, \"M\", \"誠\"),\n        (0x2F9D0, \"M\", \"諭\"),\n        (0x2F9D1, \"M\", \"變\"),\n        (0x2F9D2, \"M\", \"豕\"),\n        (0x2F9D3, \"M\", \"𧲨\"),\n        (0x2F9D4, \"M\", \"貫\"),\n        (0x2F9D5, \"M\", \"賁\"),\n        (0x2F9D6, \"M\", \"贛\"),\n        (0x2F9D7, \"M\", \"起\"),\n        (0x2F9D8, \"M\", \"𧼯\"),\n        (0x2F9D9, \"M\", \"𠠄\"),\n        (0x2F9DA, \"M\", \"跋\"),\n        (0x2F9DB, \"M\", \"趼\"),\n        (0x2F9DC, \"M\", \"跰\"),\n        (0x2F9DD, \"M\", \"𠣞\"),\n        (0x2F9DE, \"M\", \"軔\"),\n        (0x2F9DF, \"M\", \"輸\"),\n        (0x2F9E0, \"M\", \"𨗒\"),\n        (0x2F9E1, \"M\", \"𨗭\"),\n        (0x2F9E2, \"M\", \"邔\"),\n        (0x2F9E3, \"M\", \"郱\"),\n        (0x2F9E4, \"M\", \"鄑\"),\n        (0x2F9E5, \"M\", \"𨜮\"),\n        (0x2F9E6, \"M\", \"鄛\"),\n        (0x2F9E7, \"M\", \"鈸\"),\n        (0x2F9E8, \"M\", \"鋗\"),\n        (0x2F9E9, \"M\", \"鋘\"),\n        (0x2F9EA, \"M\", \"鉼\"),\n        (0x2F9EB, \"M\", \"鏹\"),\n        (0x2F9EC, \"M\", \"鐕\"),\n        (0x2F9ED, \"M\", \"𨯺\"),\n        (0x2F9EE, \"M\", \"開\"),\n        (0x2F9EF, \"M\", \"䦕\"),\n        (0x2F9F0, \"M\", \"閷\"),\n        (0x2F9F1, \"M\", \"𨵷\"),\n        (0x2F9F2, \"M\", \"䧦\"),\n        (0x2F9F3, \"M\", \"雃\"),\n        (0x2F9F4, \"M\", \"嶲\"),\n        (0x2F9F5, \"M\", \"霣\"),\n        (0x2F9F6, \"M\", \"𩅅\"),\n        (0x2F9F7, \"M\", \"𩈚\"),\n        (0x2F9F8, \"M\", \"䩮\"),\n        (0x2F9F9, \"M\", \"䩶\"),\n        (0x2F9FA, \"M\", \"韠\"),\n        (0x2F9FB, \"M\", \"𩐊\"),\n        (0x2F9FC, \"M\", \"䪲\"),\n        (0x2F9FD, \"M\", \"𩒖\"),\n        (0x2F9FE, \"M\", \"頋\"),\n        (0x2FA00, \"M\", \"頩\"),\n        (0x2FA01, \"M\", \"𩖶\"),\n        (0x2FA02, \"M\", \"飢\"),\n        (0x2FA03, \"M\", \"䬳\"),\n        (0x2FA04, \"M\", \"餩\"),\n        (0x2FA05, \"M\", \"馧\"),\n        (0x2FA06, \"M\", \"駂\"),\n        (0x2FA07, \"M\", \"駾\"),\n        (0x2FA08, \"M\", \"䯎\"),\n        (0x2FA09, \"M\", \"𩬰\"),\n        (0x2FA0A, \"M\", \"鬒\"),\n        (0x2FA0B, \"M\", \"鱀\"),\n        (0x2FA0C, \"M\", \"鳽\"),\n    ]\n\n\ndef _seg_83() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n        (0x2FA0D, \"M\", \"䳎\"),\n        (0x2FA0E, \"M\", \"䳭\"),\n        (0x2FA0F, \"M\", \"鵧\"),\n        (0x2FA10, \"M\", \"𪃎\"),\n        (0x2FA11, \"M\", \"䳸\"),\n        (0x2FA12, \"M\", \"𪄅\"),\n        (0x2FA13, \"M\", \"𪈎\"),\n        (0x2FA14, \"M\", \"𪊑\"),\n        (0x2FA15, \"M\", \"麻\"),\n        (0x2FA16, \"M\", \"䵖\"),\n        (0x2FA17, \"M\", \"黹\"),\n        (0x2FA18, \"M\", \"黾\"),\n        (0x2FA19, \"M\", \"鼅\"),\n        (0x2FA1A, \"M\", \"鼏\"),\n        (0x2FA1B, \"M\", \"鼖\"),\n        (0x2FA1C, \"M\", \"鼻\"),\n        (0x2FA1D, \"M\", \"𪘀\"),\n        (0x2FA1E, \"X\"),\n        (0x30000, \"V\"),\n        (0x3134B, \"X\"),\n        (0x31350, \"V\"),\n        (0x323B0, \"X\"),\n        (0xE0100, \"I\"),\n        (0xE01F0, \"X\"),\n    ]\n\n\nuts46data = tuple(\n    _seg_0()\n    + _seg_1()\n    + _seg_2()\n    + _seg_3()\n    + _seg_4()\n    + _seg_5()\n    + _seg_6()\n    + _seg_7()\n    + _seg_8()\n    + _seg_9()\n    + _seg_10()\n    + _seg_11()\n    + _seg_12()\n    + _seg_13()\n    + _seg_14()\n    + _seg_15()\n    + _seg_16()\n    + _seg_17()\n    + _seg_18()\n    + _seg_19()\n    + _seg_20()\n    + _seg_21()\n    + _seg_22()\n    + _seg_23()\n    + _seg_24()\n    + _seg_25()\n    + _seg_26()\n    + _seg_27()\n    + _seg_28()\n    + _seg_29()\n    + _seg_30()\n    + _seg_31()\n    + _seg_32()\n    + _seg_33()\n    + _seg_34()\n    + _seg_35()\n    + _seg_36()\n    + _seg_37()\n    + _seg_38()\n    + _seg_39()\n    + _seg_40()\n    + _seg_41()\n    + _seg_42()\n    + _seg_43()\n    + _seg_44()\n    + _seg_45()\n    + _seg_46()\n    + _seg_47()\n    + _seg_48()\n    + _seg_49()\n    + _seg_50()\n    + _seg_51()\n    + _seg_52()\n    + _seg_53()\n    + _seg_54()\n    + _seg_55()\n    + _seg_56()\n    + _seg_57()\n    + _seg_58()\n    + _seg_59()\n    + _seg_60()\n    + _seg_61()\n    + _seg_62()\n    + _seg_63()\n    + _seg_64()\n    + _seg_65()\n    + _seg_66()\n    + _seg_67()\n    + _seg_68()\n    + _seg_69()\n    + _seg_70()\n    + _seg_71()\n    + _seg_72()\n    + _seg_73()\n    + _seg_74()\n    + _seg_75()\n    + _seg_76()\n    + _seg_77()\n    + _seg_78()\n    + _seg_79()\n    + _seg_80()\n    + _seg_81()\n    + _seg_82()\n    + _seg_83()\n)  # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...]\n"
  },
  {
    "path": "src/pip/_vendor/msgpack/COPYING",
    "content": "Copyright (C) 2008-2011 INADA Naoki <songofacandy@gmail.com>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "src/pip/_vendor/msgpack/__init__.py",
    "content": "# ruff: noqa: F401\nimport os\n\nfrom .exceptions import *  # noqa: F403\nfrom .ext import ExtType, Timestamp\n\nversion = (1, 1, 2)\n__version__ = \"1.1.2\"\n\n\nif os.environ.get(\"MSGPACK_PUREPYTHON\"):\n    from .fallback import Packer, Unpacker, unpackb\nelse:\n    try:\n        from ._cmsgpack import Packer, Unpacker, unpackb\n    except ImportError:\n        from .fallback import Packer, Unpacker, unpackb\n\n\ndef pack(o, stream, **kwargs):\n    \"\"\"\n    Pack object `o` and write it to `stream`\n\n    See :class:`Packer` for options.\n    \"\"\"\n    packer = Packer(**kwargs)\n    stream.write(packer.pack(o))\n\n\ndef packb(o, **kwargs):\n    \"\"\"\n    Pack object `o` and return packed bytes\n\n    See :class:`Packer` for options.\n    \"\"\"\n    return Packer(**kwargs).pack(o)\n\n\ndef unpack(stream, **kwargs):\n    \"\"\"\n    Unpack an object from `stream`.\n\n    Raises `ExtraData` when `stream` contains extra bytes.\n    See :class:`Unpacker` for options.\n    \"\"\"\n    data = stream.read()\n    return unpackb(data, **kwargs)\n\n\n# alias for compatibility to simplejson/marshal/pickle.\nload = unpack\nloads = unpackb\n\ndump = pack\ndumps = packb\n"
  },
  {
    "path": "src/pip/_vendor/msgpack/exceptions.py",
    "content": "class UnpackException(Exception):\n    \"\"\"Base class for some exceptions raised while unpacking.\n\n    NOTE: unpack may raise exception other than subclass of\n    UnpackException.  If you want to catch all error, catch\n    Exception instead.\n    \"\"\"\n\n\nclass BufferFull(UnpackException):\n    pass\n\n\nclass OutOfData(UnpackException):\n    pass\n\n\nclass FormatError(ValueError, UnpackException):\n    \"\"\"Invalid msgpack format\"\"\"\n\n\nclass StackError(ValueError, UnpackException):\n    \"\"\"Too nested\"\"\"\n\n\n# Deprecated.  Use ValueError instead\nUnpackValueError = ValueError\n\n\nclass ExtraData(UnpackValueError):\n    \"\"\"ExtraData is raised when there is trailing data.\n\n    This exception is raised while only one-shot (not streaming)\n    unpack.\n    \"\"\"\n\n    def __init__(self, unpacked, extra):\n        self.unpacked = unpacked\n        self.extra = extra\n\n    def __str__(self):\n        return \"unpack(b) received extra data.\"\n\n\n# Deprecated.  Use Exception instead to catch all exception during packing.\nPackException = Exception\nPackValueError = ValueError\nPackOverflowError = OverflowError\n"
  },
  {
    "path": "src/pip/_vendor/msgpack/ext.py",
    "content": "import datetime\nimport struct\nfrom collections import namedtuple\n\n\nclass ExtType(namedtuple(\"ExtType\", \"code data\")):\n    \"\"\"ExtType represents ext type in msgpack.\"\"\"\n\n    def __new__(cls, code, data):\n        if not isinstance(code, int):\n            raise TypeError(\"code must be int\")\n        if not isinstance(data, bytes):\n            raise TypeError(\"data must be bytes\")\n        if not 0 <= code <= 127:\n            raise ValueError(\"code must be 0~127\")\n        return super().__new__(cls, code, data)\n\n\nclass Timestamp:\n    \"\"\"Timestamp represents the Timestamp extension type in msgpack.\n\n    When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`.\n    When using pure-Python msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and\n    unpack `Timestamp`.\n\n    This class is immutable: Do not override seconds and nanoseconds.\n    \"\"\"\n\n    __slots__ = [\"seconds\", \"nanoseconds\"]\n\n    def __init__(self, seconds, nanoseconds=0):\n        \"\"\"Initialize a Timestamp object.\n\n        :param int seconds:\n            Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds).\n            May be negative.\n\n        :param int nanoseconds:\n            Number of nanoseconds to add to `seconds` to get fractional time.\n            Maximum is 999_999_999.  Default is 0.\n\n        Note: Negative times (before the UNIX epoch) are represented as neg. seconds + pos. ns.\n        \"\"\"\n        if not isinstance(seconds, int):\n            raise TypeError(\"seconds must be an integer\")\n        if not isinstance(nanoseconds, int):\n            raise TypeError(\"nanoseconds must be an integer\")\n        if not (0 <= nanoseconds < 10**9):\n            raise ValueError(\"nanoseconds must be a non-negative integer less than 999999999.\")\n        self.seconds = seconds\n        self.nanoseconds = nanoseconds\n\n    def __repr__(self):\n        \"\"\"String representation of Timestamp.\"\"\"\n        return f\"Timestamp(seconds={self.seconds}, nanoseconds={self.nanoseconds})\"\n\n    def __eq__(self, other):\n        \"\"\"Check for equality with another Timestamp object\"\"\"\n        if type(other) is self.__class__:\n            return self.seconds == other.seconds and self.nanoseconds == other.nanoseconds\n        return False\n\n    def __ne__(self, other):\n        \"\"\"not-equals method (see :func:`__eq__()`)\"\"\"\n        return not self.__eq__(other)\n\n    def __hash__(self):\n        return hash((self.seconds, self.nanoseconds))\n\n    @staticmethod\n    def from_bytes(b):\n        \"\"\"Unpack bytes into a `Timestamp` object.\n\n        Used for pure-Python msgpack unpacking.\n\n        :param b: Payload from msgpack ext message with code -1\n        :type b: bytes\n\n        :returns: Timestamp object unpacked from msgpack ext payload\n        :rtype: Timestamp\n        \"\"\"\n        if len(b) == 4:\n            seconds = struct.unpack(\"!L\", b)[0]\n            nanoseconds = 0\n        elif len(b) == 8:\n            data64 = struct.unpack(\"!Q\", b)[0]\n            seconds = data64 & 0x00000003FFFFFFFF\n            nanoseconds = data64 >> 34\n        elif len(b) == 12:\n            nanoseconds, seconds = struct.unpack(\"!Iq\", b)\n        else:\n            raise ValueError(\n                \"Timestamp type can only be created from 32, 64, or 96-bit byte objects\"\n            )\n        return Timestamp(seconds, nanoseconds)\n\n    def to_bytes(self):\n        \"\"\"Pack this Timestamp object into bytes.\n\n        Used for pure-Python msgpack packing.\n\n        :returns data: Payload for EXT message with code -1 (timestamp type)\n        :rtype: bytes\n        \"\"\"\n        if (self.seconds >> 34) == 0:  # seconds is non-negative and fits in 34 bits\n            data64 = self.nanoseconds << 34 | self.seconds\n            if data64 & 0xFFFFFFFF00000000 == 0:\n                # nanoseconds is zero and seconds < 2**32, so timestamp 32\n                data = struct.pack(\"!L\", data64)\n            else:\n                # timestamp 64\n                data = struct.pack(\"!Q\", data64)\n        else:\n            # timestamp 96\n            data = struct.pack(\"!Iq\", self.nanoseconds, self.seconds)\n        return data\n\n    @staticmethod\n    def from_unix(unix_sec):\n        \"\"\"Create a Timestamp from posix timestamp in seconds.\n\n        :param unix_float: Posix timestamp in seconds.\n        :type unix_float: int or float\n        \"\"\"\n        seconds = int(unix_sec // 1)\n        nanoseconds = int((unix_sec % 1) * 10**9)\n        return Timestamp(seconds, nanoseconds)\n\n    def to_unix(self):\n        \"\"\"Get the timestamp as a floating-point value.\n\n        :returns: posix timestamp\n        :rtype: float\n        \"\"\"\n        return self.seconds + self.nanoseconds / 1e9\n\n    @staticmethod\n    def from_unix_nano(unix_ns):\n        \"\"\"Create a Timestamp from posix timestamp in nanoseconds.\n\n        :param int unix_ns: Posix timestamp in nanoseconds.\n        :rtype: Timestamp\n        \"\"\"\n        return Timestamp(*divmod(unix_ns, 10**9))\n\n    def to_unix_nano(self):\n        \"\"\"Get the timestamp as a unixtime in nanoseconds.\n\n        :returns: posix timestamp in nanoseconds\n        :rtype: int\n        \"\"\"\n        return self.seconds * 10**9 + self.nanoseconds\n\n    def to_datetime(self):\n        \"\"\"Get the timestamp as a UTC datetime.\n\n        :rtype: `datetime.datetime`\n        \"\"\"\n        utc = datetime.timezone.utc\n        return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta(\n            seconds=self.seconds, microseconds=self.nanoseconds // 1000\n        )\n\n    @staticmethod\n    def from_datetime(dt):\n        \"\"\"Create a Timestamp from datetime with tzinfo.\n\n        :rtype: Timestamp\n        \"\"\"\n        return Timestamp(seconds=int(dt.timestamp()), nanoseconds=dt.microsecond * 1000)\n"
  },
  {
    "path": "src/pip/_vendor/msgpack/fallback.py",
    "content": "\"\"\"Fallback pure Python implementation of msgpack\"\"\"\n\nimport struct\nimport sys\nfrom datetime import datetime as _DateTime\n\nif hasattr(sys, \"pypy_version_info\"):\n    from __pypy__ import newlist_hint\n    from __pypy__.builders import BytesBuilder\n\n    _USING_STRINGBUILDER = True\n\n    class BytesIO:\n        def __init__(self, s=b\"\"):\n            if s:\n                self.builder = BytesBuilder(len(s))\n                self.builder.append(s)\n            else:\n                self.builder = BytesBuilder()\n\n        def write(self, s):\n            if isinstance(s, memoryview):\n                s = s.tobytes()\n            elif isinstance(s, bytearray):\n                s = bytes(s)\n            self.builder.append(s)\n\n        def getvalue(self):\n            return self.builder.build()\n\nelse:\n    from io import BytesIO\n\n    _USING_STRINGBUILDER = False\n\n    def newlist_hint(size):\n        return []\n\n\nfrom .exceptions import BufferFull, ExtraData, FormatError, OutOfData, StackError\nfrom .ext import ExtType, Timestamp\n\nEX_SKIP = 0\nEX_CONSTRUCT = 1\nEX_READ_ARRAY_HEADER = 2\nEX_READ_MAP_HEADER = 3\n\nTYPE_IMMEDIATE = 0\nTYPE_ARRAY = 1\nTYPE_MAP = 2\nTYPE_RAW = 3\nTYPE_BIN = 4\nTYPE_EXT = 5\n\nDEFAULT_RECURSE_LIMIT = 511\n\n\ndef _check_type_strict(obj, t, type=type, tuple=tuple):\n    if type(t) is tuple:\n        return type(obj) in t\n    else:\n        return type(obj) is t\n\n\ndef _get_data_from_buffer(obj):\n    view = memoryview(obj)\n    if view.itemsize != 1:\n        raise ValueError(\"cannot unpack from multi-byte object\")\n    return view\n\n\ndef unpackb(packed, **kwargs):\n    \"\"\"\n    Unpack an object from `packed`.\n\n    Raises ``ExtraData`` when *packed* contains extra bytes.\n    Raises ``ValueError`` when *packed* is incomplete.\n    Raises ``FormatError`` when *packed* is not valid msgpack.\n    Raises ``StackError`` when *packed* contains too nested.\n    Other exceptions can be raised during unpacking.\n\n    See :class:`Unpacker` for options.\n    \"\"\"\n    unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs)\n    unpacker.feed(packed)\n    try:\n        ret = unpacker._unpack()\n    except OutOfData:\n        raise ValueError(\"Unpack failed: incomplete input\")\n    except RecursionError:\n        raise StackError\n    if unpacker._got_extradata():\n        raise ExtraData(ret, unpacker._get_extradata())\n    return ret\n\n\n_NO_FORMAT_USED = \"\"\n_MSGPACK_HEADERS = {\n    0xC4: (1, _NO_FORMAT_USED, TYPE_BIN),\n    0xC5: (2, \">H\", TYPE_BIN),\n    0xC6: (4, \">I\", TYPE_BIN),\n    0xC7: (2, \"Bb\", TYPE_EXT),\n    0xC8: (3, \">Hb\", TYPE_EXT),\n    0xC9: (5, \">Ib\", TYPE_EXT),\n    0xCA: (4, \">f\"),\n    0xCB: (8, \">d\"),\n    0xCC: (1, _NO_FORMAT_USED),\n    0xCD: (2, \">H\"),\n    0xCE: (4, \">I\"),\n    0xCF: (8, \">Q\"),\n    0xD0: (1, \"b\"),\n    0xD1: (2, \">h\"),\n    0xD2: (4, \">i\"),\n    0xD3: (8, \">q\"),\n    0xD4: (1, \"b1s\", TYPE_EXT),\n    0xD5: (2, \"b2s\", TYPE_EXT),\n    0xD6: (4, \"b4s\", TYPE_EXT),\n    0xD7: (8, \"b8s\", TYPE_EXT),\n    0xD8: (16, \"b16s\", TYPE_EXT),\n    0xD9: (1, _NO_FORMAT_USED, TYPE_RAW),\n    0xDA: (2, \">H\", TYPE_RAW),\n    0xDB: (4, \">I\", TYPE_RAW),\n    0xDC: (2, \">H\", TYPE_ARRAY),\n    0xDD: (4, \">I\", TYPE_ARRAY),\n    0xDE: (2, \">H\", TYPE_MAP),\n    0xDF: (4, \">I\", TYPE_MAP),\n}\n\n\nclass Unpacker:\n    \"\"\"Streaming unpacker.\n\n    Arguments:\n\n    :param file_like:\n        File-like object having `.read(n)` method.\n        If specified, unpacker reads serialized data from it and `.feed()` is not usable.\n\n    :param int read_size:\n        Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)\n\n    :param bool use_list:\n        If true, unpack msgpack array to Python list.\n        Otherwise, unpack to Python tuple. (default: True)\n\n    :param bool raw:\n        If true, unpack msgpack raw to Python bytes.\n        Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).\n\n    :param int timestamp:\n        Control how timestamp type is unpacked:\n\n            0 - Timestamp\n            1 - float  (Seconds from the EPOCH)\n            2 - int  (Nanoseconds from the EPOCH)\n            3 - datetime.datetime  (UTC).\n\n    :param bool strict_map_key:\n        If true (default), only str or bytes are accepted for map (dict) keys.\n\n    :param object_hook:\n        When specified, it should be callable.\n        Unpacker calls it with a dict argument after unpacking msgpack map.\n        (See also simplejson)\n\n    :param object_pairs_hook:\n        When specified, it should be callable.\n        Unpacker calls it with a list of key-value pairs after unpacking msgpack map.\n        (See also simplejson)\n\n    :param str unicode_errors:\n        The error handler for decoding unicode. (default: 'strict')\n        This option should be used only when you have msgpack data which\n        contains invalid UTF-8 string.\n\n    :param int max_buffer_size:\n        Limits size of data waiting unpacked.  0 means 2**32-1.\n        The default value is 100*1024*1024 (100MiB).\n        Raises `BufferFull` exception when it is insufficient.\n        You should set this parameter when unpacking data from untrusted source.\n\n    :param int max_str_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max length of str. (default: max_buffer_size)\n\n    :param int max_bin_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max length of bin. (default: max_buffer_size)\n\n    :param int max_array_len:\n        Limits max length of array.\n        (default: max_buffer_size)\n\n    :param int max_map_len:\n        Limits max length of map.\n        (default: max_buffer_size//2)\n\n    :param int max_ext_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max size of ext type.  (default: max_buffer_size)\n\n    Example of streaming deserialize from file-like object::\n\n        unpacker = Unpacker(file_like)\n        for o in unpacker:\n            process(o)\n\n    Example of streaming deserialize from socket::\n\n        unpacker = Unpacker()\n        while True:\n            buf = sock.recv(1024**2)\n            if not buf:\n                break\n            unpacker.feed(buf)\n            for o in unpacker:\n                process(o)\n\n    Raises ``ExtraData`` when *packed* contains extra bytes.\n    Raises ``OutOfData`` when *packed* is incomplete.\n    Raises ``FormatError`` when *packed* is not valid msgpack.\n    Raises ``StackError`` when *packed* contains too nested.\n    Other exceptions can be raised during unpacking.\n    \"\"\"\n\n    def __init__(\n        self,\n        file_like=None,\n        *,\n        read_size=0,\n        use_list=True,\n        raw=False,\n        timestamp=0,\n        strict_map_key=True,\n        object_hook=None,\n        object_pairs_hook=None,\n        list_hook=None,\n        unicode_errors=None,\n        max_buffer_size=100 * 1024 * 1024,\n        ext_hook=ExtType,\n        max_str_len=-1,\n        max_bin_len=-1,\n        max_array_len=-1,\n        max_map_len=-1,\n        max_ext_len=-1,\n    ):\n        if unicode_errors is None:\n            unicode_errors = \"strict\"\n\n        if file_like is None:\n            self._feeding = True\n        else:\n            if not callable(file_like.read):\n                raise TypeError(\"`file_like.read` must be callable\")\n            self.file_like = file_like\n            self._feeding = False\n\n        #: array of bytes fed.\n        self._buffer = bytearray()\n        #: Which position we currently reads\n        self._buff_i = 0\n\n        # When Unpacker is used as an iterable, between the calls to next(),\n        # the buffer is not \"consumed\" completely, for efficiency sake.\n        # Instead, it is done sloppily.  To make sure we raise BufferFull at\n        # the correct moments, we have to keep track of how sloppy we were.\n        # Furthermore, when the buffer is incomplete (that is: in the case\n        # we raise an OutOfData) we need to rollback the buffer to the correct\n        # state, which _buf_checkpoint records.\n        self._buf_checkpoint = 0\n\n        if not max_buffer_size:\n            max_buffer_size = 2**31 - 1\n        if max_str_len == -1:\n            max_str_len = max_buffer_size\n        if max_bin_len == -1:\n            max_bin_len = max_buffer_size\n        if max_array_len == -1:\n            max_array_len = max_buffer_size\n        if max_map_len == -1:\n            max_map_len = max_buffer_size // 2\n        if max_ext_len == -1:\n            max_ext_len = max_buffer_size\n\n        self._max_buffer_size = max_buffer_size\n        if read_size > self._max_buffer_size:\n            raise ValueError(\"read_size must be smaller than max_buffer_size\")\n        self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)\n        self._raw = bool(raw)\n        self._strict_map_key = bool(strict_map_key)\n        self._unicode_errors = unicode_errors\n        self._use_list = use_list\n        if not (0 <= timestamp <= 3):\n            raise ValueError(\"timestamp must be 0..3\")\n        self._timestamp = timestamp\n        self._list_hook = list_hook\n        self._object_hook = object_hook\n        self._object_pairs_hook = object_pairs_hook\n        self._ext_hook = ext_hook\n        self._max_str_len = max_str_len\n        self._max_bin_len = max_bin_len\n        self._max_array_len = max_array_len\n        self._max_map_len = max_map_len\n        self._max_ext_len = max_ext_len\n        self._stream_offset = 0\n\n        if list_hook is not None and not callable(list_hook):\n            raise TypeError(\"`list_hook` is not callable\")\n        if object_hook is not None and not callable(object_hook):\n            raise TypeError(\"`object_hook` is not callable\")\n        if object_pairs_hook is not None and not callable(object_pairs_hook):\n            raise TypeError(\"`object_pairs_hook` is not callable\")\n        if object_hook is not None and object_pairs_hook is not None:\n            raise TypeError(\"object_pairs_hook and object_hook are mutually exclusive\")\n        if not callable(ext_hook):\n            raise TypeError(\"`ext_hook` is not callable\")\n\n    def feed(self, next_bytes):\n        assert self._feeding\n        view = _get_data_from_buffer(next_bytes)\n        if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size:\n            raise BufferFull\n\n        # Strip buffer before checkpoint before reading file.\n        if self._buf_checkpoint > 0:\n            del self._buffer[: self._buf_checkpoint]\n            self._buff_i -= self._buf_checkpoint\n            self._buf_checkpoint = 0\n\n        # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython\n        self._buffer.extend(view)\n        view.release()\n\n    def _consume(self):\n        \"\"\"Gets rid of the used parts of the buffer.\"\"\"\n        self._stream_offset += self._buff_i - self._buf_checkpoint\n        self._buf_checkpoint = self._buff_i\n\n    def _got_extradata(self):\n        return self._buff_i < len(self._buffer)\n\n    def _get_extradata(self):\n        return self._buffer[self._buff_i :]\n\n    def read_bytes(self, n):\n        ret = self._read(n, raise_outofdata=False)\n        self._consume()\n        return ret\n\n    def _read(self, n, raise_outofdata=True):\n        # (int) -> bytearray\n        self._reserve(n, raise_outofdata=raise_outofdata)\n        i = self._buff_i\n        ret = self._buffer[i : i + n]\n        self._buff_i = i + len(ret)\n        return ret\n\n    def _reserve(self, n, raise_outofdata=True):\n        remain_bytes = len(self._buffer) - self._buff_i - n\n\n        # Fast path: buffer has n bytes already\n        if remain_bytes >= 0:\n            return\n\n        if self._feeding:\n            self._buff_i = self._buf_checkpoint\n            raise OutOfData\n\n        # Strip buffer before checkpoint before reading file.\n        if self._buf_checkpoint > 0:\n            del self._buffer[: self._buf_checkpoint]\n            self._buff_i -= self._buf_checkpoint\n            self._buf_checkpoint = 0\n\n        # Read from file\n        remain_bytes = -remain_bytes\n        if remain_bytes + len(self._buffer) > self._max_buffer_size:\n            raise BufferFull\n        while remain_bytes > 0:\n            to_read_bytes = max(self._read_size, remain_bytes)\n            read_data = self.file_like.read(to_read_bytes)\n            if not read_data:\n                break\n            assert isinstance(read_data, bytes)\n            self._buffer += read_data\n            remain_bytes -= len(read_data)\n\n        if len(self._buffer) < n + self._buff_i and raise_outofdata:\n            self._buff_i = 0  # rollback\n            raise OutOfData\n\n    def _read_header(self):\n        typ = TYPE_IMMEDIATE\n        n = 0\n        obj = None\n        self._reserve(1)\n        b = self._buffer[self._buff_i]\n        self._buff_i += 1\n        if b & 0b10000000 == 0:\n            obj = b\n        elif b & 0b11100000 == 0b11100000:\n            obj = -1 - (b ^ 0xFF)\n        elif b & 0b11100000 == 0b10100000:\n            n = b & 0b00011111\n            typ = TYPE_RAW\n            if n > self._max_str_len:\n                raise ValueError(f\"{n} exceeds max_str_len({self._max_str_len})\")\n            obj = self._read(n)\n        elif b & 0b11110000 == 0b10010000:\n            n = b & 0b00001111\n            typ = TYPE_ARRAY\n            if n > self._max_array_len:\n                raise ValueError(f\"{n} exceeds max_array_len({self._max_array_len})\")\n        elif b & 0b11110000 == 0b10000000:\n            n = b & 0b00001111\n            typ = TYPE_MAP\n            if n > self._max_map_len:\n                raise ValueError(f\"{n} exceeds max_map_len({self._max_map_len})\")\n        elif b == 0xC0:\n            obj = None\n        elif b == 0xC2:\n            obj = False\n        elif b == 0xC3:\n            obj = True\n        elif 0xC4 <= b <= 0xC6:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                n = struct.unpack_from(fmt, self._buffer, self._buff_i)[0]\n            else:\n                n = self._buffer[self._buff_i]\n            self._buff_i += size\n            if n > self._max_bin_len:\n                raise ValueError(f\"{n} exceeds max_bin_len({self._max_bin_len})\")\n            obj = self._read(n)\n        elif 0xC7 <= b <= 0xC9:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            L, n = struct.unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if L > self._max_ext_len:\n                raise ValueError(f\"{L} exceeds max_ext_len({self._max_ext_len})\")\n            obj = self._read(L)\n        elif 0xCA <= b <= 0xD3:\n            size, fmt = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                obj = struct.unpack_from(fmt, self._buffer, self._buff_i)[0]\n            else:\n                obj = self._buffer[self._buff_i]\n            self._buff_i += size\n        elif 0xD4 <= b <= 0xD8:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            if self._max_ext_len < size:\n                raise ValueError(f\"{size} exceeds max_ext_len({self._max_ext_len})\")\n            self._reserve(size + 1)\n            n, obj = struct.unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size + 1\n        elif 0xD9 <= b <= 0xDB:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)\n            else:\n                n = self._buffer[self._buff_i]\n            self._buff_i += size\n            if n > self._max_str_len:\n                raise ValueError(f\"{n} exceeds max_str_len({self._max_str_len})\")\n            obj = self._read(n)\n        elif 0xDC <= b <= 0xDD:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if n > self._max_array_len:\n                raise ValueError(f\"{n} exceeds max_array_len({self._max_array_len})\")\n        elif 0xDE <= b <= 0xDF:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if n > self._max_map_len:\n                raise ValueError(f\"{n} exceeds max_map_len({self._max_map_len})\")\n        else:\n            raise FormatError(\"Unknown header: 0x%x\" % b)\n        return typ, n, obj\n\n    def _unpack(self, execute=EX_CONSTRUCT):\n        typ, n, obj = self._read_header()\n\n        if execute == EX_READ_ARRAY_HEADER:\n            if typ != TYPE_ARRAY:\n                raise ValueError(\"Expected array\")\n            return n\n        if execute == EX_READ_MAP_HEADER:\n            if typ != TYPE_MAP:\n                raise ValueError(\"Expected map\")\n            return n\n        # TODO should we eliminate the recursion?\n        if typ == TYPE_ARRAY:\n            if execute == EX_SKIP:\n                for i in range(n):\n                    # TODO check whether we need to call `list_hook`\n                    self._unpack(EX_SKIP)\n                return\n            ret = newlist_hint(n)\n            for i in range(n):\n                ret.append(self._unpack(EX_CONSTRUCT))\n            if self._list_hook is not None:\n                ret = self._list_hook(ret)\n            # TODO is the interaction between `list_hook` and `use_list` ok?\n            return ret if self._use_list else tuple(ret)\n        if typ == TYPE_MAP:\n            if execute == EX_SKIP:\n                for i in range(n):\n                    # TODO check whether we need to call hooks\n                    self._unpack(EX_SKIP)\n                    self._unpack(EX_SKIP)\n                return\n            if self._object_pairs_hook is not None:\n                ret = self._object_pairs_hook(\n                    (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT)) for _ in range(n)\n                )\n            else:\n                ret = {}\n                for _ in range(n):\n                    key = self._unpack(EX_CONSTRUCT)\n                    if self._strict_map_key and type(key) not in (str, bytes):\n                        raise ValueError(\"%s is not allowed for map key\" % str(type(key)))\n                    if isinstance(key, str):\n                        key = sys.intern(key)\n                    ret[key] = self._unpack(EX_CONSTRUCT)\n                if self._object_hook is not None:\n                    ret = self._object_hook(ret)\n            return ret\n        if execute == EX_SKIP:\n            return\n        if typ == TYPE_RAW:\n            if self._raw:\n                obj = bytes(obj)\n            else:\n                obj = obj.decode(\"utf_8\", self._unicode_errors)\n            return obj\n        if typ == TYPE_BIN:\n            return bytes(obj)\n        if typ == TYPE_EXT:\n            if n == -1:  # timestamp\n                ts = Timestamp.from_bytes(bytes(obj))\n                if self._timestamp == 1:\n                    return ts.to_unix()\n                elif self._timestamp == 2:\n                    return ts.to_unix_nano()\n                elif self._timestamp == 3:\n                    return ts.to_datetime()\n                else:\n                    return ts\n            else:\n                return self._ext_hook(n, bytes(obj))\n        assert typ == TYPE_IMMEDIATE\n        return obj\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        try:\n            ret = self._unpack(EX_CONSTRUCT)\n            self._consume()\n            return ret\n        except OutOfData:\n            self._consume()\n            raise StopIteration\n        except RecursionError:\n            raise StackError\n\n    next = __next__\n\n    def skip(self):\n        self._unpack(EX_SKIP)\n        self._consume()\n\n    def unpack(self):\n        try:\n            ret = self._unpack(EX_CONSTRUCT)\n        except RecursionError:\n            raise StackError\n        self._consume()\n        return ret\n\n    def read_array_header(self):\n        ret = self._unpack(EX_READ_ARRAY_HEADER)\n        self._consume()\n        return ret\n\n    def read_map_header(self):\n        ret = self._unpack(EX_READ_MAP_HEADER)\n        self._consume()\n        return ret\n\n    def tell(self):\n        return self._stream_offset\n\n\nclass Packer:\n    \"\"\"\n    MessagePack Packer\n\n    Usage::\n\n        packer = Packer()\n        astream.write(packer.pack(a))\n        astream.write(packer.pack(b))\n\n    Packer's constructor has some keyword arguments:\n\n    :param default:\n        When specified, it should be callable.\n        Convert user type to builtin type that Packer supports.\n        See also simplejson's document.\n\n    :param bool use_single_float:\n        Use single precision float type for float. (default: False)\n\n    :param bool autoreset:\n        Reset buffer after each pack and return its content as `bytes`. (default: True).\n        If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.\n\n    :param bool use_bin_type:\n        Use bin type introduced in msgpack spec 2.0 for bytes.\n        It also enables str8 type for unicode. (default: True)\n\n    :param bool strict_types:\n        If set to true, types will be checked to be exact. Derived classes\n        from serializable types will not be serialized and will be\n        treated as unsupported type and forwarded to default.\n        Additionally tuples will not be serialized as lists.\n        This is useful when trying to implement accurate serialization\n        for python types.\n\n    :param bool datetime:\n        If set to true, datetime with tzinfo is packed into Timestamp type.\n        Note that the tzinfo is stripped in the timestamp.\n        You can get UTC datetime with `timestamp=3` option of the Unpacker.\n\n    :param str unicode_errors:\n        The error handler for encoding unicode. (default: 'strict')\n        DO NOT USE THIS!!  This option is kept for very specific usage.\n\n    :param int buf_size:\n        Internal buffer size. This option is used only for C implementation.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        default=None,\n        use_single_float=False,\n        autoreset=True,\n        use_bin_type=True,\n        strict_types=False,\n        datetime=False,\n        unicode_errors=None,\n        buf_size=None,\n    ):\n        self._strict_types = strict_types\n        self._use_float = use_single_float\n        self._autoreset = autoreset\n        self._use_bin_type = use_bin_type\n        self._buffer = BytesIO()\n        self._datetime = bool(datetime)\n        self._unicode_errors = unicode_errors or \"strict\"\n        if default is not None and not callable(default):\n            raise TypeError(\"default must be callable\")\n        self._default = default\n\n    def _pack(\n        self,\n        obj,\n        nest_limit=DEFAULT_RECURSE_LIMIT,\n        check=isinstance,\n        check_type_strict=_check_type_strict,\n    ):\n        default_used = False\n        if self._strict_types:\n            check = check_type_strict\n            list_types = list\n        else:\n            list_types = (list, tuple)\n        while True:\n            if nest_limit < 0:\n                raise ValueError(\"recursion limit exceeded\")\n            if obj is None:\n                return self._buffer.write(b\"\\xc0\")\n            if check(obj, bool):\n                if obj:\n                    return self._buffer.write(b\"\\xc3\")\n                return self._buffer.write(b\"\\xc2\")\n            if check(obj, int):\n                if 0 <= obj < 0x80:\n                    return self._buffer.write(struct.pack(\"B\", obj))\n                if -0x20 <= obj < 0:\n                    return self._buffer.write(struct.pack(\"b\", obj))\n                if 0x80 <= obj <= 0xFF:\n                    return self._buffer.write(struct.pack(\"BB\", 0xCC, obj))\n                if -0x80 <= obj < 0:\n                    return self._buffer.write(struct.pack(\">Bb\", 0xD0, obj))\n                if 0xFF < obj <= 0xFFFF:\n                    return self._buffer.write(struct.pack(\">BH\", 0xCD, obj))\n                if -0x8000 <= obj < -0x80:\n                    return self._buffer.write(struct.pack(\">Bh\", 0xD1, obj))\n                if 0xFFFF < obj <= 0xFFFFFFFF:\n                    return self._buffer.write(struct.pack(\">BI\", 0xCE, obj))\n                if -0x80000000 <= obj < -0x8000:\n                    return self._buffer.write(struct.pack(\">Bi\", 0xD2, obj))\n                if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:\n                    return self._buffer.write(struct.pack(\">BQ\", 0xCF, obj))\n                if -0x8000000000000000 <= obj < -0x80000000:\n                    return self._buffer.write(struct.pack(\">Bq\", 0xD3, obj))\n                if not default_used and self._default is not None:\n                    obj = self._default(obj)\n                    default_used = True\n                    continue\n                raise OverflowError(\"Integer value out of range\")\n            if check(obj, (bytes, bytearray)):\n                n = len(obj)\n                if n >= 2**32:\n                    raise ValueError(\"%s is too large\" % type(obj).__name__)\n                self._pack_bin_header(n)\n                return self._buffer.write(obj)\n            if check(obj, str):\n                obj = obj.encode(\"utf-8\", self._unicode_errors)\n                n = len(obj)\n                if n >= 2**32:\n                    raise ValueError(\"String is too large\")\n                self._pack_raw_header(n)\n                return self._buffer.write(obj)\n            if check(obj, memoryview):\n                n = obj.nbytes\n                if n >= 2**32:\n                    raise ValueError(\"Memoryview is too large\")\n                self._pack_bin_header(n)\n                return self._buffer.write(obj)\n            if check(obj, float):\n                if self._use_float:\n                    return self._buffer.write(struct.pack(\">Bf\", 0xCA, obj))\n                return self._buffer.write(struct.pack(\">Bd\", 0xCB, obj))\n            if check(obj, (ExtType, Timestamp)):\n                if check(obj, Timestamp):\n                    code = -1\n                    data = obj.to_bytes()\n                else:\n                    code = obj.code\n                    data = obj.data\n                assert isinstance(code, int)\n                assert isinstance(data, bytes)\n                L = len(data)\n                if L == 1:\n                    self._buffer.write(b\"\\xd4\")\n                elif L == 2:\n                    self._buffer.write(b\"\\xd5\")\n                elif L == 4:\n                    self._buffer.write(b\"\\xd6\")\n                elif L == 8:\n                    self._buffer.write(b\"\\xd7\")\n                elif L == 16:\n                    self._buffer.write(b\"\\xd8\")\n                elif L <= 0xFF:\n                    self._buffer.write(struct.pack(\">BB\", 0xC7, L))\n                elif L <= 0xFFFF:\n                    self._buffer.write(struct.pack(\">BH\", 0xC8, L))\n                else:\n                    self._buffer.write(struct.pack(\">BI\", 0xC9, L))\n                self._buffer.write(struct.pack(\"b\", code))\n                self._buffer.write(data)\n                return\n            if check(obj, list_types):\n                n = len(obj)\n                self._pack_array_header(n)\n                for i in range(n):\n                    self._pack(obj[i], nest_limit - 1)\n                return\n            if check(obj, dict):\n                return self._pack_map_pairs(len(obj), obj.items(), nest_limit - 1)\n\n            if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None:\n                obj = Timestamp.from_datetime(obj)\n                default_used = 1\n                continue\n\n            if not default_used and self._default is not None:\n                obj = self._default(obj)\n                default_used = 1\n                continue\n\n            if self._datetime and check(obj, _DateTime):\n                raise ValueError(f\"Cannot serialize {obj!r} where tzinfo=None\")\n\n            raise TypeError(f\"Cannot serialize {obj!r}\")\n\n    def pack(self, obj):\n        try:\n            self._pack(obj)\n        except:\n            self._buffer = BytesIO()  # force reset\n            raise\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = BytesIO()\n            return ret\n\n    def pack_map_pairs(self, pairs):\n        self._pack_map_pairs(len(pairs), pairs)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = BytesIO()\n            return ret\n\n    def pack_array_header(self, n):\n        if n >= 2**32:\n            raise ValueError\n        self._pack_array_header(n)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = BytesIO()\n            return ret\n\n    def pack_map_header(self, n):\n        if n >= 2**32:\n            raise ValueError\n        self._pack_map_header(n)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = BytesIO()\n            return ret\n\n    def pack_ext_type(self, typecode, data):\n        if not isinstance(typecode, int):\n            raise TypeError(\"typecode must have int type.\")\n        if not 0 <= typecode <= 127:\n            raise ValueError(\"typecode should be 0-127\")\n        if not isinstance(data, bytes):\n            raise TypeError(\"data must have bytes type\")\n        L = len(data)\n        if L > 0xFFFFFFFF:\n            raise ValueError(\"Too large data\")\n        if L == 1:\n            self._buffer.write(b\"\\xd4\")\n        elif L == 2:\n            self._buffer.write(b\"\\xd5\")\n        elif L == 4:\n            self._buffer.write(b\"\\xd6\")\n        elif L == 8:\n            self._buffer.write(b\"\\xd7\")\n        elif L == 16:\n            self._buffer.write(b\"\\xd8\")\n        elif L <= 0xFF:\n            self._buffer.write(b\"\\xc7\" + struct.pack(\"B\", L))\n        elif L <= 0xFFFF:\n            self._buffer.write(b\"\\xc8\" + struct.pack(\">H\", L))\n        else:\n            self._buffer.write(b\"\\xc9\" + struct.pack(\">I\", L))\n        self._buffer.write(struct.pack(\"B\", typecode))\n        self._buffer.write(data)\n\n    def _pack_array_header(self, n):\n        if n <= 0x0F:\n            return self._buffer.write(struct.pack(\"B\", 0x90 + n))\n        if n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xDC, n))\n        if n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xDD, n))\n        raise ValueError(\"Array is too large\")\n\n    def _pack_map_header(self, n):\n        if n <= 0x0F:\n            return self._buffer.write(struct.pack(\"B\", 0x80 + n))\n        if n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xDE, n))\n        if n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xDF, n))\n        raise ValueError(\"Dict is too large\")\n\n    def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):\n        self._pack_map_header(n)\n        for k, v in pairs:\n            self._pack(k, nest_limit - 1)\n            self._pack(v, nest_limit - 1)\n\n    def _pack_raw_header(self, n):\n        if n <= 0x1F:\n            self._buffer.write(struct.pack(\"B\", 0xA0 + n))\n        elif self._use_bin_type and n <= 0xFF:\n            self._buffer.write(struct.pack(\">BB\", 0xD9, n))\n        elif n <= 0xFFFF:\n            self._buffer.write(struct.pack(\">BH\", 0xDA, n))\n        elif n <= 0xFFFFFFFF:\n            self._buffer.write(struct.pack(\">BI\", 0xDB, n))\n        else:\n            raise ValueError(\"Raw is too large\")\n\n    def _pack_bin_header(self, n):\n        if not self._use_bin_type:\n            return self._pack_raw_header(n)\n        elif n <= 0xFF:\n            return self._buffer.write(struct.pack(\">BB\", 0xC4, n))\n        elif n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xC5, n))\n        elif n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xC6, n))\n        else:\n            raise ValueError(\"Bin is too large\")\n\n    def bytes(self):\n        \"\"\"Return internal buffer contents as bytes object\"\"\"\n        return self._buffer.getvalue()\n\n    def reset(self):\n        \"\"\"Reset internal buffer.\n\n        This method is useful only when autoreset=False.\n        \"\"\"\n        self._buffer = BytesIO()\n\n    def getbuffer(self):\n        \"\"\"Return view of internal buffer.\"\"\"\n        if _USING_STRINGBUILDER:\n            return memoryview(self.bytes())\n        else:\n            return self._buffer.getbuffer()\n"
  },
  {
    "path": "src/pip/_vendor/msgpack.pyi",
    "content": "from msgpack import *"
  },
  {
    "path": "src/pip/_vendor/packaging/LICENSE",
    "content": "This software is made available under the terms of *either* of the licenses\nfound in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made\nunder the terms of *both* these licenses.\n"
  },
  {
    "path": "src/pip/_vendor/packaging/LICENSE.APACHE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "src/pip/_vendor/packaging/LICENSE.BSD",
    "content": "Copyright (c) Donald Stufft and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright\n       notice, this list of conditions and the following disclaimer in the\n       documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "src/pip/_vendor/packaging/__init__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n__title__ = \"packaging\"\n__summary__ = \"Core utilities for Python packages\"\n__uri__ = \"https://github.com/pypa/packaging\"\n\n__version__ = \"26.0\"\n\n__author__ = \"Donald Stufft and individual contributors\"\n__email__ = \"donald@stufft.io\"\n\n__license__ = \"BSD-2-Clause or Apache-2.0\"\n__copyright__ = f\"2014 {__author__}\"\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_elffile.py",
    "content": "\"\"\"\nELF file parser.\n\nThis provides a class ``ELFFile`` that parses an ELF executable in a similar\ninterface to ``ZipFile``. Only the read interface is implemented.\n\nELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html\n\"\"\"\n\nfrom __future__ import annotations\n\nimport enum\nimport os\nimport struct\nfrom typing import IO\n\n\nclass ELFInvalid(ValueError):\n    pass\n\n\nclass EIClass(enum.IntEnum):\n    C32 = 1\n    C64 = 2\n\n\nclass EIData(enum.IntEnum):\n    Lsb = 1\n    Msb = 2\n\n\nclass EMachine(enum.IntEnum):\n    I386 = 3\n    S390 = 22\n    Arm = 40\n    X8664 = 62\n    AArc64 = 183\n\n\nclass ELFFile:\n    \"\"\"\n    Representation of an ELF executable.\n    \"\"\"\n\n    def __init__(self, f: IO[bytes]) -> None:\n        self._f = f\n\n        try:\n            ident = self._read(\"16B\")\n        except struct.error as e:\n            raise ELFInvalid(\"unable to parse identification\") from e\n        magic = bytes(ident[:4])\n        if magic != b\"\\x7fELF\":\n            raise ELFInvalid(f\"invalid magic: {magic!r}\")\n\n        self.capacity = ident[4]  # Format for program header (bitness).\n        self.encoding = ident[5]  # Data structure encoding (endianness).\n\n        try:\n            # e_fmt: Format for program header.\n            # p_fmt: Format for section header.\n            # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n            e_fmt, self._p_fmt, self._p_idx = {\n                (1, 1): (\"<HHIIIIIHHH\", \"<IIIIIIII\", (0, 1, 4)),  # 32-bit LSB.\n                (1, 2): (\">HHIIIIIHHH\", \">IIIIIIII\", (0, 1, 4)),  # 32-bit MSB.\n                (2, 1): (\"<HHIQQQIHHH\", \"<IIQQQQQQ\", (0, 2, 5)),  # 64-bit LSB.\n                (2, 2): (\">HHIQQQIHHH\", \">IIQQQQQQ\", (0, 2, 5)),  # 64-bit MSB.\n            }[(self.capacity, self.encoding)]\n        except KeyError as e:\n            raise ELFInvalid(\n                f\"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})\"\n            ) from e\n\n        try:\n            (\n                _,\n                self.machine,  # Architecture type.\n                _,\n                _,\n                self._e_phoff,  # Offset of program header.\n                _,\n                self.flags,  # Processor-specific flags.\n                _,\n                self._e_phentsize,  # Size of section.\n                self._e_phnum,  # Number of sections.\n            ) = self._read(e_fmt)\n        except struct.error as e:\n            raise ELFInvalid(\"unable to parse machine and section information\") from e\n\n    def _read(self, fmt: str) -> tuple[int, ...]:\n        return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))\n\n    @property\n    def interpreter(self) -> str | None:\n        \"\"\"\n        The path recorded in the ``PT_INTERP`` section header.\n        \"\"\"\n        for index in range(self._e_phnum):\n            self._f.seek(self._e_phoff + self._e_phentsize * index)\n            try:\n                data = self._read(self._p_fmt)\n            except struct.error:\n                continue\n            if data[self._p_idx[0]] != 3:  # Not PT_INTERP.\n                continue\n            self._f.seek(data[self._p_idx[1]])\n            return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip(\"\\0\")\n        return None\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_manylinux.py",
    "content": "from __future__ import annotations\n\nimport collections\nimport contextlib\nimport functools\nimport os\nimport re\nimport sys\nimport warnings\nfrom typing import Generator, Iterator, NamedTuple, Sequence\n\nfrom ._elffile import EIClass, EIData, ELFFile, EMachine\n\nEF_ARM_ABIMASK = 0xFF000000\nEF_ARM_ABI_VER5 = 0x05000000\nEF_ARM_ABI_FLOAT_HARD = 0x00000400\n\n_ALLOWED_ARCHS = {\n    \"x86_64\",\n    \"aarch64\",\n    \"ppc64\",\n    \"ppc64le\",\n    \"s390x\",\n    \"loongarch64\",\n    \"riscv64\",\n}\n\n\n# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`\n# as the type for `path` until then.\n@contextlib.contextmanager\ndef _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:\n    try:\n        with open(path, \"rb\") as f:\n            yield ELFFile(f)\n    except (OSError, TypeError, ValueError):\n        yield None\n\n\ndef _is_linux_armhf(executable: str) -> bool:\n    # hard-float ABI can be detected from the ELF header of the running\n    # process\n    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf\n    with _parse_elf(executable) as f:\n        return (\n            f is not None\n            and f.capacity == EIClass.C32\n            and f.encoding == EIData.Lsb\n            and f.machine == EMachine.Arm\n            and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5\n            and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD\n        )\n\n\ndef _is_linux_i686(executable: str) -> bool:\n    with _parse_elf(executable) as f:\n        return (\n            f is not None\n            and f.capacity == EIClass.C32\n            and f.encoding == EIData.Lsb\n            and f.machine == EMachine.I386\n        )\n\n\ndef _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:\n    if \"armv7l\" in archs:\n        return _is_linux_armhf(executable)\n    if \"i686\" in archs:\n        return _is_linux_i686(executable)\n    return any(arch in _ALLOWED_ARCHS for arch in archs)\n\n\n# If glibc ever changes its major version, we need to know what the last\n# minor version was, so we can build the complete list of all versions.\n# For now, guess what the highest minor version might be, assume it will\n# be 50 for testing. Once this actually happens, update the dictionary\n# with the actual value.\n_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)\n\n\nclass _GLibCVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _glibc_version_string_confstr() -> str | None:\n    \"\"\"\n    Primary implementation of glibc_version_string using os.confstr.\n    \"\"\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module.\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183\n    try:\n        # Should be a string like \"glibc 2.17\".\n        version_string: str | None = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        assert version_string is not None\n        _, version = version_string.rsplit()\n    except (AssertionError, AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef _glibc_version_string_ctypes() -> str | None:\n    \"\"\"\n    Fallback implementation of glibc_version_string using ctypes.\n    \"\"\"\n    try:\n        import ctypes  # noqa: PLC0415\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\ndef _glibc_version_string() -> str | None:\n    \"\"\"Returns glibc version string, or None if not using glibc.\"\"\"\n    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()\n\n\ndef _parse_glibc_version(version_str: str) -> _GLibCVersion:\n    \"\"\"Parse glibc version.\n\n    We use a regexp instead of str.split because we want to discard any\n    random junk that might come after the minor version -- this might happen\n    in patched/forked versions of glibc (e.g. Linaro's version of glibc\n    uses version strings like \"2.20-2014.11\"). See gh-3588.\n    \"\"\"\n    m = re.match(r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\", version_str)\n    if not m:\n        warnings.warn(\n            f\"Expected glibc version with 2 components major.minor, got: {version_str}\",\n            RuntimeWarning,\n            stacklevel=2,\n        )\n        return _GLibCVersion(-1, -1)\n    return _GLibCVersion(int(m.group(\"major\")), int(m.group(\"minor\")))\n\n\n@functools.lru_cache\ndef _get_glibc_version() -> _GLibCVersion:\n    version_str = _glibc_version_string()\n    if version_str is None:\n        return _GLibCVersion(-1, -1)\n    return _parse_glibc_version(version_str)\n\n\n# From PEP 513, PEP 600\ndef _is_compatible(arch: str, version: _GLibCVersion) -> bool:\n    sys_glibc = _get_glibc_version()\n    if sys_glibc < version:\n        return False\n    # Check for presence of _manylinux module.\n    try:\n        import _manylinux  # noqa: PLC0415\n    except ImportError:\n        return True\n    if hasattr(_manylinux, \"manylinux_compatible\"):\n        result = _manylinux.manylinux_compatible(version[0], version[1], arch)\n        if result is not None:\n            return bool(result)\n        return True\n    if version == _GLibCVersion(2, 5) and hasattr(_manylinux, \"manylinux1_compatible\"):\n        return bool(_manylinux.manylinux1_compatible)\n    if version == _GLibCVersion(2, 12) and hasattr(\n        _manylinux, \"manylinux2010_compatible\"\n    ):\n        return bool(_manylinux.manylinux2010_compatible)\n    if version == _GLibCVersion(2, 17) and hasattr(\n        _manylinux, \"manylinux2014_compatible\"\n    ):\n        return bool(_manylinux.manylinux2014_compatible)\n    return True\n\n\n_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {\n    # CentOS 7 w/ glibc 2.17 (PEP 599)\n    _GLibCVersion(2, 17): \"manylinux2014\",\n    # CentOS 6 w/ glibc 2.12 (PEP 571)\n    _GLibCVersion(2, 12): \"manylinux2010\",\n    # CentOS 5 w/ glibc 2.5 (PEP 513)\n    _GLibCVersion(2, 5): \"manylinux1\",\n}\n\n\ndef platform_tags(archs: Sequence[str]) -> Iterator[str]:\n    \"\"\"Generate manylinux tags compatible to the current platform.\n\n    :param archs: Sequence of compatible architectures.\n        The first one shall be the closest to the actual architecture and be the part of\n        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.\n        The ``linux_`` prefix is assumed as a prerequisite for the current platform to\n        be manylinux-compatible.\n\n    :returns: An iterator of compatible manylinux tags.\n    \"\"\"\n    if not _have_compatible_abi(sys.executable, archs):\n        return\n    # Oldest glibc to be supported regardless of architecture is (2, 17).\n    too_old_glibc2 = _GLibCVersion(2, 16)\n    if set(archs) & {\"x86_64\", \"i686\"}:\n        # On x86/i686 also oldest glibc to be supported is (2, 5).\n        too_old_glibc2 = _GLibCVersion(2, 4)\n    current_glibc = _GLibCVersion(*_get_glibc_version())\n    glibc_max_list = [current_glibc]\n    # We can assume compatibility across glibc major versions.\n    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n    #\n    # Build a list of maximum glibc versions so that we can\n    # output the canonical list of all glibc from current_glibc\n    # down to too_old_glibc2, including all intermediary versions.\n    for glibc_major in range(current_glibc.major - 1, 1, -1):\n        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n    for arch in archs:\n        for glibc_max in glibc_max_list:\n            if glibc_max.major == too_old_glibc2.major:\n                min_minor = too_old_glibc2.minor\n            else:\n                # For other glibc major versions oldest supported is (x, 0).\n                min_minor = -1\n            for glibc_minor in range(glibc_max.minor, min_minor, -1):\n                glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n                if _is_compatible(arch, glibc_version):\n                    yield \"manylinux_{}_{}_{}\".format(*glibc_version, arch)\n\n                    # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n                    if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):\n                        yield f\"{legacy_tag}_{arch}\"\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_musllinux.py",
    "content": "\"\"\"PEP 656 support.\n\nThis module implements logic to detect if the currently running Python is\nlinked against musl, and what musl version is used.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\nimport re\nimport subprocess\nimport sys\nfrom typing import Iterator, NamedTuple, Sequence\n\nfrom ._elffile import ELFFile\n\n\nclass _MuslVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _parse_musl_version(output: str) -> _MuslVersion | None:\n    lines = [n for n in (n.strip() for n in output.splitlines()) if n]\n    if len(lines) < 2 or lines[0][:4] != \"musl\":\n        return None\n    m = re.match(r\"Version (\\d+)\\.(\\d+)\", lines[1])\n    if not m:\n        return None\n    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))\n\n\n@functools.lru_cache\ndef _get_musl_version(executable: str) -> _MuslVersion | None:\n    \"\"\"Detect currently-running musl runtime version.\n\n    This is done by checking the specified executable's dynamic linking\n    information, and invoking the loader to parse its output for a version\n    string. If the loader is musl, the output would be something like::\n\n        musl libc (x86_64)\n        Version 1.2.2\n        Dynamic Program Loader\n    \"\"\"\n    try:\n        with open(executable, \"rb\") as f:\n            ld = ELFFile(f).interpreter\n    except (OSError, TypeError, ValueError):\n        return None\n    if ld is None or \"musl\" not in ld:\n        return None\n    proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)\n    return _parse_musl_version(proc.stderr)\n\n\ndef platform_tags(archs: Sequence[str]) -> Iterator[str]:\n    \"\"\"Generate musllinux tags compatible to the current platform.\n\n    :param archs: Sequence of compatible architectures.\n        The first one shall be the closest to the actual architecture and be the part of\n        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.\n        The ``linux_`` prefix is assumed as a prerequisite for the current platform to\n        be musllinux-compatible.\n\n    :returns: An iterator of compatible musllinux tags.\n    \"\"\"\n    sys_musl = _get_musl_version(sys.executable)\n    if sys_musl is None:  # Python not dynamically linked against musl.\n        return\n    for arch in archs:\n        for minor in range(sys_musl.minor, -1, -1):\n            yield f\"musllinux_{sys_musl.major}_{minor}_{arch}\"\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sysconfig\n\n    plat = sysconfig.get_platform()\n    assert plat.startswith(\"linux-\"), \"not linux\"\n\n    print(\"plat:\", plat)\n    print(\"musl:\", _get_musl_version(sys.executable))\n    print(\"tags:\", end=\" \")\n    for t in platform_tags(re.sub(r\"[.-]\", \"_\", plat.split(\"-\", 1)[-1])):\n        print(t, end=\"\\n      \")\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_parser.py",
    "content": "\"\"\"Handwritten parser of dependency specifiers.\n\nThe docstring for each __parse_* function contains EBNF-inspired grammar representing\nthe implementation.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nfrom typing import List, Literal, NamedTuple, Sequence, Tuple, Union\n\nfrom ._tokenizer import DEFAULT_RULES, Tokenizer\n\n\nclass Node:\n    __slots__ = (\"value\",)\n\n    def __init__(self, value: str) -> None:\n        self.value = value\n\n    def __str__(self) -> str:\n        return self.value\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}({self.value!r})>\"\n\n    def serialize(self) -> str:\n        raise NotImplementedError\n\n\nclass Variable(Node):\n    __slots__ = ()\n\n    def serialize(self) -> str:\n        return str(self)\n\n\nclass Value(Node):\n    __slots__ = ()\n\n    def serialize(self) -> str:\n        return f'\"{self}\"'\n\n\nclass Op(Node):\n    __slots__ = ()\n\n    def serialize(self) -> str:\n        return str(self)\n\n\nMarkerLogical = Literal[\"and\", \"or\"]\nMarkerVar = Union[Variable, Value]\nMarkerItem = Tuple[MarkerVar, Op, MarkerVar]\nMarkerAtom = Union[MarkerItem, Sequence[\"MarkerAtom\"]]\nMarkerList = List[Union[\"MarkerList\", MarkerAtom, MarkerLogical]]\n\n\nclass ParsedRequirement(NamedTuple):\n    name: str\n    url: str\n    extras: list[str]\n    specifier: str\n    marker: MarkerList | None\n\n\n# --------------------------------------------------------------------------------------\n# Recursive descent parser for dependency specifier\n# --------------------------------------------------------------------------------------\ndef parse_requirement(source: str) -> ParsedRequirement:\n    return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))\n\n\ndef _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:\n    \"\"\"\n    requirement = WS? IDENTIFIER WS? extras WS? requirement_details\n    \"\"\"\n    tokenizer.consume(\"WS\")\n\n    name_token = tokenizer.expect(\n        \"IDENTIFIER\", expected=\"package name at the start of dependency specifier\"\n    )\n    name = name_token.text\n    tokenizer.consume(\"WS\")\n\n    extras = _parse_extras(tokenizer)\n    tokenizer.consume(\"WS\")\n\n    url, specifier, marker = _parse_requirement_details(tokenizer)\n    tokenizer.expect(\"END\", expected=\"end of dependency specifier\")\n\n    return ParsedRequirement(name, url, extras, specifier, marker)\n\n\ndef _parse_requirement_details(\n    tokenizer: Tokenizer,\n) -> tuple[str, str, MarkerList | None]:\n    \"\"\"\n    requirement_details = AT URL (WS requirement_marker?)?\n                        | specifier WS? (requirement_marker)?\n    \"\"\"\n\n    specifier = \"\"\n    url = \"\"\n    marker = None\n\n    if tokenizer.check(\"AT\"):\n        tokenizer.read()\n        tokenizer.consume(\"WS\")\n\n        url_start = tokenizer.position\n        url = tokenizer.expect(\"URL\", expected=\"URL after @\").text\n        if tokenizer.check(\"END\", peek=True):\n            return (url, specifier, marker)\n\n        tokenizer.expect(\"WS\", expected=\"whitespace after URL\")\n\n        # The input might end after whitespace.\n        if tokenizer.check(\"END\", peek=True):\n            return (url, specifier, marker)\n\n        marker = _parse_requirement_marker(\n            tokenizer,\n            span_start=url_start,\n            expected=\"semicolon (after URL and whitespace)\",\n        )\n    else:\n        specifier_start = tokenizer.position\n        specifier = _parse_specifier(tokenizer)\n        tokenizer.consume(\"WS\")\n\n        if tokenizer.check(\"END\", peek=True):\n            return (url, specifier, marker)\n\n        marker = _parse_requirement_marker(\n            tokenizer,\n            span_start=specifier_start,\n            expected=(\n                \"comma (within version specifier), semicolon (after version specifier)\"\n                if specifier\n                else \"semicolon (after name with no version specifier)\"\n            ),\n        )\n\n    return (url, specifier, marker)\n\n\ndef _parse_requirement_marker(\n    tokenizer: Tokenizer, *, span_start: int, expected: str\n) -> MarkerList:\n    \"\"\"\n    requirement_marker = SEMICOLON marker WS?\n    \"\"\"\n\n    if not tokenizer.check(\"SEMICOLON\"):\n        tokenizer.raise_syntax_error(\n            f\"Expected {expected} or end\",\n            span_start=span_start,\n            span_end=None,\n        )\n    tokenizer.read()\n\n    marker = _parse_marker(tokenizer)\n    tokenizer.consume(\"WS\")\n\n    return marker\n\n\ndef _parse_extras(tokenizer: Tokenizer) -> list[str]:\n    \"\"\"\n    extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?\n    \"\"\"\n    if not tokenizer.check(\"LEFT_BRACKET\", peek=True):\n        return []\n\n    with tokenizer.enclosing_tokens(\n        \"LEFT_BRACKET\",\n        \"RIGHT_BRACKET\",\n        around=\"extras\",\n    ):\n        tokenizer.consume(\"WS\")\n        extras = _parse_extras_list(tokenizer)\n        tokenizer.consume(\"WS\")\n\n    return extras\n\n\ndef _parse_extras_list(tokenizer: Tokenizer) -> list[str]:\n    \"\"\"\n    extras_list = identifier (wsp* ',' wsp* identifier)*\n    \"\"\"\n    extras: list[str] = []\n\n    if not tokenizer.check(\"IDENTIFIER\"):\n        return extras\n\n    extras.append(tokenizer.read().text)\n\n    while True:\n        tokenizer.consume(\"WS\")\n        if tokenizer.check(\"IDENTIFIER\", peek=True):\n            tokenizer.raise_syntax_error(\"Expected comma between extra names\")\n        elif not tokenizer.check(\"COMMA\"):\n            break\n\n        tokenizer.read()\n        tokenizer.consume(\"WS\")\n\n        extra_token = tokenizer.expect(\"IDENTIFIER\", expected=\"extra name after comma\")\n        extras.append(extra_token.text)\n\n    return extras\n\n\ndef _parse_specifier(tokenizer: Tokenizer) -> str:\n    \"\"\"\n    specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS\n              | WS? version_many WS?\n    \"\"\"\n    with tokenizer.enclosing_tokens(\n        \"LEFT_PARENTHESIS\",\n        \"RIGHT_PARENTHESIS\",\n        around=\"version specifier\",\n    ):\n        tokenizer.consume(\"WS\")\n        parsed_specifiers = _parse_version_many(tokenizer)\n        tokenizer.consume(\"WS\")\n\n    return parsed_specifiers\n\n\ndef _parse_version_many(tokenizer: Tokenizer) -> str:\n    \"\"\"\n    version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?\n    \"\"\"\n    parsed_specifiers = \"\"\n    while tokenizer.check(\"SPECIFIER\"):\n        span_start = tokenizer.position\n        parsed_specifiers += tokenizer.read().text\n        if tokenizer.check(\"VERSION_PREFIX_TRAIL\", peek=True):\n            tokenizer.raise_syntax_error(\n                \".* suffix can only be used with `==` or `!=` operators\",\n                span_start=span_start,\n                span_end=tokenizer.position + 1,\n            )\n        if tokenizer.check(\"VERSION_LOCAL_LABEL_TRAIL\", peek=True):\n            tokenizer.raise_syntax_error(\n                \"Local version label can only be used with `==` or `!=` operators\",\n                span_start=span_start,\n                span_end=tokenizer.position,\n            )\n        tokenizer.consume(\"WS\")\n        if not tokenizer.check(\"COMMA\"):\n            break\n        parsed_specifiers += tokenizer.read().text\n        tokenizer.consume(\"WS\")\n\n    return parsed_specifiers\n\n\n# --------------------------------------------------------------------------------------\n# Recursive descent parser for marker expression\n# --------------------------------------------------------------------------------------\ndef parse_marker(source: str) -> MarkerList:\n    return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))\n\n\ndef _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:\n    retval = _parse_marker(tokenizer)\n    tokenizer.expect(\"END\", expected=\"end of marker expression\")\n    return retval\n\n\ndef _parse_marker(tokenizer: Tokenizer) -> MarkerList:\n    \"\"\"\n    marker = marker_atom (BOOLOP marker_atom)+\n    \"\"\"\n    expression = [_parse_marker_atom(tokenizer)]\n    while tokenizer.check(\"BOOLOP\"):\n        token = tokenizer.read()\n        expr_right = _parse_marker_atom(tokenizer)\n        expression.extend((token.text, expr_right))\n    return expression\n\n\ndef _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:\n    \"\"\"\n    marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?\n                | WS? marker_item WS?\n    \"\"\"\n\n    tokenizer.consume(\"WS\")\n    if tokenizer.check(\"LEFT_PARENTHESIS\", peek=True):\n        with tokenizer.enclosing_tokens(\n            \"LEFT_PARENTHESIS\",\n            \"RIGHT_PARENTHESIS\",\n            around=\"marker expression\",\n        ):\n            tokenizer.consume(\"WS\")\n            marker: MarkerAtom = _parse_marker(tokenizer)\n            tokenizer.consume(\"WS\")\n    else:\n        marker = _parse_marker_item(tokenizer)\n    tokenizer.consume(\"WS\")\n    return marker\n\n\ndef _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:\n    \"\"\"\n    marker_item = WS? marker_var WS? marker_op WS? marker_var WS?\n    \"\"\"\n    tokenizer.consume(\"WS\")\n    marker_var_left = _parse_marker_var(tokenizer)\n    tokenizer.consume(\"WS\")\n    marker_op = _parse_marker_op(tokenizer)\n    tokenizer.consume(\"WS\")\n    marker_var_right = _parse_marker_var(tokenizer)\n    tokenizer.consume(\"WS\")\n    return (marker_var_left, marker_op, marker_var_right)\n\n\ndef _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:  # noqa: RET503\n    \"\"\"\n    marker_var = VARIABLE | QUOTED_STRING\n    \"\"\"\n    if tokenizer.check(\"VARIABLE\"):\n        return process_env_var(tokenizer.read().text.replace(\".\", \"_\"))\n    elif tokenizer.check(\"QUOTED_STRING\"):\n        return process_python_str(tokenizer.read().text)\n    else:\n        tokenizer.raise_syntax_error(\n            message=\"Expected a marker variable or quoted string\"\n        )\n\n\ndef process_env_var(env_var: str) -> Variable:\n    if env_var in (\"platform_python_implementation\", \"python_implementation\"):\n        return Variable(\"platform_python_implementation\")\n    else:\n        return Variable(env_var)\n\n\ndef process_python_str(python_str: str) -> Value:\n    value = ast.literal_eval(python_str)\n    return Value(str(value))\n\n\ndef _parse_marker_op(tokenizer: Tokenizer) -> Op:\n    \"\"\"\n    marker_op = IN | NOT IN | OP\n    \"\"\"\n    if tokenizer.check(\"IN\"):\n        tokenizer.read()\n        return Op(\"in\")\n    elif tokenizer.check(\"NOT\"):\n        tokenizer.read()\n        tokenizer.expect(\"WS\", expected=\"whitespace after 'not'\")\n        tokenizer.expect(\"IN\", expected=\"'in' after 'not'\")\n        return Op(\"not in\")\n    elif tokenizer.check(\"OP\"):\n        return Op(tokenizer.read().text)\n    else:\n        return tokenizer.raise_syntax_error(\n            \"Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\"\n        )\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_structures.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport typing\n\n\n@typing.final\nclass InfinityType:\n    __slots__ = ()\n\n    def __repr__(self) -> str:\n        return \"Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return False\n\n    def __le__(self, other: object) -> bool:\n        return False\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return True\n\n    def __ge__(self, other: object) -> bool:\n        return True\n\n    def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\n@typing.final\nclass NegativeInfinityType:\n    __slots__ = ()\n\n    def __repr__(self) -> str:\n        return \"-Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return True\n\n    def __le__(self, other: object) -> bool:\n        return True\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return False\n\n    def __ge__(self, other: object) -> bool:\n        return False\n\n    def __neg__(self: object) -> InfinityType:\n        return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n"
  },
  {
    "path": "src/pip/_vendor/packaging/_tokenizer.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport re\nfrom dataclasses import dataclass\nfrom typing import Generator, Mapping, NoReturn\n\nfrom .specifiers import Specifier\n\n\n@dataclass\nclass Token:\n    name: str\n    text: str\n    position: int\n\n\nclass ParserSyntaxError(Exception):\n    \"\"\"The provided source text could not be parsed correctly.\"\"\"\n\n    def __init__(\n        self,\n        message: str,\n        *,\n        source: str,\n        span: tuple[int, int],\n    ) -> None:\n        self.span = span\n        self.message = message\n        self.source = source\n\n        super().__init__()\n\n    def __str__(self) -> str:\n        marker = \" \" * self.span[0] + \"~\" * (self.span[1] - self.span[0]) + \"^\"\n        return f\"{self.message}\\n    {self.source}\\n    {marker}\"\n\n\nDEFAULT_RULES: dict[str, re.Pattern[str]] = {\n    \"LEFT_PARENTHESIS\": re.compile(r\"\\(\"),\n    \"RIGHT_PARENTHESIS\": re.compile(r\"\\)\"),\n    \"LEFT_BRACKET\": re.compile(r\"\\[\"),\n    \"RIGHT_BRACKET\": re.compile(r\"\\]\"),\n    \"SEMICOLON\": re.compile(r\";\"),\n    \"COMMA\": re.compile(r\",\"),\n    \"QUOTED_STRING\": re.compile(\n        r\"\"\"\n            (\n                ('[^']*')\n                |\n                (\"[^\"]*\")\n            )\n        \"\"\",\n        re.VERBOSE,\n    ),\n    \"OP\": re.compile(r\"(===|==|~=|!=|<=|>=|<|>)\"),\n    \"BOOLOP\": re.compile(r\"\\b(or|and)\\b\"),\n    \"IN\": re.compile(r\"\\bin\\b\"),\n    \"NOT\": re.compile(r\"\\bnot\\b\"),\n    \"VARIABLE\": re.compile(\n        r\"\"\"\n            \\b(\n                python_version\n                |python_full_version\n                |os[._]name\n                |sys[._]platform\n                |platform_(release|system)\n                |platform[._](version|machine|python_implementation)\n                |python_implementation\n                |implementation_(name|version)\n                |extras?\n                |dependency_groups\n            )\\b\n        \"\"\",\n        re.VERBOSE,\n    ),\n    \"SPECIFIER\": re.compile(\n        Specifier._operator_regex_str + Specifier._version_regex_str,\n        re.VERBOSE | re.IGNORECASE,\n    ),\n    \"AT\": re.compile(r\"\\@\"),\n    \"URL\": re.compile(r\"[^ \\t]+\"),\n    \"IDENTIFIER\": re.compile(r\"\\b[a-zA-Z0-9][a-zA-Z0-9._-]*\\b\"),\n    \"VERSION_PREFIX_TRAIL\": re.compile(r\"\\.\\*\"),\n    \"VERSION_LOCAL_LABEL_TRAIL\": re.compile(r\"\\+[a-z0-9]+(?:[-_\\.][a-z0-9]+)*\"),\n    \"WS\": re.compile(r\"[ \\t]+\"),\n    \"END\": re.compile(r\"$\"),\n}\n\n\nclass Tokenizer:\n    \"\"\"Context-sensitive token parsing.\n\n    Provides methods to examine the input stream to check whether the next token\n    matches.\n    \"\"\"\n\n    def __init__(\n        self,\n        source: str,\n        *,\n        rules: Mapping[str, re.Pattern[str]],\n    ) -> None:\n        self.source = source\n        self.rules = rules\n        self.next_token: Token | None = None\n        self.position = 0\n\n    def consume(self, name: str) -> None:\n        \"\"\"Move beyond provided token name, if at current position.\"\"\"\n        if self.check(name):\n            self.read()\n\n    def check(self, name: str, *, peek: bool = False) -> bool:\n        \"\"\"Check whether the next token has the provided name.\n\n        By default, if the check succeeds, the token *must* be read before\n        another check. If `peek` is set to `True`, the token is not loaded and\n        would need to be checked again.\n        \"\"\"\n        assert self.next_token is None, (\n            f\"Cannot check for {name!r}, already have {self.next_token!r}\"\n        )\n        assert name in self.rules, f\"Unknown token name: {name!r}\"\n\n        expression = self.rules[name]\n\n        match = expression.match(self.source, self.position)\n        if match is None:\n            return False\n        if not peek:\n            self.next_token = Token(name, match[0], self.position)\n        return True\n\n    def expect(self, name: str, *, expected: str) -> Token:\n        \"\"\"Expect a certain token name next, failing with a syntax error otherwise.\n\n        The token is *not* read.\n        \"\"\"\n        if not self.check(name):\n            raise self.raise_syntax_error(f\"Expected {expected}\")\n        return self.read()\n\n    def read(self) -> Token:\n        \"\"\"Consume the next token and return it.\"\"\"\n        token = self.next_token\n        assert token is not None\n\n        self.position += len(token.text)\n        self.next_token = None\n\n        return token\n\n    def raise_syntax_error(\n        self,\n        message: str,\n        *,\n        span_start: int | None = None,\n        span_end: int | None = None,\n    ) -> NoReturn:\n        \"\"\"Raise ParserSyntaxError at the given position.\"\"\"\n        span = (\n            self.position if span_start is None else span_start,\n            self.position if span_end is None else span_end,\n        )\n        raise ParserSyntaxError(\n            message,\n            source=self.source,\n            span=span,\n        )\n\n    @contextlib.contextmanager\n    def enclosing_tokens(\n        self, open_token: str, close_token: str, *, around: str\n    ) -> Generator[None, None, None]:\n        if self.check(open_token):\n            open_position = self.position\n            self.read()\n        else:\n            open_position = None\n\n        yield\n\n        if open_position is None:\n            return\n\n        if not self.check(close_token):\n            self.raise_syntax_error(\n                f\"Expected matching {close_token} for {open_token}, after {around}\",\n                span_start=open_position,\n            )\n\n        self.read()\n"
  },
  {
    "path": "src/pip/_vendor/packaging/licenses/__init__.py",
    "content": "#######################################################################################\n#\n# Adapted from:\n#  https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py\n#\n# MIT License\n#\n# Copyright (c) 2017-present Ofek Lev <oss@ofek.dev>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify,\n# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies\n# or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n#\n# With additional allowance of arbitrary `LicenseRef-` identifiers, not just\n# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.\n#\n#######################################################################################\nfrom __future__ import annotations\n\nimport re\nfrom typing import NewType, cast\n\nfrom ._spdx import EXCEPTIONS, LICENSES\n\n__all__ = [\n    \"InvalidLicenseExpression\",\n    \"NormalizedLicenseExpression\",\n    \"canonicalize_license_expression\",\n]\n\nlicense_ref_allowed = re.compile(\"^[A-Za-z0-9.-]*$\")\n\nNormalizedLicenseExpression = NewType(\"NormalizedLicenseExpression\", str)\n\n\nclass InvalidLicenseExpression(ValueError):\n    \"\"\"Raised when a license-expression string is invalid\n\n    >>> canonicalize_license_expression(\"invalid\")\n    Traceback (most recent call last):\n        ...\n    packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid'\n    \"\"\"\n\n\ndef canonicalize_license_expression(\n    raw_license_expression: str,\n) -> NormalizedLicenseExpression:\n    if not raw_license_expression:\n        message = f\"Invalid license expression: {raw_license_expression!r}\"\n        raise InvalidLicenseExpression(message)\n\n    # Pad any parentheses so tokenization can be achieved by merely splitting on\n    # whitespace.\n    license_expression = raw_license_expression.replace(\"(\", \" ( \").replace(\")\", \" ) \")\n    licenseref_prefix = \"LicenseRef-\"\n    license_refs = {\n        ref.lower(): \"LicenseRef-\" + ref[len(licenseref_prefix) :]\n        for ref in license_expression.split()\n        if ref.lower().startswith(licenseref_prefix.lower())\n    }\n\n    # Normalize to lower case so we can look up licenses/exceptions\n    # and so boolean operators are Python-compatible.\n    license_expression = license_expression.lower()\n\n    tokens = license_expression.split()\n\n    # Rather than implementing a parenthesis/boolean logic parser, create an\n    # expression that Python can parse. Everything that is not involved with the\n    # grammar itself is replaced with the placeholder `False` and the resultant\n    # expression should become a valid Python expression.\n    python_tokens = []\n    for token in tokens:\n        if token not in {\"or\", \"and\", \"with\", \"(\", \")\"}:\n            python_tokens.append(\"False\")\n        elif token == \"with\":\n            python_tokens.append(\"or\")\n        elif (\n            token == \"(\"\n            and python_tokens\n            and python_tokens[-1] not in {\"or\", \"and\", \"(\"}\n        ) or (token == \")\" and python_tokens and python_tokens[-1] == \"(\"):\n            message = f\"Invalid license expression: {raw_license_expression!r}\"\n            raise InvalidLicenseExpression(message)\n        else:\n            python_tokens.append(token)\n\n    python_expression = \" \".join(python_tokens)\n    try:\n        compile(python_expression, \"\", \"eval\")\n    except SyntaxError:\n        message = f\"Invalid license expression: {raw_license_expression!r}\"\n        raise InvalidLicenseExpression(message) from None\n\n    # Take a final pass to check for unknown licenses/exceptions.\n    normalized_tokens = []\n    for token in tokens:\n        if token in {\"or\", \"and\", \"with\", \"(\", \")\"}:\n            normalized_tokens.append(token.upper())\n            continue\n\n        if normalized_tokens and normalized_tokens[-1] == \"WITH\":\n            if token not in EXCEPTIONS:\n                message = f\"Unknown license exception: {token!r}\"\n                raise InvalidLicenseExpression(message)\n\n            normalized_tokens.append(EXCEPTIONS[token][\"id\"])\n        else:\n            if token.endswith(\"+\"):\n                final_token = token[:-1]\n                suffix = \"+\"\n            else:\n                final_token = token\n                suffix = \"\"\n\n            if final_token.startswith(\"licenseref-\"):\n                if not license_ref_allowed.match(final_token):\n                    message = f\"Invalid licenseref: {final_token!r}\"\n                    raise InvalidLicenseExpression(message)\n                normalized_tokens.append(license_refs[final_token] + suffix)\n            else:\n                if final_token not in LICENSES:\n                    message = f\"Unknown license: {final_token!r}\"\n                    raise InvalidLicenseExpression(message)\n                normalized_tokens.append(LICENSES[final_token][\"id\"] + suffix)\n\n    normalized_expression = \" \".join(normalized_tokens)\n\n    return cast(\n        \"NormalizedLicenseExpression\",\n        normalized_expression.replace(\"( \", \"(\").replace(\" )\", \")\"),\n    )\n"
  },
  {
    "path": "src/pip/_vendor/packaging/licenses/_spdx.py",
    "content": "\nfrom __future__ import annotations\n\nfrom typing import TypedDict\n\nclass SPDXLicense(TypedDict):\n    id: str\n    deprecated: bool\n\nclass SPDXException(TypedDict):\n    id: str\n    deprecated: bool\n\n\nVERSION = '3.27.0'\n\nLICENSES: dict[str, SPDXLicense] = {\n    '0bsd': {'id': '0BSD', 'deprecated': False},\n    '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False},\n    'aal': {'id': 'AAL', 'deprecated': False},\n    'abstyles': {'id': 'Abstyles', 'deprecated': False},\n    'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False},\n    'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False},\n    'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False},\n    'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False},\n    'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False},\n    'adsl': {'id': 'ADSL', 'deprecated': False},\n    'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False},\n    'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False},\n    'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False},\n    'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False},\n    'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False},\n    'afmparse': {'id': 'Afmparse', 'deprecated': False},\n    'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True},\n    'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False},\n    'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False},\n    'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True},\n    'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False},\n    'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False},\n    'aladdin': {'id': 'Aladdin', 'deprecated': False},\n    'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False},\n    'amdplpa': {'id': 'AMDPLPA', 'deprecated': False},\n    'aml': {'id': 'AML', 'deprecated': False},\n    'aml-glslang': {'id': 'AML-glslang', 'deprecated': False},\n    'ampas': {'id': 'AMPAS', 'deprecated': False},\n    'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False},\n    'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False},\n    'any-osi': {'id': 'any-OSI', 'deprecated': False},\n    'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False},\n    'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False},\n    'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False},\n    'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False},\n    'apafml': {'id': 'APAFML', 'deprecated': False},\n    'apl-1.0': {'id': 'APL-1.0', 'deprecated': False},\n    'app-s2p': {'id': 'App-s2p', 'deprecated': False},\n    'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False},\n    'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False},\n    'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False},\n    'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False},\n    'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False},\n    'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False},\n    'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False},\n    'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False},\n    'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False},\n    'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False},\n    'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False},\n    'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False},\n    'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False},\n    'baekmuk': {'id': 'Baekmuk', 'deprecated': False},\n    'bahyph': {'id': 'Bahyph', 'deprecated': False},\n    'barr': {'id': 'Barr', 'deprecated': False},\n    'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False},\n    'beerware': {'id': 'Beerware', 'deprecated': False},\n    'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False},\n    'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False},\n    'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False},\n    'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False},\n    'blessing': {'id': 'blessing', 'deprecated': False},\n    'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False},\n    'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False},\n    'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False},\n    'borceux': {'id': 'Borceux', 'deprecated': False},\n    'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False},\n    'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False},\n    'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False},\n    'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False},\n    'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False},\n    'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False},\n    'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True},\n    'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True},\n    'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False},\n    'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False},\n    'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False},\n    'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False},\n    'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False},\n    'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False},\n    'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False},\n    'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False},\n    'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False},\n    'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False},\n    'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False},\n    'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False},\n    'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False},\n    'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False},\n    'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False},\n    'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False},\n    'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False},\n    'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False},\n    'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False},\n    'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False},\n    'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False},\n    'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False},\n    'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False},\n    'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False},\n    'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False},\n    'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False},\n    'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False},\n    'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False},\n    'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False},\n    'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False},\n    'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False},\n    'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False},\n    'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True},\n    'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False},\n    'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False},\n    'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False},\n    'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False},\n    'caldera': {'id': 'Caldera', 'deprecated': False},\n    'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False},\n    'catharon': {'id': 'Catharon', 'deprecated': False},\n    'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False},\n    'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False},\n    'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False},\n    'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False},\n    'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False},\n    'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False},\n    'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False},\n    'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False},\n    'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False},\n    'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False},\n    'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False},\n    'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False},\n    'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False},\n    'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False},\n    'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False},\n    'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False},\n    'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False},\n    'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False},\n    'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False},\n    'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False},\n    'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False},\n    'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False},\n    'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False},\n    'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False},\n    'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False},\n    'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False},\n    'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False},\n    'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False},\n    'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False},\n    'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False},\n    'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False},\n    'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False},\n    'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False},\n    'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False},\n    'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False},\n    'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False},\n    'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False},\n    'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False},\n    'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False},\n    'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False},\n    'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False},\n    'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False},\n    'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False},\n    'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False},\n    'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False},\n    'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False},\n    'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False},\n    'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False},\n    'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False},\n    'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False},\n    'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False},\n    'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False},\n    'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False},\n    'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False},\n    'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False},\n    'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False},\n    'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False},\n    'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False},\n    'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False},\n    'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False},\n    'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False},\n    'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False},\n    'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False},\n    'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False},\n    'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False},\n    'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False},\n    'cecill-b': {'id': 'CECILL-B', 'deprecated': False},\n    'cecill-c': {'id': 'CECILL-C', 'deprecated': False},\n    'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False},\n    'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False},\n    'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False},\n    'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False},\n    'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False},\n    'cfitsio': {'id': 'CFITSIO', 'deprecated': False},\n    'check-cvs': {'id': 'check-cvs', 'deprecated': False},\n    'checkmk': {'id': 'checkmk', 'deprecated': False},\n    'clartistic': {'id': 'ClArtistic', 'deprecated': False},\n    'clips': {'id': 'Clips', 'deprecated': False},\n    'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False},\n    'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False},\n    'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False},\n    'cnri-python': {'id': 'CNRI-Python', 'deprecated': False},\n    'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False},\n    'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False},\n    'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False},\n    'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False},\n    'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False},\n    'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False},\n    'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False},\n    'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False},\n    'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False},\n    'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False},\n    'cronyx': {'id': 'Cronyx', 'deprecated': False},\n    'crossword': {'id': 'Crossword', 'deprecated': False},\n    'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False},\n    'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False},\n    'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False},\n    'cube': {'id': 'Cube', 'deprecated': False},\n    'curl': {'id': 'curl', 'deprecated': False},\n    'cve-tou': {'id': 'cve-tou', 'deprecated': False},\n    'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False},\n    'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False},\n    'diffmark': {'id': 'diffmark', 'deprecated': False},\n    'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False},\n    'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False},\n    'doc': {'id': 'DOC', 'deprecated': False},\n    'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False},\n    'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False},\n    'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False},\n    'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False},\n    'dotseqn': {'id': 'Dotseqn', 'deprecated': False},\n    'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False},\n    'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False},\n    'dsdp': {'id': 'DSDP', 'deprecated': False},\n    'dtoa': {'id': 'dtoa', 'deprecated': False},\n    'dvipdfm': {'id': 'dvipdfm', 'deprecated': False},\n    'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False},\n    'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False},\n    'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True},\n    'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False},\n    'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False},\n    'egenix': {'id': 'eGenix', 'deprecated': False},\n    'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False},\n    'entessa': {'id': 'Entessa', 'deprecated': False},\n    'epics': {'id': 'EPICS', 'deprecated': False},\n    'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False},\n    'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False},\n    'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False},\n    'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False},\n    'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False},\n    'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False},\n    'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False},\n    'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False},\n    'eurosym': {'id': 'Eurosym', 'deprecated': False},\n    'fair': {'id': 'Fair', 'deprecated': False},\n    'fbm': {'id': 'FBM', 'deprecated': False},\n    'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False},\n    'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False},\n    'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False},\n    'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False},\n    'freeimage': {'id': 'FreeImage', 'deprecated': False},\n    'fsfap': {'id': 'FSFAP', 'deprecated': False},\n    'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False},\n    'fsful': {'id': 'FSFUL', 'deprecated': False},\n    'fsfullr': {'id': 'FSFULLR', 'deprecated': False},\n    'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False},\n    'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False},\n    'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False},\n    'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False},\n    'ftl': {'id': 'FTL', 'deprecated': False},\n    'furuseth': {'id': 'Furuseth', 'deprecated': False},\n    'fwlw': {'id': 'fwlw', 'deprecated': False},\n    'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False},\n    'gcr-docs': {'id': 'GCR-docs', 'deprecated': False},\n    'gd': {'id': 'GD', 'deprecated': False},\n    'generic-xts': {'id': 'generic-xts', 'deprecated': False},\n    'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True},\n    'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False},\n    'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False},\n    'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False},\n    'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False},\n    'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False},\n    'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False},\n    'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True},\n    'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False},\n    'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False},\n    'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False},\n    'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False},\n    'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False},\n    'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False},\n    'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True},\n    'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False},\n    'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False},\n    'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False},\n    'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False},\n    'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False},\n    'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False},\n    'giftware': {'id': 'Giftware', 'deprecated': False},\n    'gl2ps': {'id': 'GL2PS', 'deprecated': False},\n    'glide': {'id': 'Glide', 'deprecated': False},\n    'glulxe': {'id': 'Glulxe', 'deprecated': False},\n    'glwtpl': {'id': 'GLWTPL', 'deprecated': False},\n    'gnuplot': {'id': 'gnuplot', 'deprecated': False},\n    'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True},\n    'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True},\n    'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False},\n    'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False},\n    'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True},\n    'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True},\n    'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False},\n    'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False},\n    'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True},\n    'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True},\n    'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True},\n    'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True},\n    'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True},\n    'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True},\n    'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True},\n    'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False},\n    'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False},\n    'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True},\n    'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True},\n    'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False},\n    'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False},\n    'gtkbook': {'id': 'gtkbook', 'deprecated': False},\n    'gutmann': {'id': 'Gutmann', 'deprecated': False},\n    'haskellreport': {'id': 'HaskellReport', 'deprecated': False},\n    'hdf5': {'id': 'HDF5', 'deprecated': False},\n    'hdparm': {'id': 'hdparm', 'deprecated': False},\n    'hidapi': {'id': 'HIDAPI', 'deprecated': False},\n    'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False},\n    'hp-1986': {'id': 'HP-1986', 'deprecated': False},\n    'hp-1989': {'id': 'HP-1989', 'deprecated': False},\n    'hpnd': {'id': 'HPND', 'deprecated': False},\n    'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False},\n    'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False},\n    'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False},\n    'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False},\n    'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False},\n    'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False},\n    'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False},\n    'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False},\n    'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False},\n    'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False},\n    'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False},\n    'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False},\n    'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False},\n    'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False},\n    'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False},\n    'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False},\n    'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False},\n    'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False},\n    'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False},\n    'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False},\n    'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False},\n    'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False},\n    'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False},\n    'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False},\n    'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False},\n    'icu': {'id': 'ICU', 'deprecated': False},\n    'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False},\n    'ijg': {'id': 'IJG', 'deprecated': False},\n    'ijg-short': {'id': 'IJG-short', 'deprecated': False},\n    'imagemagick': {'id': 'ImageMagick', 'deprecated': False},\n    'imatix': {'id': 'iMatix', 'deprecated': False},\n    'imlib2': {'id': 'Imlib2', 'deprecated': False},\n    'info-zip': {'id': 'Info-ZIP', 'deprecated': False},\n    'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False},\n    'innosetup': {'id': 'InnoSetup', 'deprecated': False},\n    'intel': {'id': 'Intel', 'deprecated': False},\n    'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False},\n    'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False},\n    'ipa': {'id': 'IPA', 'deprecated': False},\n    'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False},\n    'isc': {'id': 'ISC', 'deprecated': False},\n    'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False},\n    'jam': {'id': 'Jam', 'deprecated': False},\n    'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False},\n    'jove': {'id': 'jove', 'deprecated': False},\n    'jpl-image': {'id': 'JPL-image', 'deprecated': False},\n    'jpnic': {'id': 'JPNIC', 'deprecated': False},\n    'json': {'id': 'JSON', 'deprecated': False},\n    'kastrup': {'id': 'Kastrup', 'deprecated': False},\n    'kazlib': {'id': 'Kazlib', 'deprecated': False},\n    'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False},\n    'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False},\n    'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False},\n    'latex2e': {'id': 'Latex2e', 'deprecated': False},\n    'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False},\n    'leptonica': {'id': 'Leptonica', 'deprecated': False},\n    'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True},\n    'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True},\n    'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False},\n    'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False},\n    'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True},\n    'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True},\n    'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False},\n    'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False},\n    'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True},\n    'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True},\n    'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False},\n    'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False},\n    'lgpllr': {'id': 'LGPLLR', 'deprecated': False},\n    'libpng': {'id': 'Libpng', 'deprecated': False},\n    'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False},\n    'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False},\n    'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False},\n    'libtiff': {'id': 'libtiff', 'deprecated': False},\n    'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False},\n    'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False},\n    'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False},\n    'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False},\n    'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False},\n    'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False},\n    'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False},\n    'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False},\n    'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False},\n    'loop': {'id': 'LOOP', 'deprecated': False},\n    'lpd-document': {'id': 'LPD-document', 'deprecated': False},\n    'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False},\n    'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False},\n    'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False},\n    'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False},\n    'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False},\n    'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False},\n    'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False},\n    'lsof': {'id': 'lsof', 'deprecated': False},\n    'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False},\n    'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False},\n    'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False},\n    'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False},\n    'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False},\n    'magaz': {'id': 'magaz', 'deprecated': False},\n    'mailprio': {'id': 'mailprio', 'deprecated': False},\n    'makeindex': {'id': 'MakeIndex', 'deprecated': False},\n    'man2html': {'id': 'man2html', 'deprecated': False},\n    'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False},\n    'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False},\n    'metamail': {'id': 'metamail', 'deprecated': False},\n    'minpack': {'id': 'Minpack', 'deprecated': False},\n    'mips': {'id': 'MIPS', 'deprecated': False},\n    'miros': {'id': 'MirOS', 'deprecated': False},\n    'mit': {'id': 'MIT', 'deprecated': False},\n    'mit-0': {'id': 'MIT-0', 'deprecated': False},\n    'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False},\n    'mit-click': {'id': 'MIT-Click', 'deprecated': False},\n    'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False},\n    'mit-enna': {'id': 'MIT-enna', 'deprecated': False},\n    'mit-feh': {'id': 'MIT-feh', 'deprecated': False},\n    'mit-festival': {'id': 'MIT-Festival', 'deprecated': False},\n    'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False},\n    'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False},\n    'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False},\n    'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False},\n    'mit-wu': {'id': 'MIT-Wu', 'deprecated': False},\n    'mitnfa': {'id': 'MITNFA', 'deprecated': False},\n    'mmixware': {'id': 'MMIXware', 'deprecated': False},\n    'motosoto': {'id': 'Motosoto', 'deprecated': False},\n    'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False},\n    'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False},\n    'mpich2': {'id': 'mpich2', 'deprecated': False},\n    'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False},\n    'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False},\n    'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False},\n    'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False},\n    'mplus': {'id': 'mplus', 'deprecated': False},\n    'ms-lpl': {'id': 'MS-LPL', 'deprecated': False},\n    'ms-pl': {'id': 'MS-PL', 'deprecated': False},\n    'ms-rl': {'id': 'MS-RL', 'deprecated': False},\n    'mtll': {'id': 'MTLL', 'deprecated': False},\n    'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False},\n    'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False},\n    'multics': {'id': 'Multics', 'deprecated': False},\n    'mup': {'id': 'Mup', 'deprecated': False},\n    'naist-2003': {'id': 'NAIST-2003', 'deprecated': False},\n    'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False},\n    'naumen': {'id': 'Naumen', 'deprecated': False},\n    'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False},\n    'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False},\n    'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False},\n    'ncl': {'id': 'NCL', 'deprecated': False},\n    'ncsa': {'id': 'NCSA', 'deprecated': False},\n    'net-snmp': {'id': 'Net-SNMP', 'deprecated': True},\n    'netcdf': {'id': 'NetCDF', 'deprecated': False},\n    'newsletr': {'id': 'Newsletr', 'deprecated': False},\n    'ngpl': {'id': 'NGPL', 'deprecated': False},\n    'ngrep': {'id': 'ngrep', 'deprecated': False},\n    'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False},\n    'nist-pd': {'id': 'NIST-PD', 'deprecated': False},\n    'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False},\n    'nist-software': {'id': 'NIST-Software', 'deprecated': False},\n    'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False},\n    'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False},\n    'nlpl': {'id': 'NLPL', 'deprecated': False},\n    'nokia': {'id': 'Nokia', 'deprecated': False},\n    'nosl': {'id': 'NOSL', 'deprecated': False},\n    'noweb': {'id': 'Noweb', 'deprecated': False},\n    'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False},\n    'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False},\n    'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False},\n    'nrl': {'id': 'NRL', 'deprecated': False},\n    'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False},\n    'ntp': {'id': 'NTP', 'deprecated': False},\n    'ntp-0': {'id': 'NTP-0', 'deprecated': False},\n    'nunit': {'id': 'Nunit', 'deprecated': True},\n    'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False},\n    'oar': {'id': 'OAR', 'deprecated': False},\n    'occt-pl': {'id': 'OCCT-PL', 'deprecated': False},\n    'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False},\n    'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False},\n    'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False},\n    'offis': {'id': 'OFFIS', 'deprecated': False},\n    'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False},\n    'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False},\n    'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False},\n    'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False},\n    'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False},\n    'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False},\n    'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False},\n    'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False},\n    'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False},\n    'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False},\n    'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False},\n    'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False},\n    'ogtsl': {'id': 'OGTSL', 'deprecated': False},\n    'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False},\n    'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False},\n    'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False},\n    'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False},\n    'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False},\n    'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False},\n    'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False},\n    'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False},\n    'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False},\n    'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False},\n    'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False},\n    'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False},\n    'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False},\n    'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False},\n    'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False},\n    'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False},\n    'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False},\n    'oml': {'id': 'OML', 'deprecated': False},\n    'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False},\n    'openssl': {'id': 'OpenSSL', 'deprecated': False},\n    'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False},\n    'openvision': {'id': 'OpenVision', 'deprecated': False},\n    'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False},\n    'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False},\n    'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False},\n    'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False},\n    'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False},\n    'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False},\n    'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False},\n    'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False},\n    'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False},\n    'padl': {'id': 'PADL', 'deprecated': False},\n    'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False},\n    'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False},\n    'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False},\n    'php-3.0': {'id': 'PHP-3.0', 'deprecated': False},\n    'php-3.01': {'id': 'PHP-3.01', 'deprecated': False},\n    'pixar': {'id': 'Pixar', 'deprecated': False},\n    'pkgconf': {'id': 'pkgconf', 'deprecated': False},\n    'plexus': {'id': 'Plexus', 'deprecated': False},\n    'pnmstitch': {'id': 'pnmstitch', 'deprecated': False},\n    'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False},\n    'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False},\n    'postgresql': {'id': 'PostgreSQL', 'deprecated': False},\n    'ppl': {'id': 'PPL', 'deprecated': False},\n    'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False},\n    'psfrag': {'id': 'psfrag', 'deprecated': False},\n    'psutils': {'id': 'psutils', 'deprecated': False},\n    'python-2.0': {'id': 'Python-2.0', 'deprecated': False},\n    'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False},\n    'python-ldap': {'id': 'python-ldap', 'deprecated': False},\n    'qhull': {'id': 'Qhull', 'deprecated': False},\n    'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False},\n    'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False},\n    'radvd': {'id': 'radvd', 'deprecated': False},\n    'rdisc': {'id': 'Rdisc', 'deprecated': False},\n    'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False},\n    'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False},\n    'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False},\n    'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False},\n    'rsa-md': {'id': 'RSA-MD', 'deprecated': False},\n    'rscpl': {'id': 'RSCPL', 'deprecated': False},\n    'ruby': {'id': 'Ruby', 'deprecated': False},\n    'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False},\n    'sax-pd': {'id': 'SAX-PD', 'deprecated': False},\n    'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False},\n    'saxpath': {'id': 'Saxpath', 'deprecated': False},\n    'scea': {'id': 'SCEA', 'deprecated': False},\n    'schemereport': {'id': 'SchemeReport', 'deprecated': False},\n    'sendmail': {'id': 'Sendmail', 'deprecated': False},\n    'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False},\n    'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False},\n    'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False},\n    'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False},\n    'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False},\n    'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False},\n    'sgp4': {'id': 'SGP4', 'deprecated': False},\n    'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False},\n    'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False},\n    'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False},\n    'sissl': {'id': 'SISSL', 'deprecated': False},\n    'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False},\n    'sl': {'id': 'SL', 'deprecated': False},\n    'sleepycat': {'id': 'Sleepycat', 'deprecated': False},\n    'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False},\n    'smlnj': {'id': 'SMLNJ', 'deprecated': False},\n    'smppl': {'id': 'SMPPL', 'deprecated': False},\n    'snia': {'id': 'SNIA', 'deprecated': False},\n    'snprintf': {'id': 'snprintf', 'deprecated': False},\n    'sofa': {'id': 'SOFA', 'deprecated': False},\n    'softsurfer': {'id': 'softSurfer', 'deprecated': False},\n    'soundex': {'id': 'Soundex', 'deprecated': False},\n    'spencer-86': {'id': 'Spencer-86', 'deprecated': False},\n    'spencer-94': {'id': 'Spencer-94', 'deprecated': False},\n    'spencer-99': {'id': 'Spencer-99', 'deprecated': False},\n    'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False},\n    'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False},\n    'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False},\n    'ssh-short': {'id': 'SSH-short', 'deprecated': False},\n    'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False},\n    'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False},\n    'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True},\n    'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False},\n    'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False},\n    'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False},\n    'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False},\n    'sunpro': {'id': 'SunPro', 'deprecated': False},\n    'swl': {'id': 'SWL', 'deprecated': False},\n    'swrule': {'id': 'swrule', 'deprecated': False},\n    'symlinks': {'id': 'Symlinks', 'deprecated': False},\n    'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False},\n    'tcl': {'id': 'TCL', 'deprecated': False},\n    'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False},\n    'termreadkey': {'id': 'TermReadKey', 'deprecated': False},\n    'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False},\n    'thirdeye': {'id': 'ThirdEye', 'deprecated': False},\n    'threeparttable': {'id': 'threeparttable', 'deprecated': False},\n    'tmate': {'id': 'TMate', 'deprecated': False},\n    'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False},\n    'tosl': {'id': 'TOSL', 'deprecated': False},\n    'tpdl': {'id': 'TPDL', 'deprecated': False},\n    'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False},\n    'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False},\n    'ttwl': {'id': 'TTWL', 'deprecated': False},\n    'ttyp0': {'id': 'TTYP0', 'deprecated': False},\n    'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False},\n    'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False},\n    'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False},\n    'ucar': {'id': 'UCAR', 'deprecated': False},\n    'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False},\n    'ulem': {'id': 'ulem', 'deprecated': False},\n    'umich-merit': {'id': 'UMich-Merit', 'deprecated': False},\n    'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False},\n    'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False},\n    'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False},\n    'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False},\n    'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False},\n    'unlicense': {'id': 'Unlicense', 'deprecated': False},\n    'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False},\n    'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False},\n    'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False},\n    'urt-rle': {'id': 'URT-RLE', 'deprecated': False},\n    'vim': {'id': 'Vim', 'deprecated': False},\n    'vostrom': {'id': 'VOSTROM', 'deprecated': False},\n    'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False},\n    'w3c': {'id': 'W3C', 'deprecated': False},\n    'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False},\n    'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False},\n    'w3m': {'id': 'w3m', 'deprecated': False},\n    'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False},\n    'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False},\n    'wsuipa': {'id': 'Wsuipa', 'deprecated': False},\n    'wtfpl': {'id': 'WTFPL', 'deprecated': False},\n    'wwl': {'id': 'wwl', 'deprecated': False},\n    'wxwindows': {'id': 'wxWindows', 'deprecated': True},\n    'x11': {'id': 'X11', 'deprecated': False},\n    'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False},\n    'x11-swapped': {'id': 'X11-swapped', 'deprecated': False},\n    'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False},\n    'xerox': {'id': 'Xerox', 'deprecated': False},\n    'xfig': {'id': 'Xfig', 'deprecated': False},\n    'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False},\n    'xinetd': {'id': 'xinetd', 'deprecated': False},\n    'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False},\n    'xlock': {'id': 'xlock', 'deprecated': False},\n    'xnet': {'id': 'Xnet', 'deprecated': False},\n    'xpp': {'id': 'xpp', 'deprecated': False},\n    'xskat': {'id': 'XSkat', 'deprecated': False},\n    'xzoom': {'id': 'xzoom', 'deprecated': False},\n    'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False},\n    'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False},\n    'zed': {'id': 'Zed', 'deprecated': False},\n    'zeeff': {'id': 'Zeeff', 'deprecated': False},\n    'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False},\n    'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False},\n    'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False},\n    'zlib': {'id': 'Zlib', 'deprecated': False},\n    'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False},\n    'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False},\n    'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False},\n    'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False},\n}\n\nEXCEPTIONS: dict[str, SPDXException] = {\n    '389-exception': {'id': '389-exception', 'deprecated': False},\n    'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False},\n    'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False},\n    'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False},\n    'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False},\n    'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False},\n    'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False},\n    'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False},\n    'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False},\n    'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False},\n    'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False},\n    'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False},\n    'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False},\n    'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False},\n    'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False},\n    'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False},\n    'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False},\n    'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False},\n    'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False},\n    'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False},\n    'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False},\n    'fmt-exception': {'id': 'fmt-exception', 'deprecated': False},\n    'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False},\n    'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False},\n    'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False},\n    'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False},\n    'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False},\n    'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False},\n    'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False},\n    'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False},\n    'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False},\n    'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False},\n    'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False},\n    'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False},\n    'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False},\n    'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False},\n    'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False},\n    'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False},\n    'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False},\n    'harbour-exception': {'id': 'harbour-exception', 'deprecated': False},\n    'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False},\n    'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False},\n    'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False},\n    'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False},\n    'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False},\n    'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False},\n    'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False},\n    'llgpl': {'id': 'LLGPL', 'deprecated': False},\n    'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False},\n    'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False},\n    'mif-exception': {'id': 'mif-exception', 'deprecated': False},\n    'mxml-exception': {'id': 'mxml-exception', 'deprecated': False},\n    'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True},\n    'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False},\n    'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False},\n    'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False},\n    'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False},\n    'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False},\n    'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False},\n    'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False},\n    'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False},\n    'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False},\n    'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False},\n    'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False},\n    'romic-exception': {'id': 'romic-exception', 'deprecated': False},\n    'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False},\n    'sane-exception': {'id': 'SANE-exception', 'deprecated': False},\n    'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False},\n    'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False},\n    'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False},\n    'swi-exception': {'id': 'SWI-exception', 'deprecated': False},\n    'swift-exception': {'id': 'Swift-exception', 'deprecated': False},\n    'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False},\n    'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False},\n    'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False},\n    'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False},\n    'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False},\n    'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False},\n    'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False},\n}\n"
  },
  {
    "path": "src/pip/_vendor/packaging/markers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import annotations\n\nimport operator\nimport os\nimport platform\nimport sys\nfrom typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast\n\nfrom ._parser import MarkerAtom, MarkerList, Op, Value, Variable\nfrom ._parser import parse_marker as _parse_marker\nfrom ._tokenizer import ParserSyntaxError\nfrom .specifiers import InvalidSpecifier, Specifier\nfrom .utils import canonicalize_name\n\n__all__ = [\n    \"Environment\",\n    \"EvaluateContext\",\n    \"InvalidMarker\",\n    \"Marker\",\n    \"UndefinedComparison\",\n    \"UndefinedEnvironmentName\",\n    \"default_environment\",\n]\n\nOperator = Callable[[str, Union[str, AbstractSet[str]]], bool]\nEvaluateContext = Literal[\"metadata\", \"lock_file\", \"requirement\"]\nMARKERS_ALLOWING_SET = {\"extras\", \"dependency_groups\"}\nMARKERS_REQUIRING_VERSION = {\n    \"implementation_version\",\n    \"platform_release\",\n    \"python_full_version\",\n    \"python_version\",\n}\n\n\nclass InvalidMarker(ValueError):\n    \"\"\"\n    An invalid marker was found, users should refer to PEP 508.\n    \"\"\"\n\n\nclass UndefinedComparison(ValueError):\n    \"\"\"\n    An invalid operation was attempted on a value that doesn't support it.\n    \"\"\"\n\n\nclass UndefinedEnvironmentName(ValueError):\n    \"\"\"\n    A name was attempted to be used that does not exist inside of the\n    environment.\n    \"\"\"\n\n\nclass Environment(TypedDict):\n    implementation_name: str\n    \"\"\"The implementation's identifier, e.g. ``'cpython'``.\"\"\"\n\n    implementation_version: str\n    \"\"\"\n    The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or\n    ``'7.3.13'`` for PyPy3.10 v7.3.13.\n    \"\"\"\n\n    os_name: str\n    \"\"\"\n    The value of :py:data:`os.name`. The name of the operating system dependent module\n    imported, e.g. ``'posix'``.\n    \"\"\"\n\n    platform_machine: str\n    \"\"\"\n    Returns the machine type, e.g. ``'i386'``.\n\n    An empty string if the value cannot be determined.\n    \"\"\"\n\n    platform_release: str\n    \"\"\"\n    The system's release, e.g. ``'2.2.0'`` or ``'NT'``.\n\n    An empty string if the value cannot be determined.\n    \"\"\"\n\n    platform_system: str\n    \"\"\"\n    The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.\n\n    An empty string if the value cannot be determined.\n    \"\"\"\n\n    platform_version: str\n    \"\"\"\n    The system's release version, e.g. ``'#3 on degas'``.\n\n    An empty string if the value cannot be determined.\n    \"\"\"\n\n    python_full_version: str\n    \"\"\"\n    The Python version as string ``'major.minor.patchlevel'``.\n\n    Note that unlike the Python :py:data:`sys.version`, this value will always include\n    the patchlevel (it defaults to 0).\n    \"\"\"\n\n    platform_python_implementation: str\n    \"\"\"\n    A string identifying the Python implementation, e.g. ``'CPython'``.\n    \"\"\"\n\n    python_version: str\n    \"\"\"The Python version as string ``'major.minor'``.\"\"\"\n\n    sys_platform: str\n    \"\"\"\n    This string contains a platform identifier that can be used to append\n    platform-specific components to :py:data:`sys.path`, for instance.\n\n    For Unix systems, except on Linux and AIX, this is the lowercased OS name as\n    returned by ``uname -s`` with the first part of the version as returned by\n    ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python\n    was built.\n    \"\"\"\n\n\ndef _normalize_extras(\n    result: MarkerList | MarkerAtom | str,\n) -> MarkerList | MarkerAtom | str:\n    if not isinstance(result, tuple):\n        return result\n\n    lhs, op, rhs = result\n    if isinstance(lhs, Variable) and lhs.value == \"extra\":\n        normalized_extra = canonicalize_name(rhs.value)\n        rhs = Value(normalized_extra)\n    elif isinstance(rhs, Variable) and rhs.value == \"extra\":\n        normalized_extra = canonicalize_name(lhs.value)\n        lhs = Value(normalized_extra)\n    return lhs, op, rhs\n\n\ndef _normalize_extra_values(results: MarkerList) -> MarkerList:\n    \"\"\"\n    Normalize extra values.\n    \"\"\"\n\n    return [_normalize_extras(r) for r in results]\n\n\ndef _format_marker(\n    marker: list[str] | MarkerAtom | str, first: bool | None = True\n) -> str:\n    assert isinstance(marker, (list, tuple, str))\n\n    # Sometimes we have a structure like [[...]] which is a single item list\n    # where the single item is itself it's own list. In that case we want skip\n    # the rest of this function so that we don't get extraneous () on the\n    # outside.\n    if (\n        isinstance(marker, list)\n        and len(marker) == 1\n        and isinstance(marker[0], (list, tuple))\n    ):\n        return _format_marker(marker[0])\n\n    if isinstance(marker, list):\n        inner = (_format_marker(m, first=False) for m in marker)\n        if first:\n            return \" \".join(inner)\n        else:\n            return \"(\" + \" \".join(inner) + \")\"\n    elif isinstance(marker, tuple):\n        return \" \".join([m.serialize() for m in marker])\n    else:\n        return marker\n\n\n_operators: dict[str, Operator] = {\n    \"in\": lambda lhs, rhs: lhs in rhs,\n    \"not in\": lambda lhs, rhs: lhs not in rhs,\n    \"<\": lambda _lhs, _rhs: False,\n    \"<=\": operator.eq,\n    \"==\": operator.eq,\n    \"!=\": operator.ne,\n    \">=\": operator.eq,\n    \">\": lambda _lhs, _rhs: False,\n}\n\n\ndef _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:\n    op_str = op.serialize()\n    if key in MARKERS_REQUIRING_VERSION:\n        try:\n            spec = Specifier(f\"{op_str}{rhs}\")\n        except InvalidSpecifier:\n            pass\n        else:\n            return spec.contains(lhs, prereleases=True)\n\n    oper: Operator | None = _operators.get(op_str)\n    if oper is None:\n        raise UndefinedComparison(f\"Undefined {op!r} on {lhs!r} and {rhs!r}.\")\n\n    return oper(lhs, rhs)\n\n\ndef _normalize(\n    lhs: str, rhs: str | AbstractSet[str], key: str\n) -> tuple[str, str | AbstractSet[str]]:\n    # PEP 685 - Comparison of extra names for optional distribution dependencies\n    # https://peps.python.org/pep-0685/\n    # > When comparing extra names, tools MUST normalize the names being\n    # > compared using the semantics outlined in PEP 503 for names\n    if key == \"extra\":\n        assert isinstance(rhs, str), \"extra value must be a string\"\n        # Both sides are normalized at this point already\n        return (lhs, rhs)\n    if key in MARKERS_ALLOWING_SET:\n        if isinstance(rhs, str):  # pragma: no cover\n            return (canonicalize_name(lhs), canonicalize_name(rhs))\n        else:\n            return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})\n\n    # other environment markers don't have such standards\n    return lhs, rhs\n\n\ndef _evaluate_markers(\n    markers: MarkerList, environment: dict[str, str | AbstractSet[str]]\n) -> bool:\n    groups: list[list[bool]] = [[]]\n\n    for marker in markers:\n        if isinstance(marker, list):\n            groups[-1].append(_evaluate_markers(marker, environment))\n        elif isinstance(marker, tuple):\n            lhs, op, rhs = marker\n\n            if isinstance(lhs, Variable):\n                environment_key = lhs.value\n                lhs_value = environment[environment_key]\n                rhs_value = rhs.value\n            else:\n                lhs_value = lhs.value\n                environment_key = rhs.value\n                rhs_value = environment[environment_key]\n\n            assert isinstance(lhs_value, str), \"lhs must be a string\"\n            lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)\n            groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))\n        elif marker == \"or\":\n            groups.append([])\n        elif marker == \"and\":\n            pass\n        else:  # pragma: nocover\n            raise TypeError(f\"Unexpected marker {marker!r}\")\n\n    return any(all(item) for item in groups)\n\n\ndef format_full_version(info: sys._version_info) -> str:\n    version = f\"{info.major}.{info.minor}.{info.micro}\"\n    kind = info.releaselevel\n    if kind != \"final\":\n        version += kind[0] + str(info.serial)\n    return version\n\n\ndef default_environment() -> Environment:\n    iver = format_full_version(sys.implementation.version)\n    implementation_name = sys.implementation.name\n    return {\n        \"implementation_name\": implementation_name,\n        \"implementation_version\": iver,\n        \"os_name\": os.name,\n        \"platform_machine\": platform.machine(),\n        \"platform_release\": platform.release(),\n        \"platform_system\": platform.system(),\n        \"platform_version\": platform.version(),\n        \"python_full_version\": platform.python_version(),\n        \"platform_python_implementation\": platform.python_implementation(),\n        \"python_version\": \".\".join(platform.python_version_tuple()[:2]),\n        \"sys_platform\": sys.platform,\n    }\n\n\nclass Marker:\n    def __init__(self, marker: str) -> None:\n        # Note: We create a Marker object without calling this constructor in\n        #       packaging.requirements.Requirement. If any additional logic is\n        #       added here, make sure to mirror/adapt Requirement.\n\n        # If this fails and throws an error, the repr still expects _markers to\n        # be defined.\n        self._markers: MarkerList = []\n\n        try:\n            self._markers = _normalize_extra_values(_parse_marker(marker))\n            # The attribute `_markers` can be described in terms of a recursive type:\n            # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]\n            #\n            # For example, the following expression:\n            # python_version > \"3.6\" or (python_version == \"3.6\" and os_name == \"unix\")\n            #\n            # is parsed into:\n            # [\n            #     (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),\n            #     'and',\n            #     [\n            #         (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),\n            #         'or',\n            #         (<Variable('os_name')>, <Op('==')>, <Value('unix')>)\n            #     ]\n            # ]\n        except ParserSyntaxError as e:\n            raise InvalidMarker(str(e)) from e\n\n    def __str__(self) -> str:\n        return _format_marker(self._markers)\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}('{self}')>\"\n\n    def __hash__(self) -> int:\n        return hash(str(self))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Marker):\n            return NotImplemented\n\n        return str(self) == str(other)\n\n    def evaluate(\n        self,\n        environment: Mapping[str, str | AbstractSet[str]] | None = None,\n        context: EvaluateContext = \"metadata\",\n    ) -> bool:\n        \"\"\"Evaluate a marker.\n\n        Return the boolean from evaluating the given marker against the\n        environment. environment is an optional argument to override all or\n        part of the determined environment. The *context* parameter specifies what\n        context the markers are being evaluated for, which influences what markers\n        are considered valid. Acceptable values are \"metadata\" (for core metadata;\n        default), \"lock_file\", and \"requirement\" (i.e. all other situations).\n\n        The environment is determined from the current Python process.\n        \"\"\"\n        current_environment = cast(\n            \"dict[str, str | AbstractSet[str]]\", default_environment()\n        )\n        if context == \"lock_file\":\n            current_environment.update(\n                extras=frozenset(), dependency_groups=frozenset()\n            )\n        elif context == \"metadata\":\n            current_environment[\"extra\"] = \"\"\n\n        if environment is not None:\n            current_environment.update(environment)\n            if \"extra\" in current_environment:\n                # The API used to allow setting extra to None. We need to handle\n                # this case for backwards compatibility. Also skip running\n                # normalize name if extra is empty.\n                extra = cast(\"str | None\", current_environment[\"extra\"])\n                current_environment[\"extra\"] = canonicalize_name(extra) if extra else \"\"\n\n        return _evaluate_markers(\n            self._markers, _repair_python_full_version(current_environment)\n        )\n\n\ndef _repair_python_full_version(\n    env: dict[str, str | AbstractSet[str]],\n) -> dict[str, str | AbstractSet[str]]:\n    \"\"\"\n    Work around platform.python_version() returning something that is not PEP 440\n    compliant for non-tagged Python builds.\n    \"\"\"\n    python_full_version = cast(\"str\", env[\"python_full_version\"])\n    if python_full_version.endswith(\"+\"):\n        env[\"python_full_version\"] = f\"{python_full_version}local\"\n    return env\n"
  },
  {
    "path": "src/pip/_vendor/packaging/metadata.py",
    "content": "from __future__ import annotations\n\nimport email.feedparser\nimport email.header\nimport email.message\nimport email.parser\nimport email.policy\nimport keyword\nimport pathlib\nimport sys\nimport typing\nfrom typing import (\n    Any,\n    Callable,\n    Generic,\n    Literal,\n    TypedDict,\n    cast,\n)\n\nfrom . import licenses, requirements, specifiers, utils\nfrom . import version as version_module\n\nif typing.TYPE_CHECKING:\n    from .licenses import NormalizedLicenseExpression\n\nT = typing.TypeVar(\"T\")\n\n\nif sys.version_info >= (3, 11):  # pragma: no cover\n    ExceptionGroup = ExceptionGroup  # noqa: F821\nelse:  # pragma: no cover\n\n    class ExceptionGroup(Exception):\n        \"\"\"A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.\n\n        If :external:exc:`ExceptionGroup` is already defined by Python itself,\n        that version is used instead.\n        \"\"\"\n\n        message: str\n        exceptions: list[Exception]\n\n        def __init__(self, message: str, exceptions: list[Exception]) -> None:\n            self.message = message\n            self.exceptions = exceptions\n\n        def __repr__(self) -> str:\n            return f\"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})\"\n\n\nclass InvalidMetadata(ValueError):\n    \"\"\"A metadata field contains invalid data.\"\"\"\n\n    field: str\n    \"\"\"The name of the field that contains invalid data.\"\"\"\n\n    def __init__(self, field: str, message: str) -> None:\n        self.field = field\n        super().__init__(message)\n\n\n# The RawMetadata class attempts to make as few assumptions about the underlying\n# serialization formats as possible. The idea is that as long as a serialization\n# formats offer some very basic primitives in *some* way then we can support\n# serializing to and from that format.\nclass RawMetadata(TypedDict, total=False):\n    \"\"\"A dictionary of raw core metadata.\n\n    Each field in core metadata maps to a key of this dictionary (when data is\n    provided). The key is lower-case and underscores are used instead of dashes\n    compared to the equivalent core metadata field. Any core metadata field that\n    can be specified multiple times or can hold multiple values in a single\n    field have a key with a plural name. See :class:`Metadata` whose attributes\n    match the keys of this dictionary.\n\n    Core metadata fields that can be specified multiple times are stored as a\n    list or dict depending on which is appropriate for the field. Any fields\n    which hold multiple values in a single field are stored as a list.\n\n    \"\"\"\n\n    # Metadata 1.0 - PEP 241\n    metadata_version: str\n    name: str\n    version: str\n    platforms: list[str]\n    summary: str\n    description: str\n    keywords: list[str]\n    home_page: str\n    author: str\n    author_email: str\n    license: str\n\n    # Metadata 1.1 - PEP 314\n    supported_platforms: list[str]\n    download_url: str\n    classifiers: list[str]\n    requires: list[str]\n    provides: list[str]\n    obsoletes: list[str]\n\n    # Metadata 1.2 - PEP 345\n    maintainer: str\n    maintainer_email: str\n    requires_dist: list[str]\n    provides_dist: list[str]\n    obsoletes_dist: list[str]\n    requires_python: str\n    requires_external: list[str]\n    project_urls: dict[str, str]\n\n    # Metadata 2.0\n    # PEP 426 attempted to completely revamp the metadata format\n    # but got stuck without ever being able to build consensus on\n    # it and ultimately ended up withdrawn.\n    #\n    # However, a number of tools had started emitting METADATA with\n    # `2.0` Metadata-Version, so for historical reasons, this version\n    # was skipped.\n\n    # Metadata 2.1 - PEP 566\n    description_content_type: str\n    provides_extra: list[str]\n\n    # Metadata 2.2 - PEP 643\n    dynamic: list[str]\n\n    # Metadata 2.3 - PEP 685\n    # No new fields were added in PEP 685, just some edge case were\n    # tightened up to provide better interoperability.\n\n    # Metadata 2.4 - PEP 639\n    license_expression: str\n    license_files: list[str]\n\n    # Metadata 2.5 - PEP 794\n    import_names: list[str]\n    import_namespaces: list[str]\n\n\n# 'keywords' is special as it's a string in the core metadata spec, but we\n# represent it as a list.\n_STRING_FIELDS = {\n    \"author\",\n    \"author_email\",\n    \"description\",\n    \"description_content_type\",\n    \"download_url\",\n    \"home_page\",\n    \"license\",\n    \"license_expression\",\n    \"maintainer\",\n    \"maintainer_email\",\n    \"metadata_version\",\n    \"name\",\n    \"requires_python\",\n    \"summary\",\n    \"version\",\n}\n\n_LIST_FIELDS = {\n    \"classifiers\",\n    \"dynamic\",\n    \"license_files\",\n    \"obsoletes\",\n    \"obsoletes_dist\",\n    \"platforms\",\n    \"provides\",\n    \"provides_dist\",\n    \"provides_extra\",\n    \"requires\",\n    \"requires_dist\",\n    \"requires_external\",\n    \"supported_platforms\",\n    \"import_names\",\n    \"import_namespaces\",\n}\n\n_DICT_FIELDS = {\n    \"project_urls\",\n}\n\n\ndef _parse_keywords(data: str) -> list[str]:\n    \"\"\"Split a string of comma-separated keywords into a list of keywords.\"\"\"\n    return [k.strip() for k in data.split(\",\")]\n\n\ndef _parse_project_urls(data: list[str]) -> dict[str, str]:\n    \"\"\"Parse a list of label/URL string pairings separated by a comma.\"\"\"\n    urls = {}\n    for pair in data:\n        # Our logic is slightly tricky here as we want to try and do\n        # *something* reasonable with malformed data.\n        #\n        # The main thing that we have to worry about, is data that does\n        # not have a ',' at all to split the label from the Value. There\n        # isn't a singular right answer here, and we will fail validation\n        # later on (if the caller is validating) so it doesn't *really*\n        # matter, but since the missing value has to be an empty str\n        # and our return value is dict[str, str], if we let the key\n        # be the missing value, then they'd have multiple '' values that\n        # overwrite each other in a accumulating dict.\n        #\n        # The other potential issue is that it's possible to have the\n        # same label multiple times in the metadata, with no solid \"right\"\n        # answer with what to do in that case. As such, we'll do the only\n        # thing we can, which is treat the field as unparsable and add it\n        # to our list of unparsed fields.\n        #\n        # TODO: The spec doesn't say anything about if the keys should be\n        #       considered case sensitive or not... logically they should\n        #       be case-preserving and case-insensitive, but doing that\n        #       would open up more cases where we might have duplicate\n        #       entries.\n        label, _, url = (s.strip() for s in pair.partition(\",\"))\n\n        if label in urls:\n            # The label already exists in our set of urls, so this field\n            # is unparsable, and we can just add the whole thing to our\n            # unparsable data and stop processing it.\n            raise KeyError(\"duplicate labels in project urls\")\n        urls[label] = url\n\n    return urls\n\n\ndef _get_payload(msg: email.message.Message, source: bytes | str) -> str:\n    \"\"\"Get the body of the message.\"\"\"\n    # If our source is a str, then our caller has managed encodings for us,\n    # and we don't need to deal with it.\n    if isinstance(source, str):\n        payload = msg.get_payload()\n        assert isinstance(payload, str)\n        return payload\n    # If our source is a bytes, then we're managing the encoding and we need\n    # to deal with it.\n    else:\n        bpayload = msg.get_payload(decode=True)\n        assert isinstance(bpayload, bytes)\n        try:\n            return bpayload.decode(\"utf8\", \"strict\")\n        except UnicodeDecodeError as exc:\n            raise ValueError(\"payload in an invalid encoding\") from exc\n\n\n# The various parse_FORMAT functions here are intended to be as lenient as\n# possible in their parsing, while still returning a correctly typed\n# RawMetadata.\n#\n# To aid in this, we also generally want to do as little touching of the\n# data as possible, except where there are possibly some historic holdovers\n# that make valid data awkward to work with.\n#\n# While this is a lower level, intermediate format than our ``Metadata``\n# class, some light touch ups can make a massive difference in usability.\n\n# Map METADATA fields to RawMetadata.\n_EMAIL_TO_RAW_MAPPING = {\n    \"author\": \"author\",\n    \"author-email\": \"author_email\",\n    \"classifier\": \"classifiers\",\n    \"description\": \"description\",\n    \"description-content-type\": \"description_content_type\",\n    \"download-url\": \"download_url\",\n    \"dynamic\": \"dynamic\",\n    \"home-page\": \"home_page\",\n    \"import-name\": \"import_names\",\n    \"import-namespace\": \"import_namespaces\",\n    \"keywords\": \"keywords\",\n    \"license\": \"license\",\n    \"license-expression\": \"license_expression\",\n    \"license-file\": \"license_files\",\n    \"maintainer\": \"maintainer\",\n    \"maintainer-email\": \"maintainer_email\",\n    \"metadata-version\": \"metadata_version\",\n    \"name\": \"name\",\n    \"obsoletes\": \"obsoletes\",\n    \"obsoletes-dist\": \"obsoletes_dist\",\n    \"platform\": \"platforms\",\n    \"project-url\": \"project_urls\",\n    \"provides\": \"provides\",\n    \"provides-dist\": \"provides_dist\",\n    \"provides-extra\": \"provides_extra\",\n    \"requires\": \"requires\",\n    \"requires-dist\": \"requires_dist\",\n    \"requires-external\": \"requires_external\",\n    \"requires-python\": \"requires_python\",\n    \"summary\": \"summary\",\n    \"supported-platform\": \"supported_platforms\",\n    \"version\": \"version\",\n}\n_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}\n\n\n# This class is for writing RFC822 messages\nclass RFC822Policy(email.policy.EmailPolicy):\n    \"\"\"\n    This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``\n    implementation that handles multi-line values, and some nice defaults.\n    \"\"\"\n\n    utf8 = True\n    mangle_from_ = False\n    max_line_length = 0\n\n    def header_store_parse(self, name: str, value: str) -> tuple[str, str]:\n        size = len(name) + 2\n        value = value.replace(\"\\n\", \"\\n\" + \" \" * size)\n        return (name, value)\n\n\n# This class is for writing RFC822 messages\nclass RFC822Message(email.message.EmailMessage):\n    \"\"\"\n    This is :class:`email.message.EmailMessage` with two small changes: it defaults to\n    our `RFC822Policy`, and it correctly writes unicode when being called\n    with `bytes()`.\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(policy=RFC822Policy())\n\n    def as_bytes(\n        self, unixfrom: bool = False, policy: email.policy.Policy | None = None\n    ) -> bytes:\n        \"\"\"\n        Return the bytes representation of the message.\n\n        This handles unicode encoding.\n        \"\"\"\n        return self.as_string(unixfrom, policy=policy).encode(\"utf-8\")\n\n\ndef parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:\n    \"\"\"Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).\n\n    This function returns a two-item tuple of dicts. The first dict is of\n    recognized fields from the core metadata specification. Fields that can be\n    parsed and translated into Python's built-in types are converted\n    appropriately. All other fields are left as-is. Fields that are allowed to\n    appear multiple times are stored as lists.\n\n    The second dict contains all other fields from the metadata. This includes\n    any unrecognized fields. It also includes any fields which are expected to\n    be parsed into a built-in type but were not formatted appropriately. Finally,\n    any fields that are expected to appear only once but are repeated are\n    included in this dict.\n\n    \"\"\"\n    raw: dict[str, str | list[str] | dict[str, str]] = {}\n    unparsed: dict[str, list[str]] = {}\n\n    if isinstance(data, str):\n        parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)\n    else:\n        parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)\n\n    # We have to wrap parsed.keys() in a set, because in the case of multiple\n    # values for a key (a list), the key will appear multiple times in the\n    # list of keys, but we're avoiding that by using get_all().\n    for name_with_case in frozenset(parsed.keys()):\n        # Header names in RFC are case insensitive, so we'll normalize to all\n        # lower case to make comparisons easier.\n        name = name_with_case.lower()\n\n        # We use get_all() here, even for fields that aren't multiple use,\n        # because otherwise someone could have e.g. two Name fields, and we\n        # would just silently ignore it rather than doing something about it.\n        headers = parsed.get_all(name) or []\n\n        # The way the email module works when parsing bytes is that it\n        # unconditionally decodes the bytes as ascii using the surrogateescape\n        # handler. When you pull that data back out (such as with get_all() ),\n        # it looks to see if the str has any surrogate escapes, and if it does\n        # it wraps it in a Header object instead of returning the string.\n        #\n        # As such, we'll look for those Header objects, and fix up the encoding.\n        value = []\n        # Flag if we have run into any issues processing the headers, thus\n        # signalling that the data belongs in 'unparsed'.\n        valid_encoding = True\n        for h in headers:\n            # It's unclear if this can return more types than just a Header or\n            # a str, so we'll just assert here to make sure.\n            assert isinstance(h, (email.header.Header, str))\n\n            # If it's a header object, we need to do our little dance to get\n            # the real data out of it. In cases where there is invalid data\n            # we're going to end up with mojibake, but there's no obvious, good\n            # way around that without reimplementing parts of the Header object\n            # ourselves.\n            #\n            # That should be fine since, if mojibacked happens, this key is\n            # going into the unparsed dict anyways.\n            if isinstance(h, email.header.Header):\n                # The Header object stores it's data as chunks, and each chunk\n                # can be independently encoded, so we'll need to check each\n                # of them.\n                chunks: list[tuple[bytes, str | None]] = []\n                for binary, _encoding in email.header.decode_header(h):\n                    try:\n                        binary.decode(\"utf8\", \"strict\")\n                    except UnicodeDecodeError:\n                        # Enable mojibake.\n                        encoding = \"latin1\"\n                        valid_encoding = False\n                    else:\n                        encoding = \"utf8\"\n                    chunks.append((binary, encoding))\n\n                # Turn our chunks back into a Header object, then let that\n                # Header object do the right thing to turn them into a\n                # string for us.\n                value.append(str(email.header.make_header(chunks)))\n            # This is already a string, so just add it.\n            else:\n                value.append(h)\n\n        # We've processed all of our values to get them into a list of str,\n        # but we may have mojibake data, in which case this is an unparsed\n        # field.\n        if not valid_encoding:\n            unparsed[name] = value\n            continue\n\n        raw_name = _EMAIL_TO_RAW_MAPPING.get(name)\n        if raw_name is None:\n            # This is a bit of a weird situation, we've encountered a key that\n            # we don't know what it means, so we don't know whether it's meant\n            # to be a list or not.\n            #\n            # Since we can't really tell one way or another, we'll just leave it\n            # as a list, even though it may be a single item list, because that's\n            # what makes the most sense for email headers.\n            unparsed[name] = value\n            continue\n\n        # If this is one of our string fields, then we'll check to see if our\n        # value is a list of a single item. If it is then we'll assume that\n        # it was emitted as a single string, and unwrap the str from inside\n        # the list.\n        #\n        # If it's any other kind of data, then we haven't the faintest clue\n        # what we should parse it as, and we have to just add it to our list\n        # of unparsed stuff.\n        if raw_name in _STRING_FIELDS and len(value) == 1:\n            raw[raw_name] = value[0]\n        # If this is import_names, we need to special case the empty field\n        # case, which converts to an empty list instead of None. We can't let\n        # the empty case slip through, as it will fail validation.\n        elif raw_name == \"import_names\" and value == [\"\"]:\n            raw[raw_name] = []\n        # If this is one of our list of string fields, then we can just assign\n        # the value, since email *only* has strings, and our get_all() call\n        # above ensures that this is a list.\n        elif raw_name in _LIST_FIELDS:\n            raw[raw_name] = value\n        # Special Case: Keywords\n        # The keywords field is implemented in the metadata spec as a str,\n        # but it conceptually is a list of strings, and is serialized using\n        # \", \".join(keywords), so we'll do some light data massaging to turn\n        # this into what it logically is.\n        elif raw_name == \"keywords\" and len(value) == 1:\n            raw[raw_name] = _parse_keywords(value[0])\n        # Special Case: Project-URL\n        # The project urls is implemented in the metadata spec as a list of\n        # specially-formatted strings that represent a key and a value, which\n        # is fundamentally a mapping, however the email format doesn't support\n        # mappings in a sane way, so it was crammed into a list of strings\n        # instead.\n        #\n        # We will do a little light data massaging to turn this into a map as\n        # it logically should be.\n        elif raw_name == \"project_urls\":\n            try:\n                raw[raw_name] = _parse_project_urls(value)\n            except KeyError:\n                unparsed[name] = value\n        # Nothing that we've done has managed to parse this, so it'll just\n        # throw it in our unparsable data and move on.\n        else:\n            unparsed[name] = value\n\n    # We need to support getting the Description from the message payload in\n    # addition to getting it from the the headers. This does mean, though, there\n    # is the possibility of it being set both ways, in which case we put both\n    # in 'unparsed' since we don't know which is right.\n    try:\n        payload = _get_payload(parsed, data)\n    except ValueError:\n        unparsed.setdefault(\"description\", []).append(\n            parsed.get_payload(decode=isinstance(data, bytes))  # type: ignore[call-overload]\n        )\n    else:\n        if payload:\n            # Check to see if we've already got a description, if so then both\n            # it, and this body move to unparsable.\n            if \"description\" in raw:\n                description_header = cast(\"str\", raw.pop(\"description\"))\n                unparsed.setdefault(\"description\", []).extend(\n                    [description_header, payload]\n                )\n            elif \"description\" in unparsed:\n                unparsed[\"description\"].append(payload)\n            else:\n                raw[\"description\"] = payload\n\n    # We need to cast our `raw` to a metadata, because a TypedDict only support\n    # literal key names, but we're computing our key names on purpose, but the\n    # way this function is implemented, our `TypedDict` can only have valid key\n    # names.\n    return cast(\"RawMetadata\", raw), unparsed\n\n\n_NOT_FOUND = object()\n\n\n# Keep the two values in sync.\n_VALID_METADATA_VERSIONS = [\"1.0\", \"1.1\", \"1.2\", \"2.1\", \"2.2\", \"2.3\", \"2.4\", \"2.5\"]\n_MetadataVersion = Literal[\"1.0\", \"1.1\", \"1.2\", \"2.1\", \"2.2\", \"2.3\", \"2.4\", \"2.5\"]\n\n_REQUIRED_ATTRS = frozenset([\"metadata_version\", \"name\", \"version\"])\n\n\nclass _Validator(Generic[T]):\n    \"\"\"Validate a metadata field.\n\n    All _process_*() methods correspond to a core metadata field. The method is\n    called with the field's raw value. If the raw value is valid it is returned\n    in its \"enriched\" form (e.g. ``version.Version`` for the ``Version`` field).\n    If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause\n    as appropriate).\n    \"\"\"\n\n    name: str\n    raw_name: str\n    added: _MetadataVersion\n\n    def __init__(\n        self,\n        *,\n        added: _MetadataVersion = \"1.0\",\n    ) -> None:\n        self.added = added\n\n    def __set_name__(self, _owner: Metadata, name: str) -> None:\n        self.name = name\n        self.raw_name = _RAW_TO_EMAIL_MAPPING[name]\n\n    def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:\n        # With Python 3.8, the caching can be replaced with functools.cached_property().\n        # No need to check the cache as attribute lookup will resolve into the\n        # instance's __dict__ before __get__ is called.\n        cache = instance.__dict__\n        value = instance._raw.get(self.name)\n\n        # To make the _process_* methods easier, we'll check if the value is None\n        # and if this field is NOT a required attribute, and if both of those\n        # things are true, we'll skip the the converter. This will mean that the\n        # converters never have to deal with the None union.\n        if self.name in _REQUIRED_ATTRS or value is not None:\n            try:\n                converter: Callable[[Any], T] = getattr(self, f\"_process_{self.name}\")\n            except AttributeError:\n                pass\n            else:\n                value = converter(value)\n\n        cache[self.name] = value\n        try:\n            del instance._raw[self.name]  # type: ignore[misc]\n        except KeyError:\n            pass\n\n        return cast(\"T\", value)\n\n    def _invalid_metadata(\n        self, msg: str, cause: Exception | None = None\n    ) -> InvalidMetadata:\n        exc = InvalidMetadata(\n            self.raw_name, msg.format_map({\"field\": repr(self.raw_name)})\n        )\n        exc.__cause__ = cause\n        return exc\n\n    def _process_metadata_version(self, value: str) -> _MetadataVersion:\n        # Implicitly makes Metadata-Version required.\n        if value not in _VALID_METADATA_VERSIONS:\n            raise self._invalid_metadata(f\"{value!r} is not a valid metadata version\")\n        return cast(\"_MetadataVersion\", value)\n\n    def _process_name(self, value: str) -> str:\n        if not value:\n            raise self._invalid_metadata(\"{field} is a required field\")\n        # Validate the name as a side-effect.\n        try:\n            utils.canonicalize_name(value, validate=True)\n        except utils.InvalidName as exc:\n            raise self._invalid_metadata(\n                f\"{value!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n        else:\n            return value\n\n    def _process_version(self, value: str) -> version_module.Version:\n        if not value:\n            raise self._invalid_metadata(\"{field} is a required field\")\n        try:\n            return version_module.parse(value)\n        except version_module.InvalidVersion as exc:\n            raise self._invalid_metadata(\n                f\"{value!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n\n    def _process_summary(self, value: str) -> str:\n        \"\"\"Check the field contains no newlines.\"\"\"\n        if \"\\n\" in value:\n            raise self._invalid_metadata(\"{field} must be a single line\")\n        return value\n\n    def _process_description_content_type(self, value: str) -> str:\n        content_types = {\"text/plain\", \"text/x-rst\", \"text/markdown\"}\n        message = email.message.EmailMessage()\n        message[\"content-type\"] = value\n\n        content_type, parameters = (\n            # Defaults to `text/plain` if parsing failed.\n            message.get_content_type().lower(),\n            message[\"content-type\"].params,\n        )\n        # Check if content-type is valid or defaulted to `text/plain` and thus was\n        # not parseable.\n        if content_type not in content_types or content_type not in value.lower():\n            raise self._invalid_metadata(\n                f\"{{field}} must be one of {list(content_types)}, not {value!r}\"\n            )\n\n        charset = parameters.get(\"charset\", \"UTF-8\")\n        if charset != \"UTF-8\":\n            raise self._invalid_metadata(\n                f\"{{field}} can only specify the UTF-8 charset, not {list(charset)}\"\n            )\n\n        markdown_variants = {\"GFM\", \"CommonMark\"}\n        variant = parameters.get(\"variant\", \"GFM\")  # Use an acceptable default.\n        if content_type == \"text/markdown\" and variant not in markdown_variants:\n            raise self._invalid_metadata(\n                f\"valid Markdown variants for {{field}} are {list(markdown_variants)}, \"\n                f\"not {variant!r}\",\n            )\n        return value\n\n    def _process_dynamic(self, value: list[str]) -> list[str]:\n        for dynamic_field in map(str.lower, value):\n            if dynamic_field in {\"name\", \"version\", \"metadata-version\"}:\n                raise self._invalid_metadata(\n                    f\"{dynamic_field!r} is not allowed as a dynamic field\"\n                )\n            elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:\n                raise self._invalid_metadata(\n                    f\"{dynamic_field!r} is not a valid dynamic field\"\n                )\n        return list(map(str.lower, value))\n\n    def _process_provides_extra(\n        self,\n        value: list[str],\n    ) -> list[utils.NormalizedName]:\n        normalized_names = []\n        try:\n            for name in value:\n                normalized_names.append(utils.canonicalize_name(name, validate=True))\n        except utils.InvalidName as exc:\n            raise self._invalid_metadata(\n                f\"{name!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n        else:\n            return normalized_names\n\n    def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:\n        try:\n            return specifiers.SpecifierSet(value)\n        except specifiers.InvalidSpecifier as exc:\n            raise self._invalid_metadata(\n                f\"{value!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n\n    def _process_requires_dist(\n        self,\n        value: list[str],\n    ) -> list[requirements.Requirement]:\n        reqs = []\n        try:\n            for req in value:\n                reqs.append(requirements.Requirement(req))\n        except requirements.InvalidRequirement as exc:\n            raise self._invalid_metadata(\n                f\"{req!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n        else:\n            return reqs\n\n    def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:\n        try:\n            return licenses.canonicalize_license_expression(value)\n        except ValueError as exc:\n            raise self._invalid_metadata(\n                f\"{value!r} is invalid for {{field}}\", cause=exc\n            ) from exc\n\n    def _process_license_files(self, value: list[str]) -> list[str]:\n        paths = []\n        for path in value:\n            if \"..\" in path:\n                raise self._invalid_metadata(\n                    f\"{path!r} is invalid for {{field}}, \"\n                    \"parent directory indicators are not allowed\"\n                )\n            if \"*\" in path:\n                raise self._invalid_metadata(\n                    f\"{path!r} is invalid for {{field}}, paths must be resolved\"\n                )\n            if (\n                pathlib.PurePosixPath(path).is_absolute()\n                or pathlib.PureWindowsPath(path).is_absolute()\n            ):\n                raise self._invalid_metadata(\n                    f\"{path!r} is invalid for {{field}}, paths must be relative\"\n                )\n            if pathlib.PureWindowsPath(path).as_posix() != path:\n                raise self._invalid_metadata(\n                    f\"{path!r} is invalid for {{field}}, paths must use '/' delimiter\"\n                )\n            paths.append(path)\n        return paths\n\n    def _process_import_names(self, value: list[str]) -> list[str]:\n        for import_name in value:\n            name, semicolon, private = import_name.partition(\";\")\n            name = name.rstrip()\n            for identifier in name.split(\".\"):\n                if not identifier.isidentifier():\n                    raise self._invalid_metadata(\n                        f\"{name!r} is invalid for {{field}}; \"\n                        f\"{identifier!r} is not a valid identifier\"\n                    )\n                elif keyword.iskeyword(identifier):\n                    raise self._invalid_metadata(\n                        f\"{name!r} is invalid for {{field}}; \"\n                        f\"{identifier!r} is a keyword\"\n                    )\n            if semicolon and private.lstrip() != \"private\":\n                raise self._invalid_metadata(\n                    f\"{import_name!r} is invalid for {{field}}; \"\n                    \"the only valid option is 'private'\"\n                )\n        return value\n\n    _process_import_namespaces = _process_import_names\n\n\nclass Metadata:\n    \"\"\"Representation of distribution metadata.\n\n    Compared to :class:`RawMetadata`, this class provides objects representing\n    metadata fields instead of only using built-in types. Any invalid metadata\n    will cause :exc:`InvalidMetadata` to be raised (with a\n    :py:attr:`~BaseException.__cause__` attribute as appropriate).\n    \"\"\"\n\n    _raw: RawMetadata\n\n    @classmethod\n    def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:\n        \"\"\"Create an instance from :class:`RawMetadata`.\n\n        If *validate* is true, all metadata will be validated. All exceptions\n        related to validation will be gathered and raised as an :class:`ExceptionGroup`.\n        \"\"\"\n        ins = cls()\n        ins._raw = data.copy()  # Mutations occur due to caching enriched values.\n\n        if validate:\n            exceptions: list[Exception] = []\n            try:\n                metadata_version = ins.metadata_version\n                metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)\n            except InvalidMetadata as metadata_version_exc:\n                exceptions.append(metadata_version_exc)\n                metadata_version = None\n\n            # Make sure to check for the fields that are present, the required\n            # fields (so their absence can be reported).\n            fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS\n            # Remove fields that have already been checked.\n            fields_to_check -= {\"metadata_version\"}\n\n            for key in fields_to_check:\n                try:\n                    if metadata_version:\n                        # Can't use getattr() as that triggers descriptor protocol which\n                        # will fail due to no value for the instance argument.\n                        try:\n                            field_metadata_version = cls.__dict__[key].added\n                        except KeyError:\n                            exc = InvalidMetadata(key, f\"unrecognized field: {key!r}\")\n                            exceptions.append(exc)\n                            continue\n                        field_age = _VALID_METADATA_VERSIONS.index(\n                            field_metadata_version\n                        )\n                        if field_age > metadata_age:\n                            field = _RAW_TO_EMAIL_MAPPING[key]\n                            exc = InvalidMetadata(\n                                field,\n                                f\"{field} introduced in metadata version \"\n                                f\"{field_metadata_version}, not {metadata_version}\",\n                            )\n                            exceptions.append(exc)\n                            continue\n                    getattr(ins, key)\n                except InvalidMetadata as exc:\n                    exceptions.append(exc)\n\n            if exceptions:\n                raise ExceptionGroup(\"invalid metadata\", exceptions)\n\n        return ins\n\n    @classmethod\n    def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:\n        \"\"\"Parse metadata from email headers.\n\n        If *validate* is true, the metadata will be validated. All exceptions\n        related to validation will be gathered and raised as an :class:`ExceptionGroup`.\n        \"\"\"\n        raw, unparsed = parse_email(data)\n\n        if validate:\n            exceptions: list[Exception] = []\n            for unparsed_key in unparsed:\n                if unparsed_key in _EMAIL_TO_RAW_MAPPING:\n                    message = f\"{unparsed_key!r} has invalid data\"\n                else:\n                    message = f\"unrecognized field: {unparsed_key!r}\"\n                exceptions.append(InvalidMetadata(unparsed_key, message))\n\n            if exceptions:\n                raise ExceptionGroup(\"unparsed\", exceptions)\n\n        try:\n            return cls.from_raw(raw, validate=validate)\n        except ExceptionGroup as exc_group:\n            raise ExceptionGroup(\n                \"invalid or unparsed metadata\", exc_group.exceptions\n            ) from None\n\n    metadata_version: _Validator[_MetadataVersion] = _Validator()\n    \"\"\":external:ref:`core-metadata-metadata-version`\n    (required; validated to be a valid metadata version)\"\"\"\n    # `name` is not normalized/typed to NormalizedName so as to provide access to\n    # the original/raw name.\n    name: _Validator[str] = _Validator()\n    \"\"\":external:ref:`core-metadata-name`\n    (required; validated using :func:`~packaging.utils.canonicalize_name` and its\n    *validate* parameter)\"\"\"\n    version: _Validator[version_module.Version] = _Validator()\n    \"\"\":external:ref:`core-metadata-version` (required)\"\"\"\n    dynamic: _Validator[list[str] | None] = _Validator(\n        added=\"2.2\",\n    )\n    \"\"\":external:ref:`core-metadata-dynamic`\n    (validated against core metadata field names and lowercased)\"\"\"\n    platforms: _Validator[list[str] | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-platform`\"\"\"\n    supported_platforms: _Validator[list[str] | None] = _Validator(added=\"1.1\")\n    \"\"\":external:ref:`core-metadata-supported-platform`\"\"\"\n    summary: _Validator[str | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-summary` (validated to contain no newlines)\"\"\"\n    description: _Validator[str | None] = _Validator()  # TODO 2.1: can be in body\n    \"\"\":external:ref:`core-metadata-description`\"\"\"\n    description_content_type: _Validator[str | None] = _Validator(added=\"2.1\")\n    \"\"\":external:ref:`core-metadata-description-content-type` (validated)\"\"\"\n    keywords: _Validator[list[str] | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-keywords`\"\"\"\n    home_page: _Validator[str | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-home-page`\"\"\"\n    download_url: _Validator[str | None] = _Validator(added=\"1.1\")\n    \"\"\":external:ref:`core-metadata-download-url`\"\"\"\n    author: _Validator[str | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-author`\"\"\"\n    author_email: _Validator[str | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-author-email`\"\"\"\n    maintainer: _Validator[str | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-maintainer`\"\"\"\n    maintainer_email: _Validator[str | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-maintainer-email`\"\"\"\n    license: _Validator[str | None] = _Validator()\n    \"\"\":external:ref:`core-metadata-license`\"\"\"\n    license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(\n        added=\"2.4\"\n    )\n    \"\"\":external:ref:`core-metadata-license-expression`\"\"\"\n    license_files: _Validator[list[str] | None] = _Validator(added=\"2.4\")\n    \"\"\":external:ref:`core-metadata-license-file`\"\"\"\n    classifiers: _Validator[list[str] | None] = _Validator(added=\"1.1\")\n    \"\"\":external:ref:`core-metadata-classifier`\"\"\"\n    requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(\n        added=\"1.2\"\n    )\n    \"\"\":external:ref:`core-metadata-requires-dist`\"\"\"\n    requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(\n        added=\"1.2\"\n    )\n    \"\"\":external:ref:`core-metadata-requires-python`\"\"\"\n    # Because `Requires-External` allows for non-PEP 440 version specifiers, we\n    # don't do any processing on the values.\n    requires_external: _Validator[list[str] | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-requires-external`\"\"\"\n    project_urls: _Validator[dict[str, str] | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-project-url`\"\"\"\n    # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation\n    # regardless of metadata version.\n    provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(\n        added=\"2.1\",\n    )\n    \"\"\":external:ref:`core-metadata-provides-extra`\"\"\"\n    provides_dist: _Validator[list[str] | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-provides-dist`\"\"\"\n    obsoletes_dist: _Validator[list[str] | None] = _Validator(added=\"1.2\")\n    \"\"\":external:ref:`core-metadata-obsoletes-dist`\"\"\"\n    import_names: _Validator[list[str] | None] = _Validator(added=\"2.5\")\n    \"\"\":external:ref:`core-metadata-import-name`\"\"\"\n    import_namespaces: _Validator[list[str] | None] = _Validator(added=\"2.5\")\n    \"\"\":external:ref:`core-metadata-import-namespace`\"\"\"\n    requires: _Validator[list[str] | None] = _Validator(added=\"1.1\")\n    \"\"\"``Requires`` (deprecated)\"\"\"\n    provides: _Validator[list[str] | None] = _Validator(added=\"1.1\")\n    \"\"\"``Provides`` (deprecated)\"\"\"\n    obsoletes: _Validator[list[str] | None] = _Validator(added=\"1.1\")\n    \"\"\"``Obsoletes`` (deprecated)\"\"\"\n\n    def as_rfc822(self) -> RFC822Message:\n        \"\"\"\n        Return an RFC822 message with the metadata.\n        \"\"\"\n        message = RFC822Message()\n        self._write_metadata(message)\n        return message\n\n    def _write_metadata(self, message: RFC822Message) -> None:\n        \"\"\"\n        Return an RFC822 message with the metadata.\n        \"\"\"\n        for name, validator in self.__class__.__dict__.items():\n            if isinstance(validator, _Validator) and name != \"description\":\n                value = getattr(self, name)\n                email_name = _RAW_TO_EMAIL_MAPPING[name]\n                if value is not None:\n                    if email_name == \"project-url\":\n                        for label, url in value.items():\n                            message[email_name] = f\"{label}, {url}\"\n                    elif email_name == \"keywords\":\n                        message[email_name] = \",\".join(value)\n                    elif email_name == \"import-name\" and value == []:\n                        message[email_name] = \"\"\n                    elif isinstance(value, list):\n                        for item in value:\n                            message[email_name] = str(item)\n                    else:\n                        message[email_name] = str(value)\n\n        # The description is a special case because it is in the body of the message.\n        if self.description is not None:\n            message.set_payload(self.description)\n"
  },
  {
    "path": "src/pip/_vendor/packaging/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/packaging/pylock.py",
    "content": "from __future__ import annotations\n\nimport dataclasses\nimport logging\nimport re\nfrom collections.abc import Mapping, Sequence\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Protocol,\n    TypeVar,\n)\n\nfrom .markers import Marker\nfrom .specifiers import SpecifierSet\nfrom .utils import NormalizedName, is_normalized_name\nfrom .version import Version\n\nif TYPE_CHECKING:  # pragma: no cover\n    from pathlib import Path\n\n    from typing_extensions import Self\n\n_logger = logging.getLogger(__name__)\n\n__all__ = [\n    \"Package\",\n    \"PackageArchive\",\n    \"PackageDirectory\",\n    \"PackageSdist\",\n    \"PackageVcs\",\n    \"PackageWheel\",\n    \"Pylock\",\n    \"PylockUnsupportedVersionError\",\n    \"PylockValidationError\",\n    \"is_valid_pylock_path\",\n]\n\n_T = TypeVar(\"_T\")\n_T2 = TypeVar(\"_T2\")\n\n\nclass _FromMappingProtocol(Protocol):  # pragma: no cover\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...\n\n\n_FromMappingProtocolT = TypeVar(\"_FromMappingProtocolT\", bound=_FromMappingProtocol)\n\n\n_PYLOCK_FILE_NAME_RE = re.compile(r\"^pylock\\.([^.]+)\\.toml$\")\n\n\ndef is_valid_pylock_path(path: Path) -> bool:\n    \"\"\"Check if the given path is a valid pylock file path.\"\"\"\n    return path.name == \"pylock.toml\" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))\n\n\ndef _toml_key(key: str) -> str:\n    return key.replace(\"_\", \"-\")\n\n\ndef _toml_value(key: str, value: Any) -> Any:  # noqa: ANN401\n    if isinstance(value, (Version, Marker, SpecifierSet)):\n        return str(value)\n    if isinstance(value, Sequence) and key == \"environments\":\n        return [str(v) for v in value]\n    return value\n\n\ndef _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:\n    return {\n        _toml_key(key): _toml_value(key, value)\n        for key, value in data\n        if value is not None\n    }\n\n\ndef _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:\n    \"\"\"Get a value from the dictionary and verify it's the expected type.\"\"\"\n    if (value := d.get(key)) is None:\n        return None\n    if not isinstance(value, expected_type):\n        raise PylockValidationError(\n            f\"Unexpected type {type(value).__name__} \"\n            f\"(expected {expected_type.__name__})\",\n            context=key,\n        )\n    return value\n\n\ndef _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:\n    \"\"\"Get a required value from the dictionary and verify it's the expected type.\"\"\"\n    if (value := _get(d, expected_type, key)) is None:\n        raise _PylockRequiredKeyError(key)\n    return value\n\n\ndef _get_sequence(\n    d: Mapping[str, Any], expected_item_type: type[_T], key: str\n) -> Sequence[_T] | None:\n    \"\"\"Get a list value from the dictionary and verify it's the expected items type.\"\"\"\n    if (value := _get(d, Sequence, key)) is None:  # type: ignore[type-abstract]\n        return None\n    if isinstance(value, (str, bytes)):\n        # special case: str and bytes are Sequences, but we want to reject it\n        raise PylockValidationError(\n            f\"Unexpected type {type(value).__name__} (expected Sequence)\",\n            context=key,\n        )\n    for i, item in enumerate(value):\n        if not isinstance(item, expected_item_type):\n            raise PylockValidationError(\n                f\"Unexpected type {type(item).__name__} \"\n                f\"(expected {expected_item_type.__name__})\",\n                context=f\"{key}[{i}]\",\n            )\n    return value\n\n\ndef _get_as(\n    d: Mapping[str, Any],\n    expected_type: type[_T],\n    target_type: Callable[[_T], _T2],\n    key: str,\n) -> _T2 | None:\n    \"\"\"Get a value from the dictionary, verify it's the expected type,\n    and convert to the target type.\n\n    This assumes the target_type constructor accepts the value.\n    \"\"\"\n    if (value := _get(d, expected_type, key)) is None:\n        return None\n    try:\n        return target_type(value)\n    except Exception as e:\n        raise PylockValidationError(e, context=key) from e\n\n\ndef _get_required_as(\n    d: Mapping[str, Any],\n    expected_type: type[_T],\n    target_type: Callable[[_T], _T2],\n    key: str,\n) -> _T2:\n    \"\"\"Get a required value from the dict, verify it's the expected type,\n    and convert to the target type.\"\"\"\n    if (value := _get_as(d, expected_type, target_type, key)) is None:\n        raise _PylockRequiredKeyError(key)\n    return value\n\n\ndef _get_sequence_as(\n    d: Mapping[str, Any],\n    expected_item_type: type[_T],\n    target_item_type: Callable[[_T], _T2],\n    key: str,\n) -> list[_T2] | None:\n    \"\"\"Get list value from dictionary and verify expected items type.\"\"\"\n    if (value := _get_sequence(d, expected_item_type, key)) is None:\n        return None\n    result = []\n    try:\n        for item in value:\n            typed_item = target_item_type(item)\n            result.append(typed_item)\n    except Exception as e:\n        raise PylockValidationError(e, context=f\"{key}[{len(result)}]\") from e\n    return result\n\n\ndef _get_object(\n    d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str\n) -> _FromMappingProtocolT | None:\n    \"\"\"Get a dictionary value from the dictionary and convert it to a dataclass.\"\"\"\n    if (value := _get(d, Mapping, key)) is None:  # type: ignore[type-abstract]\n        return None\n    try:\n        return target_type._from_dict(value)\n    except Exception as e:\n        raise PylockValidationError(e, context=key) from e\n\n\ndef _get_sequence_of_objects(\n    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str\n) -> list[_FromMappingProtocolT] | None:\n    \"\"\"Get a list value from the dictionary and convert its items to a dataclass.\"\"\"\n    if (value := _get_sequence(d, Mapping, key)) is None:  # type: ignore[type-abstract]\n        return None\n    result: list[_FromMappingProtocolT] = []\n    try:\n        for item in value:\n            typed_item = target_item_type._from_dict(item)\n            result.append(typed_item)\n    except Exception as e:\n        raise PylockValidationError(e, context=f\"{key}[{len(result)}]\") from e\n    return result\n\n\ndef _get_required_sequence_of_objects(\n    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str\n) -> Sequence[_FromMappingProtocolT]:\n    \"\"\"Get a required list value from the dictionary and convert its items to a\n    dataclass.\"\"\"\n    if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:\n        raise _PylockRequiredKeyError(key)\n    return result\n\n\ndef _validate_normalized_name(name: str) -> NormalizedName:\n    \"\"\"Validate that a string is a NormalizedName.\"\"\"\n    if not is_normalized_name(name):\n        raise PylockValidationError(f\"Name {name!r} is not normalized\")\n    return NormalizedName(name)\n\n\ndef _validate_path_url(path: str | None, url: str | None) -> None:\n    if not path and not url:\n        raise PylockValidationError(\"path or url must be provided\")\n\n\ndef _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:\n    if not hashes:\n        raise PylockValidationError(\"At least one hash must be provided\")\n    if not all(isinstance(hash_val, str) for hash_val in hashes.values()):\n        raise PylockValidationError(\"Hash values must be strings\")\n    return hashes\n\n\nclass PylockValidationError(Exception):\n    \"\"\"Raised when when input data is not spec-compliant.\"\"\"\n\n    context: str | None = None\n    message: str\n\n    def __init__(\n        self,\n        cause: str | Exception,\n        *,\n        context: str | None = None,\n    ) -> None:\n        if isinstance(cause, PylockValidationError):\n            if cause.context:\n                self.context = (\n                    f\"{context}.{cause.context}\" if context else cause.context\n                )\n            else:\n                self.context = context\n            self.message = cause.message\n        else:\n            self.context = context\n            self.message = str(cause)\n\n    def __str__(self) -> str:\n        if self.context:\n            return f\"{self.message} in {self.context!r}\"\n        return self.message\n\n\nclass _PylockRequiredKeyError(PylockValidationError):\n    def __init__(self, key: str) -> None:\n        super().__init__(\"Missing required value\", context=key)\n\n\nclass PylockUnsupportedVersionError(PylockValidationError):\n    \"\"\"Raised when encountering an unsupported `lock_version`.\"\"\"\n\n\n@dataclass(frozen=True, init=False)\nclass PackageVcs:\n    type: str\n    url: str | None = None\n    path: str | None = None\n    requested_revision: str | None = None\n    commit_id: str  # type: ignore[misc]\n    subdirectory: str | None = None\n\n    def __init__(\n        self,\n        *,\n        type: str,\n        url: str | None = None,\n        path: str | None = None,\n        requested_revision: str | None = None,\n        commit_id: str,\n        subdirectory: str | None = None,\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"type\", type)\n        object.__setattr__(self, \"url\", url)\n        object.__setattr__(self, \"path\", path)\n        object.__setattr__(self, \"requested_revision\", requested_revision)\n        object.__setattr__(self, \"commit_id\", commit_id)\n        object.__setattr__(self, \"subdirectory\", subdirectory)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        package_vcs = cls(\n            type=_get_required(d, str, \"type\"),\n            url=_get(d, str, \"url\"),\n            path=_get(d, str, \"path\"),\n            requested_revision=_get(d, str, \"requested-revision\"),\n            commit_id=_get_required(d, str, \"commit-id\"),\n            subdirectory=_get(d, str, \"subdirectory\"),\n        )\n        _validate_path_url(package_vcs.path, package_vcs.url)\n        return package_vcs\n\n\n@dataclass(frozen=True, init=False)\nclass PackageDirectory:\n    path: str\n    editable: bool | None = None\n    subdirectory: str | None = None\n\n    def __init__(\n        self,\n        *,\n        path: str,\n        editable: bool | None = None,\n        subdirectory: str | None = None,\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"path\", path)\n        object.__setattr__(self, \"editable\", editable)\n        object.__setattr__(self, \"subdirectory\", subdirectory)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        return cls(\n            path=_get_required(d, str, \"path\"),\n            editable=_get(d, bool, \"editable\"),\n            subdirectory=_get(d, str, \"subdirectory\"),\n        )\n\n\n@dataclass(frozen=True, init=False)\nclass PackageArchive:\n    url: str | None = None\n    path: str | None = None\n    size: int | None = None\n    upload_time: datetime | None = None\n    hashes: Mapping[str, str]  # type: ignore[misc]\n    subdirectory: str | None = None\n\n    def __init__(\n        self,\n        *,\n        url: str | None = None,\n        path: str | None = None,\n        size: int | None = None,\n        upload_time: datetime | None = None,\n        hashes: Mapping[str, str],\n        subdirectory: str | None = None,\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"url\", url)\n        object.__setattr__(self, \"path\", path)\n        object.__setattr__(self, \"size\", size)\n        object.__setattr__(self, \"upload_time\", upload_time)\n        object.__setattr__(self, \"hashes\", hashes)\n        object.__setattr__(self, \"subdirectory\", subdirectory)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        package_archive = cls(\n            url=_get(d, str, \"url\"),\n            path=_get(d, str, \"path\"),\n            size=_get(d, int, \"size\"),\n            upload_time=_get(d, datetime, \"upload-time\"),\n            hashes=_get_required_as(d, Mapping, _validate_hashes, \"hashes\"),  # type: ignore[type-abstract]\n            subdirectory=_get(d, str, \"subdirectory\"),\n        )\n        _validate_path_url(package_archive.path, package_archive.url)\n        return package_archive\n\n\n@dataclass(frozen=True, init=False)\nclass PackageSdist:\n    name: str | None = None\n    upload_time: datetime | None = None\n    url: str | None = None\n    path: str | None = None\n    size: int | None = None\n    hashes: Mapping[str, str]  # type: ignore[misc]\n\n    def __init__(\n        self,\n        *,\n        name: str | None = None,\n        upload_time: datetime | None = None,\n        url: str | None = None,\n        path: str | None = None,\n        size: int | None = None,\n        hashes: Mapping[str, str],\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"name\", name)\n        object.__setattr__(self, \"upload_time\", upload_time)\n        object.__setattr__(self, \"url\", url)\n        object.__setattr__(self, \"path\", path)\n        object.__setattr__(self, \"size\", size)\n        object.__setattr__(self, \"hashes\", hashes)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        package_sdist = cls(\n            name=_get(d, str, \"name\"),\n            upload_time=_get(d, datetime, \"upload-time\"),\n            url=_get(d, str, \"url\"),\n            path=_get(d, str, \"path\"),\n            size=_get(d, int, \"size\"),\n            hashes=_get_required_as(d, Mapping, _validate_hashes, \"hashes\"),  # type: ignore[type-abstract]\n        )\n        _validate_path_url(package_sdist.path, package_sdist.url)\n        return package_sdist\n\n\n@dataclass(frozen=True, init=False)\nclass PackageWheel:\n    name: str | None = None\n    upload_time: datetime | None = None\n    url: str | None = None\n    path: str | None = None\n    size: int | None = None\n    hashes: Mapping[str, str]  # type: ignore[misc]\n\n    def __init__(\n        self,\n        *,\n        name: str | None = None,\n        upload_time: datetime | None = None,\n        url: str | None = None,\n        path: str | None = None,\n        size: int | None = None,\n        hashes: Mapping[str, str],\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"name\", name)\n        object.__setattr__(self, \"upload_time\", upload_time)\n        object.__setattr__(self, \"url\", url)\n        object.__setattr__(self, \"path\", path)\n        object.__setattr__(self, \"size\", size)\n        object.__setattr__(self, \"hashes\", hashes)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        package_wheel = cls(\n            name=_get(d, str, \"name\"),\n            upload_time=_get(d, datetime, \"upload-time\"),\n            url=_get(d, str, \"url\"),\n            path=_get(d, str, \"path\"),\n            size=_get(d, int, \"size\"),\n            hashes=_get_required_as(d, Mapping, _validate_hashes, \"hashes\"),  # type: ignore[type-abstract]\n        )\n        _validate_path_url(package_wheel.path, package_wheel.url)\n        return package_wheel\n\n\n@dataclass(frozen=True, init=False)\nclass Package:\n    name: NormalizedName\n    version: Version | None = None\n    marker: Marker | None = None\n    requires_python: SpecifierSet | None = None\n    dependencies: Sequence[Mapping[str, Any]] | None = None\n    vcs: PackageVcs | None = None\n    directory: PackageDirectory | None = None\n    archive: PackageArchive | None = None\n    index: str | None = None\n    sdist: PackageSdist | None = None\n    wheels: Sequence[PackageWheel] | None = None\n    attestation_identities: Sequence[Mapping[str, Any]] | None = None\n    tool: Mapping[str, Any] | None = None\n\n    def __init__(\n        self,\n        *,\n        name: NormalizedName,\n        version: Version | None = None,\n        marker: Marker | None = None,\n        requires_python: SpecifierSet | None = None,\n        dependencies: Sequence[Mapping[str, Any]] | None = None,\n        vcs: PackageVcs | None = None,\n        directory: PackageDirectory | None = None,\n        archive: PackageArchive | None = None,\n        index: str | None = None,\n        sdist: PackageSdist | None = None,\n        wheels: Sequence[PackageWheel] | None = None,\n        attestation_identities: Sequence[Mapping[str, Any]] | None = None,\n        tool: Mapping[str, Any] | None = None,\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"name\", name)\n        object.__setattr__(self, \"version\", version)\n        object.__setattr__(self, \"marker\", marker)\n        object.__setattr__(self, \"requires_python\", requires_python)\n        object.__setattr__(self, \"dependencies\", dependencies)\n        object.__setattr__(self, \"vcs\", vcs)\n        object.__setattr__(self, \"directory\", directory)\n        object.__setattr__(self, \"archive\", archive)\n        object.__setattr__(self, \"index\", index)\n        object.__setattr__(self, \"sdist\", sdist)\n        object.__setattr__(self, \"wheels\", wheels)\n        object.__setattr__(self, \"attestation_identities\", attestation_identities)\n        object.__setattr__(self, \"tool\", tool)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        package = cls(\n            name=_get_required_as(d, str, _validate_normalized_name, \"name\"),\n            version=_get_as(d, str, Version, \"version\"),\n            requires_python=_get_as(d, str, SpecifierSet, \"requires-python\"),\n            dependencies=_get_sequence(d, Mapping, \"dependencies\"),  # type: ignore[type-abstract]\n            marker=_get_as(d, str, Marker, \"marker\"),\n            vcs=_get_object(d, PackageVcs, \"vcs\"),\n            directory=_get_object(d, PackageDirectory, \"directory\"),\n            archive=_get_object(d, PackageArchive, \"archive\"),\n            index=_get(d, str, \"index\"),\n            sdist=_get_object(d, PackageSdist, \"sdist\"),\n            wheels=_get_sequence_of_objects(d, PackageWheel, \"wheels\"),\n            attestation_identities=_get_sequence(d, Mapping, \"attestation-identities\"),  # type: ignore[type-abstract]\n            tool=_get(d, Mapping, \"tool\"),  # type: ignore[type-abstract]\n        )\n        distributions = bool(package.sdist) + len(package.wheels or [])\n        direct_urls = (\n            bool(package.vcs) + bool(package.directory) + bool(package.archive)\n        )\n        if distributions > 0 and direct_urls > 0:\n            raise PylockValidationError(\n                \"None of vcs, directory, archive must be set if sdist or wheels are set\"\n            )\n        if distributions == 0 and direct_urls != 1:\n            raise PylockValidationError(\n                \"Exactly one of vcs, directory, archive must be set \"\n                \"if sdist and wheels are not set\"\n            )\n        try:\n            for i, attestation_identity in enumerate(  # noqa: B007\n                package.attestation_identities or []\n            ):\n                _get_required(attestation_identity, str, \"kind\")\n        except Exception as e:\n            raise PylockValidationError(\n                e, context=f\"attestation-identities[{i}]\"\n            ) from e\n        return package\n\n    @property\n    def is_direct(self) -> bool:\n        return not (self.sdist or self.wheels)\n\n\n@dataclass(frozen=True, init=False)\nclass Pylock:\n    \"\"\"A class representing a pylock file.\"\"\"\n\n    lock_version: Version\n    environments: Sequence[Marker] | None = None\n    requires_python: SpecifierSet | None = None\n    extras: Sequence[NormalizedName] | None = None\n    dependency_groups: Sequence[str] | None = None\n    default_groups: Sequence[str] | None = None\n    created_by: str  # type: ignore[misc]\n    packages: Sequence[Package]  # type: ignore[misc]\n    tool: Mapping[str, Any] | None = None\n\n    def __init__(\n        self,\n        *,\n        lock_version: Version,\n        environments: Sequence[Marker] | None = None,\n        requires_python: SpecifierSet | None = None,\n        extras: Sequence[NormalizedName] | None = None,\n        dependency_groups: Sequence[str] | None = None,\n        default_groups: Sequence[str] | None = None,\n        created_by: str,\n        packages: Sequence[Package],\n        tool: Mapping[str, Any] | None = None,\n    ) -> None:\n        # In Python 3.10+ make dataclass kw_only=True and remove __init__\n        object.__setattr__(self, \"lock_version\", lock_version)\n        object.__setattr__(self, \"environments\", environments)\n        object.__setattr__(self, \"requires_python\", requires_python)\n        object.__setattr__(self, \"extras\", extras)\n        object.__setattr__(self, \"dependency_groups\", dependency_groups)\n        object.__setattr__(self, \"default_groups\", default_groups)\n        object.__setattr__(self, \"created_by\", created_by)\n        object.__setattr__(self, \"packages\", packages)\n        object.__setattr__(self, \"tool\", tool)\n\n    @classmethod\n    def _from_dict(cls, d: Mapping[str, Any]) -> Self:\n        pylock = cls(\n            lock_version=_get_required_as(d, str, Version, \"lock-version\"),\n            environments=_get_sequence_as(d, str, Marker, \"environments\"),\n            extras=_get_sequence_as(d, str, _validate_normalized_name, \"extras\"),\n            dependency_groups=_get_sequence(d, str, \"dependency-groups\"),\n            default_groups=_get_sequence(d, str, \"default-groups\"),\n            created_by=_get_required(d, str, \"created-by\"),\n            requires_python=_get_as(d, str, SpecifierSet, \"requires-python\"),\n            packages=_get_required_sequence_of_objects(d, Package, \"packages\"),\n            tool=_get(d, Mapping, \"tool\"),  # type: ignore[type-abstract]\n        )\n        if not Version(\"1\") <= pylock.lock_version < Version(\"2\"):\n            raise PylockUnsupportedVersionError(\n                f\"pylock version {pylock.lock_version} is not supported\"\n            )\n        if pylock.lock_version > Version(\"1.0\"):\n            _logger.warning(\n                \"pylock minor version %s is not supported\", pylock.lock_version\n            )\n        return pylock\n\n    @classmethod\n    def from_dict(cls, d: Mapping[str, Any], /) -> Self:\n        \"\"\"Create and validate a Pylock instance from a TOML dictionary.\n\n        Raises :class:`PylockValidationError` if the input data is not\n        spec-compliant.\n        \"\"\"\n        return cls._from_dict(d)\n\n    def to_dict(self) -> Mapping[str, Any]:\n        \"\"\"Convert the Pylock instance to a TOML dictionary.\"\"\"\n        return dataclasses.asdict(self, dict_factory=_toml_dict_factory)\n\n    def validate(self) -> None:\n        \"\"\"Validate the Pylock instance against the specification.\n\n        Raises :class:`PylockValidationError` otherwise.\"\"\"\n        self.from_dict(self.to_dict())\n"
  },
  {
    "path": "src/pip/_vendor/packaging/requirements.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\nfrom __future__ import annotations\n\nfrom typing import Iterator\n\nfrom ._parser import parse_requirement as _parse_requirement\nfrom ._tokenizer import ParserSyntaxError\nfrom .markers import Marker, _normalize_extra_values\nfrom .specifiers import SpecifierSet\nfrom .utils import canonicalize_name\n\n\nclass InvalidRequirement(ValueError):\n    \"\"\"\n    An invalid requirement was found, users should refer to PEP 508.\n    \"\"\"\n\n\nclass Requirement:\n    \"\"\"Parse a requirement.\n\n    Parse a given requirement string into its parts, such as name, specifier,\n    URL, and extras. Raises InvalidRequirement on a badly-formed requirement\n    string.\n    \"\"\"\n\n    # TODO: Can we test whether something is contained within a requirement?\n    #       If so how do we do that? Do we need to test against the _name_ of\n    #       the thing as well as the version? What about the markers?\n    # TODO: Can we normalize the name and extra name?\n\n    def __init__(self, requirement_string: str) -> None:\n        try:\n            parsed = _parse_requirement(requirement_string)\n        except ParserSyntaxError as e:\n            raise InvalidRequirement(str(e)) from e\n\n        self.name: str = parsed.name\n        self.url: str | None = parsed.url or None\n        self.extras: set[str] = set(parsed.extras or [])\n        self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)\n        self.marker: Marker | None = None\n        if parsed.marker is not None:\n            self.marker = Marker.__new__(Marker)\n            self.marker._markers = _normalize_extra_values(parsed.marker)\n\n    def _iter_parts(self, name: str) -> Iterator[str]:\n        yield name\n\n        if self.extras:\n            formatted_extras = \",\".join(sorted(self.extras))\n            yield f\"[{formatted_extras}]\"\n\n        if self.specifier:\n            yield str(self.specifier)\n\n        if self.url:\n            yield f\" @ {self.url}\"\n            if self.marker:\n                yield \" \"\n\n        if self.marker:\n            yield f\"; {self.marker}\"\n\n    def __str__(self) -> str:\n        return \"\".join(self._iter_parts(self.name))\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}('{self}')>\"\n\n    def __hash__(self) -> int:\n        return hash(tuple(self._iter_parts(canonicalize_name(self.name))))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Requirement):\n            return NotImplemented\n\n        return (\n            canonicalize_name(self.name) == canonicalize_name(other.name)\n            and self.extras == other.extras\n            and self.specifier == other.specifier\n            and self.url == other.url\n            and self.marker == other.marker\n        )\n"
  },
  {
    "path": "src/pip/_vendor/packaging/specifiers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\"\"\"\n.. testsetup::\n\n    from pip._vendor.packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier\n    from pip._vendor.packaging.version import Version\n\"\"\"\n\nfrom __future__ import annotations\n\nimport abc\nimport itertools\nimport re\nfrom typing import Callable, Final, Iterable, Iterator, TypeVar, Union\n\nfrom .utils import canonicalize_version\nfrom .version import InvalidVersion, Version\n\nUnparsedVersion = Union[Version, str]\nUnparsedVersionVar = TypeVar(\"UnparsedVersionVar\", bound=UnparsedVersion)\nCallableOperator = Callable[[Version, str], bool]\n\n\ndef _coerce_version(version: UnparsedVersion) -> Version | None:\n    if not isinstance(version, Version):\n        try:\n            version = Version(version)\n        except InvalidVersion:\n            return None\n    return version\n\n\ndef _public_version(version: Version) -> Version:\n    return version.__replace__(local=None)\n\n\ndef _base_version(version: Version) -> Version:\n    return version.__replace__(pre=None, post=None, dev=None, local=None)\n\n\nclass InvalidSpecifier(ValueError):\n    \"\"\"\n    Raised when attempting to create a :class:`Specifier` with a specifier\n    string that is invalid.\n\n    >>> Specifier(\"lolwat\")\n    Traceback (most recent call last):\n        ...\n    packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'\n    \"\"\"\n\n\nclass BaseSpecifier(metaclass=abc.ABCMeta):\n    __slots__ = ()\n    __match_args__ = (\"_str\",)\n\n    @property\n    def _str(self) -> str:\n        \"\"\"Internal property for match_args\"\"\"\n        return str(self)\n\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\n        Returns the str representation of this Specifier-like object. This\n        should be representative of the Specifier itself.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __hash__(self) -> int:\n        \"\"\"\n        Returns a hash value for this Specifier-like object.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __eq__(self, other: object) -> bool:\n        \"\"\"\n        Returns a boolean representing whether or not the two Specifier-like\n        objects are equal.\n\n        :param other: The other object to check against.\n        \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def prereleases(self) -> bool | None:\n        \"\"\"Whether or not pre-releases as a whole are allowed.\n\n        This can be set to either ``True`` or ``False`` to explicitly enable or disable\n        prereleases or it can be set to ``None`` (the default) to use default semantics.\n        \"\"\"\n\n    @prereleases.setter  # noqa: B027\n    def prereleases(self, value: bool) -> None:\n        \"\"\"Setter for :attr:`prereleases`.\n\n        :param value: The value to set.\n        \"\"\"\n\n    @abc.abstractmethod\n    def contains(self, item: str, prereleases: bool | None = None) -> bool:\n        \"\"\"\n        Determines if the given item is contained within this specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def filter(\n        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None\n    ) -> Iterator[UnparsedVersionVar]:\n        \"\"\"\n        Takes an iterable of items and filters them so that only items which\n        are contained within this specifier are allowed in it.\n        \"\"\"\n\n\nclass Specifier(BaseSpecifier):\n    \"\"\"This class abstracts handling of version specifiers.\n\n    .. tip::\n\n        It is generally not required to instantiate this manually. You should instead\n        prefer to work with :class:`SpecifierSet` instead, which can parse\n        comma-separated version specifiers (which is what package metadata contains).\n    \"\"\"\n\n    __slots__ = (\"_prereleases\", \"_spec\", \"_spec_version\")\n\n    _operator_regex_str = r\"\"\"\n        (?P<operator>(~=|==|!=|<=|>=|<|>|===))\n        \"\"\"\n    _version_regex_str = r\"\"\"\n        (?P<version>\n            (?:\n                # The identity operators allow for an escape hatch that will\n                # do an exact string match of the version you wish to install.\n                # This will not be parsed by PEP 440 and we cannot determine\n                # any semantic meaning from it. This operator is discouraged\n                # but included entirely as an escape hatch.\n                (?<====)  # Only match for the identity operator\n                \\s*\n                [^\\s;)]*  # The arbitrary version can be just about anything,\n                          # we match everything except for whitespace, a\n                          # semi-colon for marker support, and a closing paren\n                          # since versions can be enclosed in them.\n            )\n            |\n            (?:\n                # The (non)equality operators allow for wild card and local\n                # versions to be specified so we have to define these two\n                # operators separately to enable that.\n                (?<===|!=)            # Only match for equals and not equals\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n\n                # You cannot use a wild card and a pre-release, post-release, a dev or\n                # local version together so group them with a | and make them optional.\n                (?:\n                    \\.\\*  # Wild card syntax of .*\n                    |\n                    (?:                                  # pre release\n                        [-_\\.]?\n                        (alpha|beta|preview|pre|a|b|c|rc)\n                        [-_\\.]?\n                        [0-9]*\n                    )?\n                    (?:                                  # post release\n                        (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                    )?\n                    (?:[-_\\.]?dev[-_\\.]?[0-9]*)?         # dev release\n                    (?:\\+[a-z0-9]+(?:[-_\\.][a-z0-9]+)*)? # local\n                )?\n            )\n            |\n            (?:\n                # The compatible operator requires at least two digits in the\n                # release segment.\n                (?<=~=)               # Only match for the compatible operator\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)+   # release  (We have a + instead of a *)\n                (?:                   # pre release\n                    [-_\\.]?\n                    (alpha|beta|preview|pre|a|b|c|rc)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n            |\n            (?:\n                # All other operators only allow a sub set of what the\n                # (non)equality operators do. Specifically they do not allow\n                # local versions to be specified nor do they allow the prefix\n                # matching wild cards.\n                (?<!==|!=|~=)         # We have special cases for these\n                                      # operators so we want to make sure they\n                                      # don't match here.\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (alpha|beta|preview|pre|a|b|c|rc)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n        )\n        \"\"\"\n\n    _regex = re.compile(\n        r\"\\s*\" + _operator_regex_str + _version_regex_str + r\"\\s*\",\n        re.VERBOSE | re.IGNORECASE,\n    )\n\n    _operators: Final = {\n        \"~=\": \"compatible\",\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n        \"===\": \"arbitrary\",\n    }\n\n    def __init__(self, spec: str = \"\", prereleases: bool | None = None) -> None:\n        \"\"\"Initialize a Specifier instance.\n\n        :param spec:\n            The string representation of a specifier which will be parsed and\n            normalized before use.\n        :param prereleases:\n            This tells the specifier if it should accept prerelease versions if\n            applicable or not. The default of ``None`` will autodetect it from the\n            given specifiers.\n        :raises InvalidSpecifier:\n            If the given specifier is invalid (i.e. bad syntax).\n        \"\"\"\n        match = self._regex.fullmatch(spec)\n        if not match:\n            raise InvalidSpecifier(f\"Invalid specifier: {spec!r}\")\n\n        self._spec: tuple[str, str] = (\n            match.group(\"operator\").strip(),\n            match.group(\"version\").strip(),\n        )\n\n        # Store whether or not this Specifier should accept prereleases\n        self._prereleases = prereleases\n\n        # Specifier version cache\n        self._spec_version: tuple[str, Version] | None = None\n\n    def _get_spec_version(self, version: str) -> Version | None:\n        \"\"\"One element cache, as only one spec Version is needed per Specifier.\"\"\"\n        if self._spec_version is not None and self._spec_version[0] == version:\n            return self._spec_version[1]\n\n        version_specifier = _coerce_version(version)\n        if version_specifier is None:\n            return None\n\n        self._spec_version = (version, version_specifier)\n        return version_specifier\n\n    def _require_spec_version(self, version: str) -> Version:\n        \"\"\"Get spec version, asserting it's valid (not for === operator).\n\n        This method should only be called for operators where version\n        strings are guaranteed to be valid PEP 440 versions (not ===).\n        \"\"\"\n        spec_version = self._get_spec_version(version)\n        assert spec_version is not None\n        return spec_version\n\n    @property\n    def prereleases(self) -> bool | None:\n        # If there is an explicit prereleases set for this, then we'll just\n        # blindly use that.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # Only the \"!=\" operator does not imply prereleases when\n        # the version in the specifier is a prerelease.\n        operator, version_str = self._spec\n        if operator != \"!=\":\n            # The == specifier with trailing .* cannot include prereleases\n            # e.g. \"==1.0a1.*\" is not valid.\n            if operator == \"==\" and version_str.endswith(\".*\"):\n                return False\n\n            # \"===\" can have arbitrary string versions, so we cannot parse\n            # those, we take prereleases as unknown (None) for those.\n            version = self._get_spec_version(version_str)\n            if version is None:\n                return None\n\n            # For all other operators, use the check if spec Version\n            # object implies pre-releases.\n            if version.is_prerelease:\n                return True\n\n        return False\n\n    @prereleases.setter\n    def prereleases(self, value: bool | None) -> None:\n        self._prereleases = value\n\n    @property\n    def operator(self) -> str:\n        \"\"\"The operator of this specifier.\n\n        >>> Specifier(\"==1.2.3\").operator\n        '=='\n        \"\"\"\n        return self._spec[0]\n\n    @property\n    def version(self) -> str:\n        \"\"\"The version of this specifier.\n\n        >>> Specifier(\"==1.2.3\").version\n        '1.2.3'\n        \"\"\"\n        return self._spec[1]\n\n    def __repr__(self) -> str:\n        \"\"\"A representation of the Specifier that shows all internal state.\n\n        >>> Specifier('>=1.0.0')\n        <Specifier('>=1.0.0')>\n        >>> Specifier('>=1.0.0', prereleases=False)\n        <Specifier('>=1.0.0', prereleases=False)>\n        >>> Specifier('>=1.0.0', prereleases=True)\n        <Specifier('>=1.0.0', prereleases=True)>\n        \"\"\"\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<{self.__class__.__name__}({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        \"\"\"A string representation of the Specifier that can be round-tripped.\n\n        >>> str(Specifier('>=1.0.0'))\n        '>=1.0.0'\n        >>> str(Specifier('>=1.0.0', prereleases=False))\n        '>=1.0.0'\n        \"\"\"\n        return \"{}{}\".format(*self._spec)\n\n    @property\n    def _canonical_spec(self) -> tuple[str, str]:\n        operator, version = self._spec\n        if operator == \"===\" or version.endswith(\".*\"):\n            return operator, version\n\n        spec_version = self._require_spec_version(version)\n\n        canonical_version = canonicalize_version(\n            spec_version, strip_trailing_zero=(operator != \"~=\")\n        )\n\n        return operator, canonical_version\n\n    def __hash__(self) -> int:\n        return hash(self._canonical_spec)\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Whether or not the two Specifier-like objects are equal.\n\n        :param other: The other object to check against.\n\n        The value of :attr:`prereleases` is ignored.\n\n        >>> Specifier(\"==1.2.3\") == Specifier(\"== 1.2.3.0\")\n        True\n        >>> (Specifier(\"==1.2.3\", prereleases=False) ==\n        ...  Specifier(\"==1.2.3\", prereleases=True))\n        True\n        >>> Specifier(\"==1.2.3\") == \"==1.2.3\"\n        True\n        >>> Specifier(\"==1.2.3\") == Specifier(\"==1.2.4\")\n        False\n        >>> Specifier(\"==1.2.3\") == Specifier(\"~=1.2.3\")\n        False\n        \"\"\"\n        if isinstance(other, str):\n            try:\n                other = self.__class__(str(other))\n            except InvalidSpecifier:\n                return NotImplemented\n        elif not isinstance(other, self.__class__):\n            return NotImplemented\n\n        return self._canonical_spec == other._canonical_spec\n\n    def _get_operator(self, op: str) -> CallableOperator:\n        operator_callable: CallableOperator = getattr(\n            self, f\"_compare_{self._operators[op]}\"\n        )\n        return operator_callable\n\n    def _compare_compatible(self, prospective: Version, spec: str) -> bool:\n        # Compatible releases have an equivalent combination of >= and ==. That\n        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to\n        # implement this in terms of the other specifiers instead of\n        # implementing it ourselves. The only thing we need to do is construct\n        # the other specifiers.\n\n        # We want everything but the last item in the version, but we want to\n        # ignore suffix segments.\n        prefix = _version_join(\n            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]\n        )\n\n        # Add the prefix notation to the end of our string\n        prefix += \".*\"\n\n        return self._get_operator(\">=\")(prospective, spec) and self._get_operator(\"==\")(\n            prospective, prefix\n        )\n\n    def _compare_equal(self, prospective: Version, spec: str) -> bool:\n        # We need special logic to handle prefix matching\n        if spec.endswith(\".*\"):\n            # In the case of prefix matching we want to ignore local segment.\n            normalized_prospective = canonicalize_version(\n                _public_version(prospective), strip_trailing_zero=False\n            )\n            # Get the normalized version string ignoring the trailing .*\n            normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)\n            # Split the spec out by bangs and dots, and pretend that there is\n            # an implicit dot in between a release segment and a pre-release segment.\n            split_spec = _version_split(normalized_spec)\n\n            # Split the prospective version out by bangs and dots, and pretend\n            # that there is an implicit dot in between a release segment and\n            # a pre-release segment.\n            split_prospective = _version_split(normalized_prospective)\n\n            # 0-pad the prospective version before shortening it to get the correct\n            # shortened version.\n            padded_prospective, _ = _pad_version(split_prospective, split_spec)\n\n            # Shorten the prospective version to be the same length as the spec\n            # so that we can determine if the specifier is a prefix of the\n            # prospective version or not.\n            shortened_prospective = padded_prospective[: len(split_spec)]\n\n            return shortened_prospective == split_spec\n        else:\n            # Convert our spec string into a Version\n            spec_version = self._require_spec_version(spec)\n\n            # If the specifier does not have a local segment, then we want to\n            # act as if the prospective version also does not have a local\n            # segment.\n            if not spec_version.local:\n                prospective = _public_version(prospective)\n\n            return prospective == spec_version\n\n    def _compare_not_equal(self, prospective: Version, spec: str) -> bool:\n        return not self._compare_equal(prospective, spec)\n\n    def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return _public_version(prospective) <= self._require_spec_version(spec)\n\n    def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return _public_version(prospective) >= self._require_spec_version(spec)\n\n    def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = self._require_spec_version(spec_str)\n\n        # Check to see if the prospective version is less than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective < spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a pre-release version, that we do not accept pre-release\n        # versions for the version mentioned in the specifier (e.g. <3.1 should\n        # not match 3.1.dev0, but should match 3.0.dev0).\n        if (\n            not spec.is_prerelease\n            and prospective.is_prerelease\n            and _base_version(prospective) == _base_version(spec)\n        ):\n            return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # less than the spec version *and* it's not a pre-release of the same\n        # version in the spec.\n        return True\n\n    def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = self._require_spec_version(spec_str)\n\n        # Check to see if the prospective version is greater than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective > spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a post-release version, that we do not accept\n        # post-release versions for the version mentioned in the specifier\n        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).\n        if (\n            not spec.is_postrelease\n            and prospective.is_postrelease\n            and _base_version(prospective) == _base_version(spec)\n        ):\n            return False\n\n        # Ensure that we do not allow a local version of the version mentioned\n        # in the specifier, which is technically greater than, to match.\n        if prospective.local is not None and _base_version(\n            prospective\n        ) == _base_version(spec):\n            return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # greater than the spec version *and* it's not a pre-release of the\n        # same version in the spec.\n        return True\n\n    def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool:\n        return str(prospective).lower() == str(spec).lower()\n\n    def __contains__(self, item: str | Version) -> bool:\n        \"\"\"Return whether or not the item is contained in this specifier.\n\n        :param item: The item to check for.\n\n        This is used for the ``in`` operator and behaves the same as\n        :meth:`contains` with no ``prereleases`` argument passed.\n\n        >>> \"1.2.3\" in Specifier(\">=1.2.3\")\n        True\n        >>> Version(\"1.2.3\") in Specifier(\">=1.2.3\")\n        True\n        >>> \"1.0.0\" in Specifier(\">=1.2.3\")\n        False\n        >>> \"1.3.0a1\" in Specifier(\">=1.2.3\")\n        True\n        >>> \"1.3.0a1\" in Specifier(\">=1.2.3\", prereleases=True)\n        True\n        \"\"\"\n        return self.contains(item)\n\n    def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:\n        \"\"\"Return whether or not the item is contained in this specifier.\n\n        :param item:\n            The item to check for, which can be a version string or a\n            :class:`Version` instance.\n        :param prereleases:\n            Whether or not to match prereleases with this Specifier. If set to\n            ``None`` (the default), it will follow the recommendation from\n            :pep:`440` and match prereleases, as there are no other versions.\n\n        >>> Specifier(\">=1.2.3\").contains(\"1.2.3\")\n        True\n        >>> Specifier(\">=1.2.3\").contains(Version(\"1.2.3\"))\n        True\n        >>> Specifier(\">=1.2.3\").contains(\"1.0.0\")\n        False\n        >>> Specifier(\">=1.2.3\").contains(\"1.3.0a1\")\n        True\n        >>> Specifier(\">=1.2.3\", prereleases=False).contains(\"1.3.0a1\")\n        False\n        >>> Specifier(\">=1.2.3\").contains(\"1.3.0a1\")\n        True\n        \"\"\"\n\n        return bool(list(self.filter([item], prereleases=prereleases)))\n\n    def filter(\n        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None\n    ) -> Iterator[UnparsedVersionVar]:\n        \"\"\"Filter items in the given iterable, that match the specifier.\n\n        :param iterable:\n            An iterable that can contain version strings and :class:`Version` instances.\n            The items in the iterable will be filtered according to the specifier.\n        :param prereleases:\n            Whether or not to allow prereleases in the returned iterator. If set to\n            ``None`` (the default), it will follow the recommendation from :pep:`440`\n            and match prereleases if there are no other versions.\n\n        >>> list(Specifier(\">=1.2.3\").filter([\"1.2\", \"1.3\", \"1.5a1\"]))\n        ['1.3']\n        >>> list(Specifier(\">=1.2.3\").filter([\"1.2\", \"1.2.3\", \"1.3\", Version(\"1.4\")]))\n        ['1.2.3', '1.3', <Version('1.4')>]\n        >>> list(Specifier(\">=1.2.3\").filter([\"1.2\", \"1.5a1\"]))\n        ['1.5a1']\n        >>> list(Specifier(\">=1.2.3\").filter([\"1.3\", \"1.5a1\"], prereleases=True))\n        ['1.3', '1.5a1']\n        >>> list(Specifier(\">=1.2.3\", prereleases=True).filter([\"1.3\", \"1.5a1\"]))\n        ['1.3', '1.5a1']\n        \"\"\"\n        prereleases_versions = []\n        found_non_prereleases = False\n\n        # Determine if to include prereleases by default\n        include_prereleases = (\n            prereleases if prereleases is not None else self.prereleases\n        )\n\n        # Get the matching operator\n        operator_callable = self._get_operator(self.operator)\n\n        # Filter versions\n        for version in iterable:\n            parsed_version = _coerce_version(version)\n            if parsed_version is None:\n                # === operator can match arbitrary (non-version) strings\n                if self.operator == \"===\" and self._compare_arbitrary(\n                    version, self.version\n                ):\n                    yield version\n            elif operator_callable(parsed_version, self.version):\n                # If it's not a prerelease or prereleases are allowed, yield it directly\n                if not parsed_version.is_prerelease or include_prereleases:\n                    found_non_prereleases = True\n                    yield version\n                # Otherwise collect prereleases for potential later use\n                elif prereleases is None and self._prereleases is not False:\n                    prereleases_versions.append(version)\n\n        # If no non-prereleases were found and prereleases weren't\n        # explicitly forbidden, yield the collected prereleases\n        if (\n            not found_non_prereleases\n            and prereleases is None\n            and self._prereleases is not False\n        ):\n            yield from prereleases_versions\n\n\n_prefix_regex = re.compile(r\"([0-9]+)((?:a|b|c|rc)[0-9]+)\")\n\n\ndef _version_split(version: str) -> list[str]:\n    \"\"\"Split version into components.\n\n    The split components are intended for version comparison. The logic does\n    not attempt to retain the original version string, so joining the\n    components back with :func:`_version_join` may not produce the original\n    version string.\n    \"\"\"\n    result: list[str] = []\n\n    epoch, _, rest = version.rpartition(\"!\")\n    result.append(epoch or \"0\")\n\n    for item in rest.split(\".\"):\n        match = _prefix_regex.fullmatch(item)\n        if match:\n            result.extend(match.groups())\n        else:\n            result.append(item)\n    return result\n\n\ndef _version_join(components: list[str]) -> str:\n    \"\"\"Join split version components into a version string.\n\n    This function assumes the input came from :func:`_version_split`, where the\n    first component must be the epoch (either empty or numeric), and all other\n    components numeric.\n    \"\"\"\n    epoch, *rest = components\n    return f\"{epoch}!{'.'.join(rest)}\"\n\n\ndef _is_not_suffix(segment: str) -> bool:\n    return not any(\n        segment.startswith(prefix) for prefix in (\"dev\", \"a\", \"b\", \"rc\", \"post\")\n    )\n\n\ndef _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]:\n    left_split, right_split = [], []\n\n    # Get the release segment of our versions\n    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))\n    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))\n\n    # Get the rest of our versions\n    left_split.append(left[len(left_split[0]) :])\n    right_split.append(right[len(right_split[0]) :])\n\n    # Insert our padding\n    left_split.insert(1, [\"0\"] * max(0, len(right_split[0]) - len(left_split[0])))\n    right_split.insert(1, [\"0\"] * max(0, len(left_split[0]) - len(right_split[0])))\n\n    return (\n        list(itertools.chain.from_iterable(left_split)),\n        list(itertools.chain.from_iterable(right_split)),\n    )\n\n\nclass SpecifierSet(BaseSpecifier):\n    \"\"\"This class abstracts handling of a set of version specifiers.\n\n    It can be passed a single specifier (``>=3.0``), a comma-separated list of\n    specifiers (``>=3.0,!=3.1``), or no specifier at all.\n    \"\"\"\n\n    __slots__ = (\"_prereleases\", \"_specs\")\n\n    def __init__(\n        self,\n        specifiers: str | Iterable[Specifier] = \"\",\n        prereleases: bool | None = None,\n    ) -> None:\n        \"\"\"Initialize a SpecifierSet instance.\n\n        :param specifiers:\n            The string representation of a specifier or a comma-separated list of\n            specifiers which will be parsed and normalized before use.\n            May also be an iterable of ``Specifier`` instances, which will be used\n            as is.\n        :param prereleases:\n            This tells the SpecifierSet if it should accept prerelease versions if\n            applicable or not. The default of ``None`` will autodetect it from the\n            given specifiers.\n\n        :raises InvalidSpecifier:\n            If the given ``specifiers`` are not parseable than this exception will be\n            raised.\n        \"\"\"\n\n        if isinstance(specifiers, str):\n            # Split on `,` to break each individual specifier into its own item, and\n            # strip each item to remove leading/trailing whitespace.\n            split_specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n\n            # Make each individual specifier a Specifier and save in a frozen set\n            # for later.\n            self._specs = frozenset(map(Specifier, split_specifiers))\n        else:\n            # Save the supplied specifiers in a frozen set.\n            self._specs = frozenset(specifiers)\n\n        # Store our prereleases value so we can use it later to determine if\n        # we accept prereleases or not.\n        self._prereleases = prereleases\n\n    @property\n    def prereleases(self) -> bool | None:\n        # If we have been given an explicit prerelease modifier, then we'll\n        # pass that through here.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # If we don't have any specifiers, and we don't have a forced value,\n        # then we'll just return None since we don't know if this should have\n        # pre-releases or not.\n        if not self._specs:\n            return None\n\n        # Otherwise we'll see if any of the given specifiers accept\n        # prereleases, if any of them do we'll return True, otherwise False.\n        if any(s.prereleases for s in self._specs):\n            return True\n\n        return None\n\n    @prereleases.setter\n    def prereleases(self, value: bool | None) -> None:\n        self._prereleases = value\n\n    def __repr__(self) -> str:\n        \"\"\"A representation of the specifier set that shows all internal state.\n\n        Note that the ordering of the individual specifiers within the set may not\n        match the input string.\n\n        >>> SpecifierSet('>=1.0.0,!=2.0.0')\n        <SpecifierSet('!=2.0.0,>=1.0.0')>\n        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)\n        <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)>\n        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)\n        <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)>\n        \"\"\"\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<SpecifierSet({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        \"\"\"A string representation of the specifier set that can be round-tripped.\n\n        Note that the ordering of the individual specifiers within the set may not\n        match the input string.\n\n        >>> str(SpecifierSet(\">=1.0.0,!=1.0.1\"))\n        '!=1.0.1,>=1.0.0'\n        >>> str(SpecifierSet(\">=1.0.0,!=1.0.1\", prereleases=False))\n        '!=1.0.1,>=1.0.0'\n        \"\"\"\n        return \",\".join(sorted(str(s) for s in self._specs))\n\n    def __hash__(self) -> int:\n        return hash(self._specs)\n\n    def __and__(self, other: SpecifierSet | str) -> SpecifierSet:\n        \"\"\"Return a SpecifierSet which is a combination of the two sets.\n\n        :param other: The other object to combine with.\n\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") & '<=2.0.0,!=2.0.1'\n        <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") & SpecifierSet('<=2.0.0,!=2.0.1')\n        <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>\n        \"\"\"\n        if isinstance(other, str):\n            other = SpecifierSet(other)\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        specifier = SpecifierSet()\n        specifier._specs = frozenset(self._specs | other._specs)\n\n        if self._prereleases is None and other._prereleases is not None:\n            specifier._prereleases = other._prereleases\n        elif (\n            self._prereleases is not None and other._prereleases is None\n        ) or self._prereleases == other._prereleases:\n            specifier._prereleases = self._prereleases\n        else:\n            raise ValueError(\n                \"Cannot combine SpecifierSets with True and False prerelease overrides.\"\n            )\n\n        return specifier\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Whether or not the two SpecifierSet-like objects are equal.\n\n        :param other: The other object to check against.\n\n        The value of :attr:`prereleases` is ignored.\n\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") == SpecifierSet(\">=1.0.0,!=1.0.1\")\n        True\n        >>> (SpecifierSet(\">=1.0.0,!=1.0.1\", prereleases=False) ==\n        ...  SpecifierSet(\">=1.0.0,!=1.0.1\", prereleases=True))\n        True\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") == \">=1.0.0,!=1.0.1\"\n        True\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") == SpecifierSet(\">=1.0.0\")\n        False\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\") == SpecifierSet(\">=1.0.0,!=1.0.2\")\n        False\n        \"\"\"\n        if isinstance(other, (str, Specifier)):\n            other = SpecifierSet(str(other))\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        return self._specs == other._specs\n\n    def __len__(self) -> int:\n        \"\"\"Returns the number of specifiers in this specifier set.\"\"\"\n        return len(self._specs)\n\n    def __iter__(self) -> Iterator[Specifier]:\n        \"\"\"\n        Returns an iterator over all the underlying :class:`Specifier` instances\n        in this specifier set.\n\n        >>> sorted(SpecifierSet(\">=1.0.0,!=1.0.1\"), key=str)\n        [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>]\n        \"\"\"\n        return iter(self._specs)\n\n    def __contains__(self, item: UnparsedVersion) -> bool:\n        \"\"\"Return whether or not the item is contained in this specifier.\n\n        :param item: The item to check for.\n\n        This is used for the ``in`` operator and behaves the same as\n        :meth:`contains` with no ``prereleases`` argument passed.\n\n        >>> \"1.2.3\" in SpecifierSet(\">=1.0.0,!=1.0.1\")\n        True\n        >>> Version(\"1.2.3\") in SpecifierSet(\">=1.0.0,!=1.0.1\")\n        True\n        >>> \"1.0.1\" in SpecifierSet(\">=1.0.0,!=1.0.1\")\n        False\n        >>> \"1.3.0a1\" in SpecifierSet(\">=1.0.0,!=1.0.1\")\n        True\n        >>> \"1.3.0a1\" in SpecifierSet(\">=1.0.0,!=1.0.1\", prereleases=True)\n        True\n        \"\"\"\n        return self.contains(item)\n\n    def contains(\n        self,\n        item: UnparsedVersion,\n        prereleases: bool | None = None,\n        installed: bool | None = None,\n    ) -> bool:\n        \"\"\"Return whether or not the item is contained in this SpecifierSet.\n\n        :param item:\n            The item to check for, which can be a version string or a\n            :class:`Version` instance.\n        :param prereleases:\n            Whether or not to match prereleases with this SpecifierSet. If set to\n            ``None`` (the default), it will follow the recommendation from :pep:`440`\n            and match prereleases, as there are no other versions.\n        :param installed:\n            Whether or not the item is installed. If set to ``True``, it will\n            accept prerelease versions even if the specifier does not allow them.\n\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\").contains(\"1.2.3\")\n        True\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\").contains(Version(\"1.2.3\"))\n        True\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\").contains(\"1.0.1\")\n        False\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\").contains(\"1.3.0a1\")\n        True\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\", prereleases=False).contains(\"1.3.0a1\")\n        False\n        >>> SpecifierSet(\">=1.0.0,!=1.0.1\").contains(\"1.3.0a1\", prereleases=True)\n        True\n        \"\"\"\n        version = _coerce_version(item)\n\n        if version is not None and installed and version.is_prerelease:\n            prereleases = True\n\n        check_item = item if version is None else version\n        return bool(list(self.filter([check_item], prereleases=prereleases)))\n\n    def filter(\n        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None\n    ) -> Iterator[UnparsedVersionVar]:\n        \"\"\"Filter items in the given iterable, that match the specifiers in this set.\n\n        :param iterable:\n            An iterable that can contain version strings and :class:`Version` instances.\n            The items in the iterable will be filtered according to the specifier.\n        :param prereleases:\n            Whether or not to allow prereleases in the returned iterator. If set to\n            ``None`` (the default), it will follow the recommendation from :pep:`440`\n            and match prereleases if there are no other versions.\n\n        >>> list(SpecifierSet(\">=1.2.3\").filter([\"1.2\", \"1.3\", \"1.5a1\"]))\n        ['1.3']\n        >>> list(SpecifierSet(\">=1.2.3\").filter([\"1.2\", \"1.3\", Version(\"1.4\")]))\n        ['1.3', <Version('1.4')>]\n        >>> list(SpecifierSet(\">=1.2.3\").filter([\"1.2\", \"1.5a1\"]))\n        ['1.5a1']\n        >>> list(SpecifierSet(\">=1.2.3\").filter([\"1.3\", \"1.5a1\"], prereleases=True))\n        ['1.3', '1.5a1']\n        >>> list(SpecifierSet(\">=1.2.3\", prereleases=True).filter([\"1.3\", \"1.5a1\"]))\n        ['1.3', '1.5a1']\n\n        An \"empty\" SpecifierSet will filter items based on the presence of prerelease\n        versions in the set.\n\n        >>> list(SpecifierSet(\"\").filter([\"1.3\", \"1.5a1\"]))\n        ['1.3']\n        >>> list(SpecifierSet(\"\").filter([\"1.5a1\"]))\n        ['1.5a1']\n        >>> list(SpecifierSet(\"\", prereleases=True).filter([\"1.3\", \"1.5a1\"]))\n        ['1.3', '1.5a1']\n        >>> list(SpecifierSet(\"\").filter([\"1.3\", \"1.5a1\"], prereleases=True))\n        ['1.3', '1.5a1']\n        \"\"\"\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None and self.prereleases is not None:\n            prereleases = self.prereleases\n\n        # If we have any specifiers, then we want to wrap our iterable in the\n        # filter method for each one, this will act as a logical AND amongst\n        # each specifier.\n        if self._specs:\n            # When prereleases is None, we need to let all versions through\n            # the individual filters, then decide about prereleases at the end\n            # based on whether any non-prereleases matched ALL specs.\n            for spec in self._specs:\n                iterable = spec.filter(\n                    iterable, prereleases=True if prereleases is None else prereleases\n                )\n\n            if prereleases is not None:\n                # If we have a forced prereleases value,\n                # we can immediately return the iterator.\n                return iter(iterable)\n        else:\n            # Handle empty SpecifierSet cases where prereleases is not None.\n            if prereleases is True:\n                return iter(iterable)\n\n            if prereleases is False:\n                return (\n                    item\n                    for item in iterable\n                    if (version := _coerce_version(item)) is None\n                    or not version.is_prerelease\n                )\n\n        # Finally if prereleases is None, apply PEP 440 logic:\n        # exclude prereleases unless there are no final releases that matched.\n        filtered_items: list[UnparsedVersionVar] = []\n        found_prereleases: list[UnparsedVersionVar] = []\n        found_final_release = False\n\n        for item in iterable:\n            parsed_version = _coerce_version(item)\n            # Arbitrary strings are always included as it is not\n            # possible to determine if they are prereleases,\n            # and they have already passed all specifiers.\n            if parsed_version is None:\n                filtered_items.append(item)\n                found_prereleases.append(item)\n            elif parsed_version.is_prerelease:\n                found_prereleases.append(item)\n            else:\n                filtered_items.append(item)\n                found_final_release = True\n\n        return iter(filtered_items if found_final_release else found_prereleases)\n"
  },
  {
    "path": "src/pip/_vendor/packaging/tags.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import annotations\n\nimport logging\nimport platform\nimport re\nimport struct\nimport subprocess\nimport sys\nimport sysconfig\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom typing import (\n    Any,\n    Iterable,\n    Iterator,\n    Sequence,\n    Tuple,\n    cast,\n)\n\nfrom . import _manylinux, _musllinux\n\nlogger = logging.getLogger(__name__)\n\nPythonVersion = Sequence[int]\nAppleVersion = Tuple[int, int]\n\nINTERPRETER_SHORT_NAMES: dict[str, str] = {\n    \"python\": \"py\",  # Generic.\n    \"cpython\": \"cp\",\n    \"pypy\": \"pp\",\n    \"ironpython\": \"ip\",\n    \"jython\": \"jy\",\n}\n\n\n_32_BIT_INTERPRETER = struct.calcsize(\"P\") == 4\n\n\nclass Tag:\n    \"\"\"\n    A representation of the tag triple for a wheel.\n\n    Instances are considered immutable and thus are hashable. Equality checking\n    is also supported.\n    \"\"\"\n\n    __slots__ = [\"_abi\", \"_hash\", \"_interpreter\", \"_platform\"]\n\n    def __init__(self, interpreter: str, abi: str, platform: str) -> None:\n        self._interpreter = interpreter.lower()\n        self._abi = abi.lower()\n        self._platform = platform.lower()\n        # The __hash__ of every single element in a Set[Tag] will be evaluated each time\n        # that a set calls its `.disjoint()` method, which may be called hundreds of\n        # times when scanning a page of links for packages with tags matching that\n        # Set[Tag]. Pre-computing the value here produces significant speedups for\n        # downstream consumers.\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n    @property\n    def interpreter(self) -> str:\n        return self._interpreter\n\n    @property\n    def abi(self) -> str:\n        return self._abi\n\n    @property\n    def platform(self) -> str:\n        return self._platform\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Tag):\n            return NotImplemented\n\n        return (\n            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.\n            and (self._platform == other._platform)\n            and (self._abi == other._abi)\n            and (self._interpreter == other._interpreter)\n        )\n\n    def __hash__(self) -> int:\n        return self._hash\n\n    def __str__(self) -> str:\n        return f\"{self._interpreter}-{self._abi}-{self._platform}\"\n\n    def __repr__(self) -> str:\n        return f\"<{self} @ {id(self)}>\"\n\n    def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None:\n        # The cached _hash is wrong when unpickling.\n        _, slots = state\n        for k, v in slots.items():\n            setattr(self, k, v)\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n\ndef parse_tag(tag: str) -> frozenset[Tag]:\n    \"\"\"\n    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.\n\n    Returning a set is required due to the possibility that the tag is a\n    compressed tag set.\n    \"\"\"\n    tags = set()\n    interpreters, abis, platforms = tag.split(\"-\")\n    for interpreter in interpreters.split(\".\"):\n        for abi in abis.split(\".\"):\n            for platform_ in platforms.split(\".\"):\n                tags.add(Tag(interpreter, abi, platform_))\n    return frozenset(tags)\n\n\ndef _get_config_var(name: str, warn: bool = False) -> int | str | None:\n    value: int | str | None = sysconfig.get_config_var(name)\n    if value is None and warn:\n        logger.debug(\n            \"Config variable '%s' is unset, Python ABI tag may be incorrect\", name\n        )\n    return value\n\n\ndef _normalize_string(string: str) -> str:\n    return string.replace(\".\", \"_\").replace(\"-\", \"_\").replace(\" \", \"_\")\n\n\ndef _is_threaded_cpython(abis: list[str]) -> bool:\n    \"\"\"\n    Determine if the ABI corresponds to a threaded (`--disable-gil`) build.\n\n    The threaded builds are indicated by a \"t\" in the abiflags.\n    \"\"\"\n    if len(abis) == 0:\n        return False\n    # expect e.g., cp313\n    m = re.match(r\"cp\\d+(.*)\", abis[0])\n    if not m:\n        return False\n    abiflags = m.group(1)\n    return \"t\" in abiflags\n\n\ndef _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:\n    \"\"\"\n    Determine if the Python version supports abi3.\n\n    PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)\n    builds do not support abi3.\n    \"\"\"\n    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading\n\n\ndef _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]:\n    py_version = tuple(py_version)  # To allow for version comparison.\n    abis = []\n    version = _version_nodot(py_version[:2])\n    threading = debug = pymalloc = ucs4 = \"\"\n    with_debug = _get_config_var(\"Py_DEBUG\", warn)\n    has_refcount = hasattr(sys, \"gettotalrefcount\")\n    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled\n    # extension modules is the best option.\n    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692\n    has_ext = \"_d.pyd\" in EXTENSION_SUFFIXES\n    if with_debug or (with_debug is None and (has_refcount or has_ext)):\n        debug = \"d\"\n    if py_version >= (3, 13) and _get_config_var(\"Py_GIL_DISABLED\", warn):\n        threading = \"t\"\n    if py_version < (3, 8):\n        with_pymalloc = _get_config_var(\"WITH_PYMALLOC\", warn)\n        if with_pymalloc or with_pymalloc is None:\n            pymalloc = \"m\"\n        if py_version < (3, 3):\n            unicode_size = _get_config_var(\"Py_UNICODE_SIZE\", warn)\n            if unicode_size == 4 or (\n                unicode_size is None and sys.maxunicode == 0x10FFFF\n            ):\n                ucs4 = \"u\"\n    elif debug:\n        # Debug builds can also load \"normal\" extension modules.\n        # We can also assume no UCS-4 or pymalloc requirement.\n        abis.append(f\"cp{version}{threading}\")\n    abis.insert(0, f\"cp{version}{threading}{debug}{pymalloc}{ucs4}\")\n    return abis\n\n\ndef cpython_tags(\n    python_version: PythonVersion | None = None,\n    abis: Iterable[str] | None = None,\n    platforms: Iterable[str] | None = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a CPython interpreter.\n\n    The tags consist of:\n    - cp<python_version>-<abi>-<platform>\n    - cp<python_version>-abi3-<platform>\n    - cp<python_version>-none-<platform>\n    - cp<less than python_version>-abi3-<platform>  # Older Python versions down to 3.2.\n\n    If python_version only specifies a major version then user-provided ABIs and\n    the 'none' ABItag will be used.\n\n    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n    their normal position and not at the beginning.\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n\n    interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n    if abis is None:\n        abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else []\n    abis = list(abis)\n    # 'abi3' and 'none' are explicitly handled later.\n    for explicit_abi in (\"abi3\", \"none\"):\n        try:\n            abis.remove(explicit_abi)\n        except ValueError:  # noqa: PERF203\n            pass\n\n    platforms = list(platforms or platform_tags())\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n    threading = _is_threaded_cpython(abis)\n    use_abi3 = _abi3_applies(python_version, threading)\n    if use_abi3:\n        yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n    yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n    if use_abi3:\n        for minor_version in range(python_version[1] - 1, 1, -1):\n            for platform_ in platforms:\n                version = _version_nodot((python_version[0], minor_version))\n                interpreter = f\"cp{version}\"\n                yield Tag(interpreter, \"abi3\", platform_)\n\n\ndef _generic_abi() -> list[str]:\n    \"\"\"\n    Return the ABI tag based on EXT_SUFFIX.\n    \"\"\"\n    # The following are examples of `EXT_SUFFIX`.\n    # We want to keep the parts which are related to the ABI and remove the\n    # parts which are related to the platform:\n    # - linux:   '.cpython-310-x86_64-linux-gnu.so' => cp310\n    # - mac:     '.cpython-310-darwin.so'           => cp310\n    # - win:     '.cp310-win_amd64.pyd'             => cp310\n    # - win:     '.pyd'                             => cp37 (uses _cpython_abis())\n    # - pypy:    '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73\n    # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'\n    #                                               => graalpy_38_native\n\n    ext_suffix = _get_config_var(\"EXT_SUFFIX\", warn=True)\n    if not isinstance(ext_suffix, str) or ext_suffix[0] != \".\":\n        raise SystemError(\"invalid sysconfig.get_config_var('EXT_SUFFIX')\")\n    parts = ext_suffix.split(\".\")\n    if len(parts) < 3:\n        # CPython3.7 and earlier uses \".pyd\" on Windows.\n        return _cpython_abis(sys.version_info[:2])\n    soabi = parts[1]\n    if soabi.startswith(\"cpython\"):\n        # non-windows\n        abi = \"cp\" + soabi.split(\"-\")[1]\n    elif soabi.startswith(\"cp\"):\n        # windows\n        abi = soabi.split(\"-\")[0]\n    elif soabi.startswith(\"pypy\"):\n        abi = \"-\".join(soabi.split(\"-\")[:2])\n    elif soabi.startswith(\"graalpy\"):\n        abi = \"-\".join(soabi.split(\"-\")[:3])\n    elif soabi:\n        # pyston, ironpython, others?\n        abi = soabi\n    else:\n        return []\n    return [_normalize_string(abi)]\n\n\ndef generic_tags(\n    interpreter: str | None = None,\n    abis: Iterable[str] | None = None,\n    platforms: Iterable[str] | None = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a generic interpreter.\n\n    The tags consist of:\n    - <interpreter>-<abi>-<platform>\n\n    The \"none\" ABI will be added if it was not explicitly provided.\n    \"\"\"\n    if not interpreter:\n        interp_name = interpreter_name()\n        interp_version = interpreter_version(warn=warn)\n        interpreter = f\"{interp_name}{interp_version}\"\n    abis = _generic_abi() if abis is None else list(abis)\n    platforms = list(platforms or platform_tags())\n    if \"none\" not in abis:\n        abis.append(\"none\")\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n\ndef _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:\n    \"\"\"\n    Yields Python versions in descending order.\n\n    After the latest version, the major-only version will be yielded, and then\n    all previous versions of that major version.\n    \"\"\"\n    if len(py_version) > 1:\n        yield f\"py{_version_nodot(py_version[:2])}\"\n    yield f\"py{py_version[0]}\"\n    if len(py_version) > 1:\n        for minor in range(py_version[1] - 1, -1, -1):\n            yield f\"py{_version_nodot((py_version[0], minor))}\"\n\n\ndef compatible_tags(\n    python_version: PythonVersion | None = None,\n    interpreter: str | None = None,\n    platforms: Iterable[str] | None = None,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the sequence of tags that are compatible with a specific version of Python.\n\n    The tags consist of:\n    - py*-none-<platform>\n    - <interpreter>-none-any  # ... if `interpreter` is provided.\n    - py*-none-any\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n    platforms = list(platforms or platform_tags())\n    for version in _py_interpreter_range(python_version):\n        for platform_ in platforms:\n            yield Tag(version, \"none\", platform_)\n    if interpreter:\n        yield Tag(interpreter, \"none\", \"any\")\n    for version in _py_interpreter_range(python_version):\n        yield Tag(version, \"none\", \"any\")\n\n\ndef _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:\n    if not is_32bit:\n        return arch\n\n    if arch.startswith(\"ppc\"):\n        return \"ppc\"\n\n    return \"i386\"\n\n\ndef _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]:\n    formats = [cpu_arch]\n    if cpu_arch == \"x86_64\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat64\", \"fat32\"])\n\n    elif cpu_arch == \"i386\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat32\", \"fat\"])\n\n    elif cpu_arch == \"ppc64\":\n        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?\n        if version > (10, 5) or version < (10, 4):\n            return []\n        formats.append(\"fat64\")\n\n    elif cpu_arch == \"ppc\":\n        if version > (10, 6):\n            return []\n        formats.extend([\"fat32\", \"fat\"])\n\n    if cpu_arch in {\"arm64\", \"x86_64\"}:\n        formats.append(\"universal2\")\n\n    if cpu_arch in {\"x86_64\", \"i386\", \"ppc64\", \"ppc\", \"intel\"}:\n        formats.append(\"universal\")\n\n    return formats\n\n\ndef mac_platforms(\n    version: AppleVersion | None = None, arch: str | None = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for a macOS system.\n\n    The `version` parameter is a two-item tuple specifying the macOS version to\n    generate platform tags for. The `arch` parameter is the CPU architecture to\n    generate platform tags for. Both parameters default to the appropriate value\n    for the current system.\n    \"\"\"\n    version_str, _, cpu_arch = platform.mac_ver()\n    if version is None:\n        version = cast(\"AppleVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n        if version == (10, 16):\n            # When built against an older macOS SDK, Python will report macOS 10.16\n            # instead of the real version.\n            version_str = subprocess.run(\n                [\n                    sys.executable,\n                    \"-sS\",\n                    \"-c\",\n                    \"import platform; print(platform.mac_ver()[0])\",\n                ],\n                check=True,\n                env={\"SYSTEM_VERSION_COMPAT\": \"0\"},\n                stdout=subprocess.PIPE,\n                text=True,\n            ).stdout\n            version = cast(\"AppleVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n\n    if arch is None:\n        arch = _mac_arch(cpu_arch)\n\n    if (10, 0) <= version < (11, 0):\n        # Prior to Mac OS 11, each yearly release of Mac OS bumped the\n        # \"minor\" version number.  The major version was always 10.\n        major_version = 10\n        for minor_version in range(version[1], -1, -1):\n            compat_version = major_version, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield f\"macosx_{major_version}_{minor_version}_{binary_format}\"\n\n    if version >= (11, 0):\n        # Starting with Mac OS 11, each yearly release bumps the major version\n        # number.   The minor versions are now the midyear updates.\n        minor_version = 0\n        for major_version in range(version[0], 10, -1):\n            compat_version = major_version, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield f\"macosx_{major_version}_{minor_version}_{binary_format}\"\n\n    if version >= (11, 0):\n        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.\n        # Arm64 support was introduced in 11.0, so no Arm binaries from previous\n        # releases exist.\n        #\n        # However, the \"universal2\" binary format can have a\n        # macOS version earlier than 11.0 when the x86_64 part of the binary supports\n        # that version of macOS.\n        major_version = 10\n        if arch == \"x86_64\":\n            for minor_version in range(16, 3, -1):\n                compat_version = major_version, minor_version\n                binary_formats = _mac_binary_formats(compat_version, arch)\n                for binary_format in binary_formats:\n                    yield f\"macosx_{major_version}_{minor_version}_{binary_format}\"\n        else:\n            for minor_version in range(16, 3, -1):\n                compat_version = major_version, minor_version\n                binary_format = \"universal2\"\n                yield f\"macosx_{major_version}_{minor_version}_{binary_format}\"\n\n\ndef ios_platforms(\n    version: AppleVersion | None = None, multiarch: str | None = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for an iOS system.\n\n    :param version: A two-item tuple specifying the iOS version to generate\n        platform tags for. Defaults to the current iOS version.\n    :param multiarch: The CPU architecture+ABI to generate platform tags for -\n        (the value used by `sys.implementation._multiarch` e.g.,\n        `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current\n        multiarch value.\n    \"\"\"\n    if version is None:\n        # if iOS is the current platform, ios_ver *must* be defined. However,\n        # it won't exist for CPython versions before 3.13, which causes a mypy\n        # error.\n        _, release, _, _ = platform.ios_ver()  # type: ignore[attr-defined, unused-ignore]\n        version = cast(\"AppleVersion\", tuple(map(int, release.split(\".\")[:2])))\n\n    if multiarch is None:\n        multiarch = sys.implementation._multiarch\n    multiarch = multiarch.replace(\"-\", \"_\")\n\n    ios_platform_template = \"ios_{major}_{minor}_{multiarch}\"\n\n    # Consider any iOS major.minor version from the version requested, down to\n    # 12.0. 12.0 is the first iOS version that is known to have enough features\n    # to support CPython. Consider every possible minor release up to X.9. There\n    # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra\n    # candidates that won't ever match doesn't really hurt, and it saves us from\n    # having to keep an explicit list of known iOS versions in the code. Return\n    # the results descending order of version number.\n\n    # If the requested major version is less than 12, there won't be any matches.\n    if version[0] < 12:\n        return\n\n    # Consider the actual X.Y version that was requested.\n    yield ios_platform_template.format(\n        major=version[0], minor=version[1], multiarch=multiarch\n    )\n\n    # Consider every minor version from X.0 to the minor version prior to the\n    # version requested by the platform.\n    for minor in range(version[1] - 1, -1, -1):\n        yield ios_platform_template.format(\n            major=version[0], minor=minor, multiarch=multiarch\n        )\n\n    for major in range(version[0] - 1, 11, -1):\n        for minor in range(9, -1, -1):\n            yield ios_platform_template.format(\n                major=major, minor=minor, multiarch=multiarch\n            )\n\n\ndef android_platforms(\n    api_level: int | None = None, abi: str | None = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on\n    non-Android platforms, the ``api_level`` and ``abi`` arguments are required.\n\n    :param int api_level: The maximum `API level\n        <https://developer.android.com/tools/releases/platforms>`__ to return. Defaults\n        to the current system's version, as returned by ``platform.android_ver``.\n    :param str abi: The `Android ABI <https://developer.android.com/ndk/guides/abis>`__,\n        e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by\n        ``sysconfig.get_platform``. Hyphens and periods will be replaced with\n        underscores.\n    \"\"\"\n    if platform.system() != \"Android\" and (api_level is None or abi is None):\n        raise TypeError(\n            \"on non-Android platforms, the api_level and abi arguments are required\"\n        )\n\n    if api_level is None:\n        # Python 3.13 was the first version to return platform.system() == \"Android\",\n        # and also the first version to define platform.android_ver().\n        api_level = platform.android_ver().api_level  # type: ignore[attr-defined]\n\n    if abi is None:\n        abi = sysconfig.get_platform().split(\"-\")[-1]\n    abi = _normalize_string(abi)\n\n    # 16 is the minimum API level known to have enough features to support CPython\n    # without major patching. Yield every API level from the maximum down to the\n    # minimum, inclusive.\n    min_api_level = 16\n    for ver in range(api_level, min_api_level - 1, -1):\n        yield f\"android_{ver}_{abi}\"\n\n\ndef _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:\n    linux = _normalize_string(sysconfig.get_platform())\n    if not linux.startswith(\"linux_\"):\n        # we should never be here, just yield the sysconfig one and return\n        yield linux\n        return\n    if is_32bit:\n        if linux == \"linux_x86_64\":\n            linux = \"linux_i686\"\n        elif linux == \"linux_aarch64\":\n            linux = \"linux_armv8l\"\n    _, arch = linux.split(\"_\", 1)\n    archs = {\"armv8l\": [\"armv8l\", \"armv7l\"]}.get(arch, [arch])\n    yield from _manylinux.platform_tags(archs)\n    yield from _musllinux.platform_tags(archs)\n    for arch in archs:\n        yield f\"linux_{arch}\"\n\n\ndef _generic_platforms() -> Iterator[str]:\n    yield _normalize_string(sysconfig.get_platform())\n\n\ndef platform_tags() -> Iterator[str]:\n    \"\"\"\n    Provides the platform tags for this installation.\n    \"\"\"\n    if platform.system() == \"Darwin\":\n        return mac_platforms()\n    elif platform.system() == \"iOS\":\n        return ios_platforms()\n    elif platform.system() == \"Android\":\n        return android_platforms()\n    elif platform.system() == \"Linux\":\n        return _linux_platforms()\n    else:\n        return _generic_platforms()\n\n\ndef interpreter_name() -> str:\n    \"\"\"\n    Returns the name of the running interpreter.\n\n    Some implementations have a reserved, two-letter abbreviation which will\n    be returned when appropriate.\n    \"\"\"\n    name = sys.implementation.name\n    return INTERPRETER_SHORT_NAMES.get(name) or name\n\n\ndef interpreter_version(*, warn: bool = False) -> str:\n    \"\"\"\n    Returns the version of the running interpreter.\n    \"\"\"\n    version = _get_config_var(\"py_version_nodot\", warn=warn)\n    return str(version) if version else _version_nodot(sys.version_info[:2])\n\n\ndef _version_nodot(version: PythonVersion) -> str:\n    return \"\".join(map(str, version))\n\n\ndef sys_tags(*, warn: bool = False) -> Iterator[Tag]:\n    \"\"\"\n    Returns the sequence of tag triples for the running interpreter.\n\n    The order of the sequence corresponds to priority order for the\n    interpreter, from most to least important.\n    \"\"\"\n\n    interp_name = interpreter_name()\n    if interp_name == \"cp\":\n        yield from cpython_tags(warn=warn)\n    else:\n        yield from generic_tags()\n\n    if interp_name == \"pp\":\n        interp = \"pp3\"\n    elif interp_name == \"cp\":\n        interp = \"cp\" + interpreter_version(warn=warn)\n    else:\n        interp = None\n    yield from compatible_tags(interpreter=interp)\n"
  },
  {
    "path": "src/pip/_vendor/packaging/utils.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import annotations\n\nimport re\nfrom typing import NewType, Tuple, Union, cast\n\nfrom .tags import Tag, parse_tag\nfrom .version import InvalidVersion, Version, _TrimmedRelease\n\nBuildTag = Union[Tuple[()], Tuple[int, str]]\nNormalizedName = NewType(\"NormalizedName\", str)\n\n\nclass InvalidName(ValueError):\n    \"\"\"\n    An invalid distribution name; users should refer to the packaging user guide.\n    \"\"\"\n\n\nclass InvalidWheelFilename(ValueError):\n    \"\"\"\n    An invalid wheel filename was found, users should refer to PEP 427.\n    \"\"\"\n\n\nclass InvalidSdistFilename(ValueError):\n    \"\"\"\n    An invalid sdist filename was found, users should refer to the packaging user guide.\n    \"\"\"\n\n\n# Core metadata spec for `Name`\n_validate_regex = re.compile(r\"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]\", re.IGNORECASE)\n_normalized_regex = re.compile(r\"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]\")\n# PEP 427: The build number must start with a digit.\n_build_tag_regex = re.compile(r\"(\\d+)(.*)\")\n\n\ndef canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:\n    if validate and not _validate_regex.fullmatch(name):\n        raise InvalidName(f\"name is invalid: {name!r}\")\n    # Ensure all ``.`` and ``_`` are ``-``\n    # Emulates ``re.sub(r\"[-_.]+\", \"-\", name).lower()`` from PEP 503\n    # Much faster than re, and even faster than str.translate\n    value = name.lower().replace(\"_\", \"-\").replace(\".\", \"-\")\n    # Condense repeats (faster than regex)\n    while \"--\" in value:\n        value = value.replace(\"--\", \"-\")\n    return cast(\"NormalizedName\", value)\n\n\ndef is_normalized_name(name: str) -> bool:\n    return _normalized_regex.fullmatch(name) is not None\n\n\ndef canonicalize_version(\n    version: Version | str, *, strip_trailing_zero: bool = True\n) -> str:\n    \"\"\"\n    Return a canonical form of a version as a string.\n\n    >>> canonicalize_version('1.0.1')\n    '1.0.1'\n\n    Per PEP 625, versions may have multiple canonical forms, differing\n    only by trailing zeros.\n\n    >>> canonicalize_version('1.0.0')\n    '1'\n    >>> canonicalize_version('1.0.0', strip_trailing_zero=False)\n    '1.0.0'\n\n    Invalid versions are returned unaltered.\n\n    >>> canonicalize_version('foo bar baz')\n    'foo bar baz'\n    \"\"\"\n    if isinstance(version, str):\n        try:\n            version = Version(version)\n        except InvalidVersion:\n            return str(version)\n    return str(_TrimmedRelease(version) if strip_trailing_zero else version)\n\n\ndef parse_wheel_filename(\n    filename: str,\n) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]:\n    if not filename.endswith(\".whl\"):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (extension must be '.whl'): {filename!r}\"\n        )\n\n    filename = filename[:-4]\n    dashes = filename.count(\"-\")\n    if dashes not in (4, 5):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (wrong number of parts): {filename!r}\"\n        )\n\n    parts = filename.split(\"-\", dashes - 2)\n    name_part = parts[0]\n    # See PEP 427 for the rules on escaping the project name.\n    if \"__\" in name_part or re.match(r\"^[\\w\\d._]*$\", name_part, re.UNICODE) is None:\n        raise InvalidWheelFilename(f\"Invalid project name: {filename!r}\")\n    name = canonicalize_name(name_part)\n\n    try:\n        version = Version(parts[1])\n    except InvalidVersion as e:\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (invalid version): {filename!r}\"\n        ) from e\n\n    if dashes == 5:\n        build_part = parts[2]\n        build_match = _build_tag_regex.match(build_part)\n        if build_match is None:\n            raise InvalidWheelFilename(\n                f\"Invalid build number: {build_part} in {filename!r}\"\n            )\n        build = cast(\"BuildTag\", (int(build_match.group(1)), build_match.group(2)))\n    else:\n        build = ()\n    tags = parse_tag(parts[-1])\n    return (name, version, build, tags)\n\n\ndef parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]:\n    if filename.endswith(\".tar.gz\"):\n        file_stem = filename[: -len(\".tar.gz\")]\n    elif filename.endswith(\".zip\"):\n        file_stem = filename[: -len(\".zip\")]\n    else:\n        raise InvalidSdistFilename(\n            f\"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):\"\n            f\" {filename!r}\"\n        )\n\n    # We are requiring a PEP 440 version, which cannot contain dashes,\n    # so we split on the last dash.\n    name_part, sep, version_part = file_stem.rpartition(\"-\")\n    if not sep:\n        raise InvalidSdistFilename(f\"Invalid sdist filename: {filename!r}\")\n\n    name = canonicalize_name(name_part)\n\n    try:\n        version = Version(version_part)\n    except InvalidVersion as e:\n        raise InvalidSdistFilename(\n            f\"Invalid sdist filename (invalid version): {filename!r}\"\n        ) from e\n\n    return (name, version)\n"
  },
  {
    "path": "src/pip/_vendor/packaging/version.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\"\"\"\n.. testsetup::\n\n    from pip._vendor.packaging.version import parse, Version\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nimport sys\nimport typing\nfrom typing import (\n    Any,\n    Callable,\n    Literal,\n    NamedTuple,\n    SupportsInt,\n    Tuple,\n    TypedDict,\n    Union,\n)\n\nfrom ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType\n\nif typing.TYPE_CHECKING:\n    from typing_extensions import Self, Unpack\n\nif sys.version_info >= (3, 13):  # pragma: no cover\n    from warnings import deprecated as _deprecated\nelif typing.TYPE_CHECKING:\n    from typing_extensions import deprecated as _deprecated\nelse:  # pragma: no cover\n    import functools\n    import warnings\n\n    def _deprecated(message: str) -> object:\n        def decorator(func: object) -> object:\n            @functools.wraps(func)\n            def wrapper(*args: object, **kwargs: object) -> object:\n                warnings.warn(\n                    message,\n                    category=DeprecationWarning,\n                    stacklevel=2,\n                )\n                return func(*args, **kwargs)\n\n            return wrapper\n\n        return decorator\n\n\n_LETTER_NORMALIZATION = {\n    \"alpha\": \"a\",\n    \"beta\": \"b\",\n    \"c\": \"rc\",\n    \"pre\": \"rc\",\n    \"preview\": \"rc\",\n    \"rev\": \"post\",\n    \"r\": \"post\",\n}\n\n__all__ = [\"VERSION_PATTERN\", \"InvalidVersion\", \"Version\", \"parse\"]\n\nLocalType = Tuple[Union[int, str], ...]\n\nCmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]\nCmpLocalType = Union[\n    NegativeInfinityType,\n    Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],\n]\nCmpKey = Tuple[\n    int,\n    Tuple[int, ...],\n    CmpPrePostDevType,\n    CmpPrePostDevType,\n    CmpPrePostDevType,\n    CmpLocalType,\n]\nVersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]\n\n\nclass _VersionReplace(TypedDict, total=False):\n    epoch: int | None\n    release: tuple[int, ...] | None\n    pre: tuple[Literal[\"a\", \"b\", \"rc\"], int] | None\n    post: int | None\n    dev: int | None\n    local: str | None\n\n\ndef parse(version: str) -> Version:\n    \"\"\"Parse the given version string.\n\n    >>> parse('1.0.dev1')\n    <Version('1.0.dev1')>\n\n    :param version: The version string to parse.\n    :raises InvalidVersion: When the version string is not a valid version.\n    \"\"\"\n    return Version(version)\n\n\nclass InvalidVersion(ValueError):\n    \"\"\"Raised when a version string is not a valid version.\n\n    >>> Version(\"invalid\")\n    Traceback (most recent call last):\n        ...\n    packaging.version.InvalidVersion: Invalid version: 'invalid'\n    \"\"\"\n\n\nclass _BaseVersion:\n    __slots__ = ()\n\n    # This can also be a normal member (see the packaging_legacy package);\n    # we are just requiring it to be readable. Actually defining a property\n    # has runtime effect on subclasses, so it's typing only.\n    if typing.TYPE_CHECKING:\n\n        @property\n        def _key(self) -> tuple[Any, ...]: ...\n\n    def __hash__(self) -> int:\n        return hash(self._key)\n\n    # Please keep the duplicated `isinstance` check\n    # in the six comparisons hereunder\n    # unless you find a way to avoid adding overhead function calls.\n    def __lt__(self, other: _BaseVersion) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key < other._key\n\n    def __le__(self, other: _BaseVersion) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key <= other._key\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key == other._key\n\n    def __ge__(self, other: _BaseVersion) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key >= other._key\n\n    def __gt__(self, other: _BaseVersion) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key > other._key\n\n    def __ne__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key != other._key\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\n\n# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here\n_VERSION_PATTERN = r\"\"\"\n    v?+                                                   # optional leading v\n    (?:\n        (?:(?P<epoch>[0-9]+)!)?+                          # epoch\n        (?P<release>[0-9]+(?:\\.[0-9]+)*+)                 # release segment\n        (?P<pre>                                          # pre-release\n            [._-]?+\n            (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)\n            [._-]?+\n            (?P<pre_n>[0-9]+)?\n        )?+\n        (?P<post>                                         # post release\n            (?:-(?P<post_n1>[0-9]+))\n            |\n            (?:\n                [._-]?\n                (?P<post_l>post|rev|r)\n                [._-]?\n                (?P<post_n2>[0-9]+)?\n            )\n        )?+\n        (?P<dev>                                          # dev release\n            [._-]?+\n            (?P<dev_l>dev)\n            [._-]?+\n            (?P<dev_n>[0-9]+)?\n        )?+\n    )\n    (?:\\+\n        (?P<local>                                        # local version\n            [a-z0-9]+\n            (?:[._-][a-z0-9]+)*+\n        )\n    )?+\n\"\"\"\n\n_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace(\"*+\", \"*\").replace(\"?+\", \"?\")\n\n# Possessive qualifiers were added in Python 3.11.\n# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795\n# Older PyPy also had a bug.\nVERSION_PATTERN = (\n    _VERSION_PATTERN_OLD\n    if (sys.implementation.name == \"cpython\" and sys.version_info < (3, 11, 5))\n    or (sys.implementation.name == \"pypy\" and sys.version_info < (3, 11, 13))\n    or sys.version_info < (3, 11)\n    else _VERSION_PATTERN\n)\n\"\"\"\nA string containing the regular expression used to match a valid version.\n\nThe pattern is not anchored at either end, and is intended for embedding in larger\nexpressions (for example, matching a version number as part of a file name). The\nregular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``\nflags set.\n\n:meta hide-value:\n\"\"\"\n\n\n# Validation pattern for local version in replace()\n_LOCAL_PATTERN = re.compile(r\"[a-z0-9]+(?:[._-][a-z0-9]+)*\", re.IGNORECASE)\n\n\ndef _validate_epoch(value: object, /) -> int:\n    epoch = value or 0\n    if isinstance(epoch, int) and epoch >= 0:\n        return epoch\n    msg = f\"epoch must be non-negative integer, got {epoch}\"\n    raise InvalidVersion(msg)\n\n\ndef _validate_release(value: object, /) -> tuple[int, ...]:\n    release = (0,) if value is None else value\n    if (\n        isinstance(release, tuple)\n        and len(release) > 0\n        and all(isinstance(i, int) and i >= 0 for i in release)\n    ):\n        return release\n    msg = f\"release must be a non-empty tuple of non-negative integers, got {release}\"\n    raise InvalidVersion(msg)\n\n\ndef _validate_pre(value: object, /) -> tuple[Literal[\"a\", \"b\", \"rc\"], int] | None:\n    if value is None:\n        return value\n    if (\n        isinstance(value, tuple)\n        and len(value) == 2\n        and value[0] in (\"a\", \"b\", \"rc\")\n        and isinstance(value[1], int)\n        and value[1] >= 0\n    ):\n        return value\n    msg = f\"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}\"\n    raise InvalidVersion(msg)\n\n\ndef _validate_post(value: object, /) -> tuple[Literal[\"post\"], int] | None:\n    if value is None:\n        return value\n    if isinstance(value, int) and value >= 0:\n        return (\"post\", value)\n    msg = f\"post must be non-negative integer, got {value}\"\n    raise InvalidVersion(msg)\n\n\ndef _validate_dev(value: object, /) -> tuple[Literal[\"dev\"], int] | None:\n    if value is None:\n        return value\n    if isinstance(value, int) and value >= 0:\n        return (\"dev\", value)\n    msg = f\"dev must be non-negative integer, got {value}\"\n    raise InvalidVersion(msg)\n\n\ndef _validate_local(value: object, /) -> LocalType | None:\n    if value is None:\n        return value\n    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):\n        return _parse_local_version(value)\n    msg = f\"local must be a valid version string, got {value!r}\"\n    raise InvalidVersion(msg)\n\n\n# Backward compatibility for internals before 26.0. Do not use.\nclass _Version(NamedTuple):\n    epoch: int\n    release: tuple[int, ...]\n    dev: tuple[str, int] | None\n    pre: tuple[str, int] | None\n    post: tuple[str, int] | None\n    local: LocalType | None\n\n\nclass Version(_BaseVersion):\n    \"\"\"This class abstracts handling of a project's versions.\n\n    A :class:`Version` instance is comparison aware and can be compared and\n    sorted using the standard Python interfaces.\n\n    >>> v1 = Version(\"1.0a5\")\n    >>> v2 = Version(\"1.0\")\n    >>> v1\n    <Version('1.0a5')>\n    >>> v2\n    <Version('1.0')>\n    >>> v1 < v2\n    True\n    >>> v1 == v2\n    False\n    >>> v1 > v2\n    False\n    >>> v1 >= v2\n    False\n    >>> v1 <= v2\n    True\n    \"\"\"\n\n    __slots__ = (\"_dev\", \"_epoch\", \"_key_cache\", \"_local\", \"_post\", \"_pre\", \"_release\")\n    __match_args__ = (\"_str\",)\n\n    _regex = re.compile(r\"\\s*\" + VERSION_PATTERN + r\"\\s*\", re.VERBOSE | re.IGNORECASE)\n\n    _epoch: int\n    _release: tuple[int, ...]\n    _dev: tuple[str, int] | None\n    _pre: tuple[str, int] | None\n    _post: tuple[str, int] | None\n    _local: LocalType | None\n\n    _key_cache: CmpKey | None\n\n    def __init__(self, version: str) -> None:\n        \"\"\"Initialize a Version object.\n\n        :param version:\n            The string representation of a version which will be parsed and normalized\n            before use.\n        :raises InvalidVersion:\n            If the ``version`` does not conform to PEP 440 in any way then this\n            exception will be raised.\n        \"\"\"\n        # Validate the version and parse it into pieces\n        match = self._regex.fullmatch(version)\n        if not match:\n            raise InvalidVersion(f\"Invalid version: {version!r}\")\n        self._epoch = int(match.group(\"epoch\")) if match.group(\"epoch\") else 0\n        self._release = tuple(map(int, match.group(\"release\").split(\".\")))\n        self._pre = _parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\"))\n        self._post = _parse_letter_version(\n            match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n        )\n        self._dev = _parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\"))\n        self._local = _parse_local_version(match.group(\"local\"))\n\n        # Key which will be used for sorting\n        self._key_cache = None\n\n    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:\n        epoch = _validate_epoch(kwargs[\"epoch\"]) if \"epoch\" in kwargs else self._epoch\n        release = (\n            _validate_release(kwargs[\"release\"])\n            if \"release\" in kwargs\n            else self._release\n        )\n        pre = _validate_pre(kwargs[\"pre\"]) if \"pre\" in kwargs else self._pre\n        post = _validate_post(kwargs[\"post\"]) if \"post\" in kwargs else self._post\n        dev = _validate_dev(kwargs[\"dev\"]) if \"dev\" in kwargs else self._dev\n        local = _validate_local(kwargs[\"local\"]) if \"local\" in kwargs else self._local\n\n        if (\n            epoch == self._epoch\n            and release == self._release\n            and pre == self._pre\n            and post == self._post\n            and dev == self._dev\n            and local == self._local\n        ):\n            return self\n\n        new_version = self.__class__.__new__(self.__class__)\n        new_version._key_cache = None\n        new_version._epoch = epoch\n        new_version._release = release\n        new_version._pre = pre\n        new_version._post = post\n        new_version._dev = dev\n        new_version._local = local\n\n        return new_version\n\n    @property\n    def _key(self) -> CmpKey:\n        if self._key_cache is None:\n            self._key_cache = _cmpkey(\n                self._epoch,\n                self._release,\n                self._pre,\n                self._post,\n                self._dev,\n                self._local,\n            )\n        return self._key_cache\n\n    @property\n    @_deprecated(\"Version._version is private and will be removed soon\")\n    def _version(self) -> _Version:\n        return _Version(\n            self._epoch, self._release, self._dev, self._pre, self._post, self._local\n        )\n\n    @_version.setter\n    @_deprecated(\"Version._version is private and will be removed soon\")\n    def _version(self, value: _Version) -> None:\n        self._epoch = value.epoch\n        self._release = value.release\n        self._dev = value.dev\n        self._pre = value.pre\n        self._post = value.post\n        self._local = value.local\n        self._key_cache = None\n\n    def __repr__(self) -> str:\n        \"\"\"A representation of the Version that shows all internal state.\n\n        >>> Version('1.0.0')\n        <Version('1.0.0')>\n        \"\"\"\n        return f\"<Version('{self}')>\"\n\n    def __str__(self) -> str:\n        \"\"\"A string representation of the version that can be round-tripped.\n\n        >>> str(Version(\"1.0a5\"))\n        '1.0a5'\n        \"\"\"\n        # This is a hot function, so not calling self.base_version\n        version = \".\".join(map(str, self.release))\n\n        # Epoch\n        if self.epoch:\n            version = f\"{self.epoch}!{version}\"\n\n        # Pre-release\n        if self.pre is not None:\n            version += \"\".join(map(str, self.pre))\n\n        # Post-release\n        if self.post is not None:\n            version += f\".post{self.post}\"\n\n        # Development release\n        if self.dev is not None:\n            version += f\".dev{self.dev}\"\n\n        # Local version segment\n        if self.local is not None:\n            version += f\"+{self.local}\"\n\n        return version\n\n    @property\n    def _str(self) -> str:\n        \"\"\"Internal property for match_args\"\"\"\n        return str(self)\n\n    @property\n    def epoch(self) -> int:\n        \"\"\"The epoch of the version.\n\n        >>> Version(\"2.0.0\").epoch\n        0\n        >>> Version(\"1!2.0.0\").epoch\n        1\n        \"\"\"\n        return self._epoch\n\n    @property\n    def release(self) -> tuple[int, ...]:\n        \"\"\"The components of the \"release\" segment of the version.\n\n        >>> Version(\"1.2.3\").release\n        (1, 2, 3)\n        >>> Version(\"2.0.0\").release\n        (2, 0, 0)\n        >>> Version(\"1!2.0.0.post0\").release\n        (2, 0, 0)\n\n        Includes trailing zeroes but not the epoch or any pre-release / development /\n        post-release suffixes.\n        \"\"\"\n        return self._release\n\n    @property\n    def pre(self) -> tuple[str, int] | None:\n        \"\"\"The pre-release segment of the version.\n\n        >>> print(Version(\"1.2.3\").pre)\n        None\n        >>> Version(\"1.2.3a1\").pre\n        ('a', 1)\n        >>> Version(\"1.2.3b1\").pre\n        ('b', 1)\n        >>> Version(\"1.2.3rc1\").pre\n        ('rc', 1)\n        \"\"\"\n        return self._pre\n\n    @property\n    def post(self) -> int | None:\n        \"\"\"The post-release number of the version.\n\n        >>> print(Version(\"1.2.3\").post)\n        None\n        >>> Version(\"1.2.3.post1\").post\n        1\n        \"\"\"\n        return self._post[1] if self._post else None\n\n    @property\n    def dev(self) -> int | None:\n        \"\"\"The development number of the version.\n\n        >>> print(Version(\"1.2.3\").dev)\n        None\n        >>> Version(\"1.2.3.dev1\").dev\n        1\n        \"\"\"\n        return self._dev[1] if self._dev else None\n\n    @property\n    def local(self) -> str | None:\n        \"\"\"The local version segment of the version.\n\n        >>> print(Version(\"1.2.3\").local)\n        None\n        >>> Version(\"1.2.3+abc\").local\n        'abc'\n        \"\"\"\n        if self._local:\n            return \".\".join(str(x) for x in self._local)\n        else:\n            return None\n\n    @property\n    def public(self) -> str:\n        \"\"\"The public portion of the version.\n\n        >>> Version(\"1.2.3\").public\n        '1.2.3'\n        >>> Version(\"1.2.3+abc\").public\n        '1.2.3'\n        >>> Version(\"1!1.2.3dev1+abc\").public\n        '1!1.2.3.dev1'\n        \"\"\"\n        return str(self).split(\"+\", 1)[0]\n\n    @property\n    def base_version(self) -> str:\n        \"\"\"The \"base version\" of the version.\n\n        >>> Version(\"1.2.3\").base_version\n        '1.2.3'\n        >>> Version(\"1.2.3+abc\").base_version\n        '1.2.3'\n        >>> Version(\"1!1.2.3dev1+abc\").base_version\n        '1!1.2.3'\n\n        The \"base version\" is the public version of the project without any pre or post\n        release markers.\n        \"\"\"\n        release_segment = \".\".join(map(str, self.release))\n        return f\"{self.epoch}!{release_segment}\" if self.epoch else release_segment\n\n    @property\n    def is_prerelease(self) -> bool:\n        \"\"\"Whether this version is a pre-release.\n\n        >>> Version(\"1.2.3\").is_prerelease\n        False\n        >>> Version(\"1.2.3a1\").is_prerelease\n        True\n        >>> Version(\"1.2.3b1\").is_prerelease\n        True\n        >>> Version(\"1.2.3rc1\").is_prerelease\n        True\n        >>> Version(\"1.2.3dev1\").is_prerelease\n        True\n        \"\"\"\n        return self.dev is not None or self.pre is not None\n\n    @property\n    def is_postrelease(self) -> bool:\n        \"\"\"Whether this version is a post-release.\n\n        >>> Version(\"1.2.3\").is_postrelease\n        False\n        >>> Version(\"1.2.3.post1\").is_postrelease\n        True\n        \"\"\"\n        return self.post is not None\n\n    @property\n    def is_devrelease(self) -> bool:\n        \"\"\"Whether this version is a development release.\n\n        >>> Version(\"1.2.3\").is_devrelease\n        False\n        >>> Version(\"1.2.3.dev1\").is_devrelease\n        True\n        \"\"\"\n        return self.dev is not None\n\n    @property\n    def major(self) -> int:\n        \"\"\"The first item of :attr:`release` or ``0`` if unavailable.\n\n        >>> Version(\"1.2.3\").major\n        1\n        \"\"\"\n        return self.release[0] if len(self.release) >= 1 else 0\n\n    @property\n    def minor(self) -> int:\n        \"\"\"The second item of :attr:`release` or ``0`` if unavailable.\n\n        >>> Version(\"1.2.3\").minor\n        2\n        >>> Version(\"1\").minor\n        0\n        \"\"\"\n        return self.release[1] if len(self.release) >= 2 else 0\n\n    @property\n    def micro(self) -> int:\n        \"\"\"The third item of :attr:`release` or ``0`` if unavailable.\n\n        >>> Version(\"1.2.3\").micro\n        3\n        >>> Version(\"1\").micro\n        0\n        \"\"\"\n        return self.release[2] if len(self.release) >= 3 else 0\n\n\nclass _TrimmedRelease(Version):\n    __slots__ = ()\n\n    def __init__(self, version: str | Version) -> None:\n        if isinstance(version, Version):\n            self._epoch = version._epoch\n            self._release = version._release\n            self._dev = version._dev\n            self._pre = version._pre\n            self._post = version._post\n            self._local = version._local\n            self._key_cache = version._key_cache\n            return\n        super().__init__(version)  # pragma: no cover\n\n    @property\n    def release(self) -> tuple[int, ...]:\n        \"\"\"\n        Release segment without any trailing zeros.\n\n        >>> _TrimmedRelease('1.0.0').release\n        (1,)\n        >>> _TrimmedRelease('0.0').release\n        (0,)\n        \"\"\"\n        # This leaves one 0.\n        rel = super().release\n        len_release = len(rel)\n        i = len_release\n        while i > 1 and rel[i - 1] == 0:\n            i -= 1\n        return rel if i == len_release else rel[:i]\n\n\ndef _parse_letter_version(\n    letter: str | None, number: str | bytes | SupportsInt | None\n) -> tuple[str, int] | None:\n    if letter:\n        # We normalize any letters to their lower case form\n        letter = letter.lower()\n\n        # We consider some words to be alternate spellings of other words and\n        # in those cases we want to normalize the spellings to our preferred\n        # spelling.\n        letter = _LETTER_NORMALIZATION.get(letter, letter)\n\n        # We consider there to be an implicit 0 in a pre-release if there is\n        # not a numeral associated with it.\n        return letter, int(number or 0)\n\n    if number:\n        # We assume if we are given a number, but we are not given a letter\n        # then this is using the implicit post release syntax (e.g. 1.0-1)\n        return \"post\", int(number)\n\n    return None\n\n\n_local_version_separators = re.compile(r\"[\\._-]\")\n\n\ndef _parse_local_version(local: str | None) -> LocalType | None:\n    \"\"\"\n    Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n    \"\"\"\n    if local is not None:\n        return tuple(\n            part.lower() if not part.isdigit() else int(part)\n            for part in _local_version_separators.split(local)\n        )\n    return None\n\n\ndef _cmpkey(\n    epoch: int,\n    release: tuple[int, ...],\n    pre: tuple[str, int] | None,\n    post: tuple[str, int] | None,\n    dev: tuple[str, int] | None,\n    local: LocalType | None,\n) -> CmpKey:\n    # When we compare a release version, we want to compare it with all of the\n    # trailing zeros removed. We will use this for our sorting key.\n    len_release = len(release)\n    i = len_release\n    while i and release[i - 1] == 0:\n        i -= 1\n    _release = release if i == len_release else release[:i]\n\n    # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n    # We'll do this by abusing the pre segment, but we _only_ want to do this\n    # if there is not a pre or a post segment. If we have one of those then\n    # the normal sorting rules will handle this case correctly.\n    if pre is None and post is None and dev is not None:\n        _pre: CmpPrePostDevType = NegativeInfinity\n    # Versions without a pre-release (except as noted above) should sort after\n    # those with one.\n    elif pre is None:\n        _pre = Infinity\n    else:\n        _pre = pre\n\n    # Versions without a post segment should sort before those with one.\n    if post is None:\n        _post: CmpPrePostDevType = NegativeInfinity\n\n    else:\n        _post = post\n\n    # Versions without a development segment should sort after those with one.\n    if dev is None:\n        _dev: CmpPrePostDevType = Infinity\n\n    else:\n        _dev = dev\n\n    if local is None:\n        # Versions without a local segment should sort before those with one.\n        _local: CmpLocalType = NegativeInfinity\n    else:\n        # Versions with a local segment need that segment parsed to implement\n        # the sorting rules in PEP440.\n        # - Alpha numeric segments sort before numeric segments\n        # - Alpha numeric segments sort lexicographically\n        # - Numeric segments sort numerically\n        # - Shorter versions sort before longer versions when the prefixes\n        #   match exactly\n        _local = tuple(\n            (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n        )\n\n    return epoch, _release, _pre, _post, _dev, _local\n"
  },
  {
    "path": "src/pip/_vendor/pkg_resources/LICENSE",
    "content": "Permission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/pkg_resources/__init__.py",
    "content": "# TODO: Add Generic type annotations to initialized collections.\n# For now we'd simply use implicit Any/Unknown which would add redundant annotations\n# mypy: disable-error-code=\"var-annotated\"\n\"\"\"\nPackage resource API\n--------------------\n\nA resource is a logical file contained within a package, or a logical\nsubdirectory thereof.  The package resource API expects resource names\nto have their path parts separated with ``/``, *not* whatever the local\npath separator is.  Do not use os.path operations to manipulate resource\nnames being passed into the API.\n\nThe package resource API is designed to work with normal filesystem packages,\n.egg files, and unpacked .egg files.  It can also work in a limited way with\n.zip files and with custom PEP 302 loaders that support the ``get_data()``\nmethod.\n\nThis module is deprecated. Users are directed to :mod:`importlib.resources`,\n:mod:`importlib.metadata` and :pypi:`packaging` instead.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\nif sys.version_info < (3, 8):  # noqa: UP036 # Check for unsupported versions\n    raise RuntimeError(\"Python 3.8 or later is required\")\n\nimport os\nimport io\nimport time\nimport re\nimport types\nfrom typing import (\n    Any,\n    Literal,\n    Dict,\n    Iterator,\n    Mapping,\n    MutableSequence,\n    NamedTuple,\n    NoReturn,\n    Tuple,\n    Union,\n    TYPE_CHECKING,\n    Protocol,\n    Callable,\n    Iterable,\n    TypeVar,\n    overload,\n)\nimport zipfile\nimport zipimport\nimport warnings\nimport stat\nimport functools\nimport pkgutil\nimport operator\nimport platform\nimport collections\nimport plistlib\nimport email.parser\nimport errno\nimport tempfile\nimport textwrap\nimport inspect\nimport ntpath\nimport posixpath\nimport importlib\nimport importlib.abc\nimport importlib.machinery\nfrom pkgutil import get_importer\n\nimport _imp\n\n# capture these to bypass sandboxing\nfrom os import utime\nfrom os import open as os_open\nfrom os.path import isdir, split\n\ntry:\n    from os import mkdir, rename, unlink\n\n    WRITE_SUPPORT = True\nexcept ImportError:\n    # no write support, probably under GAE\n    WRITE_SUPPORT = False\n\nfrom pip._internal.utils._jaraco_text import (\n    yield_lines,\n    drop_comment,\n    join_continuation,\n)\nfrom pip._vendor.packaging import markers as _packaging_markers\nfrom pip._vendor.packaging import requirements as _packaging_requirements\nfrom pip._vendor.packaging import utils as _packaging_utils\nfrom pip._vendor.packaging import version as _packaging_version\nfrom pip._vendor.platformdirs import user_cache_dir as _user_cache_dir\n\nif TYPE_CHECKING:\n    from _typeshed import BytesPath, StrPath, StrOrBytesPath\n    from typing_extensions import Self\n\n\n# Patch: Remove deprecation warning from vendored pkg_resources.\n# Setting PYTHONWARNINGS=error to verify builds produce no warnings\n# causes immediate exceptions.\n# See https://github.com/pypa/pip/issues/12243\n\n\n_T = TypeVar(\"_T\")\n_DistributionT = TypeVar(\"_DistributionT\", bound=\"Distribution\")\n# Type aliases\n_NestedStr = Union[str, Iterable[Union[str, Iterable[\"_NestedStr\"]]]]\n_InstallerTypeT = Callable[[\"Requirement\"], \"_DistributionT\"]\n_InstallerType = Callable[[\"Requirement\"], Union[\"Distribution\", None]]\n_PkgReqType = Union[str, \"Requirement\"]\n_EPDistType = Union[\"Distribution\", _PkgReqType]\n_MetadataType = Union[\"IResourceProvider\", None]\n_ResolvedEntryPoint = Any  # Can be any attribute in the module\n_ResourceStream = Any  # TODO / Incomplete: A readable file-like object\n# Any object works, but let's indicate we expect something like a module (optionally has __loader__ or __file__)\n_ModuleLike = Union[object, types.ModuleType]\n# Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__\n_ProviderFactoryType = Callable[[Any], \"IResourceProvider\"]\n_DistFinderType = Callable[[_T, str, bool], Iterable[\"Distribution\"]]\n_NSHandlerType = Callable[[_T, str, str, types.ModuleType], Union[str, None]]\n_AdapterT = TypeVar(\n    \"_AdapterT\", _DistFinderType[Any], _ProviderFactoryType, _NSHandlerType[Any]\n)\n\n\n# Use _typeshed.importlib.LoaderProtocol once available https://github.com/python/typeshed/pull/11890\nclass _LoaderProtocol(Protocol):\n    def load_module(self, fullname: str, /) -> types.ModuleType: ...\n\n\nclass _ZipLoaderModule(Protocol):\n    __loader__: zipimport.zipimporter\n\n\n_PEP440_FALLBACK = re.compile(r\"^v?(?P<safe>(?:[0-9]+!)?[0-9]+(?:\\.[0-9]+)*)\", re.I)\n\n\nclass PEP440Warning(RuntimeWarning):\n    \"\"\"\n    Used when there is an issue with a version or specifier not complying with\n    PEP 440.\n    \"\"\"\n\n\nparse_version = _packaging_version.Version\n\n\n_state_vars: dict[str, str] = {}\n\n\ndef _declare_state(vartype: str, varname: str, initial_value: _T) -> _T:\n    _state_vars[varname] = vartype\n    return initial_value\n\n\ndef __getstate__() -> dict[str, Any]:\n    state = {}\n    g = globals()\n    for k, v in _state_vars.items():\n        state[k] = g['_sget_' + v](g[k])\n    return state\n\n\ndef __setstate__(state: dict[str, Any]) -> dict[str, Any]:\n    g = globals()\n    for k, v in state.items():\n        g['_sset_' + _state_vars[k]](k, g[k], v)\n    return state\n\n\ndef _sget_dict(val):\n    return val.copy()\n\n\ndef _sset_dict(key, ob, state):\n    ob.clear()\n    ob.update(state)\n\n\ndef _sget_object(val):\n    return val.__getstate__()\n\n\ndef _sset_object(key, ob, state):\n    ob.__setstate__(state)\n\n\n_sget_none = _sset_none = lambda *args: None\n\n\ndef get_supported_platform():\n    \"\"\"Return this platform's maximum compatible version.\n\n    distutils.util.get_platform() normally reports the minimum version\n    of macOS that would be required to *use* extensions produced by\n    distutils.  But what we want when checking compatibility is to know the\n    version of macOS that we are *running*.  To allow usage of packages that\n    explicitly require a newer version of macOS, we must also know the\n    current version of the OS.\n\n    If this condition occurs for any other platform with a version in its\n    platform strings, this function should be extended accordingly.\n    \"\"\"\n    plat = get_build_platform()\n    m = macosVersionString.match(plat)\n    if m is not None and sys.platform == \"darwin\":\n        try:\n            plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))\n        except ValueError:\n            # not macOS\n            pass\n    return plat\n\n\n__all__ = [\n    # Basic resource access and distribution/entry point discovery\n    'require',\n    'run_script',\n    'get_provider',\n    'get_distribution',\n    'load_entry_point',\n    'get_entry_map',\n    'get_entry_info',\n    'iter_entry_points',\n    'resource_string',\n    'resource_stream',\n    'resource_filename',\n    'resource_listdir',\n    'resource_exists',\n    'resource_isdir',\n    # Environmental control\n    'declare_namespace',\n    'working_set',\n    'add_activation_listener',\n    'find_distributions',\n    'set_extraction_path',\n    'cleanup_resources',\n    'get_default_cache',\n    # Primary implementation classes\n    'Environment',\n    'WorkingSet',\n    'ResourceManager',\n    'Distribution',\n    'Requirement',\n    'EntryPoint',\n    # Exceptions\n    'ResolutionError',\n    'VersionConflict',\n    'DistributionNotFound',\n    'UnknownExtra',\n    'ExtractionError',\n    # Warnings\n    'PEP440Warning',\n    # Parsing functions and string utilities\n    'parse_requirements',\n    'parse_version',\n    'safe_name',\n    'safe_version',\n    'get_platform',\n    'compatible_platforms',\n    'yield_lines',\n    'split_sections',\n    'safe_extra',\n    'to_filename',\n    'invalid_marker',\n    'evaluate_marker',\n    # filesystem utilities\n    'ensure_directory',\n    'normalize_path',\n    # Distribution \"precedence\" constants\n    'EGG_DIST',\n    'BINARY_DIST',\n    'SOURCE_DIST',\n    'CHECKOUT_DIST',\n    'DEVELOP_DIST',\n    # \"Provider\" interfaces, implementations, and registration/lookup APIs\n    'IMetadataProvider',\n    'IResourceProvider',\n    'FileMetadata',\n    'PathMetadata',\n    'EggMetadata',\n    'EmptyProvider',\n    'empty_provider',\n    'NullProvider',\n    'EggProvider',\n    'DefaultProvider',\n    'ZipProvider',\n    'register_finder',\n    'register_namespace_handler',\n    'register_loader_type',\n    'fixup_namespace_packages',\n    'get_importer',\n    # Warnings\n    'PkgResourcesDeprecationWarning',\n    # Deprecated/backward compatibility only\n    'run_main',\n    'AvailableDistributions',\n]\n\n\nclass ResolutionError(Exception):\n    \"\"\"Abstract base for dependency resolution errors\"\"\"\n\n    def __repr__(self):\n        return self.__class__.__name__ + repr(self.args)\n\n\nclass VersionConflict(ResolutionError):\n    \"\"\"\n    An already-installed version conflicts with the requested version.\n\n    Should be initialized with the installed Distribution and the requested\n    Requirement.\n    \"\"\"\n\n    _template = \"{self.dist} is installed but {self.req} is required\"\n\n    @property\n    def dist(self) -> Distribution:\n        return self.args[0]\n\n    @property\n    def req(self) -> Requirement:\n        return self.args[1]\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def with_context(self, required_by: set[Distribution | str]):\n        \"\"\"\n        If required_by is non-empty, return a version of self that is a\n        ContextualVersionConflict.\n        \"\"\"\n        if not required_by:\n            return self\n        args = self.args + (required_by,)\n        return ContextualVersionConflict(*args)\n\n\nclass ContextualVersionConflict(VersionConflict):\n    \"\"\"\n    A VersionConflict that accepts a third parameter, the set of the\n    requirements that required the installed Distribution.\n    \"\"\"\n\n    _template = VersionConflict._template + ' by {self.required_by}'\n\n    @property\n    def required_by(self) -> set[str]:\n        return self.args[2]\n\n\nclass DistributionNotFound(ResolutionError):\n    \"\"\"A requested distribution was not found\"\"\"\n\n    _template = (\n        \"The '{self.req}' distribution was not found \"\n        \"and is required by {self.requirers_str}\"\n    )\n\n    @property\n    def req(self) -> Requirement:\n        return self.args[0]\n\n    @property\n    def requirers(self) -> set[str] | None:\n        return self.args[1]\n\n    @property\n    def requirers_str(self):\n        if not self.requirers:\n            return 'the application'\n        return ', '.join(self.requirers)\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def __str__(self):\n        return self.report()\n\n\nclass UnknownExtra(ResolutionError):\n    \"\"\"Distribution doesn't have an \"extra feature\" of the given name\"\"\"\n\n\n_provider_factories: dict[type[_ModuleLike], _ProviderFactoryType] = {}\n\nPY_MAJOR = '{}.{}'.format(*sys.version_info)\nEGG_DIST = 3\nBINARY_DIST = 2\nSOURCE_DIST = 1\nCHECKOUT_DIST = 0\nDEVELOP_DIST = -1\n\n\ndef register_loader_type(\n    loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType\n):\n    \"\"\"Register `provider_factory` to make providers for `loader_type`\n\n    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,\n    and `provider_factory` is a function that, passed a *module* object,\n    returns an ``IResourceProvider`` for that module.\n    \"\"\"\n    _provider_factories[loader_type] = provider_factory\n\n\n@overload\ndef get_provider(moduleOrReq: str) -> IResourceProvider: ...\n@overload\ndef get_provider(moduleOrReq: Requirement) -> Distribution: ...\ndef get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribution:\n    \"\"\"Return an IResourceProvider for the named module or requirement\"\"\"\n    if isinstance(moduleOrReq, Requirement):\n        return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]\n    try:\n        module = sys.modules[moduleOrReq]\n    except KeyError:\n        __import__(moduleOrReq)\n        module = sys.modules[moduleOrReq]\n    loader = getattr(module, '__loader__', None)\n    return _find_adapter(_provider_factories, loader)(module)\n\n\n@functools.lru_cache(maxsize=None)\ndef _macos_vers():\n    version = platform.mac_ver()[0]\n    # fallback for MacPorts\n    if version == '':\n        plist = '/System/Library/CoreServices/SystemVersion.plist'\n        if os.path.exists(plist):\n            with open(plist, 'rb') as fh:\n                plist_content = plistlib.load(fh)\n            if 'ProductVersion' in plist_content:\n                version = plist_content['ProductVersion']\n    return version.split('.')\n\n\ndef _macos_arch(machine):\n    return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)\n\n\ndef get_build_platform():\n    \"\"\"Return this platform's string for platform-specific distributions\n\n    XXX Currently this is the same as ``distutils.util.get_platform()``, but it\n    needs some hacks for Linux and macOS.\n    \"\"\"\n    from sysconfig import get_platform\n\n    plat = get_platform()\n    if sys.platform == \"darwin\" and not plat.startswith('macosx-'):\n        try:\n            version = _macos_vers()\n            machine = os.uname()[4].replace(\" \", \"_\")\n            return \"macosx-%d.%d-%s\" % (\n                int(version[0]),\n                int(version[1]),\n                _macos_arch(machine),\n            )\n        except ValueError:\n            # if someone is running a non-Mac darwin system, this will fall\n            # through to the default implementation\n            pass\n    return plat\n\n\nmacosVersionString = re.compile(r\"macosx-(\\d+)\\.(\\d+)-(.*)\")\ndarwinVersionString = re.compile(r\"darwin-(\\d+)\\.(\\d+)\\.(\\d+)-(.*)\")\n# XXX backward compat\nget_platform = get_build_platform\n\n\ndef compatible_platforms(provided: str | None, required: str | None):\n    \"\"\"Can code for the `provided` platform run on the `required` platform?\n\n    Returns true if either platform is ``None``, or the platforms are equal.\n\n    XXX Needs compatibility checks for Linux and other unixy OSes.\n    \"\"\"\n    if provided is None or required is None or provided == required:\n        # easy case\n        return True\n\n    # macOS special cases\n    reqMac = macosVersionString.match(required)\n    if reqMac:\n        provMac = macosVersionString.match(provided)\n\n        # is this a Mac package?\n        if not provMac:\n            # this is backwards compatibility for packages built before\n            # setuptools 0.6. All packages built after this point will\n            # use the new macOS designation.\n            provDarwin = darwinVersionString.match(provided)\n            if provDarwin:\n                dversion = int(provDarwin.group(1))\n                macosversion = \"%s.%s\" % (reqMac.group(1), reqMac.group(2))\n                if (\n                    dversion == 7\n                    and macosversion >= \"10.3\"\n                    or dversion == 8\n                    and macosversion >= \"10.4\"\n                ):\n                    return True\n            # egg isn't macOS or legacy darwin\n            return False\n\n        # are they the same major version and machine type?\n        if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):\n            return False\n\n        # is the required OS major update >= the provided one?\n        if int(provMac.group(2)) > int(reqMac.group(2)):\n            return False\n\n        return True\n\n    # XXX Linux and other platforms' special cases should go here\n    return False\n\n\n@overload\ndef get_distribution(dist: _DistributionT) -> _DistributionT: ...\n@overload\ndef get_distribution(dist: _PkgReqType) -> Distribution: ...\ndef get_distribution(dist: Distribution | _PkgReqType) -> Distribution:\n    \"\"\"Return a current distribution object for a Requirement or string\"\"\"\n    if isinstance(dist, str):\n        dist = Requirement.parse(dist)\n    if isinstance(dist, Requirement):\n        # Bad type narrowing, dist has to be a Requirement here, so get_provider has to return Distribution\n        dist = get_provider(dist)  # type: ignore[assignment]\n    if not isinstance(dist, Distribution):\n        raise TypeError(\"Expected str, Requirement, or Distribution\", dist)\n    return dist\n\n\ndef load_entry_point(dist: _EPDistType, group: str, name: str) -> _ResolvedEntryPoint:\n    \"\"\"Return `name` entry point of `group` for `dist` or raise ImportError\"\"\"\n    return get_distribution(dist).load_entry_point(group, name)\n\n\n@overload\ndef get_entry_map(\n    dist: _EPDistType, group: None = None\n) -> dict[str, dict[str, EntryPoint]]: ...\n@overload\ndef get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ...\ndef get_entry_map(dist: _EPDistType, group: str | None = None):\n    \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n    return get_distribution(dist).get_entry_map(group)\n\n\ndef get_entry_info(dist: _EPDistType, group: str, name: str):\n    \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n    return get_distribution(dist).get_entry_info(group, name)\n\n\nclass IMetadataProvider(Protocol):\n    def has_metadata(self, name: str) -> bool:\n        \"\"\"Does the package's distribution contain the named metadata?\"\"\"\n\n    def get_metadata(self, name: str) -> str:\n        \"\"\"The named metadata resource as a string\"\"\"\n\n    def get_metadata_lines(self, name: str) -> Iterator[str]:\n        \"\"\"Yield named metadata resource as list of non-blank non-comment lines\n\n        Leading and trailing whitespace is stripped from each line, and lines\n        with ``#`` as the first non-blank character are omitted.\"\"\"\n\n    def metadata_isdir(self, name: str) -> bool:\n        \"\"\"Is the named metadata a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def metadata_listdir(self, name: str) -> list[str]:\n        \"\"\"List of metadata names in the directory (like ``os.listdir()``)\"\"\"\n\n    def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:\n        \"\"\"Execute the named script in the supplied namespace dictionary\"\"\"\n\n\nclass IResourceProvider(IMetadataProvider, Protocol):\n    \"\"\"An object that provides access to package resources\"\"\"\n\n    def get_resource_filename(\n        self, manager: ResourceManager, resource_name: str\n    ) -> str:\n        \"\"\"Return a true filesystem path for `resource_name`\n\n        `manager` must be a ``ResourceManager``\"\"\"\n\n    def get_resource_stream(\n        self, manager: ResourceManager, resource_name: str\n    ) -> _ResourceStream:\n        \"\"\"Return a readable file-like object for `resource_name`\n\n        `manager` must be a ``ResourceManager``\"\"\"\n\n    def get_resource_string(\n        self, manager: ResourceManager, resource_name: str\n    ) -> bytes:\n        \"\"\"Return the contents of `resource_name` as :obj:`bytes`\n\n        `manager` must be a ``ResourceManager``\"\"\"\n\n    def has_resource(self, resource_name: str) -> bool:\n        \"\"\"Does the package contain the named resource?\"\"\"\n\n    def resource_isdir(self, resource_name: str) -> bool:\n        \"\"\"Is the named resource a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def resource_listdir(self, resource_name: str) -> list[str]:\n        \"\"\"List of resource names in the directory (like ``os.listdir()``)\"\"\"\n\n\nclass WorkingSet:\n    \"\"\"A collection of active distributions on sys.path (or a similar list)\"\"\"\n\n    def __init__(self, entries: Iterable[str] | None = None):\n        \"\"\"Create working set from list of path entries (default=sys.path)\"\"\"\n        self.entries: list[str] = []\n        self.entry_keys = {}\n        self.by_key = {}\n        self.normalized_to_canonical_keys = {}\n        self.callbacks = []\n\n        if entries is None:\n            entries = sys.path\n\n        for entry in entries:\n            self.add_entry(entry)\n\n    @classmethod\n    def _build_master(cls):\n        \"\"\"\n        Prepare the master working set.\n        \"\"\"\n        ws = cls()\n        try:\n            from __main__ import __requires__\n        except ImportError:\n            # The main program does not list any requirements\n            return ws\n\n        # ensure the requirements are met\n        try:\n            ws.require(__requires__)\n        except VersionConflict:\n            return cls._build_from_requirements(__requires__)\n\n        return ws\n\n    @classmethod\n    def _build_from_requirements(cls, req_spec):\n        \"\"\"\n        Build a working set from a requirement spec. Rewrites sys.path.\n        \"\"\"\n        # try it without defaults already on sys.path\n        # by starting with an empty path\n        ws = cls([])\n        reqs = parse_requirements(req_spec)\n        dists = ws.resolve(reqs, Environment())\n        for dist in dists:\n            ws.add(dist)\n\n        # add any missing entries from sys.path\n        for entry in sys.path:\n            if entry not in ws.entries:\n                ws.add_entry(entry)\n\n        # then copy back to sys.path\n        sys.path[:] = ws.entries\n        return ws\n\n    def add_entry(self, entry: str):\n        \"\"\"Add a path item to ``.entries``, finding any distributions on it\n\n        ``find_distributions(entry, True)`` is used to find distributions\n        corresponding to the path entry, and they are added.  `entry` is\n        always appended to ``.entries``, even if it is already present.\n        (This is because ``sys.path`` can contain the same value more than\n        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always\n        equal ``sys.path``.)\n        \"\"\"\n        self.entry_keys.setdefault(entry, [])\n        self.entries.append(entry)\n        for dist in find_distributions(entry, True):\n            self.add(dist, entry, False)\n\n    def __contains__(self, dist: Distribution) -> bool:\n        \"\"\"True if `dist` is the active distribution for its project\"\"\"\n        return self.by_key.get(dist.key) == dist\n\n    def find(self, req: Requirement) -> Distribution | None:\n        \"\"\"Find a distribution matching requirement `req`\n\n        If there is an active distribution for the requested project, this\n        returns it as long as it meets the version requirement specified by\n        `req`.  But, if there is an active distribution for the project and it\n        does *not* meet the `req` requirement, ``VersionConflict`` is raised.\n        If there is no active distribution for the requested project, ``None``\n        is returned.\n        \"\"\"\n        dist = self.by_key.get(req.key)\n\n        if dist is None:\n            canonical_key = self.normalized_to_canonical_keys.get(req.key)\n\n            if canonical_key is not None:\n                req.key = canonical_key\n                dist = self.by_key.get(canonical_key)\n\n        if dist is not None and dist not in req:\n            # XXX add more info\n            raise VersionConflict(dist, req)\n        return dist\n\n    def iter_entry_points(self, group: str, name: str | None = None):\n        \"\"\"Yield entry point objects from `group` matching `name`\n\n        If `name` is None, yields all entry points in `group` from all\n        distributions in the working set, otherwise only ones matching\n        both `group` and `name` are yielded (in distribution order).\n        \"\"\"\n        return (\n            entry\n            for dist in self\n            for entry in dist.get_entry_map(group).values()\n            if name is None or name == entry.name\n        )\n\n    def run_script(self, requires: str, script_name: str):\n        \"\"\"Locate distribution for `requires` and run `script_name` script\"\"\"\n        ns = sys._getframe(1).f_globals\n        name = ns['__name__']\n        ns.clear()\n        ns['__name__'] = name\n        self.require(requires)[0].run_script(script_name, ns)\n\n    def __iter__(self) -> Iterator[Distribution]:\n        \"\"\"Yield distributions for non-duplicate projects in the working set\n\n        The yield order is the order in which the items' path entries were\n        added to the working set.\n        \"\"\"\n        seen = set()\n        for item in self.entries:\n            if item not in self.entry_keys:\n                # workaround a cache issue\n                continue\n\n            for key in self.entry_keys[item]:\n                if key not in seen:\n                    seen.add(key)\n                    yield self.by_key[key]\n\n    def add(\n        self,\n        dist: Distribution,\n        entry: str | None = None,\n        insert: bool = True,\n        replace: bool = False,\n    ):\n        \"\"\"Add `dist` to working set, associated with `entry`\n\n        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.\n        On exit from this routine, `entry` is added to the end of the working\n        set's ``.entries`` (if it wasn't already present).\n\n        `dist` is only added to the working set if it's for a project that\n        doesn't already have a distribution in the set, unless `replace=True`.\n        If it's added, any callbacks registered with the ``subscribe()`` method\n        will be called.\n        \"\"\"\n        if insert:\n            dist.insert_on(self.entries, entry, replace=replace)\n\n        if entry is None:\n            entry = dist.location\n        keys = self.entry_keys.setdefault(entry, [])\n        keys2 = self.entry_keys.setdefault(dist.location, [])\n        if not replace and dist.key in self.by_key:\n            # ignore hidden distros\n            return\n\n        self.by_key[dist.key] = dist\n        normalized_name = _packaging_utils.canonicalize_name(dist.key)\n        self.normalized_to_canonical_keys[normalized_name] = dist.key\n        if dist.key not in keys:\n            keys.append(dist.key)\n        if dist.key not in keys2:\n            keys2.append(dist.key)\n        self._added_new(dist)\n\n    @overload\n    def resolve(\n        self,\n        requirements: Iterable[Requirement],\n        env: Environment | None,\n        installer: _InstallerTypeT[_DistributionT],\n        replace_conflicting: bool = False,\n        extras: tuple[str, ...] | None = None,\n    ) -> list[_DistributionT]: ...\n    @overload\n    def resolve(\n        self,\n        requirements: Iterable[Requirement],\n        env: Environment | None = None,\n        *,\n        installer: _InstallerTypeT[_DistributionT],\n        replace_conflicting: bool = False,\n        extras: tuple[str, ...] | None = None,\n    ) -> list[_DistributionT]: ...\n    @overload\n    def resolve(\n        self,\n        requirements: Iterable[Requirement],\n        env: Environment | None = None,\n        installer: _InstallerType | None = None,\n        replace_conflicting: bool = False,\n        extras: tuple[str, ...] | None = None,\n    ) -> list[Distribution]: ...\n    def resolve(\n        self,\n        requirements: Iterable[Requirement],\n        env: Environment | None = None,\n        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,\n        replace_conflicting: bool = False,\n        extras: tuple[str, ...] | None = None,\n    ) -> list[Distribution] | list[_DistributionT]:\n        \"\"\"List all distributions needed to (recursively) meet `requirements`\n\n        `requirements` must be a sequence of ``Requirement`` objects.  `env`,\n        if supplied, should be an ``Environment`` instance.  If\n        not supplied, it defaults to all distributions available within any\n        entry or distribution in the working set.  `installer`, if supplied,\n        will be invoked with each requirement that cannot be met by an\n        already-installed distribution; it should return a ``Distribution`` or\n        ``None``.\n\n        Unless `replace_conflicting=True`, raises a VersionConflict exception\n        if\n        any requirements are found on the path that have the correct name but\n        the wrong version.  Otherwise, if an `installer` is supplied it will be\n        invoked to obtain the correct version of the requirement and activate\n        it.\n\n        `extras` is a list of the extras to be used with these requirements.\n        This is important because extra requirements may look like `my_req;\n        extra = \"my_extra\"`, which would otherwise be interpreted as a purely\n        optional requirement.  Instead, we want to be able to assert that these\n        requirements are truly required.\n        \"\"\"\n\n        # set up the stack\n        requirements = list(requirements)[::-1]\n        # set of processed requirements\n        processed = set()\n        # key -> dist\n        best = {}\n        to_activate = []\n\n        req_extras = _ReqExtras()\n\n        # Mapping of requirement to set of distributions that required it;\n        # useful for reporting info about conflicts.\n        required_by = collections.defaultdict(set)\n\n        while requirements:\n            # process dependencies breadth-first\n            req = requirements.pop(0)\n            if req in processed:\n                # Ignore cyclic or redundant dependencies\n                continue\n\n            if not req_extras.markers_pass(req, extras):\n                continue\n\n            dist = self._resolve_dist(\n                req, best, replace_conflicting, env, installer, required_by, to_activate\n            )\n\n            # push the new requirements onto the stack\n            new_requirements = dist.requires(req.extras)[::-1]\n            requirements.extend(new_requirements)\n\n            # Register the new requirements needed by req\n            for new_requirement in new_requirements:\n                required_by[new_requirement].add(req.project_name)\n                req_extras[new_requirement] = req.extras\n\n            processed.add(req)\n\n        # return list of distros to activate\n        return to_activate\n\n    def _resolve_dist(\n        self, req, best, replace_conflicting, env, installer, required_by, to_activate\n    ) -> Distribution:\n        dist = best.get(req.key)\n        if dist is None:\n            # Find the best distribution and add it to the map\n            dist = self.by_key.get(req.key)\n            if dist is None or (dist not in req and replace_conflicting):\n                ws = self\n                if env is None:\n                    if dist is None:\n                        env = Environment(self.entries)\n                    else:\n                        # Use an empty environment and workingset to avoid\n                        # any further conflicts with the conflicting\n                        # distribution\n                        env = Environment([])\n                        ws = WorkingSet([])\n                dist = best[req.key] = env.best_match(\n                    req, ws, installer, replace_conflicting=replace_conflicting\n                )\n                if dist is None:\n                    requirers = required_by.get(req, None)\n                    raise DistributionNotFound(req, requirers)\n            to_activate.append(dist)\n        if dist not in req:\n            # Oops, the \"best\" so far conflicts with a dependency\n            dependent_req = required_by[req]\n            raise VersionConflict(dist, req).with_context(dependent_req)\n        return dist\n\n    @overload\n    def find_plugins(\n        self,\n        plugin_env: Environment,\n        full_env: Environment | None,\n        installer: _InstallerTypeT[_DistributionT],\n        fallback: bool = True,\n    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...\n    @overload\n    def find_plugins(\n        self,\n        plugin_env: Environment,\n        full_env: Environment | None = None,\n        *,\n        installer: _InstallerTypeT[_DistributionT],\n        fallback: bool = True,\n    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...\n    @overload\n    def find_plugins(\n        self,\n        plugin_env: Environment,\n        full_env: Environment | None = None,\n        installer: _InstallerType | None = None,\n        fallback: bool = True,\n    ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ...\n    def find_plugins(\n        self,\n        plugin_env: Environment,\n        full_env: Environment | None = None,\n        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,\n        fallback: bool = True,\n    ) -> tuple[\n        list[Distribution] | list[_DistributionT],\n        dict[Distribution, Exception],\n    ]:\n        \"\"\"Find all activatable distributions in `plugin_env`\n\n        Example usage::\n\n            distributions, errors = working_set.find_plugins(\n                Environment(plugin_dirlist)\n            )\n            # add plugins+libs to sys.path\n            map(working_set.add, distributions)\n            # display errors\n            print('Could not load', errors)\n\n        The `plugin_env` should be an ``Environment`` instance that contains\n        only distributions that are in the project's \"plugin directory\" or\n        directories. The `full_env`, if supplied, should be an ``Environment``\n        contains all currently-available distributions.  If `full_env` is not\n        supplied, one is created automatically from the ``WorkingSet`` this\n        method is called on, which will typically mean that every directory on\n        ``sys.path`` will be scanned for distributions.\n\n        `installer` is a standard installer callback as used by the\n        ``resolve()`` method. The `fallback` flag indicates whether we should\n        attempt to resolve older versions of a plugin if the newest version\n        cannot be resolved.\n\n        This method returns a 2-tuple: (`distributions`, `error_info`), where\n        `distributions` is a list of the distributions found in `plugin_env`\n        that were loadable, along with any other distributions that are needed\n        to resolve their dependencies.  `error_info` is a dictionary mapping\n        unloadable plugin distributions to an exception instance describing the\n        error that occurred. Usually this will be a ``DistributionNotFound`` or\n        ``VersionConflict`` instance.\n        \"\"\"\n\n        plugin_projects = list(plugin_env)\n        # scan project names in alphabetic order\n        plugin_projects.sort()\n\n        error_info: dict[Distribution, Exception] = {}\n        distributions: dict[Distribution, Exception | None] = {}\n\n        if full_env is None:\n            env = Environment(self.entries)\n            env += plugin_env\n        else:\n            env = full_env + plugin_env\n\n        shadow_set = self.__class__([])\n        # put all our entries in shadow_set\n        list(map(shadow_set.add, self))\n\n        for project_name in plugin_projects:\n            for dist in plugin_env[project_name]:\n                req = [dist.as_requirement()]\n\n                try:\n                    resolvees = shadow_set.resolve(req, env, installer)\n\n                except ResolutionError as v:\n                    # save error info\n                    error_info[dist] = v\n                    if fallback:\n                        # try the next older version of project\n                        continue\n                    else:\n                        # give up on this project, keep going\n                        break\n\n                else:\n                    list(map(shadow_set.add, resolvees))\n                    distributions.update(dict.fromkeys(resolvees))\n\n                    # success, no need to try any more versions of this project\n                    break\n\n        sorted_distributions = list(distributions)\n        sorted_distributions.sort()\n\n        return sorted_distributions, error_info\n\n    def require(self, *requirements: _NestedStr):\n        \"\"\"Ensure that distributions matching `requirements` are activated\n\n        `requirements` must be a string or a (possibly-nested) sequence\n        thereof, specifying the distributions and versions required.  The\n        return value is a sequence of the distributions that needed to be\n        activated to fulfill the requirements; all relevant distributions are\n        included, even if they were already activated in this working set.\n        \"\"\"\n        needed = self.resolve(parse_requirements(requirements))\n\n        for dist in needed:\n            self.add(dist)\n\n        return needed\n\n    def subscribe(\n        self, callback: Callable[[Distribution], object], existing: bool = True\n    ):\n        \"\"\"Invoke `callback` for all distributions\n\n        If `existing=True` (default),\n        call on all existing ones, as well.\n        \"\"\"\n        if callback in self.callbacks:\n            return\n        self.callbacks.append(callback)\n        if not existing:\n            return\n        for dist in self:\n            callback(dist)\n\n    def _added_new(self, dist):\n        for callback in self.callbacks:\n            callback(dist)\n\n    def __getstate__(self):\n        return (\n            self.entries[:],\n            self.entry_keys.copy(),\n            self.by_key.copy(),\n            self.normalized_to_canonical_keys.copy(),\n            self.callbacks[:],\n        )\n\n    def __setstate__(self, e_k_b_n_c):\n        entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c\n        self.entries = entries[:]\n        self.entry_keys = keys.copy()\n        self.by_key = by_key.copy()\n        self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()\n        self.callbacks = callbacks[:]\n\n\nclass _ReqExtras(Dict[\"Requirement\", Tuple[str, ...]]):\n    \"\"\"\n    Map each requirement to the extras that demanded it.\n    \"\"\"\n\n    def markers_pass(self, req: Requirement, extras: tuple[str, ...] | None = None):\n        \"\"\"\n        Evaluate markers for req against each extra that\n        demanded it.\n\n        Return False if the req has a marker and fails\n        evaluation. Otherwise, return True.\n        \"\"\"\n        extra_evals = (\n            req.marker.evaluate({'extra': extra})\n            for extra in self.get(req, ()) + (extras or (None,))\n        )\n        return not req.marker or any(extra_evals)\n\n\nclass Environment:\n    \"\"\"Searchable snapshot of distributions on a search path\"\"\"\n\n    def __init__(\n        self,\n        search_path: Iterable[str] | None = None,\n        platform: str | None = get_supported_platform(),\n        python: str | None = PY_MAJOR,\n    ):\n        \"\"\"Snapshot distributions available on a search path\n\n        Any distributions found on `search_path` are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.\n\n        `platform` is an optional string specifying the name of the platform\n        that platform-specific distributions must be compatible with.  If\n        unspecified, it defaults to the current platform.  `python` is an\n        optional string naming the desired version of Python (e.g. ``'3.6'``);\n        it defaults to the current version.\n\n        You may explicitly set `platform` (and/or `python`) to ``None`` if you\n        wish to map *all* distributions, not just those compatible with the\n        running platform or Python version.\n        \"\"\"\n        self._distmap = {}\n        self.platform = platform\n        self.python = python\n        self.scan(search_path)\n\n    def can_add(self, dist: Distribution):\n        \"\"\"Is distribution `dist` acceptable for this environment?\n\n        The distribution must match the platform and python version\n        requirements specified when this environment was created, or False\n        is returned.\n        \"\"\"\n        py_compat = (\n            self.python is None\n            or dist.py_version is None\n            or dist.py_version == self.python\n        )\n        return py_compat and compatible_platforms(dist.platform, self.platform)\n\n    def remove(self, dist: Distribution):\n        \"\"\"Remove `dist` from the environment\"\"\"\n        self._distmap[dist.key].remove(dist)\n\n    def scan(self, search_path: Iterable[str] | None = None):\n        \"\"\"Scan `search_path` for distributions usable in this environment\n\n        Any distributions found are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.  Only distributions conforming to\n        the platform/python version defined at initialization are added.\n        \"\"\"\n        if search_path is None:\n            search_path = sys.path\n\n        for item in search_path:\n            for dist in find_distributions(item):\n                self.add(dist)\n\n    def __getitem__(self, project_name: str) -> list[Distribution]:\n        \"\"\"Return a newest-to-oldest list of distributions for `project_name`\n\n        Uses case-insensitive `project_name` comparison, assuming all the\n        project's distributions use their project's name converted to all\n        lowercase as their key.\n\n        \"\"\"\n        distribution_key = project_name.lower()\n        return self._distmap.get(distribution_key, [])\n\n    def add(self, dist: Distribution):\n        \"\"\"Add `dist` if we ``can_add()`` it and it has not already been added\"\"\"\n        if self.can_add(dist) and dist.has_version():\n            dists = self._distmap.setdefault(dist.key, [])\n            if dist not in dists:\n                dists.append(dist)\n                dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)\n\n    @overload\n    def best_match(\n        self,\n        req: Requirement,\n        working_set: WorkingSet,\n        installer: _InstallerTypeT[_DistributionT],\n        replace_conflicting: bool = False,\n    ) -> _DistributionT: ...\n    @overload\n    def best_match(\n        self,\n        req: Requirement,\n        working_set: WorkingSet,\n        installer: _InstallerType | None = None,\n        replace_conflicting: bool = False,\n    ) -> Distribution | None: ...\n    def best_match(\n        self,\n        req: Requirement,\n        working_set: WorkingSet,\n        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,\n        replace_conflicting: bool = False,\n    ) -> Distribution | None:\n        \"\"\"Find distribution best matching `req` and usable on `working_set`\n\n        This calls the ``find(req)`` method of the `working_set` to see if a\n        suitable distribution is already active.  (This may raise\n        ``VersionConflict`` if an unsuitable version of the project is already\n        active in the specified `working_set`.)  If a suitable distribution\n        isn't active, this method returns the newest distribution in the\n        environment that meets the ``Requirement`` in `req`.  If no suitable\n        distribution is found, and `installer` is supplied, then the result of\n        calling the environment's ``obtain(req, installer)`` method will be\n        returned.\n        \"\"\"\n        try:\n            dist = working_set.find(req)\n        except VersionConflict:\n            if not replace_conflicting:\n                raise\n            dist = None\n        if dist is not None:\n            return dist\n        for dist in self[req.key]:\n            if dist in req:\n                return dist\n        # try to download/install\n        return self.obtain(req, installer)\n\n    @overload\n    def obtain(\n        self,\n        requirement: Requirement,\n        installer: _InstallerTypeT[_DistributionT],\n    ) -> _DistributionT: ...\n    @overload\n    def obtain(\n        self,\n        requirement: Requirement,\n        installer: Callable[[Requirement], None] | None = None,\n    ) -> None: ...\n    @overload\n    def obtain(\n        self,\n        requirement: Requirement,\n        installer: _InstallerType | None = None,\n    ) -> Distribution | None: ...\n    def obtain(\n        self,\n        requirement: Requirement,\n        installer: Callable[[Requirement], None]\n        | _InstallerType\n        | None\n        | _InstallerTypeT[_DistributionT] = None,\n    ) -> Distribution | None:\n        \"\"\"Obtain a distribution matching `requirement` (e.g. via download)\n\n        Obtain a distro that matches requirement (e.g. via download).  In the\n        base ``Environment`` class, this routine just returns\n        ``installer(requirement)``, unless `installer` is None, in which case\n        None is returned instead.  This method is a hook that allows subclasses\n        to attempt other ways of obtaining a distribution before falling back\n        to the `installer` argument.\"\"\"\n        return installer(requirement) if installer else None\n\n    def __iter__(self) -> Iterator[str]:\n        \"\"\"Yield the unique project names of the available distributions\"\"\"\n        for key in self._distmap.keys():\n            if self[key]:\n                yield key\n\n    def __iadd__(self, other: Distribution | Environment):\n        \"\"\"In-place addition of a distribution or environment\"\"\"\n        if isinstance(other, Distribution):\n            self.add(other)\n        elif isinstance(other, Environment):\n            for project in other:\n                for dist in other[project]:\n                    self.add(dist)\n        else:\n            raise TypeError(\"Can't add %r to environment\" % (other,))\n        return self\n\n    def __add__(self, other: Distribution | Environment):\n        \"\"\"Add an environment or distribution to an environment\"\"\"\n        new = self.__class__([], platform=None, python=None)\n        for env in self, other:\n            new += env\n        return new\n\n\n# XXX backward compatibility\nAvailableDistributions = Environment\n\n\nclass ExtractionError(RuntimeError):\n    \"\"\"An error occurred extracting a resource\n\n    The following attributes are available from instances of this exception:\n\n    manager\n        The resource manager that raised this exception\n\n    cache_path\n        The base directory for resource extraction\n\n    original_error\n        The exception instance that caused extraction to fail\n    \"\"\"\n\n    manager: ResourceManager\n    cache_path: str\n    original_error: BaseException | None\n\n\nclass ResourceManager:\n    \"\"\"Manage resource extraction and packages\"\"\"\n\n    extraction_path: str | None = None\n\n    def __init__(self):\n        self.cached_files = {}\n\n    def resource_exists(self, package_or_requirement: _PkgReqType, resource_name: str):\n        \"\"\"Does the named resource exist?\"\"\"\n        return get_provider(package_or_requirement).has_resource(resource_name)\n\n    def resource_isdir(self, package_or_requirement: _PkgReqType, resource_name: str):\n        \"\"\"Is the named resource an existing directory?\"\"\"\n        return get_provider(package_or_requirement).resource_isdir(resource_name)\n\n    def resource_filename(\n        self, package_or_requirement: _PkgReqType, resource_name: str\n    ):\n        \"\"\"Return a true filesystem path for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_filename(\n            self, resource_name\n        )\n\n    def resource_stream(self, package_or_requirement: _PkgReqType, resource_name: str):\n        \"\"\"Return a readable file-like object for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_stream(\n            self, resource_name\n        )\n\n    def resource_string(\n        self, package_or_requirement: _PkgReqType, resource_name: str\n    ) -> bytes:\n        \"\"\"Return specified resource as :obj:`bytes`\"\"\"\n        return get_provider(package_or_requirement).get_resource_string(\n            self, resource_name\n        )\n\n    def resource_listdir(self, package_or_requirement: _PkgReqType, resource_name: str):\n        \"\"\"List the contents of the named resource directory\"\"\"\n        return get_provider(package_or_requirement).resource_listdir(resource_name)\n\n    def extraction_error(self) -> NoReturn:\n        \"\"\"Give an error message for problems extracting file(s)\"\"\"\n\n        old_exc = sys.exc_info()[1]\n        cache_path = self.extraction_path or get_default_cache()\n\n        tmpl = textwrap.dedent(\n            \"\"\"\n            Can't extract file(s) to egg cache\n\n            The following error occurred while trying to extract file(s)\n            to the Python egg cache:\n\n              {old_exc}\n\n            The Python egg cache directory is currently set to:\n\n              {cache_path}\n\n            Perhaps your account does not have write access to this directory?\n            You can change the cache directory by setting the PYTHON_EGG_CACHE\n            environment variable to point to an accessible directory.\n            \"\"\"\n        ).lstrip()\n        err = ExtractionError(tmpl.format(**locals()))\n        err.manager = self\n        err.cache_path = cache_path\n        err.original_error = old_exc\n        raise err\n\n    def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()):\n        \"\"\"Return absolute location in cache for `archive_name` and `names`\n\n        The parent directory of the resulting path will be created if it does\n        not already exist.  `archive_name` should be the base filename of the\n        enclosing egg (which may not be the name of the enclosing zipfile!),\n        including its \".egg\" extension.  `names`, if provided, should be a\n        sequence of path name parts \"under\" the egg's extraction location.\n\n        This method should only be called by resource providers that need to\n        obtain an extraction location, and only for names they intend to\n        extract, as it tracks the generated names for possible cleanup later.\n        \"\"\"\n        extract_path = self.extraction_path or get_default_cache()\n        target_path = os.path.join(extract_path, archive_name + '-tmp', *names)\n        try:\n            _bypass_ensure_directory(target_path)\n        except Exception:\n            self.extraction_error()\n\n        self._warn_unsafe_extraction_path(extract_path)\n\n        self.cached_files[target_path] = True\n        return target_path\n\n    @staticmethod\n    def _warn_unsafe_extraction_path(path):\n        \"\"\"\n        If the default extraction path is overridden and set to an insecure\n        location, such as /tmp, it opens up an opportunity for an attacker to\n        replace an extracted file with an unauthorized payload. Warn the user\n        if a known insecure location is used.\n\n        See Distribute #375 for more details.\n        \"\"\"\n        if os.name == 'nt' and not path.startswith(os.environ['windir']):\n            # On Windows, permissions are generally restrictive by default\n            #  and temp directories are not writable by other users, so\n            #  bypass the warning.\n            return\n        mode = os.stat(path).st_mode\n        if mode & stat.S_IWOTH or mode & stat.S_IWGRP:\n            msg = (\n                \"Extraction path is writable by group/others \"\n                \"and vulnerable to attack when \"\n                \"used with get_resource_filename ({path}). \"\n                \"Consider a more secure \"\n                \"location (set with .set_extraction_path or the \"\n                \"PYTHON_EGG_CACHE environment variable).\"\n            ).format(**locals())\n            warnings.warn(msg, UserWarning)\n\n    def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath):\n        \"\"\"Perform any platform-specific postprocessing of `tempname`\n\n        This is where Mac header rewrites should be done; other platforms don't\n        have anything special they should do.\n\n        Resource providers should call this method ONLY after successfully\n        extracting a compressed resource.  They must NOT call it on resources\n        that are already in the filesystem.\n\n        `tempname` is the current (temporary) name of the file, and `filename`\n        is the name it will be renamed to by the caller after this routine\n        returns.\n        \"\"\"\n\n        if os.name == 'posix':\n            # Make the resource executable\n            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777\n            os.chmod(tempname, mode)\n\n    def set_extraction_path(self, path: str):\n        \"\"\"Set the base path where resources will be extracted to, if needed.\n\n        If you do not call this routine before any extractions take place, the\n        path defaults to the return value of ``get_default_cache()``.  (Which\n        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various\n        platform-specific fallbacks.  See that routine's documentation for more\n        details.)\n\n        Resources are extracted to subdirectories of this path based upon\n        information given by the ``IResourceProvider``.  You may set this to a\n        temporary directory, but then you must call ``cleanup_resources()`` to\n        delete the extracted files when done.  There is no guarantee that\n        ``cleanup_resources()`` will be able to remove all extracted files.\n\n        (Note: you may not change the extraction path for a given resource\n        manager once resources have been extracted, unless you first call\n        ``cleanup_resources()``.)\n        \"\"\"\n        if self.cached_files:\n            raise ValueError(\"Can't change extraction path, files already extracted\")\n\n        self.extraction_path = path\n\n    def cleanup_resources(self, force: bool = False) -> list[str]:\n        \"\"\"\n        Delete all extracted resource files and directories, returning a list\n        of the file and directory names that could not be successfully removed.\n        This function does not have any concurrency protection, so it should\n        generally only be called when the extraction path is a temporary\n        directory exclusive to a single process.  This method is not\n        automatically called; you must call it explicitly or register it as an\n        ``atexit`` function if you wish to ensure cleanup of a temporary\n        directory used for extractions.\n        \"\"\"\n        # XXX\n        return []\n\n\ndef get_default_cache() -> str:\n    \"\"\"\n    Return the ``PYTHON_EGG_CACHE`` environment variable\n    or a platform-relevant user cache dir for an app\n    named \"Python-Eggs\".\n    \"\"\"\n    return os.environ.get('PYTHON_EGG_CACHE') or _user_cache_dir(appname='Python-Eggs')\n\n\ndef safe_name(name: str):\n    \"\"\"Convert an arbitrary string to a standard distribution name\n\n    Any runs of non-alphanumeric/. characters are replaced with a single '-'.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.]+', '-', name)\n\n\ndef safe_version(version: str):\n    \"\"\"\n    Convert an arbitrary string to a standard version string\n    \"\"\"\n    try:\n        # normalize the version\n        return str(_packaging_version.Version(version))\n    except _packaging_version.InvalidVersion:\n        version = version.replace(' ', '.')\n        return re.sub('[^A-Za-z0-9.]+', '-', version)\n\n\ndef _forgiving_version(version):\n    \"\"\"Fallback when ``safe_version`` is not safe enough\n    >>> parse_version(_forgiving_version('0.23ubuntu1'))\n    <Version('0.23.dev0+sanitized.ubuntu1')>\n    >>> parse_version(_forgiving_version('0.23-'))\n    <Version('0.23.dev0+sanitized')>\n    >>> parse_version(_forgiving_version('0.-_'))\n    <Version('0.dev0+sanitized')>\n    >>> parse_version(_forgiving_version('42.+?1'))\n    <Version('42.dev0+sanitized.1')>\n    >>> parse_version(_forgiving_version('hello world'))\n    <Version('0.dev0+sanitized.hello.world')>\n    \"\"\"\n    version = version.replace(' ', '.')\n    match = _PEP440_FALLBACK.search(version)\n    if match:\n        safe = match[\"safe\"]\n        rest = version[len(safe) :]\n    else:\n        safe = \"0\"\n        rest = version\n    local = f\"sanitized.{_safe_segment(rest)}\".strip(\".\")\n    return f\"{safe}.dev0+{local}\"\n\n\ndef _safe_segment(segment):\n    \"\"\"Convert an arbitrary string into a safe segment\"\"\"\n    segment = re.sub('[^A-Za-z0-9.]+', '-', segment)\n    segment = re.sub('-[^A-Za-z0-9]+', '-', segment)\n    return re.sub(r'\\.[^A-Za-z0-9]+', '.', segment).strip(\".-\")\n\n\ndef safe_extra(extra: str):\n    \"\"\"Convert an arbitrary string to a standard 'extra' name\n\n    Any runs of non-alphanumeric characters are replaced with a single '_',\n    and the result is always lowercased.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()\n\n\ndef to_filename(name: str):\n    \"\"\"Convert a project or version name to its filename-escaped form\n\n    Any '-' characters are currently replaced with '_'.\n    \"\"\"\n    return name.replace('-', '_')\n\n\ndef invalid_marker(text: str):\n    \"\"\"\n    Validate text as a PEP 508 environment marker; return an exception\n    if invalid or False otherwise.\n    \"\"\"\n    try:\n        evaluate_marker(text)\n    except SyntaxError as e:\n        e.filename = None\n        e.lineno = None\n        return e\n    return False\n\n\ndef evaluate_marker(text: str, extra: str | None = None) -> bool:\n    \"\"\"\n    Evaluate a PEP 508 environment marker.\n    Return a boolean indicating the marker result in this environment.\n    Raise SyntaxError if marker is invalid.\n\n    This implementation uses the 'pyparsing' module.\n    \"\"\"\n    try:\n        marker = _packaging_markers.Marker(text)\n        return marker.evaluate()\n    except _packaging_markers.InvalidMarker as e:\n        raise SyntaxError(e) from e\n\n\nclass NullProvider:\n    \"\"\"Try to implement resources and metadata for arbitrary PEP 302 loaders\"\"\"\n\n    egg_name: str | None = None\n    egg_info: str | None = None\n    loader: _LoaderProtocol | None = None\n\n    def __init__(self, module: _ModuleLike):\n        self.loader = getattr(module, '__loader__', None)\n        self.module_path = os.path.dirname(getattr(module, '__file__', ''))\n\n    def get_resource_filename(self, manager: ResourceManager, resource_name: str):\n        return self._fn(self.module_path, resource_name)\n\n    def get_resource_stream(self, manager: ResourceManager, resource_name: str):\n        return io.BytesIO(self.get_resource_string(manager, resource_name))\n\n    def get_resource_string(\n        self, manager: ResourceManager, resource_name: str\n    ) -> bytes:\n        return self._get(self._fn(self.module_path, resource_name))\n\n    def has_resource(self, resource_name: str):\n        return self._has(self._fn(self.module_path, resource_name))\n\n    def _get_metadata_path(self, name):\n        return self._fn(self.egg_info, name)\n\n    def has_metadata(self, name: str) -> bool:\n        if not self.egg_info:\n            return False\n\n        path = self._get_metadata_path(name)\n        return self._has(path)\n\n    def get_metadata(self, name: str):\n        if not self.egg_info:\n            return \"\"\n        path = self._get_metadata_path(name)\n        value = self._get(path)\n        try:\n            return value.decode('utf-8')\n        except UnicodeDecodeError as exc:\n            # Include the path in the error message to simplify\n            # troubleshooting, and without changing the exception type.\n            exc.reason += ' in {} file at path: {}'.format(name, path)\n            raise\n\n    def get_metadata_lines(self, name: str) -> Iterator[str]:\n        return yield_lines(self.get_metadata(name))\n\n    def resource_isdir(self, resource_name: str):\n        return self._isdir(self._fn(self.module_path, resource_name))\n\n    def metadata_isdir(self, name: str) -> bool:\n        return bool(self.egg_info and self._isdir(self._fn(self.egg_info, name)))\n\n    def resource_listdir(self, resource_name: str):\n        return self._listdir(self._fn(self.module_path, resource_name))\n\n    def metadata_listdir(self, name: str) -> list[str]:\n        if self.egg_info:\n            return self._listdir(self._fn(self.egg_info, name))\n        return []\n\n    def run_script(self, script_name: str, namespace: dict[str, Any]):\n        script = 'scripts/' + script_name\n        if not self.has_metadata(script):\n            raise ResolutionError(\n                \"Script {script!r} not found in metadata at {self.egg_info!r}\".format(\n                    **locals()\n                ),\n            )\n\n        script_text = self.get_metadata(script).replace('\\r\\n', '\\n')\n        script_text = script_text.replace('\\r', '\\n')\n        script_filename = self._fn(self.egg_info, script)\n        namespace['__file__'] = script_filename\n        if os.path.exists(script_filename):\n            source = _read_utf8_with_fallback(script_filename)\n            code = compile(source, script_filename, 'exec')\n            exec(code, namespace, namespace)\n        else:\n            from linecache import cache\n\n            cache[script_filename] = (\n                len(script_text),\n                0,\n                script_text.split('\\n'),\n                script_filename,\n            )\n            script_code = compile(script_text, script_filename, 'exec')\n            exec(script_code, namespace, namespace)\n\n    def _has(self, path) -> bool:\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _isdir(self, path) -> bool:\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _listdir(self, path) -> list[str]:\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _fn(self, base: str | None, resource_name: str):\n        if base is None:\n            raise TypeError(\n                \"`base` parameter in `_fn` is `None`. Either override this method or check the parameter first.\"\n            )\n        self._validate_resource_path(resource_name)\n        if resource_name:\n            return os.path.join(base, *resource_name.split('/'))\n        return base\n\n    @staticmethod\n    def _validate_resource_path(path):\n        \"\"\"\n        Validate the resource paths according to the docs.\n        https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access\n\n        >>> warned = getfixture('recwarn')\n        >>> warnings.simplefilter('always')\n        >>> vrp = NullProvider._validate_resource_path\n        >>> vrp('foo/bar.txt')\n        >>> bool(warned)\n        False\n        >>> vrp('../foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('/foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> vrp('foo/../../bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('foo/f../bar.txt')\n        >>> bool(warned)\n        False\n\n        Windows path separators are straight-up disallowed.\n        >>> vrp(r'\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        >>> vrp(r'C:\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        Blank values are allowed\n\n        >>> vrp('')\n        >>> bool(warned)\n        False\n\n        Non-string values are not.\n\n        >>> vrp(None)\n        Traceback (most recent call last):\n        ...\n        AttributeError: ...\n        \"\"\"\n        invalid = (\n            os.path.pardir in path.split(posixpath.sep)\n            or posixpath.isabs(path)\n            or ntpath.isabs(path)\n            or path.startswith(\"\\\\\")\n        )\n        if not invalid:\n            return\n\n        msg = \"Use of .. or absolute path in a resource path is not allowed.\"\n\n        # Aggressively disallow Windows absolute paths\n        if (path.startswith(\"\\\\\") or ntpath.isabs(path)) and not posixpath.isabs(path):\n            raise ValueError(msg)\n\n        # for compatibility, warn; in future\n        # raise ValueError(msg)\n        issue_warning(\n            msg[:-1] + \" and will raise exceptions in a future release.\",\n            DeprecationWarning,\n        )\n\n    def _get(self, path) -> bytes:\n        if hasattr(self.loader, 'get_data') and self.loader:\n            # Already checked get_data exists\n            return self.loader.get_data(path)  # type: ignore[attr-defined]\n        raise NotImplementedError(\n            \"Can't perform this operation for loaders without 'get_data()'\"\n        )\n\n\nregister_loader_type(object, NullProvider)\n\n\ndef _parents(path):\n    \"\"\"\n    yield all parents of path including path\n    \"\"\"\n    last = None\n    while path != last:\n        yield path\n        last = path\n        path, _ = os.path.split(path)\n\n\nclass EggProvider(NullProvider):\n    \"\"\"Provider based on a virtual filesystem\"\"\"\n\n    def __init__(self, module: _ModuleLike):\n        super().__init__(module)\n        self._setup_prefix()\n\n    def _setup_prefix(self):\n        # Assume that metadata may be nested inside a \"basket\"\n        # of multiple eggs and use module_path instead of .archive.\n        eggs = filter(_is_egg_path, _parents(self.module_path))\n        egg = next(eggs, None)\n        egg and self._set_egg(egg)\n\n    def _set_egg(self, path: str):\n        self.egg_name = os.path.basename(path)\n        self.egg_info = os.path.join(path, 'EGG-INFO')\n        self.egg_root = path\n\n\nclass DefaultProvider(EggProvider):\n    \"\"\"Provides access to package resources in the filesystem\"\"\"\n\n    def _has(self, path) -> bool:\n        return os.path.exists(path)\n\n    def _isdir(self, path) -> bool:\n        return os.path.isdir(path)\n\n    def _listdir(self, path):\n        return os.listdir(path)\n\n    def get_resource_stream(self, manager: object, resource_name: str):\n        return open(self._fn(self.module_path, resource_name), 'rb')\n\n    def _get(self, path) -> bytes:\n        with open(path, 'rb') as stream:\n            return stream.read()\n\n    @classmethod\n    def _register(cls):\n        loader_names = (\n            'SourceFileLoader',\n            'SourcelessFileLoader',\n        )\n        for name in loader_names:\n            loader_cls = getattr(importlib.machinery, name, type(None))\n            register_loader_type(loader_cls, cls)\n\n\nDefaultProvider._register()\n\n\nclass EmptyProvider(NullProvider):\n    \"\"\"Provider that returns nothing for all requests\"\"\"\n\n    # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path\n    module_path: str | None = None  # type: ignore[assignment]\n\n    _isdir = _has = lambda self, path: False\n\n    def _get(self, path) -> bytes:\n        return b''\n\n    def _listdir(self, path):\n        return []\n\n    def __init__(self):\n        pass\n\n\nempty_provider = EmptyProvider()\n\n\nclass ZipManifests(Dict[str, \"MemoizedZipManifests.manifest_mod\"]):\n    \"\"\"\n    zip manifest builder\n    \"\"\"\n\n    # `path` could be `StrPath | IO[bytes]` but that violates the LSP for `MemoizedZipManifests.load`\n    @classmethod\n    def build(cls, path: str):\n        \"\"\"\n        Build a dictionary similar to the zipimport directory\n        caches, except instead of tuples, store ZipInfo objects.\n\n        Use a platform-specific path separator (os.sep) for the path keys\n        for compatibility with pypy on Windows.\n        \"\"\"\n        with zipfile.ZipFile(path) as zfile:\n            items = (\n                (\n                    name.replace('/', os.sep),\n                    zfile.getinfo(name),\n                )\n                for name in zfile.namelist()\n            )\n            return dict(items)\n\n    load = build\n\n\nclass MemoizedZipManifests(ZipManifests):\n    \"\"\"\n    Memoized zipfile manifests.\n    \"\"\"\n\n    class manifest_mod(NamedTuple):\n        manifest: dict[str, zipfile.ZipInfo]\n        mtime: float\n\n    def load(self, path: str) -> dict[str, zipfile.ZipInfo]:  # type: ignore[override] # ZipManifests.load is a classmethod\n        \"\"\"\n        Load a manifest at path or return a suitable manifest already loaded.\n        \"\"\"\n        path = os.path.normpath(path)\n        mtime = os.stat(path).st_mtime\n\n        if path not in self or self[path].mtime != mtime:\n            manifest = self.build(path)\n            self[path] = self.manifest_mod(manifest, mtime)\n\n        return self[path].manifest\n\n\nclass ZipProvider(EggProvider):\n    \"\"\"Resource support for zips and eggs\"\"\"\n\n    eagers: list[str] | None = None\n    _zip_manifests = MemoizedZipManifests()\n    # ZipProvider's loader should always be a zipimporter or equivalent\n    loader: zipimport.zipimporter\n\n    def __init__(self, module: _ZipLoaderModule):\n        super().__init__(module)\n        self.zip_pre = self.loader.archive + os.sep\n\n    def _zipinfo_name(self, fspath):\n        # Convert a virtual filename (full path to file) into a zipfile subpath\n        # usable with the zipimport directory cache for our target archive\n        fspath = fspath.rstrip(os.sep)\n        if fspath == self.loader.archive:\n            return ''\n        if fspath.startswith(self.zip_pre):\n            return fspath[len(self.zip_pre) :]\n        raise AssertionError(\"%s is not a subpath of %s\" % (fspath, self.zip_pre))\n\n    def _parts(self, zip_path):\n        # Convert a zipfile subpath into an egg-relative path part list.\n        # pseudo-fs path\n        fspath = self.zip_pre + zip_path\n        if fspath.startswith(self.egg_root + os.sep):\n            return fspath[len(self.egg_root) + 1 :].split(os.sep)\n        raise AssertionError(\"%s is not a subpath of %s\" % (fspath, self.egg_root))\n\n    @property\n    def zipinfo(self):\n        return self._zip_manifests.load(self.loader.archive)\n\n    def get_resource_filename(self, manager: ResourceManager, resource_name: str):\n        if not self.egg_name:\n            raise NotImplementedError(\n                \"resource_filename() only supported for .egg, not .zip\"\n            )\n        # no need to lock for extraction, since we use temp names\n        zip_path = self._resource_to_zip(resource_name)\n        eagers = self._get_eager_resources()\n        if '/'.join(self._parts(zip_path)) in eagers:\n            for name in eagers:\n                self._extract_resource(manager, self._eager_to_zip(name))\n        return self._extract_resource(manager, zip_path)\n\n    @staticmethod\n    def _get_date_and_size(zip_stat):\n        size = zip_stat.file_size\n        # ymdhms+wday, yday, dst\n        date_time = zip_stat.date_time + (0, 0, -1)\n        # 1980 offset already done\n        timestamp = time.mktime(date_time)\n        return timestamp, size\n\n    # FIXME: 'ZipProvider._extract_resource' is too complex (12)\n    def _extract_resource(self, manager: ResourceManager, zip_path) -> str:  # noqa: C901\n        if zip_path in self._index():\n            for name in self._index()[zip_path]:\n                last = self._extract_resource(manager, os.path.join(zip_path, name))\n            # return the extracted directory name\n            return os.path.dirname(last)\n\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n\n        if not WRITE_SUPPORT:\n            raise OSError(\n                '\"os.rename\" and \"os.unlink\" are not supported on this platform'\n            )\n        try:\n            if not self.egg_name:\n                raise OSError(\n                    '\"egg_name\" is empty. This likely means no egg could be found from the \"module_path\".'\n                )\n            real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))\n\n            if self._is_current(real_path, zip_path):\n                return real_path\n\n            outf, tmpnam = _mkstemp(\n                \".$extract\",\n                dir=os.path.dirname(real_path),\n            )\n            os.write(outf, self.loader.get_data(zip_path))\n            os.close(outf)\n            utime(tmpnam, (timestamp, timestamp))\n            manager.postprocess(tmpnam, real_path)\n\n            try:\n                rename(tmpnam, real_path)\n\n            except OSError:\n                if os.path.isfile(real_path):\n                    if self._is_current(real_path, zip_path):\n                        # the file became current since it was checked above,\n                        #  so proceed.\n                        return real_path\n                    # Windows, del old file and retry\n                    elif os.name == 'nt':\n                        unlink(real_path)\n                        rename(tmpnam, real_path)\n                        return real_path\n                raise\n\n        except OSError:\n            # report a user-friendly error\n            manager.extraction_error()\n\n        return real_path\n\n    def _is_current(self, file_path, zip_path):\n        \"\"\"\n        Return True if the file_path is current for this zip_path\n        \"\"\"\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n        if not os.path.isfile(file_path):\n            return False\n        stat = os.stat(file_path)\n        if stat.st_size != size or stat.st_mtime != timestamp:\n            return False\n        # check that the contents match\n        zip_contents = self.loader.get_data(zip_path)\n        with open(file_path, 'rb') as f:\n            file_contents = f.read()\n        return zip_contents == file_contents\n\n    def _get_eager_resources(self):\n        if self.eagers is None:\n            eagers = []\n            for name in ('native_libs.txt', 'eager_resources.txt'):\n                if self.has_metadata(name):\n                    eagers.extend(self.get_metadata_lines(name))\n            self.eagers = eagers\n        return self.eagers\n\n    def _index(self):\n        try:\n            return self._dirindex\n        except AttributeError:\n            ind = {}\n            for path in self.zipinfo:\n                parts = path.split(os.sep)\n                while parts:\n                    parent = os.sep.join(parts[:-1])\n                    if parent in ind:\n                        ind[parent].append(parts[-1])\n                        break\n                    else:\n                        ind[parent] = [parts.pop()]\n            self._dirindex = ind\n            return ind\n\n    def _has(self, fspath) -> bool:\n        zip_path = self._zipinfo_name(fspath)\n        return zip_path in self.zipinfo or zip_path in self._index()\n\n    def _isdir(self, fspath) -> bool:\n        return self._zipinfo_name(fspath) in self._index()\n\n    def _listdir(self, fspath):\n        return list(self._index().get(self._zipinfo_name(fspath), ()))\n\n    def _eager_to_zip(self, resource_name: str):\n        return self._zipinfo_name(self._fn(self.egg_root, resource_name))\n\n    def _resource_to_zip(self, resource_name: str):\n        return self._zipinfo_name(self._fn(self.module_path, resource_name))\n\n\nregister_loader_type(zipimport.zipimporter, ZipProvider)\n\n\nclass FileMetadata(EmptyProvider):\n    \"\"\"Metadata handler for standalone PKG-INFO files\n\n    Usage::\n\n        metadata = FileMetadata(\"/path/to/PKG-INFO\")\n\n    This provider rejects all data and metadata requests except for PKG-INFO,\n    which is treated as existing, and will be the contents of the file at\n    the provided location.\n    \"\"\"\n\n    def __init__(self, path: StrPath):\n        self.path = path\n\n    def _get_metadata_path(self, name):\n        return self.path\n\n    def has_metadata(self, name: str) -> bool:\n        return name == 'PKG-INFO' and os.path.isfile(self.path)\n\n    def get_metadata(self, name: str):\n        if name != 'PKG-INFO':\n            raise KeyError(\"No metadata except PKG-INFO is available\")\n\n        with open(self.path, encoding='utf-8', errors=\"replace\") as f:\n            metadata = f.read()\n        self._warn_on_replacement(metadata)\n        return metadata\n\n    def _warn_on_replacement(self, metadata):\n        replacement_char = '�'\n        if replacement_char in metadata:\n            tmpl = \"{self.path} could not be properly decoded in UTF-8\"\n            msg = tmpl.format(**locals())\n            warnings.warn(msg)\n\n    def get_metadata_lines(self, name: str) -> Iterator[str]:\n        return yield_lines(self.get_metadata(name))\n\n\nclass PathMetadata(DefaultProvider):\n    \"\"\"Metadata provider for egg directories\n\n    Usage::\n\n        # Development eggs:\n\n        egg_info = \"/path/to/PackageName.egg-info\"\n        base_dir = os.path.dirname(egg_info)\n        metadata = PathMetadata(base_dir, egg_info)\n        dist_name = os.path.splitext(os.path.basename(egg_info))[0]\n        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)\n\n        # Unpacked egg directories:\n\n        egg_path = \"/path/to/PackageName-ver-pyver-etc.egg\"\n        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))\n        dist = Distribution.from_filename(egg_path, metadata=metadata)\n    \"\"\"\n\n    def __init__(self, path: str, egg_info: str):\n        self.module_path = path\n        self.egg_info = egg_info\n\n\nclass EggMetadata(ZipProvider):\n    \"\"\"Metadata provider for .egg files\"\"\"\n\n    def __init__(self, importer: zipimport.zipimporter):\n        \"\"\"Create a metadata provider from a zipimporter\"\"\"\n\n        self.zip_pre = importer.archive + os.sep\n        self.loader = importer\n        if importer.prefix:\n            self.module_path = os.path.join(importer.archive, importer.prefix)\n        else:\n            self.module_path = importer.archive\n        self._setup_prefix()\n\n\n_distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state(\n    'dict', '_distribution_finders', {}\n)\n\n\ndef register_finder(importer_type: type[_T], distribution_finder: _DistFinderType[_T]):\n    \"\"\"Register `distribution_finder` to find distributions in sys.path items\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `distribution_finder` is a callable that, passed a path\n    item and the importer instance, yields ``Distribution`` instances found on\n    that path item.  See ``pkg_resources.find_on_path`` for an example.\"\"\"\n    _distribution_finders[importer_type] = distribution_finder\n\n\ndef find_distributions(path_item: str, only: bool = False):\n    \"\"\"Yield distributions accessible via `path_item`\"\"\"\n    importer = get_importer(path_item)\n    finder = _find_adapter(_distribution_finders, importer)\n    return finder(importer, path_item, only)\n\n\ndef find_eggs_in_zip(\n    importer: zipimport.zipimporter, path_item: str, only: bool = False\n) -> Iterator[Distribution]:\n    \"\"\"\n    Find eggs in zip files; possibly multiple nested eggs.\n    \"\"\"\n    if importer.archive.endswith('.whl'):\n        # wheels are not supported with this finder\n        # they don't have PKG-INFO metadata, and won't ever contain eggs\n        return\n    metadata = EggMetadata(importer)\n    if metadata.has_metadata('PKG-INFO'):\n        yield Distribution.from_filename(path_item, metadata=metadata)\n    if only:\n        # don't yield nested distros\n        return\n    for subitem in metadata.resource_listdir(''):\n        if _is_egg_path(subitem):\n            subpath = os.path.join(path_item, subitem)\n            dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)\n            yield from dists\n        elif subitem.lower().endswith(('.dist-info', '.egg-info')):\n            subpath = os.path.join(path_item, subitem)\n            submeta = EggMetadata(zipimport.zipimporter(subpath))\n            submeta.egg_info = subpath\n            yield Distribution.from_location(path_item, subitem, submeta)\n\n\nregister_finder(zipimport.zipimporter, find_eggs_in_zip)\n\n\ndef find_nothing(\n    importer: object | None, path_item: str | None, only: bool | None = False\n):\n    return ()\n\n\nregister_finder(object, find_nothing)\n\n\ndef find_on_path(importer: object | None, path_item, only=False):\n    \"\"\"Yield distributions accessible on a sys.path directory\"\"\"\n    path_item = _normalize_cached(path_item)\n\n    if _is_unpacked_egg(path_item):\n        yield Distribution.from_filename(\n            path_item,\n            metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')),\n        )\n        return\n\n    entries = (os.path.join(path_item, child) for child in safe_listdir(path_item))\n\n    # scan for .egg and .egg-info in directory\n    for entry in sorted(entries):\n        fullpath = os.path.join(path_item, entry)\n        factory = dist_factory(path_item, entry, only)\n        yield from factory(fullpath)\n\n\ndef dist_factory(path_item, entry, only):\n    \"\"\"Return a dist_factory for the given entry.\"\"\"\n    lower = entry.lower()\n    is_egg_info = lower.endswith('.egg-info')\n    is_dist_info = lower.endswith('.dist-info') and os.path.isdir(\n        os.path.join(path_item, entry)\n    )\n    is_meta = is_egg_info or is_dist_info\n    return (\n        distributions_from_metadata\n        if is_meta\n        else find_distributions\n        if not only and _is_egg_path(entry)\n        else resolve_egg_link\n        if not only and lower.endswith('.egg-link')\n        else NoDists()\n    )\n\n\nclass NoDists:\n    \"\"\"\n    >>> bool(NoDists())\n    False\n\n    >>> list(NoDists()('anything'))\n    []\n    \"\"\"\n\n    def __bool__(self):\n        return False\n\n    def __call__(self, fullpath):\n        return iter(())\n\n\ndef safe_listdir(path: StrOrBytesPath):\n    \"\"\"\n    Attempt to list contents of path, but suppress some exceptions.\n    \"\"\"\n    try:\n        return os.listdir(path)\n    except (PermissionError, NotADirectoryError):\n        pass\n    except OSError as e:\n        # Ignore the directory if does not exist, not a directory or\n        # permission denied\n        if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):\n            raise\n    return ()\n\n\ndef distributions_from_metadata(path: str):\n    root = os.path.dirname(path)\n    if os.path.isdir(path):\n        if len(os.listdir(path)) == 0:\n            # empty metadata dir; skip\n            return\n        metadata: _MetadataType = PathMetadata(root, path)\n    else:\n        metadata = FileMetadata(path)\n    entry = os.path.basename(path)\n    yield Distribution.from_location(\n        root,\n        entry,\n        metadata,\n        precedence=DEVELOP_DIST,\n    )\n\n\ndef non_empty_lines(path):\n    \"\"\"\n    Yield non-empty lines from file at path\n    \"\"\"\n    for line in _read_utf8_with_fallback(path).splitlines():\n        line = line.strip()\n        if line:\n            yield line\n\n\ndef resolve_egg_link(path):\n    \"\"\"\n    Given a path to an .egg-link, resolve distributions\n    present in the referenced path.\n    \"\"\"\n    referenced_paths = non_empty_lines(path)\n    resolved_paths = (\n        os.path.join(os.path.dirname(path), ref) for ref in referenced_paths\n    )\n    dist_groups = map(find_distributions, resolved_paths)\n    return next(dist_groups, ())\n\n\nif hasattr(pkgutil, 'ImpImporter'):\n    register_finder(pkgutil.ImpImporter, find_on_path)\n\nregister_finder(importlib.machinery.FileFinder, find_on_path)\n\n_namespace_handlers: dict[type, _NSHandlerType[Any]] = _declare_state(\n    'dict', '_namespace_handlers', {}\n)\n_namespace_packages: dict[str | None, list[str]] = _declare_state(\n    'dict', '_namespace_packages', {}\n)\n\n\ndef register_namespace_handler(\n    importer_type: type[_T], namespace_handler: _NSHandlerType[_T]\n):\n    \"\"\"Register `namespace_handler` to declare namespace packages\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `namespace_handler` is a callable like this::\n\n        def namespace_handler(importer, path_entry, moduleName, module):\n            # return a path_entry to use for child packages\n\n    Namespace handlers are only called if the importer object has already\n    agreed that it can handle the relevant path item, and they should only\n    return a subpath if the module __path__ does not already contain an\n    equivalent subpath.  For an example namespace handler, see\n    ``pkg_resources.file_ns_handler``.\n    \"\"\"\n    _namespace_handlers[importer_type] = namespace_handler\n\n\ndef _handle_ns(packageName, path_item):\n    \"\"\"Ensure that named package includes a subpath of path_item (if needed)\"\"\"\n\n    importer = get_importer(path_item)\n    if importer is None:\n        return None\n\n    # use find_spec (PEP 451) and fall-back to find_module (PEP 302)\n    try:\n        spec = importer.find_spec(packageName)\n    except AttributeError:\n        # capture warnings due to #1111\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            loader = importer.find_module(packageName)\n    else:\n        loader = spec.loader if spec else None\n\n    if loader is None:\n        return None\n    module = sys.modules.get(packageName)\n    if module is None:\n        module = sys.modules[packageName] = types.ModuleType(packageName)\n        module.__path__ = []\n        _set_parent_ns(packageName)\n    elif not hasattr(module, '__path__'):\n        raise TypeError(\"Not a package:\", packageName)\n    handler = _find_adapter(_namespace_handlers, importer)\n    subpath = handler(importer, path_item, packageName, module)\n    if subpath is not None:\n        path = module.__path__\n        path.append(subpath)\n        importlib.import_module(packageName)\n        _rebuild_mod_path(path, packageName, module)\n    return subpath\n\n\ndef _rebuild_mod_path(orig_path, package_name, module: types.ModuleType):\n    \"\"\"\n    Rebuild module.__path__ ensuring that all entries are ordered\n    corresponding to their sys.path order\n    \"\"\"\n    sys_path = [_normalize_cached(p) for p in sys.path]\n\n    def safe_sys_path_index(entry):\n        \"\"\"\n        Workaround for #520 and #513.\n        \"\"\"\n        try:\n            return sys_path.index(entry)\n        except ValueError:\n            return float('inf')\n\n    def position_in_sys_path(path):\n        \"\"\"\n        Return the ordinal of the path based on its position in sys.path\n        \"\"\"\n        path_parts = path.split(os.sep)\n        module_parts = package_name.count('.') + 1\n        parts = path_parts[:-module_parts]\n        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))\n\n    new_path = sorted(orig_path, key=position_in_sys_path)\n    new_path = [_normalize_cached(p) for p in new_path]\n\n    if isinstance(module.__path__, list):\n        module.__path__[:] = new_path\n    else:\n        module.__path__ = new_path\n\n\ndef declare_namespace(packageName: str):\n    \"\"\"Declare that package 'packageName' is a namespace package\"\"\"\n\n    msg = (\n        f\"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\\n\"\n        \"Implementing implicit namespace packages (as specified in PEP 420) \"\n        \"is preferred to `pkg_resources.declare_namespace`. \"\n        \"See https://setuptools.pypa.io/en/latest/references/\"\n        \"keywords.html#keyword-namespace-packages\"\n    )\n    warnings.warn(msg, DeprecationWarning, stacklevel=2)\n\n    _imp.acquire_lock()\n    try:\n        if packageName in _namespace_packages:\n            return\n\n        path: MutableSequence[str] = sys.path\n        parent, _, _ = packageName.rpartition('.')\n\n        if parent:\n            declare_namespace(parent)\n            if parent not in _namespace_packages:\n                __import__(parent)\n            try:\n                path = sys.modules[parent].__path__\n            except AttributeError as e:\n                raise TypeError(\"Not a package:\", parent) from e\n\n        # Track what packages are namespaces, so when new path items are added,\n        # they can be updated\n        _namespace_packages.setdefault(parent or None, []).append(packageName)\n        _namespace_packages.setdefault(packageName, [])\n\n        for path_item in path:\n            # Ensure all the parent's path items are reflected in the child,\n            # if they apply\n            _handle_ns(packageName, path_item)\n\n    finally:\n        _imp.release_lock()\n\n\ndef fixup_namespace_packages(path_item: str, parent: str | None = None):\n    \"\"\"Ensure that previously-declared namespace packages include path_item\"\"\"\n    _imp.acquire_lock()\n    try:\n        for package in _namespace_packages.get(parent, ()):\n            subpath = _handle_ns(package, path_item)\n            if subpath:\n                fixup_namespace_packages(subpath, package)\n    finally:\n        _imp.release_lock()\n\n\ndef file_ns_handler(\n    importer: object,\n    path_item: StrPath,\n    packageName: str,\n    module: types.ModuleType,\n):\n    \"\"\"Compute an ns-package subpath for a filesystem or zipfile importer\"\"\"\n\n    subpath = os.path.join(path_item, packageName.split('.')[-1])\n    normalized = _normalize_cached(subpath)\n    for item in module.__path__:\n        if _normalize_cached(item) == normalized:\n            break\n    else:\n        # Only return the path if it's not already there\n        return subpath\n\n\nif hasattr(pkgutil, 'ImpImporter'):\n    register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)\n\nregister_namespace_handler(zipimport.zipimporter, file_ns_handler)\nregister_namespace_handler(importlib.machinery.FileFinder, file_ns_handler)\n\n\ndef null_ns_handler(\n    importer: object,\n    path_item: str | None,\n    packageName: str | None,\n    module: _ModuleLike | None,\n):\n    return None\n\n\nregister_namespace_handler(object, null_ns_handler)\n\n\n@overload\ndef normalize_path(filename: StrPath) -> str: ...\n@overload\ndef normalize_path(filename: BytesPath) -> bytes: ...\ndef normalize_path(filename: StrOrBytesPath):\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))\n\n\ndef _cygwin_patch(filename: StrOrBytesPath):  # pragma: nocover\n    \"\"\"\n    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains\n    symlink components. Using\n    os.path.abspath() works around this limitation. A fix in os.getcwd()\n    would probably better, in Cygwin even more so, except\n    that this seems to be by design...\n    \"\"\"\n    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename\n\n\nif TYPE_CHECKING:\n    # https://github.com/python/mypy/issues/16261\n    # https://github.com/python/typeshed/issues/6347\n    @overload\n    def _normalize_cached(filename: StrPath) -> str: ...\n    @overload\n    def _normalize_cached(filename: BytesPath) -> bytes: ...\n    def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ...\nelse:\n\n    @functools.lru_cache(maxsize=None)\n    def _normalize_cached(filename):\n        return normalize_path(filename)\n\n\ndef _is_egg_path(path):\n    \"\"\"\n    Determine if given path appears to be an egg.\n    \"\"\"\n    return _is_zip_egg(path) or _is_unpacked_egg(path)\n\n\ndef _is_zip_egg(path):\n    return (\n        path.lower().endswith('.egg')\n        and os.path.isfile(path)\n        and zipfile.is_zipfile(path)\n    )\n\n\ndef _is_unpacked_egg(path):\n    \"\"\"\n    Determine if given path appears to be an unpacked egg.\n    \"\"\"\n    return path.lower().endswith('.egg') and os.path.isfile(\n        os.path.join(path, 'EGG-INFO', 'PKG-INFO')\n    )\n\n\ndef _set_parent_ns(packageName):\n    parts = packageName.split('.')\n    name = parts.pop()\n    if parts:\n        parent = '.'.join(parts)\n        setattr(sys.modules[parent], name, sys.modules[packageName])\n\n\nMODULE = re.compile(r\"\\w+(\\.\\w+)*$\").match\nEGG_NAME = re.compile(\n    r\"\"\"\n    (?P<name>[^-]+) (\n        -(?P<ver>[^-]+) (\n            -py(?P<pyver>[^-]+) (\n                -(?P<plat>.+)\n            )?\n        )?\n    )?\n    \"\"\",\n    re.VERBOSE | re.IGNORECASE,\n).match\n\n\nclass EntryPoint:\n    \"\"\"Object representing an advertised importable object\"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        module_name: str,\n        attrs: Iterable[str] = (),\n        extras: Iterable[str] = (),\n        dist: Distribution | None = None,\n    ):\n        if not MODULE(module_name):\n            raise ValueError(\"Invalid module name\", module_name)\n        self.name = name\n        self.module_name = module_name\n        self.attrs = tuple(attrs)\n        self.extras = tuple(extras)\n        self.dist = dist\n\n    def __str__(self):\n        s = \"%s = %s\" % (self.name, self.module_name)\n        if self.attrs:\n            s += ':' + '.'.join(self.attrs)\n        if self.extras:\n            s += ' [%s]' % ','.join(self.extras)\n        return s\n\n    def __repr__(self):\n        return \"EntryPoint.parse(%r)\" % str(self)\n\n    @overload\n    def load(\n        self,\n        require: Literal[True] = True,\n        env: Environment | None = None,\n        installer: _InstallerType | None = None,\n    ) -> _ResolvedEntryPoint: ...\n    @overload\n    def load(\n        self,\n        require: Literal[False],\n        *args: Any,\n        **kwargs: Any,\n    ) -> _ResolvedEntryPoint: ...\n    def load(\n        self,\n        require: bool = True,\n        *args: Environment | _InstallerType | None,\n        **kwargs: Environment | _InstallerType | None,\n    ) -> _ResolvedEntryPoint:\n        \"\"\"\n        Require packages for this EntryPoint, then resolve it.\n        \"\"\"\n        if not require or args or kwargs:\n            warnings.warn(\n                \"Parameters to load are deprecated.  Call .resolve and \"\n                \".require separately.\",\n                PkgResourcesDeprecationWarning,\n                stacklevel=2,\n            )\n        if require:\n            # We could pass `env` and `installer` directly,\n            # but keeping `*args` and `**kwargs` for backwards compatibility\n            self.require(*args, **kwargs)  # type: ignore\n        return self.resolve()\n\n    def resolve(self) -> _ResolvedEntryPoint:\n        \"\"\"\n        Resolve the entry point from its module and attrs.\n        \"\"\"\n        module = __import__(self.module_name, fromlist=['__name__'], level=0)\n        try:\n            return functools.reduce(getattr, self.attrs, module)\n        except AttributeError as exc:\n            raise ImportError(str(exc)) from exc\n\n    def require(\n        self,\n        env: Environment | None = None,\n        installer: _InstallerType | None = None,\n    ):\n        if not self.dist:\n            error_cls = UnknownExtra if self.extras else AttributeError\n            raise error_cls(\"Can't require() without a distribution\", self)\n\n        # Get the requirements for this entry point with all its extras and\n        # then resolve them. We have to pass `extras` along when resolving so\n        # that the working set knows what extras we want. Otherwise, for\n        # dist-info distributions, the working set will assume that the\n        # requirements for that extra are purely optional and skip over them.\n        reqs = self.dist.requires(self.extras)\n        items = working_set.resolve(reqs, env, installer, extras=self.extras)\n        list(map(working_set.add, items))\n\n    pattern = re.compile(\n        r'\\s*'\n        r'(?P<name>.+?)\\s*'\n        r'=\\s*'\n        r'(?P<module>[\\w.]+)\\s*'\n        r'(:\\s*(?P<attr>[\\w.]+))?\\s*'\n        r'(?P<extras>\\[.*\\])?\\s*$'\n    )\n\n    @classmethod\n    def parse(cls, src: str, dist: Distribution | None = None):\n        \"\"\"Parse a single entry point from string `src`\n\n        Entry point syntax follows the form::\n\n            name = some.module:some.attr [extra1, extra2]\n\n        The entry name and module name are required, but the ``:attrs`` and\n        ``[extras]`` parts are optional\n        \"\"\"\n        m = cls.pattern.match(src)\n        if not m:\n            msg = \"EntryPoint must be in 'name=module:attrs [extras]' format\"\n            raise ValueError(msg, src)\n        res = m.groupdict()\n        extras = cls._parse_extras(res['extras'])\n        attrs = res['attr'].split('.') if res['attr'] else ()\n        return cls(res['name'], res['module'], attrs, extras, dist)\n\n    @classmethod\n    def _parse_extras(cls, extras_spec):\n        if not extras_spec:\n            return ()\n        req = Requirement.parse('x' + extras_spec)\n        if req.specs:\n            raise ValueError\n        return req.extras\n\n    @classmethod\n    def parse_group(\n        cls,\n        group: str,\n        lines: _NestedStr,\n        dist: Distribution | None = None,\n    ):\n        \"\"\"Parse an entry point group\"\"\"\n        if not MODULE(group):\n            raise ValueError(\"Invalid group name\", group)\n        this: dict[str, Self] = {}\n        for line in yield_lines(lines):\n            ep = cls.parse(line, dist)\n            if ep.name in this:\n                raise ValueError(\"Duplicate entry point\", group, ep.name)\n            this[ep.name] = ep\n        return this\n\n    @classmethod\n    def parse_map(\n        cls,\n        data: str | Iterable[str] | dict[str, str | Iterable[str]],\n        dist: Distribution | None = None,\n    ):\n        \"\"\"Parse a map of entry point groups\"\"\"\n        _data: Iterable[tuple[str | None, str | Iterable[str]]]\n        if isinstance(data, dict):\n            _data = data.items()\n        else:\n            _data = split_sections(data)\n        maps: dict[str, dict[str, Self]] = {}\n        for group, lines in _data:\n            if group is None:\n                if not lines:\n                    continue\n                raise ValueError(\"Entry points must be listed in groups\")\n            group = group.strip()\n            if group in maps:\n                raise ValueError(\"Duplicate group name\", group)\n            maps[group] = cls.parse_group(group, lines, dist)\n        return maps\n\n\ndef _version_from_file(lines):\n    \"\"\"\n    Given an iterable of lines from a Metadata file, return\n    the value of the Version field, if present, or None otherwise.\n    \"\"\"\n\n    def is_version_line(line):\n        return line.lower().startswith('version:')\n\n    version_lines = filter(is_version_line, lines)\n    line = next(iter(version_lines), '')\n    _, _, value = line.partition(':')\n    return safe_version(value.strip()) or None\n\n\nclass Distribution:\n    \"\"\"Wrap an actual or potential sys.path entry w/metadata\"\"\"\n\n    PKG_INFO = 'PKG-INFO'\n\n    def __init__(\n        self,\n        location: str | None = None,\n        metadata: _MetadataType = None,\n        project_name: str | None = None,\n        version: str | None = None,\n        py_version: str | None = PY_MAJOR,\n        platform: str | None = None,\n        precedence: int = EGG_DIST,\n    ):\n        self.project_name = safe_name(project_name or 'Unknown')\n        if version is not None:\n            self._version = safe_version(version)\n        self.py_version = py_version\n        self.platform = platform\n        self.location = location\n        self.precedence = precedence\n        self._provider = metadata or empty_provider\n\n    @classmethod\n    def from_location(\n        cls,\n        location: str,\n        basename: StrPath,\n        metadata: _MetadataType = None,\n        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility\n    ) -> Distribution:\n        project_name, version, py_version, platform = [None] * 4\n        basename, ext = os.path.splitext(basename)\n        if ext.lower() in _distributionImpl:\n            cls = _distributionImpl[ext.lower()]\n\n            match = EGG_NAME(basename)\n            if match:\n                project_name, version, py_version, platform = match.group(\n                    'name', 'ver', 'pyver', 'plat'\n                )\n        return cls(\n            location,\n            metadata,\n            project_name=project_name,\n            version=version,\n            py_version=py_version,\n            platform=platform,\n            **kw,\n        )._reload_version()\n\n    def _reload_version(self):\n        return self\n\n    @property\n    def hashcmp(self):\n        return (\n            self._forgiving_parsed_version,\n            self.precedence,\n            self.key,\n            self.location,\n            self.py_version or '',\n            self.platform or '',\n        )\n\n    def __hash__(self):\n        return hash(self.hashcmp)\n\n    def __lt__(self, other: Distribution):\n        return self.hashcmp < other.hashcmp\n\n    def __le__(self, other: Distribution):\n        return self.hashcmp <= other.hashcmp\n\n    def __gt__(self, other: Distribution):\n        return self.hashcmp > other.hashcmp\n\n    def __ge__(self, other: Distribution):\n        return self.hashcmp >= other.hashcmp\n\n    def __eq__(self, other: object):\n        if not isinstance(other, self.__class__):\n            # It's not a Distribution, so they are not equal\n            return False\n        return self.hashcmp == other.hashcmp\n\n    def __ne__(self, other: object):\n        return not self == other\n\n    # These properties have to be lazy so that we don't have to load any\n    # metadata until/unless it's actually needed.  (i.e., some distributions\n    # may not know their name or version without loading PKG-INFO)\n\n    @property\n    def key(self):\n        try:\n            return self._key\n        except AttributeError:\n            self._key = key = self.project_name.lower()\n            return key\n\n    @property\n    def parsed_version(self):\n        if not hasattr(self, \"_parsed_version\"):\n            try:\n                self._parsed_version = parse_version(self.version)\n            except _packaging_version.InvalidVersion as ex:\n                info = f\"(package: {self.project_name})\"\n                if hasattr(ex, \"add_note\"):\n                    ex.add_note(info)  # PEP 678\n                    raise\n                raise _packaging_version.InvalidVersion(f\"{str(ex)} {info}\") from None\n\n        return self._parsed_version\n\n    @property\n    def _forgiving_parsed_version(self):\n        try:\n            return self.parsed_version\n        except _packaging_version.InvalidVersion as ex:\n            self._parsed_version = parse_version(_forgiving_version(self.version))\n\n            notes = \"\\n\".join(getattr(ex, \"__notes__\", []))  # PEP 678\n            msg = f\"\"\"!!\\n\\n\n            *************************************************************************\n            {str(ex)}\\n{notes}\n\n            This is a long overdue deprecation.\n            For the time being, `pkg_resources` will use `{self._parsed_version}`\n            as a replacement to avoid breaking existing environments,\n            but no future compatibility is guaranteed.\n\n            If you maintain package {self.project_name} you should implement\n            the relevant changes to adequate the project to PEP 440 immediately.\n            *************************************************************************\n            \\n\\n!!\n            \"\"\"\n            warnings.warn(msg, DeprecationWarning)\n\n            return self._parsed_version\n\n    @property\n    def version(self):\n        try:\n            return self._version\n        except AttributeError as e:\n            version = self._get_version()\n            if version is None:\n                path = self._get_metadata_path_for_display(self.PKG_INFO)\n                msg = (\"Missing 'Version:' header and/or {} file at path: {}\").format(\n                    self.PKG_INFO, path\n                )\n                raise ValueError(msg, self) from e\n\n            return version\n\n    @property\n    def _dep_map(self):\n        \"\"\"\n        A map of extra to its list of (direct) requirements\n        for this distribution, including the null extra.\n        \"\"\"\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._filter_extras(self._build_dep_map())\n        return self.__dep_map\n\n    @staticmethod\n    def _filter_extras(dm: dict[str | None, list[Requirement]]):\n        \"\"\"\n        Given a mapping of extras to dependencies, strip off\n        environment markers and filter out any dependencies\n        not matching the markers.\n        \"\"\"\n        for extra in list(filter(None, dm)):\n            new_extra: str | None = extra\n            reqs = dm.pop(extra)\n            new_extra, _, marker = extra.partition(':')\n            fails_marker = marker and (\n                invalid_marker(marker) or not evaluate_marker(marker)\n            )\n            if fails_marker:\n                reqs = []\n            new_extra = safe_extra(new_extra) or None\n\n            dm.setdefault(new_extra, []).extend(reqs)\n        return dm\n\n    def _build_dep_map(self):\n        dm = {}\n        for name in 'requires.txt', 'depends.txt':\n            for extra, reqs in split_sections(self._get_metadata(name)):\n                dm.setdefault(extra, []).extend(parse_requirements(reqs))\n        return dm\n\n    def requires(self, extras: Iterable[str] = ()):\n        \"\"\"List of Requirements needed for this distro if `extras` are used\"\"\"\n        dm = self._dep_map\n        deps: list[Requirement] = []\n        deps.extend(dm.get(None, ()))\n        for ext in extras:\n            try:\n                deps.extend(dm[safe_extra(ext)])\n            except KeyError as e:\n                raise UnknownExtra(\n                    \"%s has no such extra feature %r\" % (self, ext)\n                ) from e\n        return deps\n\n    def _get_metadata_path_for_display(self, name):\n        \"\"\"\n        Return the path to the given metadata file, if available.\n        \"\"\"\n        try:\n            # We need to access _get_metadata_path() on the provider object\n            # directly rather than through this class's __getattr__()\n            # since _get_metadata_path() is marked private.\n            path = self._provider._get_metadata_path(name)\n\n        # Handle exceptions e.g. in case the distribution's metadata\n        # provider doesn't support _get_metadata_path().\n        except Exception:\n            return '[could not detect]'\n\n        return path\n\n    def _get_metadata(self, name):\n        if self.has_metadata(name):\n            yield from self.get_metadata_lines(name)\n\n    def _get_version(self):\n        lines = self._get_metadata(self.PKG_INFO)\n        return _version_from_file(lines)\n\n    def activate(self, path: list[str] | None = None, replace: bool = False):\n        \"\"\"Ensure distribution is importable on `path` (default=sys.path)\"\"\"\n        if path is None:\n            path = sys.path\n        self.insert_on(path, replace=replace)\n        if path is sys.path and self.location is not None:\n            fixup_namespace_packages(self.location)\n            for pkg in self._get_metadata('namespace_packages.txt'):\n                if pkg in sys.modules:\n                    declare_namespace(pkg)\n\n    def egg_name(self):\n        \"\"\"Return what this distribution's standard .egg filename should be\"\"\"\n        filename = \"%s-%s-py%s\" % (\n            to_filename(self.project_name),\n            to_filename(self.version),\n            self.py_version or PY_MAJOR,\n        )\n\n        if self.platform:\n            filename += '-' + self.platform\n        return filename\n\n    def __repr__(self):\n        if self.location:\n            return \"%s (%s)\" % (self, self.location)\n        else:\n            return str(self)\n\n    def __str__(self):\n        try:\n            version = getattr(self, 'version', None)\n        except ValueError:\n            version = None\n        version = version or \"[unknown version]\"\n        return \"%s %s\" % (self.project_name, version)\n\n    def __getattr__(self, attr):\n        \"\"\"Delegate all unrecognized public attributes to .metadata provider\"\"\"\n        if attr.startswith('_'):\n            raise AttributeError(attr)\n        return getattr(self._provider, attr)\n\n    def __dir__(self):\n        return list(\n            set(super().__dir__())\n            | set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))\n        )\n\n    @classmethod\n    def from_filename(\n        cls,\n        filename: StrPath,\n        metadata: _MetadataType = None,\n        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility\n    ):\n        return cls.from_location(\n            _normalize_cached(filename), os.path.basename(filename), metadata, **kw\n        )\n\n    def as_requirement(self):\n        \"\"\"Return a ``Requirement`` that matches this distribution exactly\"\"\"\n        if isinstance(self.parsed_version, _packaging_version.Version):\n            spec = \"%s==%s\" % (self.project_name, self.parsed_version)\n        else:\n            spec = \"%s===%s\" % (self.project_name, self.parsed_version)\n\n        return Requirement.parse(spec)\n\n    def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:\n        \"\"\"Return the `name` entry point of `group` or raise ImportError\"\"\"\n        ep = self.get_entry_info(group, name)\n        if ep is None:\n            raise ImportError(\"Entry point %r not found\" % ((group, name),))\n        return ep.load()\n\n    @overload\n    def get_entry_map(self, group: None = None) -> dict[str, dict[str, EntryPoint]]: ...\n    @overload\n    def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ...\n    def get_entry_map(self, group: str | None = None):\n        \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n        if not hasattr(self, \"_ep_map\"):\n            self._ep_map = EntryPoint.parse_map(\n                self._get_metadata('entry_points.txt'), self\n            )\n        if group is not None:\n            return self._ep_map.get(group, {})\n        return self._ep_map\n\n    def get_entry_info(self, group: str, name: str):\n        \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n        return self.get_entry_map(group).get(name)\n\n    # FIXME: 'Distribution.insert_on' is too complex (13)\n    def insert_on(  # noqa: C901\n        self,\n        path: list[str],\n        loc=None,\n        replace: bool = False,\n    ):\n        \"\"\"Ensure self.location is on path\n\n        If replace=False (default):\n            - If location is already in path anywhere, do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent.\n              - Else: add to the end of path.\n        If replace=True:\n            - If location is already on path anywhere (not eggs)\n              or higher priority than its parent (eggs)\n              do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent,\n                removing any lower-priority entries.\n              - Else: add it to the front of path.\n        \"\"\"\n\n        loc = loc or self.location\n        if not loc:\n            return\n\n        nloc = _normalize_cached(loc)\n        bdir = os.path.dirname(nloc)\n        npath = [(p and _normalize_cached(p) or p) for p in path]\n\n        for p, item in enumerate(npath):\n            if item == nloc:\n                if replace:\n                    break\n                else:\n                    # don't modify path (even removing duplicates) if\n                    # found and not replace\n                    return\n            elif item == bdir and self.precedence == EGG_DIST:\n                # if it's an .egg, give it precedence over its directory\n                # UNLESS it's already been added to sys.path and replace=False\n                if (not replace) and nloc in npath[p:]:\n                    return\n                if path is sys.path:\n                    self.check_version_conflict()\n                path.insert(p, loc)\n                npath.insert(p, nloc)\n                break\n        else:\n            if path is sys.path:\n                self.check_version_conflict()\n            if replace:\n                path.insert(0, loc)\n            else:\n                path.append(loc)\n            return\n\n        # p is the spot where we found or inserted loc; now remove duplicates\n        while True:\n            try:\n                np = npath.index(nloc, p + 1)\n            except ValueError:\n                break\n            else:\n                del npath[np], path[np]\n                # ha!\n                p = np\n\n        return\n\n    def check_version_conflict(self):\n        if self.key == 'setuptools':\n            # ignore the inevitable setuptools self-conflicts  :(\n            return\n\n        nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))\n        loc = normalize_path(self.location)\n        for modname in self._get_metadata('top_level.txt'):\n            if (\n                modname not in sys.modules\n                or modname in nsp\n                or modname in _namespace_packages\n            ):\n                continue\n            if modname in ('pkg_resources', 'setuptools', 'site'):\n                continue\n            fn = getattr(sys.modules[modname], '__file__', None)\n            if fn and (\n                normalize_path(fn).startswith(loc) or fn.startswith(self.location)\n            ):\n                continue\n            issue_warning(\n                \"Module %s was already imported from %s, but %s is being added\"\n                \" to sys.path\" % (modname, fn, self.location),\n            )\n\n    def has_version(self):\n        try:\n            self.version\n        except ValueError:\n            issue_warning(\"Unbuilt egg for \" + repr(self))\n            return False\n        except SystemError:\n            # TODO: remove this except clause when python/cpython#103632 is fixed.\n            return False\n        return True\n\n    def clone(self, **kw: str | int | IResourceProvider | None):\n        \"\"\"Copy this distribution, substituting in any changed keyword args\"\"\"\n        names = 'project_name version py_version platform location precedence'\n        for attr in names.split():\n            kw.setdefault(attr, getattr(self, attr, None))\n        kw.setdefault('metadata', self._provider)\n        # Unsafely unpacking. But keeping **kw for backwards and subclassing compatibility\n        return self.__class__(**kw)  # type:ignore[arg-type]\n\n    @property\n    def extras(self):\n        return [dep for dep in self._dep_map if dep]\n\n\nclass EggInfoDistribution(Distribution):\n    def _reload_version(self):\n        \"\"\"\n        Packages installed by distutils (e.g. numpy or scipy),\n        which uses an old safe_version, and so\n        their version numbers can get mangled when\n        converted to filenames (e.g., 1.11.0.dev0+2329eae to\n        1.11.0.dev0_2329eae). These distributions will not be\n        parsed properly\n        downstream by Distribution and safe_version, so\n        take an extra step and try to get the version number from\n        the metadata file itself instead of the filename.\n        \"\"\"\n        md_version = self._get_version()\n        if md_version:\n            self._version = md_version\n        return self\n\n\nclass DistInfoDistribution(Distribution):\n    \"\"\"\n    Wrap an actual or potential sys.path entry\n    w/metadata, .dist-info style.\n    \"\"\"\n\n    PKG_INFO = 'METADATA'\n    EQEQ = re.compile(r\"([\\(,])\\s*(\\d.*?)\\s*([,\\)])\")\n\n    @property\n    def _parsed_pkg_info(self):\n        \"\"\"Parse and cache metadata\"\"\"\n        try:\n            return self._pkg_info\n        except AttributeError:\n            metadata = self.get_metadata(self.PKG_INFO)\n            self._pkg_info = email.parser.Parser().parsestr(metadata)\n            return self._pkg_info\n\n    @property\n    def _dep_map(self):\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._compute_dependencies()\n            return self.__dep_map\n\n    def _compute_dependencies(self) -> dict[str | None, list[Requirement]]:\n        \"\"\"Recompute this distribution's dependencies.\"\"\"\n        self.__dep_map: dict[str | None, list[Requirement]] = {None: []}\n\n        reqs: list[Requirement] = []\n        # Including any condition expressions\n        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:\n            reqs.extend(parse_requirements(req))\n\n        def reqs_for_extra(extra):\n            for req in reqs:\n                if not req.marker or req.marker.evaluate({'extra': extra}):\n                    yield req\n\n        common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))\n        self.__dep_map[None].extend(common)\n\n        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:\n            s_extra = safe_extra(extra.strip())\n            self.__dep_map[s_extra] = [\n                r for r in reqs_for_extra(extra) if r not in common\n            ]\n\n        return self.__dep_map\n\n\n_distributionImpl = {\n    '.egg': Distribution,\n    '.egg-info': EggInfoDistribution,\n    '.dist-info': DistInfoDistribution,\n}\n\n\ndef issue_warning(*args, **kw):\n    level = 1\n    g = globals()\n    try:\n        # find the first stack frame that is *not* code in\n        # the pkg_resources module, to use for the warning\n        while sys._getframe(level).f_globals is g:\n            level += 1\n    except ValueError:\n        pass\n    warnings.warn(stacklevel=level + 1, *args, **kw)\n\n\ndef parse_requirements(strs: _NestedStr):\n    \"\"\"\n    Yield ``Requirement`` objects for each specification in `strs`.\n\n    `strs` must be a string, or a (possibly-nested) iterable thereof.\n    \"\"\"\n    return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))\n\n\nclass RequirementParseError(_packaging_requirements.InvalidRequirement):\n    \"Compatibility wrapper for InvalidRequirement\"\n\n\nclass Requirement(_packaging_requirements.Requirement):\n    def __init__(self, requirement_string: str):\n        \"\"\"DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!\"\"\"\n        super().__init__(requirement_string)\n        self.unsafe_name = self.name\n        project_name = safe_name(self.name)\n        self.project_name, self.key = project_name, project_name.lower()\n        self.specs = [(spec.operator, spec.version) for spec in self.specifier]\n        # packaging.requirements.Requirement uses a set for its extras. We use a variable-length tuple\n        self.extras: tuple[str] = tuple(map(safe_extra, self.extras))\n        self.hashCmp = (\n            self.key,\n            self.url,\n            self.specifier,\n            frozenset(self.extras),\n            str(self.marker) if self.marker else None,\n        )\n        self.__hash = hash(self.hashCmp)\n\n    def __eq__(self, other: object):\n        return isinstance(other, Requirement) and self.hashCmp == other.hashCmp\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __contains__(self, item: Distribution | str | tuple[str, ...]) -> bool:\n        if isinstance(item, Distribution):\n            if item.key != self.key:\n                return False\n\n            item = item.version\n\n        # Allow prereleases always in order to match the previous behavior of\n        # this method. In the future this should be smarter and follow PEP 440\n        # more accurately.\n        return self.specifier.contains(item, prereleases=True)\n\n    def __hash__(self):\n        return self.__hash\n\n    def __repr__(self):\n        return \"Requirement.parse(%r)\" % str(self)\n\n    @staticmethod\n    def parse(s: str | Iterable[str]):\n        (req,) = parse_requirements(s)\n        return req\n\n\ndef _always_object(classes):\n    \"\"\"\n    Ensure object appears in the mro even\n    for old-style classes.\n    \"\"\"\n    if object not in classes:\n        return classes + (object,)\n    return classes\n\n\ndef _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT:\n    \"\"\"Return an adapter factory for `ob` from `registry`\"\"\"\n    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))\n    for t in types:\n        if t in registry:\n            return registry[t]\n    # _find_adapter would previously return None, and immediately be called.\n    # So we're raising a TypeError to keep backward compatibility if anyone depended on that behaviour.\n    raise TypeError(f\"Could not find adapter for {registry} and {ob}\")\n\n\ndef ensure_directory(path: StrOrBytesPath):\n    \"\"\"Ensure that the parent directory of `path` exists\"\"\"\n    dirname = os.path.dirname(path)\n    os.makedirs(dirname, exist_ok=True)\n\n\ndef _bypass_ensure_directory(path):\n    \"\"\"Sandbox-bypassing version of ensure_directory()\"\"\"\n    if not WRITE_SUPPORT:\n        raise OSError('\"os.mkdir\" not supported on this platform.')\n    dirname, filename = split(path)\n    if dirname and filename and not isdir(dirname):\n        _bypass_ensure_directory(dirname)\n        try:\n            mkdir(dirname, 0o755)\n        except FileExistsError:\n            pass\n\n\ndef split_sections(s: _NestedStr) -> Iterator[tuple[str | None, list[str]]]:\n    \"\"\"Split a string or iterable thereof into (section, content) pairs\n\n    Each ``section`` is a stripped version of the section header (\"[section]\")\n    and each ``content`` is a list of stripped lines excluding blank lines and\n    comment-only lines.  If there are any such lines before the first section\n    header, they're returned in a first ``section`` of ``None``.\n    \"\"\"\n    section = None\n    content = []\n    for line in yield_lines(s):\n        if line.startswith(\"[\"):\n            if line.endswith(\"]\"):\n                if section or content:\n                    yield section, content\n                section = line[1:-1].strip()\n                content = []\n            else:\n                raise ValueError(\"Invalid section heading\", line)\n        else:\n            content.append(line)\n\n    # wrap up last segment\n    yield section, content\n\n\ndef _mkstemp(*args, **kw):\n    old_open = os.open\n    try:\n        # temporarily bypass sandboxing\n        os.open = os_open\n        return tempfile.mkstemp(*args, **kw)\n    finally:\n        # and then put it back\n        os.open = old_open\n\n\n# Silence the PEP440Warning by default, so that end users don't get hit by it\n# randomly just because they use pkg_resources. We want to append the rule\n# because we want earlier uses of filterwarnings to take precedence over this\n# one.\nwarnings.filterwarnings(\"ignore\", category=PEP440Warning, append=True)\n\n\nclass PkgResourcesDeprecationWarning(Warning):\n    \"\"\"\n    Base class for warning about deprecations in ``pkg_resources``\n\n    This class is not derived from ``DeprecationWarning``, and as such is\n    visible by default.\n    \"\"\"\n\n\n# Ported from ``setuptools`` to avoid introducing an import inter-dependency:\n_LOCALE_ENCODING = \"locale\" if sys.version_info >= (3, 10) else None\n\n\ndef _read_utf8_with_fallback(file: str, fallback_encoding=_LOCALE_ENCODING) -> str:\n    \"\"\"See setuptools.unicode_utils._read_utf8_with_fallback\"\"\"\n    try:\n        with open(file, \"r\", encoding=\"utf-8\") as f:\n            return f.read()\n    except UnicodeDecodeError:  # pragma: no cover\n        msg = f\"\"\"\\\n        ********************************************************************************\n        `encoding=\"utf-8\"` fails with {file!r}, trying `encoding={fallback_encoding!r}`.\n\n        This fallback behaviour is considered **deprecated** and future versions of\n        `setuptools/pkg_resources` may not implement it.\n\n        Please encode {file!r} with \"utf-8\" to ensure future builds will succeed.\n\n        If this file was produced by `setuptools` itself, cleaning up the cached files\n        and re-building/re-installing the package with a newer version of `setuptools`\n        (e.g. by updating `build-system.requires` in its `pyproject.toml`)\n        might solve the problem.\n        ********************************************************************************\n        \"\"\"\n        # TODO: Add a deadline?\n        #       See comment in setuptools.unicode_utils._Utf8EncodingNeeded\n        warnings.warn(msg, PkgResourcesDeprecationWarning, stacklevel=2)\n        with open(file, \"r\", encoding=fallback_encoding) as f:\n            return f.read()\n\n\n# from jaraco.functools 1.3\ndef _call_aside(f, *args, **kwargs):\n    f(*args, **kwargs)\n    return f\n\n\n@_call_aside\ndef _initialize(g=globals()):\n    \"Set up global resource manager (deliberately not state-saved)\"\n    manager = ResourceManager()\n    g['_manager'] = manager\n    g.update(\n        (name, getattr(manager, name))\n        for name in dir(manager)\n        if not name.startswith('_')\n    )\n\n\n@_call_aside\ndef _initialize_master_working_set():\n    \"\"\"\n    Prepare the master working set and make the ``require()``\n    API available.\n\n    This function has explicit effects on the global state\n    of pkg_resources. It is intended to be invoked once at\n    the initialization of this module.\n\n    Invocation by other packages is unsupported and done\n    at their own risk.\n    \"\"\"\n    working_set = _declare_state('object', 'working_set', WorkingSet._build_master())\n\n    require = working_set.require\n    iter_entry_points = working_set.iter_entry_points\n    add_activation_listener = working_set.subscribe\n    run_script = working_set.run_script\n    # backward compatibility\n    run_main = run_script\n    # Activate all distributions already on sys.path with replace=False and\n    # ensure that all distributions added to the working set in the future\n    # (e.g. by calling ``require()``) will get activated as well,\n    # with higher priority (replace=True).\n    tuple(dist.activate(replace=False) for dist in working_set)\n    add_activation_listener(\n        lambda dist: dist.activate(replace=True),\n        existing=False,\n    )\n    working_set.entries = []\n    # match order\n    list(map(working_set.add_entry, sys.path))\n    globals().update(locals())\n\n\nif TYPE_CHECKING:\n    # All of these are set by the @_call_aside methods above\n    __resource_manager = ResourceManager()  # Won't exist at runtime\n    resource_exists = __resource_manager.resource_exists\n    resource_isdir = __resource_manager.resource_isdir\n    resource_filename = __resource_manager.resource_filename\n    resource_stream = __resource_manager.resource_stream\n    resource_string = __resource_manager.resource_string\n    resource_listdir = __resource_manager.resource_listdir\n    set_extraction_path = __resource_manager.set_extraction_path\n    cleanup_resources = __resource_manager.cleanup_resources\n\n    working_set = WorkingSet()\n    require = working_set.require\n    iter_entry_points = working_set.iter_entry_points\n    add_activation_listener = working_set.subscribe\n    run_script = working_set.run_script\n    run_main = run_script\n"
  },
  {
    "path": "src/pip/_vendor/pkg_resources.pyi",
    "content": "from pkg_resources import *"
  },
  {
    "path": "src/pip/_vendor/platformdirs/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2010-202x The platformdirs developers\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/__init__.py",
    "content": "\"\"\"\nUtilities for determining application-specific dirs.\n\nSee <https://github.com/platformdirs/platformdirs> for details and usage.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom typing import TYPE_CHECKING\n\nfrom .api import PlatformDirsABC\nfrom .version import __version__\nfrom .version import __version_tuple__ as __version_info__\n\nif TYPE_CHECKING:\n    from pathlib import Path\n    from typing import Literal\n\nif sys.platform == \"win32\":\n    from pip._vendor.platformdirs.windows import Windows as _Result\nelif sys.platform == \"darwin\":\n    from pip._vendor.platformdirs.macos import MacOS as _Result\nelse:\n    from pip._vendor.platformdirs.unix import Unix as _Result\n\n\ndef _set_platform_dir_class() -> type[PlatformDirsABC]:\n    if os.getenv(\"ANDROID_DATA\") == \"/data\" and os.getenv(\"ANDROID_ROOT\") == \"/system\":\n        if os.getenv(\"SHELL\") or os.getenv(\"PREFIX\"):\n            return _Result\n\n        from pip._vendor.platformdirs.android import _android_folder  # noqa: PLC0415\n\n        if _android_folder() is not None:\n            from pip._vendor.platformdirs.android import Android  # noqa: PLC0415\n\n            return Android  # return to avoid redefinition of a result\n\n    return _Result\n\n\nif TYPE_CHECKING:\n    # Work around mypy issue: https://github.com/python/mypy/issues/10962\n    PlatformDirs = _Result\nelse:\n    PlatformDirs = _set_platform_dir_class()  #: Currently active platform\nAppDirs = PlatformDirs  #: Backwards compatibility with appdirs\n\n\ndef user_data_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: data directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_data_dir\n\n\ndef site_data_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    multipath: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: data directory shared by users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        multipath=multipath,\n        ensure_exists=ensure_exists,\n    ).site_data_dir\n\n\ndef user_config_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: config directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_config_dir\n\n\ndef site_config_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    multipath: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: config directory shared by the users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        multipath=multipath,\n        ensure_exists=ensure_exists,\n    ).site_config_dir\n\n\ndef user_cache_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: cache directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_cache_dir\n\n\ndef site_cache_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: cache directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).site_cache_dir\n\n\ndef user_state_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: state directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_state_dir\n\n\ndef user_log_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: log directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_log_dir\n\n\ndef user_documents_dir() -> str:\n    \"\"\":returns: documents directory tied to the user\"\"\"\n    return PlatformDirs().user_documents_dir\n\n\ndef user_downloads_dir() -> str:\n    \"\"\":returns: downloads directory tied to the user\"\"\"\n    return PlatformDirs().user_downloads_dir\n\n\ndef user_pictures_dir() -> str:\n    \"\"\":returns: pictures directory tied to the user\"\"\"\n    return PlatformDirs().user_pictures_dir\n\n\ndef user_videos_dir() -> str:\n    \"\"\":returns: videos directory tied to the user\"\"\"\n    return PlatformDirs().user_videos_dir\n\n\ndef user_music_dir() -> str:\n    \"\"\":returns: music directory tied to the user\"\"\"\n    return PlatformDirs().user_music_dir\n\n\ndef user_desktop_dir() -> str:\n    \"\"\":returns: desktop directory tied to the user\"\"\"\n    return PlatformDirs().user_desktop_dir\n\n\ndef user_runtime_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: runtime directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_runtime_dir\n\n\ndef site_runtime_dir(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: runtime directory shared by users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).site_runtime_dir\n\n\ndef user_data_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: data path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_data_path\n\n\ndef site_data_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    multipath: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `multipath <platformdirs.api.PlatformDirsABC.multipath>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: data path shared by users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        multipath=multipath,\n        ensure_exists=ensure_exists,\n    ).site_data_path\n\n\ndef user_config_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: config path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_config_path\n\n\ndef site_config_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    multipath: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: config path shared by the users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        multipath=multipath,\n        ensure_exists=ensure_exists,\n    ).site_config_path\n\n\ndef site_cache_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: cache directory tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).site_cache_path\n\n\ndef user_cache_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: cache path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_cache_path\n\n\ndef user_state_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    roaming: bool = False,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.roaming>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: state path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        roaming=roaming,\n        ensure_exists=ensure_exists,\n    ).user_state_path\n\n\ndef user_log_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: log path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_log_path\n\n\ndef user_documents_path() -> Path:\n    \"\"\":returns: documents a path tied to the user\"\"\"\n    return PlatformDirs().user_documents_path\n\n\ndef user_downloads_path() -> Path:\n    \"\"\":returns: downloads path tied to the user\"\"\"\n    return PlatformDirs().user_downloads_path\n\n\ndef user_pictures_path() -> Path:\n    \"\"\":returns: pictures path tied to the user\"\"\"\n    return PlatformDirs().user_pictures_path\n\n\ndef user_videos_path() -> Path:\n    \"\"\":returns: videos path tied to the user\"\"\"\n    return PlatformDirs().user_videos_path\n\n\ndef user_music_path() -> Path:\n    \"\"\":returns: music path tied to the user\"\"\"\n    return PlatformDirs().user_music_path\n\n\ndef user_desktop_path() -> Path:\n    \"\"\":returns: desktop path tied to the user\"\"\"\n    return PlatformDirs().user_desktop_path\n\n\ndef user_runtime_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: runtime path tied to the user\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).user_runtime_path\n\n\ndef site_runtime_path(\n    appname: str | None = None,\n    appauthor: str | Literal[False] | None = None,\n    version: str | None = None,\n    opinion: bool = True,  # noqa: FBT001, FBT002\n    ensure_exists: bool = False,  # noqa: FBT001, FBT002\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :param ensure_exists: See `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n    :returns: runtime path shared by users\n    \"\"\"\n    return PlatformDirs(\n        appname=appname,\n        appauthor=appauthor,\n        version=version,\n        opinion=opinion,\n        ensure_exists=ensure_exists,\n    ).site_runtime_path\n\n\n__all__ = [\n    \"AppDirs\",\n    \"PlatformDirs\",\n    \"PlatformDirsABC\",\n    \"__version__\",\n    \"__version_info__\",\n    \"site_cache_dir\",\n    \"site_cache_path\",\n    \"site_config_dir\",\n    \"site_config_path\",\n    \"site_data_dir\",\n    \"site_data_path\",\n    \"site_runtime_dir\",\n    \"site_runtime_path\",\n    \"user_cache_dir\",\n    \"user_cache_path\",\n    \"user_config_dir\",\n    \"user_config_path\",\n    \"user_data_dir\",\n    \"user_data_path\",\n    \"user_desktop_dir\",\n    \"user_desktop_path\",\n    \"user_documents_dir\",\n    \"user_documents_path\",\n    \"user_downloads_dir\",\n    \"user_downloads_path\",\n    \"user_log_dir\",\n    \"user_log_path\",\n    \"user_music_dir\",\n    \"user_music_path\",\n    \"user_pictures_dir\",\n    \"user_pictures_path\",\n    \"user_runtime_dir\",\n    \"user_runtime_path\",\n    \"user_state_dir\",\n    \"user_state_path\",\n    \"user_videos_dir\",\n    \"user_videos_path\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/__main__.py",
    "content": "\"\"\"Main entry point.\"\"\"\n\nfrom __future__ import annotations\n\nfrom pip._vendor.platformdirs import PlatformDirs, __version__\n\nPROPS = (\n    \"user_data_dir\",\n    \"user_config_dir\",\n    \"user_cache_dir\",\n    \"user_state_dir\",\n    \"user_log_dir\",\n    \"user_documents_dir\",\n    \"user_downloads_dir\",\n    \"user_pictures_dir\",\n    \"user_videos_dir\",\n    \"user_music_dir\",\n    \"user_runtime_dir\",\n    \"site_data_dir\",\n    \"site_config_dir\",\n    \"site_cache_dir\",\n    \"site_runtime_dir\",\n)\n\n\ndef main() -> None:\n    \"\"\"Run the main entry point.\"\"\"\n    app_name = \"MyApp\"\n    app_author = \"MyCompany\"\n\n    print(f\"-- platformdirs {__version__} --\")  # noqa: T201\n\n    print(\"-- app dirs (with optional 'version')\")  # noqa: T201\n    dirs = PlatformDirs(app_name, app_author, version=\"1.0\")\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")  # noqa: T201\n\n    print(\"\\n-- app dirs (without optional 'version')\")  # noqa: T201\n    dirs = PlatformDirs(app_name, app_author)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")  # noqa: T201\n\n    print(\"\\n-- app dirs (without optional 'appauthor')\")  # noqa: T201\n    dirs = PlatformDirs(app_name)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")  # noqa: T201\n\n    print(\"\\n-- app dirs (with disabled 'appauthor')\")  # noqa: T201\n    dirs = PlatformDirs(app_name, appauthor=False)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")  # noqa: T201\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/android.py",
    "content": "\"\"\"Android.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, cast\n\nfrom .api import PlatformDirsABC\n\n\nclass Android(PlatformDirsABC):\n    \"\"\"\n    Follows the guidance `from here <https://android.stackexchange.com/a/216132>`_.\n\n    Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `version\n    <platformdirs.api.PlatformDirsABC.version>`, `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user, e.g. ``/data/user/<userid>/<packagename>/files/<AppName>``\"\"\"\n        return self._append_app_name_and_version(cast(\"str\", _android_folder()), \"files\")\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\"\n        :return: config directory tied to the user, e.g. \\\n        ``/data/user/<userid>/<packagename>/shared_prefs/<AppName>``\n        \"\"\"\n        return self._append_app_name_and_version(cast(\"str\", _android_folder()), \"shared_prefs\")\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, same as `user_config_dir`\"\"\"\n        return self.user_config_dir\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user, e.g.,``/data/user/<userid>/<packagename>/cache/<AppName>``\"\"\"\n        return self._append_app_name_and_version(cast(\"str\", _android_folder()), \"cache\")\n\n    @property\n    def site_cache_dir(self) -> str:\n        \"\"\":return: cache directory shared by users, same as `user_cache_dir`\"\"\"\n        return self.user_cache_dir\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\"\n        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,\n          e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/log``\n        \"\"\"\n        path = self.user_cache_dir\n        if self.opinion:\n            path = os.path.join(path, \"log\")  # noqa: PTH118\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``\"\"\"\n        return _android_documents_folder()\n\n    @property\n    def user_downloads_dir(self) -> str:\n        \"\"\":return: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``\"\"\"\n        return _android_downloads_folder()\n\n    @property\n    def user_pictures_dir(self) -> str:\n        \"\"\":return: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``\"\"\"\n        return _android_pictures_folder()\n\n    @property\n    def user_videos_dir(self) -> str:\n        \"\"\":return: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``\"\"\"\n        return _android_videos_folder()\n\n    @property\n    def user_music_dir(self) -> str:\n        \"\"\":return: music directory tied to the user e.g. ``/storage/emulated/0/Music``\"\"\"\n        return _android_music_folder()\n\n    @property\n    def user_desktop_dir(self) -> str:\n        \"\"\":return: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``\"\"\"\n        return \"/storage/emulated/0/Desktop\"\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,\n          e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/tmp``\n        \"\"\"\n        path = self.user_cache_dir\n        if self.opinion:\n            path = os.path.join(path, \"tmp\")  # noqa: PTH118\n        return path\n\n    @property\n    def site_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory shared by users, same as `user_runtime_dir`\"\"\"\n        return self.user_runtime_dir\n\n\n@lru_cache(maxsize=1)\ndef _android_folder() -> str | None:  # noqa: C901\n    \"\"\":return: base folder for the Android OS or None if it cannot be found\"\"\"\n    result: str | None = None\n    # type checker isn't happy with our \"import android\", just don't do this when type checking see\n    # https://stackoverflow.com/a/61394121\n    if not TYPE_CHECKING:\n        try:\n            # First try to get a path to android app using python4android (if available)...\n            from android import mActivity  # noqa: PLC0415\n\n            context = cast(\"android.content.Context\", mActivity.getApplicationContext())  # noqa: F821\n            result = context.getFilesDir().getParentFile().getAbsolutePath()\n        except Exception:  # noqa: BLE001\n            result = None\n    if result is None:\n        try:\n            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful\n            # result...\n            from jnius import autoclass  # noqa: PLC0415\n\n            context = autoclass(\"android.content.Context\")\n            result = context.getFilesDir().getParentFile().getAbsolutePath()\n        except Exception:  # noqa: BLE001\n            result = None\n    if result is None:\n        # and if that fails, too, find an android folder looking at path on the sys.path\n        # warning: only works for apps installed under /data, not adopted storage etc.\n        pattern = re.compile(r\"/data/(data|user/\\d+)/(.+)/files\")\n        for path in sys.path:\n            if pattern.match(path):\n                result = path.split(\"/files\")[0]\n                break\n        else:\n            result = None\n    if result is None:\n        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into\n        # account\n        pattern = re.compile(r\"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\\d+)/(.+)/files\")\n        for path in sys.path:\n            if pattern.match(path):\n                result = path.split(\"/files\")[0]\n                break\n        else:\n            result = None\n    return result\n\n\n@lru_cache(maxsize=1)\ndef _android_documents_folder() -> str:\n    \"\"\":return: documents folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass  # noqa: PLC0415\n\n        context = autoclass(\"android.content.Context\")\n        environment = autoclass(\"android.os.Environment\")\n        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()\n    except Exception:  # noqa: BLE001\n        documents_dir = \"/storage/emulated/0/Documents\"\n\n    return documents_dir\n\n\n@lru_cache(maxsize=1)\ndef _android_downloads_folder() -> str:\n    \"\"\":return: downloads folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass  # noqa: PLC0415\n\n        context = autoclass(\"android.content.Context\")\n        environment = autoclass(\"android.os.Environment\")\n        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()\n    except Exception:  # noqa: BLE001\n        downloads_dir = \"/storage/emulated/0/Downloads\"\n\n    return downloads_dir\n\n\n@lru_cache(maxsize=1)\ndef _android_pictures_folder() -> str:\n    \"\"\":return: pictures folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass  # noqa: PLC0415\n\n        context = autoclass(\"android.content.Context\")\n        environment = autoclass(\"android.os.Environment\")\n        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()\n    except Exception:  # noqa: BLE001\n        pictures_dir = \"/storage/emulated/0/Pictures\"\n\n    return pictures_dir\n\n\n@lru_cache(maxsize=1)\ndef _android_videos_folder() -> str:\n    \"\"\":return: videos folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass  # noqa: PLC0415\n\n        context = autoclass(\"android.content.Context\")\n        environment = autoclass(\"android.os.Environment\")\n        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()\n    except Exception:  # noqa: BLE001\n        videos_dir = \"/storage/emulated/0/DCIM/Camera\"\n\n    return videos_dir\n\n\n@lru_cache(maxsize=1)\ndef _android_music_folder() -> str:\n    \"\"\":return: music folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass  # noqa: PLC0415\n\n        context = autoclass(\"android.content.Context\")\n        environment = autoclass(\"android.os.Environment\")\n        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()\n    except Exception:  # noqa: BLE001\n        music_dir = \"/storage/emulated/0/Music\"\n\n    return music_dir\n\n\n__all__ = [\n    \"Android\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/api.py",
    "content": "\"\"\"Base API.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from collections.abc import Iterator\n    from typing import Literal\n\n\nclass PlatformDirsABC(ABC):  # noqa: PLR0904\n    \"\"\"Abstract base class for platform directories.\"\"\"\n\n    def __init__(  # noqa: PLR0913, PLR0917\n        self,\n        appname: str | None = None,\n        appauthor: str | Literal[False] | None = None,\n        version: str | None = None,\n        roaming: bool = False,  # noqa: FBT001, FBT002\n        multipath: bool = False,  # noqa: FBT001, FBT002\n        opinion: bool = True,  # noqa: FBT001, FBT002\n        ensure_exists: bool = False,  # noqa: FBT001, FBT002\n    ) -> None:\n        \"\"\"\n        Create a new platform directory.\n\n        :param appname: See `appname`.\n        :param appauthor: See `appauthor`.\n        :param version: See `version`.\n        :param roaming: See `roaming`.\n        :param multipath: See `multipath`.\n        :param opinion: See `opinion`.\n        :param ensure_exists: See `ensure_exists`.\n\n        \"\"\"\n        self.appname = appname  #: The name of application.\n        self.appauthor = appauthor\n        \"\"\"\n        The name of the app author or distributing body for this application.\n\n        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.\n\n        \"\"\"\n        self.version = version\n        \"\"\"\n        An optional version path element to append to the path.\n\n        You might want to use this if you want multiple versions of your app to be able to run independently. If used,\n        this would typically be ``<major>.<minor>``.\n\n        \"\"\"\n        self.roaming = roaming\n        \"\"\"\n        Whether to use the roaming appdata directory on Windows.\n\n        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on\n        login (see\n        `here <https://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>`_).\n\n        \"\"\"\n        self.multipath = multipath\n        \"\"\"\n        An optional parameter which indicates that the entire list of data dirs should be returned.\n\n        By default, the first item would only be returned.\n\n        \"\"\"\n        self.opinion = opinion  #: A flag to indicating to use opinionated values.\n        self.ensure_exists = ensure_exists\n        \"\"\"\n        Optionally create the directory (and any missing parents) upon access if it does not exist.\n\n        By default, no directories are created.\n\n        \"\"\"\n\n    def _append_app_name_and_version(self, *base: str) -> str:\n        params = list(base[1:])\n        if self.appname:\n            params.append(self.appname)\n            if self.version:\n                params.append(self.version)\n        path = os.path.join(base[0], *params)  # noqa: PTH118\n        self._optionally_create_directory(path)\n        return path\n\n    def _optionally_create_directory(self, path: str) -> None:\n        if self.ensure_exists:\n            Path(path).mkdir(parents=True, exist_ok=True)\n\n    def _first_item_as_path_if_multipath(self, directory: str) -> Path:\n        if self.multipath:\n            # If multipath is True, the first path is returned.\n            directory = directory.partition(os.pathsep)[0]\n        return Path(directory)\n\n    @property\n    @abstractmethod\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users\"\"\"\n\n    @property\n    @abstractmethod\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users\"\"\"\n\n    @property\n    @abstractmethod\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_cache_dir(self) -> str:\n        \"\"\":return: cache directory shared by users\"\"\"\n\n    @property\n    @abstractmethod\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_downloads_dir(self) -> str:\n        \"\"\":return: downloads directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_pictures_dir(self) -> str:\n        \"\"\":return: pictures directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_videos_dir(self) -> str:\n        \"\"\":return: videos directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_music_dir(self) -> str:\n        \"\"\":return: music directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_desktop_dir(self) -> str:\n        \"\"\":return: desktop directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory shared by users\"\"\"\n\n    @property\n    def user_data_path(self) -> Path:\n        \"\"\":return: data path tied to the user\"\"\"\n        return Path(self.user_data_dir)\n\n    @property\n    def site_data_path(self) -> Path:\n        \"\"\":return: data path shared by users\"\"\"\n        return Path(self.site_data_dir)\n\n    @property\n    def user_config_path(self) -> Path:\n        \"\"\":return: config path tied to the user\"\"\"\n        return Path(self.user_config_dir)\n\n    @property\n    def site_config_path(self) -> Path:\n        \"\"\":return: config path shared by the users\"\"\"\n        return Path(self.site_config_dir)\n\n    @property\n    def user_cache_path(self) -> Path:\n        \"\"\":return: cache path tied to the user\"\"\"\n        return Path(self.user_cache_dir)\n\n    @property\n    def site_cache_path(self) -> Path:\n        \"\"\":return: cache path shared by users\"\"\"\n        return Path(self.site_cache_dir)\n\n    @property\n    def user_state_path(self) -> Path:\n        \"\"\":return: state path tied to the user\"\"\"\n        return Path(self.user_state_dir)\n\n    @property\n    def user_log_path(self) -> Path:\n        \"\"\":return: log path tied to the user\"\"\"\n        return Path(self.user_log_dir)\n\n    @property\n    def user_documents_path(self) -> Path:\n        \"\"\":return: documents a path tied to the user\"\"\"\n        return Path(self.user_documents_dir)\n\n    @property\n    def user_downloads_path(self) -> Path:\n        \"\"\":return: downloads path tied to the user\"\"\"\n        return Path(self.user_downloads_dir)\n\n    @property\n    def user_pictures_path(self) -> Path:\n        \"\"\":return: pictures path tied to the user\"\"\"\n        return Path(self.user_pictures_dir)\n\n    @property\n    def user_videos_path(self) -> Path:\n        \"\"\":return: videos path tied to the user\"\"\"\n        return Path(self.user_videos_dir)\n\n    @property\n    def user_music_path(self) -> Path:\n        \"\"\":return: music path tied to the user\"\"\"\n        return Path(self.user_music_dir)\n\n    @property\n    def user_desktop_path(self) -> Path:\n        \"\"\":return: desktop path tied to the user\"\"\"\n        return Path(self.user_desktop_dir)\n\n    @property\n    def user_runtime_path(self) -> Path:\n        \"\"\":return: runtime path tied to the user\"\"\"\n        return Path(self.user_runtime_dir)\n\n    @property\n    def site_runtime_path(self) -> Path:\n        \"\"\":return: runtime path shared by users\"\"\"\n        return Path(self.site_runtime_dir)\n\n    def iter_config_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site configuration directories.\"\"\"\n        yield self.user_config_dir\n        yield self.site_config_dir\n\n    def iter_data_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site data directories.\"\"\"\n        yield self.user_data_dir\n        yield self.site_data_dir\n\n    def iter_cache_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site cache directories.\"\"\"\n        yield self.user_cache_dir\n        yield self.site_cache_dir\n\n    def iter_runtime_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site runtime directories.\"\"\"\n        yield self.user_runtime_dir\n        yield self.site_runtime_dir\n\n    def iter_config_paths(self) -> Iterator[Path]:\n        \"\"\":yield: all user and site configuration paths.\"\"\"\n        for path in self.iter_config_dirs():\n            yield Path(path)\n\n    def iter_data_paths(self) -> Iterator[Path]:\n        \"\"\":yield: all user and site data paths.\"\"\"\n        for path in self.iter_data_dirs():\n            yield Path(path)\n\n    def iter_cache_paths(self) -> Iterator[Path]:\n        \"\"\":yield: all user and site cache paths.\"\"\"\n        for path in self.iter_cache_dirs():\n            yield Path(path)\n\n    def iter_runtime_paths(self) -> Iterator[Path]:\n        \"\"\":yield: all user and site runtime paths.\"\"\"\n        for path in self.iter_runtime_dirs():\n            yield Path(path)\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/macos.py",
    "content": "\"\"\"macOS.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\nimport sys\nfrom typing import TYPE_CHECKING\n\nfrom .api import PlatformDirsABC\n\nif TYPE_CHECKING:\n    from pathlib import Path\n\n\nclass MacOS(PlatformDirsABC):\n    \"\"\"\n    Platform directories for the macOS operating system.\n\n    Follows the guidance from\n    `Apple documentation <https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html>`_.\n    Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`,\n    `version <platformdirs.api.PlatformDirsABC.version>`,\n    `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Application Support\"))  # noqa: PTH111\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\"\n        :return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``.\n          If we're using a Python binary managed by `Homebrew <https://brew.sh>`_, the directory\n          will be under the Homebrew prefix, e.g. ``$homebrew_prefix/share/$appname/$version``.\n          If `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled, and we're in Homebrew,\n          the response is a multi-path string separated by \":\", e.g.\n          ``$homebrew_prefix/share/$appname/$version:/Library/Application Support/$appname/$version``\n        \"\"\"\n        is_homebrew = \"/opt/python\" in sys.prefix\n        homebrew_prefix = sys.prefix.split(\"/opt/python\")[0] if is_homebrew else \"\"\n        path_list = [self._append_app_name_and_version(f\"{homebrew_prefix}/share\")] if is_homebrew else []\n        path_list.append(self._append_app_name_and_version(\"/Library/Application Support\"))\n        if self.multipath:\n            return os.pathsep.join(path_list)\n        return path_list[0]\n\n    @property\n    def site_data_path(self) -> Path:\n        \"\"\":return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_data_dir)\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, same as `site_data_dir`\"\"\"\n        return self.site_data_dir\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Caches\"))  # noqa: PTH111\n\n    @property\n    def site_cache_dir(self) -> str:\n        \"\"\"\n        :return: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``.\n          If we're using a Python binary managed by `Homebrew <https://brew.sh>`_, the directory\n          will be under the Homebrew prefix, e.g. ``$homebrew_prefix/var/cache/$appname/$version``.\n          If `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled, and we're in Homebrew,\n          the response is a multi-path string separated by \":\", e.g.\n          ``$homebrew_prefix/var/cache/$appname/$version:/Library/Caches/$appname/$version``\n        \"\"\"\n        is_homebrew = \"/opt/python\" in sys.prefix\n        homebrew_prefix = sys.prefix.split(\"/opt/python\")[0] if is_homebrew else \"\"\n        path_list = [self._append_app_name_and_version(f\"{homebrew_prefix}/var/cache\")] if is_homebrew else []\n        path_list.append(self._append_app_name_and_version(\"/Library/Caches\"))\n        if self.multipath:\n            return os.pathsep.join(path_list)\n        return path_list[0]\n\n    @property\n    def site_cache_path(self) -> Path:\n        \"\"\":return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_cache_dir)\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Logs\"))  # noqa: PTH111\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user, e.g. ``~/Documents``\"\"\"\n        return os.path.expanduser(\"~/Documents\")  # noqa: PTH111\n\n    @property\n    def user_downloads_dir(self) -> str:\n        \"\"\":return: downloads directory tied to the user, e.g. ``~/Downloads``\"\"\"\n        return os.path.expanduser(\"~/Downloads\")  # noqa: PTH111\n\n    @property\n    def user_pictures_dir(self) -> str:\n        \"\"\":return: pictures directory tied to the user, e.g. ``~/Pictures``\"\"\"\n        return os.path.expanduser(\"~/Pictures\")  # noqa: PTH111\n\n    @property\n    def user_videos_dir(self) -> str:\n        \"\"\":return: videos directory tied to the user, e.g. ``~/Movies``\"\"\"\n        return os.path.expanduser(\"~/Movies\")  # noqa: PTH111\n\n    @property\n    def user_music_dir(self) -> str:\n        \"\"\":return: music directory tied to the user, e.g. ``~/Music``\"\"\"\n        return os.path.expanduser(\"~/Music\")  # noqa: PTH111\n\n    @property\n    def user_desktop_dir(self) -> str:\n        \"\"\":return: desktop directory tied to the user, e.g. ``~/Desktop``\"\"\"\n        return os.path.expanduser(\"~/Desktop\")  # noqa: PTH111\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Caches/TemporaryItems\"))  # noqa: PTH111\n\n    @property\n    def site_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory shared by users, same as `user_runtime_dir`\"\"\"\n        return self.user_runtime_dir\n\n\n__all__ = [\n    \"MacOS\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/platformdirs/unix.py",
    "content": "\"\"\"Unix.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, NoReturn\n\nfrom .api import PlatformDirsABC\n\nif TYPE_CHECKING:\n    from collections.abc import Iterator\n\nif sys.platform == \"win32\":\n\n    def getuid() -> NoReturn:\n        msg = \"should only be used on Unix\"\n        raise RuntimeError(msg)\n\nelse:\n    from os import getuid\n\n\nclass Unix(PlatformDirsABC):  # noqa: PLR0904\n    \"\"\"\n    On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-\n    latest.html>`_.\n\n    The spec allows overriding directories with environment variables. The examples shown are the default values,\n    alongside the name of the environment variable that overrides them. Makes use of the `appname\n    <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath\n    <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists\n    <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\"\n        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or\n         ``$XDG_DATA_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_DATA_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.local/share\")  # noqa: PTH111\n        return self._append_app_name_and_version(path)\n\n    @property\n    def _site_data_dirs(self) -> list[str]:\n        path = os.environ.get(\"XDG_DATA_DIRS\", \"\")\n        if not path.strip():\n            path = f\"/usr/local/share{os.pathsep}/usr/share\"\n        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\"\n        :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is\n         enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the\n         OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``\n        \"\"\"\n        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False\n        dirs = self._site_data_dirs\n        if not self.multipath:\n            return dirs[0]\n        return os.pathsep.join(dirs)\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\"\n        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or\n         ``$XDG_CONFIG_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_CONFIG_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.config\")  # noqa: PTH111\n        return self._append_app_name_and_version(path)\n\n    @property\n    def _site_config_dirs(self) -> list[str]:\n        path = os.environ.get(\"XDG_CONFIG_DIRS\", \"\")\n        if not path.strip():\n            path = \"/etc/xdg\"\n        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\"\n        :return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>`\n         is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by\n         the OS path separator), e.g. ``/etc/xdg/$appname/$version``\n        \"\"\"\n        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False\n        dirs = self._site_config_dirs\n        if not self.multipath:\n            return dirs[0]\n        return os.pathsep.join(dirs)\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\"\n        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or\n         ``~/$XDG_CACHE_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_CACHE_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.cache\")  # noqa: PTH111\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_cache_dir(self) -> str:\n        \"\"\":return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(\"/var/cache\")\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\"\n        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or\n         ``$XDG_STATE_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_STATE_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.local/state\")  # noqa: PTH111\n        return self._append_app_name_and_version(path)\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it\"\"\"\n        path = self.user_state_dir\n        if self.opinion:\n            path = os.path.join(path, \"log\")  # noqa: PTH118\n            self._optionally_create_directory(path)\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user, e.g. ``~/Documents``\"\"\"\n        return _get_user_media_dir(\"XDG_DOCUMENTS_DIR\", \"~/Documents\")\n\n    @property\n    def user_downloads_dir(self) -> str:\n        \"\"\":return: downloads directory tied to the user, e.g. ``~/Downloads``\"\"\"\n        return _get_user_media_dir(\"XDG_DOWNLOAD_DIR\", \"~/Downloads\")\n\n    @property\n    def user_pictures_dir(self) -> str:\n        \"\"\":return: pictures directory tied to the user, e.g. ``~/Pictures``\"\"\"\n        return _get_user_media_dir(\"XDG_PICTURES_DIR\", \"~/Pictures\")\n\n    @property\n    def user_videos_dir(self) -> str:\n        \"\"\":return: videos directory tied to the user, e.g. ``~/Videos``\"\"\"\n        return _get_user_media_dir(\"XDG_VIDEOS_DIR\", \"~/Videos\")\n\n    @property\n    def user_music_dir(self) -> str:\n        \"\"\":return: music directory tied to the user, e.g. ``~/Music``\"\"\"\n        return _get_user_media_dir(\"XDG_MUSIC_DIR\", \"~/Music\")\n\n    @property\n    def user_desktop_dir(self) -> str:\n        \"\"\":return: desktop directory tied to the user, e.g. ``~/Desktop``\"\"\"\n        return _get_user_media_dir(\"XDG_DESKTOP_DIR\", \"~/Desktop\")\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or\n         ``$XDG_RUNTIME_DIR/$appname/$version``.\n\n         For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if\n         exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR``\n         is not set.\n        \"\"\"\n        path = os.environ.get(\"XDG_RUNTIME_DIR\", \"\")\n        if not path.strip():\n            if sys.platform.startswith((\"freebsd\", \"openbsd\", \"netbsd\")):\n                path = f\"/var/run/user/{getuid()}\"\n                if not Path(path).exists():\n                    path = f\"/tmp/runtime-{getuid()}\"  # noqa: S108\n            else:\n                path = f\"/run/user/{getuid()}\"\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \\\n        ``$XDG_RUNTIME_DIR/$appname/$version``.\n\n        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will\n        fall back to paths associated to the root user instead of a regular logged-in user if it's not set.\n\n        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir`\n        instead.\n\n        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.\n        \"\"\"\n        path = os.environ.get(\"XDG_RUNTIME_DIR\", \"\")\n        if not path.strip():\n            if sys.platform.startswith((\"freebsd\", \"openbsd\", \"netbsd\")):\n                path = \"/var/run\"\n            else:\n                path = \"/run\"\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_data_path(self) -> Path:\n        \"\"\":return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_data_dir)\n\n    @property\n    def site_config_path(self) -> Path:\n        \"\"\":return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_config_dir)\n\n    @property\n    def site_cache_path(self) -> Path:\n        \"\"\":return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_cache_dir)\n\n    def iter_config_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site configuration directories.\"\"\"\n        yield self.user_config_dir\n        yield from self._site_config_dirs\n\n    def iter_data_dirs(self) -> Iterator[str]:\n        \"\"\":yield: all user and site data directories.\"\"\"\n        yield self.user_data_dir\n        yield from self._site_data_dirs\n\n\ndef _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:\n    media_dir = _get_user_dirs_folder(env_var)\n    if media_dir is None:\n        media_dir = os.environ.get(env_var, \"\").strip()\n        if not media_dir:\n            media_dir = os.path.expanduser(fallback_tilde_path)  # noqa: PTH111\n\n    return media_dir\n\n\ndef _get_user_dirs_folder(key: str) -> str | None:\n    \"\"\"\n    Return directory from user-dirs.dirs config file.\n\n    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.\n\n    \"\"\"\n    user_dirs_config_path = Path(Unix().user_config_dir) / \"user-dirs.dirs\"\n    if user_dirs_config_path.exists():\n        parser = ConfigParser()\n\n        with user_dirs_config_path.open() as stream:\n            # Add fake section header, so ConfigParser doesn't complain\n            parser.read_string(f\"[top]\\n{stream.read()}\")\n\n        if key not in parser[\"top\"]:\n            return None\n\n        path = parser[\"top\"][key].strip('\"')\n        # Handle relative home paths\n        return path.replace(\"$HOME\", os.path.expanduser(\"~\"))  # noqa: PTH111\n\n    return None\n\n\n__all__ = [\n    \"Unix\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/version.py",
    "content": "# file generated by setuptools-scm\n# don't change, don't track in version control\n\n__all__ = [\n    \"__version__\",\n    \"__version_tuple__\",\n    \"version\",\n    \"version_tuple\",\n    \"__commit_id__\",\n    \"commit_id\",\n]\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n    from typing import Tuple\n    from typing import Union\n\n    VERSION_TUPLE = Tuple[Union[int, str], ...]\n    COMMIT_ID = Union[str, None]\nelse:\n    VERSION_TUPLE = object\n    COMMIT_ID = object\n\nversion: str\n__version__: str\n__version_tuple__: VERSION_TUPLE\nversion_tuple: VERSION_TUPLE\ncommit_id: COMMIT_ID\n__commit_id__: COMMIT_ID\n\n__version__ = version = '4.5.1'\n__version_tuple__ = version_tuple = (4, 5, 1)\n\n__commit_id__ = commit_id = None\n"
  },
  {
    "path": "src/pip/_vendor/platformdirs/windows.py",
    "content": "\"\"\"Windows.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING\n\nfrom .api import PlatformDirsABC\n\nif TYPE_CHECKING:\n    from collections.abc import Callable\n\n\nclass Windows(PlatformDirsABC):\n    \"\"\"\n    `MSDN on where to store app data files <https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_.\n\n    Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `appauthor\n    <platformdirs.api.PlatformDirsABC.appauthor>`, `version <platformdirs.api.PlatformDirsABC.version>`, `roaming\n    <platformdirs.api.PlatformDirsABC.roaming>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists\n    <platformdirs.api.PlatformDirsABC.ensure_exists>`.\n\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\"\n        :return: data directory tied to the user, e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\$appauthor\\\\$appname`` (not roaming) or\n         ``%USERPROFILE%\\\\AppData\\\\Roaming\\\\$appauthor\\\\$appname`` (roaming)\n        \"\"\"\n        const = \"CSIDL_APPDATA\" if self.roaming else \"CSIDL_LOCAL_APPDATA\"\n        path = os.path.normpath(get_win_folder(const))\n        return self._append_parts(path)\n\n    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:\n        params = []\n        if self.appname:\n            if self.appauthor is not False:\n                author = self.appauthor or self.appname\n                params.append(author)\n            params.append(self.appname)\n            if opinion_value is not None and self.opinion:\n                params.append(opinion_value)\n            if self.version:\n                params.append(self.version)\n        path = os.path.join(path, *params)  # noqa: PTH118\n        self._optionally_create_directory(path)\n        return path\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users, e.g. ``C:\\\\ProgramData\\\\$appauthor\\\\$appname``\"\"\"\n        path = os.path.normpath(get_win_folder(\"CSIDL_COMMON_APPDATA\"))\n        return self._append_parts(path)\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, same as `site_data_dir`\"\"\"\n        return self.site_data_dir\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\"\n        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\$appauthor\\\\$appname\\\\Cache\\\\$version``\n        \"\"\"\n        path = os.path.normpath(get_win_folder(\"CSIDL_LOCAL_APPDATA\"))\n        return self._append_parts(path, opinion_value=\"Cache\")\n\n    @property\n    def site_cache_dir(self) -> str:\n        \"\"\":return: cache directory shared by users, e.g. ``C:\\\\ProgramData\\\\$appauthor\\\\$appname\\\\Cache\\\\$version``\"\"\"\n        path = os.path.normpath(get_win_folder(\"CSIDL_COMMON_APPDATA\"))\n        return self._append_parts(path, opinion_value=\"Cache\")\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it\"\"\"\n        path = self.user_data_dir\n        if self.opinion:\n            path = os.path.join(path, \"Logs\")  # noqa: PTH118\n            self._optionally_create_directory(path)\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user e.g. ``%USERPROFILE%\\\\Documents``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_PERSONAL\"))\n\n    @property\n    def user_downloads_dir(self) -> str:\n        \"\"\":return: downloads directory tied to the user e.g. ``%USERPROFILE%\\\\Downloads``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_DOWNLOADS\"))\n\n    @property\n    def user_pictures_dir(self) -> str:\n        \"\"\":return: pictures directory tied to the user e.g. ``%USERPROFILE%\\\\Pictures``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_MYPICTURES\"))\n\n    @property\n    def user_videos_dir(self) -> str:\n        \"\"\":return: videos directory tied to the user e.g. ``%USERPROFILE%\\\\Videos``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_MYVIDEO\"))\n\n    @property\n    def user_music_dir(self) -> str:\n        \"\"\":return: music directory tied to the user e.g. ``%USERPROFILE%\\\\Music``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_MYMUSIC\"))\n\n    @property\n    def user_desktop_dir(self) -> str:\n        \"\"\":return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\\\Desktop``\"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_DESKTOPDIRECTORY\"))\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\Temp\\\\$appauthor\\\\$appname``\n        \"\"\"\n        path = os.path.normpath(os.path.join(get_win_folder(\"CSIDL_LOCAL_APPDATA\"), \"Temp\"))  # noqa: PTH118\n        return self._append_parts(path)\n\n    @property\n    def site_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory shared by users, same as `user_runtime_dir`\"\"\"\n        return self.user_runtime_dir\n\n\ndef get_win_folder_from_env_vars(csidl_name: str) -> str:\n    \"\"\"Get folder from environment variables.\"\"\"\n    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)\n    if result is not None:\n        return result\n\n    env_var_name = {\n        \"CSIDL_APPDATA\": \"APPDATA\",\n        \"CSIDL_COMMON_APPDATA\": \"ALLUSERSPROFILE\",\n        \"CSIDL_LOCAL_APPDATA\": \"LOCALAPPDATA\",\n    }.get(csidl_name)\n    if env_var_name is None:\n        msg = f\"Unknown CSIDL name: {csidl_name}\"\n        raise ValueError(msg)\n    result = os.environ.get(env_var_name)\n    if result is None:\n        msg = f\"Unset environment variable: {env_var_name}\"\n        raise ValueError(msg)\n    return result\n\n\ndef get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:\n    \"\"\"Get a folder for a CSIDL name that does not exist as an environment variable.\"\"\"\n    if csidl_name == \"CSIDL_PERSONAL\":\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Documents\")  # noqa: PTH118\n\n    if csidl_name == \"CSIDL_DOWNLOADS\":\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Downloads\")  # noqa: PTH118\n\n    if csidl_name == \"CSIDL_MYPICTURES\":\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Pictures\")  # noqa: PTH118\n\n    if csidl_name == \"CSIDL_MYVIDEO\":\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Videos\")  # noqa: PTH118\n\n    if csidl_name == \"CSIDL_MYMUSIC\":\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Music\")  # noqa: PTH118\n    return None\n\n\ndef get_win_folder_from_registry(csidl_name: str) -> str:\n    \"\"\"\n    Get folder from the registry.\n\n    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer\n    for all CSIDL_* names.\n\n    \"\"\"\n    machine_names = {\n        \"CSIDL_COMMON_APPDATA\",\n    }\n    shell_folder_name = {\n        \"CSIDL_APPDATA\": \"AppData\",\n        \"CSIDL_COMMON_APPDATA\": \"Common AppData\",\n        \"CSIDL_LOCAL_APPDATA\": \"Local AppData\",\n        \"CSIDL_PERSONAL\": \"Personal\",\n        \"CSIDL_DOWNLOADS\": \"{374DE290-123F-4565-9164-39C4925E467B}\",\n        \"CSIDL_MYPICTURES\": \"My Pictures\",\n        \"CSIDL_MYVIDEO\": \"My Video\",\n        \"CSIDL_MYMUSIC\": \"My Music\",\n    }.get(csidl_name)\n    if shell_folder_name is None:\n        msg = f\"Unknown CSIDL name: {csidl_name}\"\n        raise ValueError(msg)\n    if sys.platform != \"win32\":  # only needed for mypy type checker to know that this code runs only on Windows\n        raise NotImplementedError\n    import winreg  # noqa: PLC0415\n\n    # Use HKEY_LOCAL_MACHINE for system-wide folders, HKEY_CURRENT_USER for user-specific folders\n    hkey = winreg.HKEY_LOCAL_MACHINE if csidl_name in machine_names else winreg.HKEY_CURRENT_USER\n\n    key = winreg.OpenKey(hkey, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\")\n    directory, _ = winreg.QueryValueEx(key, shell_folder_name)\n    return str(directory)\n\n\ndef get_win_folder_via_ctypes(csidl_name: str) -> str:\n    \"\"\"Get folder with ctypes.\"\"\"\n    # There is no 'CSIDL_DOWNLOADS'.\n    # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.\n    # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid\n\n    import ctypes  # noqa: PLC0415\n\n    csidl_const = {\n        \"CSIDL_APPDATA\": 26,\n        \"CSIDL_COMMON_APPDATA\": 35,\n        \"CSIDL_LOCAL_APPDATA\": 28,\n        \"CSIDL_PERSONAL\": 5,\n        \"CSIDL_MYPICTURES\": 39,\n        \"CSIDL_MYVIDEO\": 14,\n        \"CSIDL_MYMUSIC\": 13,\n        \"CSIDL_DOWNLOADS\": 40,\n        \"CSIDL_DESKTOPDIRECTORY\": 16,\n    }.get(csidl_name)\n    if csidl_const is None:\n        msg = f\"Unknown CSIDL name: {csidl_name}\"\n        raise ValueError(msg)\n\n    buf = ctypes.create_unicode_buffer(1024)\n    windll = getattr(ctypes, \"windll\")  # noqa: B009 # using getattr to avoid false positive with mypy type checker\n    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)\n\n    # Downgrade to short path name if it has high-bit chars.\n    if any(ord(c) > 255 for c in buf):  # noqa: PLR2004\n        buf2 = ctypes.create_unicode_buffer(1024)\n        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):\n            buf = buf2\n\n    if csidl_name == \"CSIDL_DOWNLOADS\":\n        return os.path.join(buf.value, \"Downloads\")  # noqa: PTH118\n\n    return buf.value\n\n\ndef _pick_get_win_folder() -> Callable[[str], str]:\n    try:\n        import ctypes  # noqa: PLC0415\n    except ImportError:\n        pass\n    else:\n        if hasattr(ctypes, \"windll\"):\n            return get_win_folder_via_ctypes\n    try:\n        import winreg  # noqa: PLC0415, F401\n    except ImportError:\n        return get_win_folder_from_env_vars\n    else:\n        return get_win_folder_from_registry\n\n\nget_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())\n\n__all__ = [\n    \"Windows\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/pygments/LICENSE",
    "content": "Copyright (c) 2006-2022 by the respective authors (see AUTHORS file).\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "src/pip/_vendor/pygments/__init__.py",
    "content": "\"\"\"\n    Pygments\n    ~~~~~~~~\n\n    Pygments is a syntax highlighting package written in Python.\n\n    It is a generic syntax highlighter for general use in all kinds of software\n    such as forum systems, wikis or other applications that need to prettify\n    source code. Highlights are:\n\n    * a wide range of common languages and markup formats is supported\n    * special attention is paid to details, increasing quality by a fair amount\n    * support for new languages and formats are added easily\n    * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image\n      formats that PIL supports, and ANSI sequences\n    * it is usable as a command-line tool and as a library\n    * ... and it highlights even Brainfuck!\n\n    The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.\n\n    .. _Pygments master branch:\n       https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\nfrom io import StringIO, BytesIO\n\n__version__ = '2.19.2'\n__docformat__ = 'restructuredtext'\n\n__all__ = ['lex', 'format', 'highlight']\n\n\ndef lex(code, lexer):\n    \"\"\"\n    Lex `code` with the `lexer` (must be a `Lexer` instance)\n    and return an iterable of tokens. Currently, this only calls\n    `lexer.get_tokens()`.\n    \"\"\"\n    try:\n        return lexer.get_tokens(code)\n    except TypeError:\n        # Heuristic to catch a common mistake.\n        from pip._vendor.pygments.lexer import RegexLexer\n        if isinstance(lexer, type) and issubclass(lexer, RegexLexer):\n            raise TypeError('lex() argument must be a lexer instance, '\n                            'not a class')\n        raise\n\n\ndef format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin\n    \"\"\"\n    Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``\n    (a `Formatter` instance).\n\n    If ``outfile`` is given and a valid file object (an object with a\n    ``write`` method), the result will be written to it, otherwise it\n    is returned as a string.\n    \"\"\"\n    try:\n        if not outfile:\n            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()\n            formatter.format(tokens, realoutfile)\n            return realoutfile.getvalue()\n        else:\n            formatter.format(tokens, outfile)\n    except TypeError:\n        # Heuristic to catch a common mistake.\n        from pip._vendor.pygments.formatter import Formatter\n        if isinstance(formatter, type) and issubclass(formatter, Formatter):\n            raise TypeError('format() argument must be a formatter instance, '\n                            'not a class')\n        raise\n\n\ndef highlight(code, lexer, formatter, outfile=None):\n    \"\"\"\n    This is the most high-level highlighting function. It combines `lex` and\n    `format` in one function.\n    \"\"\"\n    return format(lex(code, lexer), formatter, outfile)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/__main__.py",
    "content": "\"\"\"\n    pygments.__main__\n    ~~~~~~~~~~~~~~~~~\n\n    Main entry point for ``python -m pygments``.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport sys\nfrom pip._vendor.pygments.cmdline import main\n\ntry:\n    sys.exit(main(sys.argv))\nexcept KeyboardInterrupt:\n    sys.exit(1)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/console.py",
    "content": "\"\"\"\n    pygments.console\n    ~~~~~~~~~~~~~~~~\n\n    Format colored console output.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nesc = \"\\x1b[\"\n\ncodes = {}\ncodes[\"\"] = \"\"\ncodes[\"reset\"] = esc + \"39;49;00m\"\n\ncodes[\"bold\"] = esc + \"01m\"\ncodes[\"faint\"] = esc + \"02m\"\ncodes[\"standout\"] = esc + \"03m\"\ncodes[\"underline\"] = esc + \"04m\"\ncodes[\"blink\"] = esc + \"05m\"\ncodes[\"overline\"] = esc + \"06m\"\n\ndark_colors = [\"black\", \"red\", \"green\", \"yellow\", \"blue\",\n               \"magenta\", \"cyan\", \"gray\"]\nlight_colors = [\"brightblack\", \"brightred\", \"brightgreen\", \"brightyellow\", \"brightblue\",\n                \"brightmagenta\", \"brightcyan\", \"white\"]\n\nx = 30\nfor dark, light in zip(dark_colors, light_colors):\n    codes[dark] = esc + \"%im\" % x\n    codes[light] = esc + \"%im\" % (60 + x)\n    x += 1\n\ndel dark, light, x\n\ncodes[\"white\"] = codes[\"bold\"]\n\n\ndef reset_color():\n    return codes[\"reset\"]\n\n\ndef colorize(color_key, text):\n    return codes[color_key] + text + codes[\"reset\"]\n\n\ndef ansiformat(attr, text):\n    \"\"\"\n    Format ``text`` with a color and/or some attributes::\n\n        color       normal color\n        *color*     bold color\n        _color_     underlined color\n        +color+     blinking color\n    \"\"\"\n    result = []\n    if attr[:1] == attr[-1:] == '+':\n        result.append(codes['blink'])\n        attr = attr[1:-1]\n    if attr[:1] == attr[-1:] == '*':\n        result.append(codes['bold'])\n        attr = attr[1:-1]\n    if attr[:1] == attr[-1:] == '_':\n        result.append(codes['underline'])\n        attr = attr[1:-1]\n    result.append(codes[attr])\n    result.append(text)\n    result.append(codes['reset'])\n    return ''.join(result)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/filter.py",
    "content": "\"\"\"\n    pygments.filter\n    ~~~~~~~~~~~~~~~\n\n    Module that implements the default filter.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n\ndef apply_filters(stream, filters, lexer=None):\n    \"\"\"\n    Use this method to apply an iterable of filters to\n    a stream. If lexer is given it's forwarded to the\n    filter, otherwise the filter receives `None`.\n    \"\"\"\n    def _apply(filter_, stream):\n        yield from filter_.filter(lexer, stream)\n    for filter_ in filters:\n        stream = _apply(filter_, stream)\n    return stream\n\n\ndef simplefilter(f):\n    \"\"\"\n    Decorator that converts a function into a filter::\n\n        @simplefilter\n        def lowercase(self, lexer, stream, options):\n            for ttype, value in stream:\n                yield ttype, value.lower()\n    \"\"\"\n    return type(f.__name__, (FunctionFilter,), {\n        '__module__': getattr(f, '__module__'),\n        '__doc__': f.__doc__,\n        'function': f,\n    })\n\n\nclass Filter:\n    \"\"\"\n    Default filter. Subclass this class or use the `simplefilter`\n    decorator to create own filters.\n    \"\"\"\n\n    def __init__(self, **options):\n        self.options = options\n\n    def filter(self, lexer, stream):\n        raise NotImplementedError()\n\n\nclass FunctionFilter(Filter):\n    \"\"\"\n    Abstract class used by `simplefilter` to create simple\n    function filters on the fly. The `simplefilter` decorator\n    automatically creates subclasses of this class for\n    functions passed to it.\n    \"\"\"\n    function = None\n\n    def __init__(self, **options):\n        if not hasattr(self, 'function'):\n            raise TypeError(f'{self.__class__.__name__!r} used without bound function')\n        Filter.__init__(self, **options)\n\n    def filter(self, lexer, stream):\n        # pylint: disable=not-callable\n        yield from self.function(lexer, stream, self.options)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/filters/__init__.py",
    "content": "\"\"\"\n    pygments.filters\n    ~~~~~~~~~~~~~~~~\n\n    Module containing filter lookup functions and default\n    filters.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\nfrom pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \\\n    string_to_tokentype\nfrom pip._vendor.pygments.filter import Filter\nfrom pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \\\n    get_choice_opt, ClassNotFound, OptionError\nfrom pip._vendor.pygments.plugin import find_plugin_filters\n\n\ndef find_filter_class(filtername):\n    \"\"\"Lookup a filter by name. Return None if not found.\"\"\"\n    if filtername in FILTERS:\n        return FILTERS[filtername]\n    for name, cls in find_plugin_filters():\n        if name == filtername:\n            return cls\n    return None\n\n\ndef get_filter_by_name(filtername, **options):\n    \"\"\"Return an instantiated filter.\n\n    Options are passed to the filter initializer if wanted.\n    Raise a ClassNotFound if not found.\n    \"\"\"\n    cls = find_filter_class(filtername)\n    if cls:\n        return cls(**options)\n    else:\n        raise ClassNotFound(f'filter {filtername!r} not found')\n\n\ndef get_all_filters():\n    \"\"\"Return a generator of all filter names.\"\"\"\n    yield from FILTERS\n    for name, _ in find_plugin_filters():\n        yield name\n\n\ndef _replace_special(ttype, value, regex, specialttype,\n                     replacefunc=lambda x: x):\n    last = 0\n    for match in regex.finditer(value):\n        start, end = match.start(), match.end()\n        if start != last:\n            yield ttype, value[last:start]\n        yield specialttype, replacefunc(value[start:end])\n        last = end\n    if last != len(value):\n        yield ttype, value[last:]\n\n\nclass CodeTagFilter(Filter):\n    \"\"\"Highlight special code tags in comments and docstrings.\n\n    Options accepted:\n\n    `codetags` : list of strings\n       A list of strings that are flagged as code tags.  The default is to\n       highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``.\n\n    .. versionchanged:: 2.13\n       Now recognizes ``FIXME`` by default.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        tags = get_list_opt(options, 'codetags',\n                            ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])\n        self.tag_re = re.compile(r'\\b({})\\b'.format('|'.join([\n            re.escape(tag) for tag in tags if tag\n        ])))\n\n    def filter(self, lexer, stream):\n        regex = self.tag_re\n        for ttype, value in stream:\n            if ttype in String.Doc or \\\n               ttype in Comment and \\\n               ttype not in Comment.Preproc:\n                yield from _replace_special(ttype, value, regex, Comment.Special)\n            else:\n                yield ttype, value\n\n\nclass SymbolFilter(Filter):\n    \"\"\"Convert mathematical symbols such as \\\\<longrightarrow> in Isabelle\n    or \\\\longrightarrow in LaTeX into Unicode characters.\n\n    This is mostly useful for HTML or console output when you want to\n    approximate the source rendering you'd see in an IDE.\n\n    Options accepted:\n\n    `lang` : string\n       The symbol language. Must be one of ``'isabelle'`` or\n       ``'latex'``.  The default is ``'isabelle'``.\n    \"\"\"\n\n    latex_symbols = {\n        '\\\\alpha'                : '\\U000003b1',\n        '\\\\beta'                 : '\\U000003b2',\n        '\\\\gamma'                : '\\U000003b3',\n        '\\\\delta'                : '\\U000003b4',\n        '\\\\varepsilon'           : '\\U000003b5',\n        '\\\\zeta'                 : '\\U000003b6',\n        '\\\\eta'                  : '\\U000003b7',\n        '\\\\vartheta'             : '\\U000003b8',\n        '\\\\iota'                 : '\\U000003b9',\n        '\\\\kappa'                : '\\U000003ba',\n        '\\\\lambda'               : '\\U000003bb',\n        '\\\\mu'                   : '\\U000003bc',\n        '\\\\nu'                   : '\\U000003bd',\n        '\\\\xi'                   : '\\U000003be',\n        '\\\\pi'                   : '\\U000003c0',\n        '\\\\varrho'               : '\\U000003c1',\n        '\\\\sigma'                : '\\U000003c3',\n        '\\\\tau'                  : '\\U000003c4',\n        '\\\\upsilon'              : '\\U000003c5',\n        '\\\\varphi'               : '\\U000003c6',\n        '\\\\chi'                  : '\\U000003c7',\n        '\\\\psi'                  : '\\U000003c8',\n        '\\\\omega'                : '\\U000003c9',\n        '\\\\Gamma'                : '\\U00000393',\n        '\\\\Delta'                : '\\U00000394',\n        '\\\\Theta'                : '\\U00000398',\n        '\\\\Lambda'               : '\\U0000039b',\n        '\\\\Xi'                   : '\\U0000039e',\n        '\\\\Pi'                   : '\\U000003a0',\n        '\\\\Sigma'                : '\\U000003a3',\n        '\\\\Upsilon'              : '\\U000003a5',\n        '\\\\Phi'                  : '\\U000003a6',\n        '\\\\Psi'                  : '\\U000003a8',\n        '\\\\Omega'                : '\\U000003a9',\n        '\\\\leftarrow'            : '\\U00002190',\n        '\\\\longleftarrow'        : '\\U000027f5',\n        '\\\\rightarrow'           : '\\U00002192',\n        '\\\\longrightarrow'       : '\\U000027f6',\n        '\\\\Leftarrow'            : '\\U000021d0',\n        '\\\\Longleftarrow'        : '\\U000027f8',\n        '\\\\Rightarrow'           : '\\U000021d2',\n        '\\\\Longrightarrow'       : '\\U000027f9',\n        '\\\\leftrightarrow'       : '\\U00002194',\n        '\\\\longleftrightarrow'   : '\\U000027f7',\n        '\\\\Leftrightarrow'       : '\\U000021d4',\n        '\\\\Longleftrightarrow'   : '\\U000027fa',\n        '\\\\mapsto'               : '\\U000021a6',\n        '\\\\longmapsto'           : '\\U000027fc',\n        '\\\\relbar'               : '\\U00002500',\n        '\\\\Relbar'               : '\\U00002550',\n        '\\\\hookleftarrow'        : '\\U000021a9',\n        '\\\\hookrightarrow'       : '\\U000021aa',\n        '\\\\leftharpoondown'      : '\\U000021bd',\n        '\\\\rightharpoondown'     : '\\U000021c1',\n        '\\\\leftharpoonup'        : '\\U000021bc',\n        '\\\\rightharpoonup'       : '\\U000021c0',\n        '\\\\rightleftharpoons'    : '\\U000021cc',\n        '\\\\leadsto'              : '\\U0000219d',\n        '\\\\downharpoonleft'      : '\\U000021c3',\n        '\\\\downharpoonright'     : '\\U000021c2',\n        '\\\\upharpoonleft'        : '\\U000021bf',\n        '\\\\upharpoonright'       : '\\U000021be',\n        '\\\\restriction'          : '\\U000021be',\n        '\\\\uparrow'              : '\\U00002191',\n        '\\\\Uparrow'              : '\\U000021d1',\n        '\\\\downarrow'            : '\\U00002193',\n        '\\\\Downarrow'            : '\\U000021d3',\n        '\\\\updownarrow'          : '\\U00002195',\n        '\\\\Updownarrow'          : '\\U000021d5',\n        '\\\\langle'               : '\\U000027e8',\n        '\\\\rangle'               : '\\U000027e9',\n        '\\\\lceil'                : '\\U00002308',\n        '\\\\rceil'                : '\\U00002309',\n        '\\\\lfloor'               : '\\U0000230a',\n        '\\\\rfloor'               : '\\U0000230b',\n        '\\\\flqq'                 : '\\U000000ab',\n        '\\\\frqq'                 : '\\U000000bb',\n        '\\\\bot'                  : '\\U000022a5',\n        '\\\\top'                  : '\\U000022a4',\n        '\\\\wedge'                : '\\U00002227',\n        '\\\\bigwedge'             : '\\U000022c0',\n        '\\\\vee'                  : '\\U00002228',\n        '\\\\bigvee'               : '\\U000022c1',\n        '\\\\forall'               : '\\U00002200',\n        '\\\\exists'               : '\\U00002203',\n        '\\\\nexists'              : '\\U00002204',\n        '\\\\neg'                  : '\\U000000ac',\n        '\\\\Box'                  : '\\U000025a1',\n        '\\\\Diamond'              : '\\U000025c7',\n        '\\\\vdash'                : '\\U000022a2',\n        '\\\\models'               : '\\U000022a8',\n        '\\\\dashv'                : '\\U000022a3',\n        '\\\\surd'                 : '\\U0000221a',\n        '\\\\le'                   : '\\U00002264',\n        '\\\\ge'                   : '\\U00002265',\n        '\\\\ll'                   : '\\U0000226a',\n        '\\\\gg'                   : '\\U0000226b',\n        '\\\\lesssim'              : '\\U00002272',\n        '\\\\gtrsim'               : '\\U00002273',\n        '\\\\lessapprox'           : '\\U00002a85',\n        '\\\\gtrapprox'            : '\\U00002a86',\n        '\\\\in'                   : '\\U00002208',\n        '\\\\notin'                : '\\U00002209',\n        '\\\\subset'               : '\\U00002282',\n        '\\\\supset'               : '\\U00002283',\n        '\\\\subseteq'             : '\\U00002286',\n        '\\\\supseteq'             : '\\U00002287',\n        '\\\\sqsubset'             : '\\U0000228f',\n        '\\\\sqsupset'             : '\\U00002290',\n        '\\\\sqsubseteq'           : '\\U00002291',\n        '\\\\sqsupseteq'           : '\\U00002292',\n        '\\\\cap'                  : '\\U00002229',\n        '\\\\bigcap'               : '\\U000022c2',\n        '\\\\cup'                  : '\\U0000222a',\n        '\\\\bigcup'               : '\\U000022c3',\n        '\\\\sqcup'                : '\\U00002294',\n        '\\\\bigsqcup'             : '\\U00002a06',\n        '\\\\sqcap'                : '\\U00002293',\n        '\\\\Bigsqcap'             : '\\U00002a05',\n        '\\\\setminus'             : '\\U00002216',\n        '\\\\propto'               : '\\U0000221d',\n        '\\\\uplus'                : '\\U0000228e',\n        '\\\\bigplus'              : '\\U00002a04',\n        '\\\\sim'                  : '\\U0000223c',\n        '\\\\doteq'                : '\\U00002250',\n        '\\\\simeq'                : '\\U00002243',\n        '\\\\approx'               : '\\U00002248',\n        '\\\\asymp'                : '\\U0000224d',\n        '\\\\cong'                 : '\\U00002245',\n        '\\\\equiv'                : '\\U00002261',\n        '\\\\Join'                 : '\\U000022c8',\n        '\\\\bowtie'               : '\\U00002a1d',\n        '\\\\prec'                 : '\\U0000227a',\n        '\\\\succ'                 : '\\U0000227b',\n        '\\\\preceq'               : '\\U0000227c',\n        '\\\\succeq'               : '\\U0000227d',\n        '\\\\parallel'             : '\\U00002225',\n        '\\\\mid'                  : '\\U000000a6',\n        '\\\\pm'                   : '\\U000000b1',\n        '\\\\mp'                   : '\\U00002213',\n        '\\\\times'                : '\\U000000d7',\n        '\\\\div'                  : '\\U000000f7',\n        '\\\\cdot'                 : '\\U000022c5',\n        '\\\\star'                 : '\\U000022c6',\n        '\\\\circ'                 : '\\U00002218',\n        '\\\\dagger'               : '\\U00002020',\n        '\\\\ddagger'              : '\\U00002021',\n        '\\\\lhd'                  : '\\U000022b2',\n        '\\\\rhd'                  : '\\U000022b3',\n        '\\\\unlhd'                : '\\U000022b4',\n        '\\\\unrhd'                : '\\U000022b5',\n        '\\\\triangleleft'         : '\\U000025c3',\n        '\\\\triangleright'        : '\\U000025b9',\n        '\\\\triangle'             : '\\U000025b3',\n        '\\\\triangleq'            : '\\U0000225c',\n        '\\\\oplus'                : '\\U00002295',\n        '\\\\bigoplus'             : '\\U00002a01',\n        '\\\\otimes'               : '\\U00002297',\n        '\\\\bigotimes'            : '\\U00002a02',\n        '\\\\odot'                 : '\\U00002299',\n        '\\\\bigodot'              : '\\U00002a00',\n        '\\\\ominus'               : '\\U00002296',\n        '\\\\oslash'               : '\\U00002298',\n        '\\\\dots'                 : '\\U00002026',\n        '\\\\cdots'                : '\\U000022ef',\n        '\\\\sum'                  : '\\U00002211',\n        '\\\\prod'                 : '\\U0000220f',\n        '\\\\coprod'               : '\\U00002210',\n        '\\\\infty'                : '\\U0000221e',\n        '\\\\int'                  : '\\U0000222b',\n        '\\\\oint'                 : '\\U0000222e',\n        '\\\\clubsuit'             : '\\U00002663',\n        '\\\\diamondsuit'          : '\\U00002662',\n        '\\\\heartsuit'            : '\\U00002661',\n        '\\\\spadesuit'            : '\\U00002660',\n        '\\\\aleph'                : '\\U00002135',\n        '\\\\emptyset'             : '\\U00002205',\n        '\\\\nabla'                : '\\U00002207',\n        '\\\\partial'              : '\\U00002202',\n        '\\\\flat'                 : '\\U0000266d',\n        '\\\\natural'              : '\\U0000266e',\n        '\\\\sharp'                : '\\U0000266f',\n        '\\\\angle'                : '\\U00002220',\n        '\\\\copyright'            : '\\U000000a9',\n        '\\\\textregistered'       : '\\U000000ae',\n        '\\\\textonequarter'       : '\\U000000bc',\n        '\\\\textonehalf'          : '\\U000000bd',\n        '\\\\textthreequarters'    : '\\U000000be',\n        '\\\\textordfeminine'      : '\\U000000aa',\n        '\\\\textordmasculine'     : '\\U000000ba',\n        '\\\\euro'                 : '\\U000020ac',\n        '\\\\pounds'               : '\\U000000a3',\n        '\\\\yen'                  : '\\U000000a5',\n        '\\\\textcent'             : '\\U000000a2',\n        '\\\\textcurrency'         : '\\U000000a4',\n        '\\\\textdegree'           : '\\U000000b0',\n    }\n\n    isabelle_symbols = {\n        '\\\\<zero>'                 : '\\U0001d7ec',\n        '\\\\<one>'                  : '\\U0001d7ed',\n        '\\\\<two>'                  : '\\U0001d7ee',\n        '\\\\<three>'                : '\\U0001d7ef',\n        '\\\\<four>'                 : '\\U0001d7f0',\n        '\\\\<five>'                 : '\\U0001d7f1',\n        '\\\\<six>'                  : '\\U0001d7f2',\n        '\\\\<seven>'                : '\\U0001d7f3',\n        '\\\\<eight>'                : '\\U0001d7f4',\n        '\\\\<nine>'                 : '\\U0001d7f5',\n        '\\\\<A>'                    : '\\U0001d49c',\n        '\\\\<B>'                    : '\\U0000212c',\n        '\\\\<C>'                    : '\\U0001d49e',\n        '\\\\<D>'                    : '\\U0001d49f',\n        '\\\\<E>'                    : '\\U00002130',\n        '\\\\<F>'                    : '\\U00002131',\n        '\\\\<G>'                    : '\\U0001d4a2',\n        '\\\\<H>'                    : '\\U0000210b',\n        '\\\\<I>'                    : '\\U00002110',\n        '\\\\<J>'                    : '\\U0001d4a5',\n        '\\\\<K>'                    : '\\U0001d4a6',\n        '\\\\<L>'                    : '\\U00002112',\n        '\\\\<M>'                    : '\\U00002133',\n        '\\\\<N>'                    : '\\U0001d4a9',\n        '\\\\<O>'                    : '\\U0001d4aa',\n        '\\\\<P>'                    : '\\U0001d4ab',\n        '\\\\<Q>'                    : '\\U0001d4ac',\n        '\\\\<R>'                    : '\\U0000211b',\n        '\\\\<S>'                    : '\\U0001d4ae',\n        '\\\\<T>'                    : '\\U0001d4af',\n        '\\\\<U>'                    : '\\U0001d4b0',\n        '\\\\<V>'                    : '\\U0001d4b1',\n        '\\\\<W>'                    : '\\U0001d4b2',\n        '\\\\<X>'                    : '\\U0001d4b3',\n        '\\\\<Y>'                    : '\\U0001d4b4',\n        '\\\\<Z>'                    : '\\U0001d4b5',\n        '\\\\<a>'                    : '\\U0001d5ba',\n        '\\\\<b>'                    : '\\U0001d5bb',\n        '\\\\<c>'                    : '\\U0001d5bc',\n        '\\\\<d>'                    : '\\U0001d5bd',\n        '\\\\<e>'                    : '\\U0001d5be',\n        '\\\\<f>'                    : '\\U0001d5bf',\n        '\\\\<g>'                    : '\\U0001d5c0',\n        '\\\\<h>'                    : '\\U0001d5c1',\n        '\\\\<i>'                    : '\\U0001d5c2',\n        '\\\\<j>'                    : '\\U0001d5c3',\n        '\\\\<k>'                    : '\\U0001d5c4',\n        '\\\\<l>'                    : '\\U0001d5c5',\n        '\\\\<m>'                    : '\\U0001d5c6',\n        '\\\\<n>'                    : '\\U0001d5c7',\n        '\\\\<o>'                    : '\\U0001d5c8',\n        '\\\\<p>'                    : '\\U0001d5c9',\n        '\\\\<q>'                    : '\\U0001d5ca',\n        '\\\\<r>'                    : '\\U0001d5cb',\n        '\\\\<s>'                    : '\\U0001d5cc',\n        '\\\\<t>'                    : '\\U0001d5cd',\n        '\\\\<u>'                    : '\\U0001d5ce',\n        '\\\\<v>'                    : '\\U0001d5cf',\n        '\\\\<w>'                    : '\\U0001d5d0',\n        '\\\\<x>'                    : '\\U0001d5d1',\n        '\\\\<y>'                    : '\\U0001d5d2',\n        '\\\\<z>'                    : '\\U0001d5d3',\n        '\\\\<AA>'                   : '\\U0001d504',\n        '\\\\<BB>'                   : '\\U0001d505',\n        '\\\\<CC>'                   : '\\U0000212d',\n        '\\\\<DD>'                   : '\\U0001d507',\n        '\\\\<EE>'                   : '\\U0001d508',\n        '\\\\<FF>'                   : '\\U0001d509',\n        '\\\\<GG>'                   : '\\U0001d50a',\n        '\\\\<HH>'                   : '\\U0000210c',\n        '\\\\<II>'                   : '\\U00002111',\n        '\\\\<JJ>'                   : '\\U0001d50d',\n        '\\\\<KK>'                   : '\\U0001d50e',\n        '\\\\<LL>'                   : '\\U0001d50f',\n        '\\\\<MM>'                   : '\\U0001d510',\n        '\\\\<NN>'                   : '\\U0001d511',\n        '\\\\<OO>'                   : '\\U0001d512',\n        '\\\\<PP>'                   : '\\U0001d513',\n        '\\\\<QQ>'                   : '\\U0001d514',\n        '\\\\<RR>'                   : '\\U0000211c',\n        '\\\\<SS>'                   : '\\U0001d516',\n        '\\\\<TT>'                   : '\\U0001d517',\n        '\\\\<UU>'                   : '\\U0001d518',\n        '\\\\<VV>'                   : '\\U0001d519',\n        '\\\\<WW>'                   : '\\U0001d51a',\n        '\\\\<XX>'                   : '\\U0001d51b',\n        '\\\\<YY>'                   : '\\U0001d51c',\n        '\\\\<ZZ>'                   : '\\U00002128',\n        '\\\\<aa>'                   : '\\U0001d51e',\n        '\\\\<bb>'                   : '\\U0001d51f',\n        '\\\\<cc>'                   : '\\U0001d520',\n        '\\\\<dd>'                   : '\\U0001d521',\n        '\\\\<ee>'                   : '\\U0001d522',\n        '\\\\<ff>'                   : '\\U0001d523',\n        '\\\\<gg>'                   : '\\U0001d524',\n        '\\\\<hh>'                   : '\\U0001d525',\n        '\\\\<ii>'                   : '\\U0001d526',\n        '\\\\<jj>'                   : '\\U0001d527',\n        '\\\\<kk>'                   : '\\U0001d528',\n        '\\\\<ll>'                   : '\\U0001d529',\n        '\\\\<mm>'                   : '\\U0001d52a',\n        '\\\\<nn>'                   : '\\U0001d52b',\n        '\\\\<oo>'                   : '\\U0001d52c',\n        '\\\\<pp>'                   : '\\U0001d52d',\n        '\\\\<qq>'                   : '\\U0001d52e',\n        '\\\\<rr>'                   : '\\U0001d52f',\n        '\\\\<ss>'                   : '\\U0001d530',\n        '\\\\<tt>'                   : '\\U0001d531',\n        '\\\\<uu>'                   : '\\U0001d532',\n        '\\\\<vv>'                   : '\\U0001d533',\n        '\\\\<ww>'                   : '\\U0001d534',\n        '\\\\<xx>'                   : '\\U0001d535',\n        '\\\\<yy>'                   : '\\U0001d536',\n        '\\\\<zz>'                   : '\\U0001d537',\n        '\\\\<alpha>'                : '\\U000003b1',\n        '\\\\<beta>'                 : '\\U000003b2',\n        '\\\\<gamma>'                : '\\U000003b3',\n        '\\\\<delta>'                : '\\U000003b4',\n        '\\\\<epsilon>'              : '\\U000003b5',\n        '\\\\<zeta>'                 : '\\U000003b6',\n        '\\\\<eta>'                  : '\\U000003b7',\n        '\\\\<theta>'                : '\\U000003b8',\n        '\\\\<iota>'                 : '\\U000003b9',\n        '\\\\<kappa>'                : '\\U000003ba',\n        '\\\\<lambda>'               : '\\U000003bb',\n        '\\\\<mu>'                   : '\\U000003bc',\n        '\\\\<nu>'                   : '\\U000003bd',\n        '\\\\<xi>'                   : '\\U000003be',\n        '\\\\<pi>'                   : '\\U000003c0',\n        '\\\\<rho>'                  : '\\U000003c1',\n        '\\\\<sigma>'                : '\\U000003c3',\n        '\\\\<tau>'                  : '\\U000003c4',\n        '\\\\<upsilon>'              : '\\U000003c5',\n        '\\\\<phi>'                  : '\\U000003c6',\n        '\\\\<chi>'                  : '\\U000003c7',\n        '\\\\<psi>'                  : '\\U000003c8',\n        '\\\\<omega>'                : '\\U000003c9',\n        '\\\\<Gamma>'                : '\\U00000393',\n        '\\\\<Delta>'                : '\\U00000394',\n        '\\\\<Theta>'                : '\\U00000398',\n        '\\\\<Lambda>'               : '\\U0000039b',\n        '\\\\<Xi>'                   : '\\U0000039e',\n        '\\\\<Pi>'                   : '\\U000003a0',\n        '\\\\<Sigma>'                : '\\U000003a3',\n        '\\\\<Upsilon>'              : '\\U000003a5',\n        '\\\\<Phi>'                  : '\\U000003a6',\n        '\\\\<Psi>'                  : '\\U000003a8',\n        '\\\\<Omega>'                : '\\U000003a9',\n        '\\\\<bool>'                 : '\\U0001d539',\n        '\\\\<complex>'              : '\\U00002102',\n        '\\\\<nat>'                  : '\\U00002115',\n        '\\\\<rat>'                  : '\\U0000211a',\n        '\\\\<real>'                 : '\\U0000211d',\n        '\\\\<int>'                  : '\\U00002124',\n        '\\\\<leftarrow>'            : '\\U00002190',\n        '\\\\<longleftarrow>'        : '\\U000027f5',\n        '\\\\<rightarrow>'           : '\\U00002192',\n        '\\\\<longrightarrow>'       : '\\U000027f6',\n        '\\\\<Leftarrow>'            : '\\U000021d0',\n        '\\\\<Longleftarrow>'        : '\\U000027f8',\n        '\\\\<Rightarrow>'           : '\\U000021d2',\n        '\\\\<Longrightarrow>'       : '\\U000027f9',\n        '\\\\<leftrightarrow>'       : '\\U00002194',\n        '\\\\<longleftrightarrow>'   : '\\U000027f7',\n        '\\\\<Leftrightarrow>'       : '\\U000021d4',\n        '\\\\<Longleftrightarrow>'   : '\\U000027fa',\n        '\\\\<mapsto>'               : '\\U000021a6',\n        '\\\\<longmapsto>'           : '\\U000027fc',\n        '\\\\<midarrow>'             : '\\U00002500',\n        '\\\\<Midarrow>'             : '\\U00002550',\n        '\\\\<hookleftarrow>'        : '\\U000021a9',\n        '\\\\<hookrightarrow>'       : '\\U000021aa',\n        '\\\\<leftharpoondown>'      : '\\U000021bd',\n        '\\\\<rightharpoondown>'     : '\\U000021c1',\n        '\\\\<leftharpoonup>'        : '\\U000021bc',\n        '\\\\<rightharpoonup>'       : '\\U000021c0',\n        '\\\\<rightleftharpoons>'    : '\\U000021cc',\n        '\\\\<leadsto>'              : '\\U0000219d',\n        '\\\\<downharpoonleft>'      : '\\U000021c3',\n        '\\\\<downharpoonright>'     : '\\U000021c2',\n        '\\\\<upharpoonleft>'        : '\\U000021bf',\n        '\\\\<upharpoonright>'       : '\\U000021be',\n        '\\\\<restriction>'          : '\\U000021be',\n        '\\\\<Colon>'                : '\\U00002237',\n        '\\\\<up>'                   : '\\U00002191',\n        '\\\\<Up>'                   : '\\U000021d1',\n        '\\\\<down>'                 : '\\U00002193',\n        '\\\\<Down>'                 : '\\U000021d3',\n        '\\\\<updown>'               : '\\U00002195',\n        '\\\\<Updown>'               : '\\U000021d5',\n        '\\\\<langle>'               : '\\U000027e8',\n        '\\\\<rangle>'               : '\\U000027e9',\n        '\\\\<lceil>'                : '\\U00002308',\n        '\\\\<rceil>'                : '\\U00002309',\n        '\\\\<lfloor>'               : '\\U0000230a',\n        '\\\\<rfloor>'               : '\\U0000230b',\n        '\\\\<lparr>'                : '\\U00002987',\n        '\\\\<rparr>'                : '\\U00002988',\n        '\\\\<lbrakk>'               : '\\U000027e6',\n        '\\\\<rbrakk>'               : '\\U000027e7',\n        '\\\\<lbrace>'               : '\\U00002983',\n        '\\\\<rbrace>'               : '\\U00002984',\n        '\\\\<guillemotleft>'        : '\\U000000ab',\n        '\\\\<guillemotright>'       : '\\U000000bb',\n        '\\\\<bottom>'               : '\\U000022a5',\n        '\\\\<top>'                  : '\\U000022a4',\n        '\\\\<and>'                  : '\\U00002227',\n        '\\\\<And>'                  : '\\U000022c0',\n        '\\\\<or>'                   : '\\U00002228',\n        '\\\\<Or>'                   : '\\U000022c1',\n        '\\\\<forall>'               : '\\U00002200',\n        '\\\\<exists>'               : '\\U00002203',\n        '\\\\<nexists>'              : '\\U00002204',\n        '\\\\<not>'                  : '\\U000000ac',\n        '\\\\<box>'                  : '\\U000025a1',\n        '\\\\<diamond>'              : '\\U000025c7',\n        '\\\\<turnstile>'            : '\\U000022a2',\n        '\\\\<Turnstile>'            : '\\U000022a8',\n        '\\\\<tturnstile>'           : '\\U000022a9',\n        '\\\\<TTurnstile>'           : '\\U000022ab',\n        '\\\\<stileturn>'            : '\\U000022a3',\n        '\\\\<surd>'                 : '\\U0000221a',\n        '\\\\<le>'                   : '\\U00002264',\n        '\\\\<ge>'                   : '\\U00002265',\n        '\\\\<lless>'                : '\\U0000226a',\n        '\\\\<ggreater>'             : '\\U0000226b',\n        '\\\\<lesssim>'              : '\\U00002272',\n        '\\\\<greatersim>'           : '\\U00002273',\n        '\\\\<lessapprox>'           : '\\U00002a85',\n        '\\\\<greaterapprox>'        : '\\U00002a86',\n        '\\\\<in>'                   : '\\U00002208',\n        '\\\\<notin>'                : '\\U00002209',\n        '\\\\<subset>'               : '\\U00002282',\n        '\\\\<supset>'               : '\\U00002283',\n        '\\\\<subseteq>'             : '\\U00002286',\n        '\\\\<supseteq>'             : '\\U00002287',\n        '\\\\<sqsubset>'             : '\\U0000228f',\n        '\\\\<sqsupset>'             : '\\U00002290',\n        '\\\\<sqsubseteq>'           : '\\U00002291',\n        '\\\\<sqsupseteq>'           : '\\U00002292',\n        '\\\\<inter>'                : '\\U00002229',\n        '\\\\<Inter>'                : '\\U000022c2',\n        '\\\\<union>'                : '\\U0000222a',\n        '\\\\<Union>'                : '\\U000022c3',\n        '\\\\<squnion>'              : '\\U00002294',\n        '\\\\<Squnion>'              : '\\U00002a06',\n        '\\\\<sqinter>'              : '\\U00002293',\n        '\\\\<Sqinter>'              : '\\U00002a05',\n        '\\\\<setminus>'             : '\\U00002216',\n        '\\\\<propto>'               : '\\U0000221d',\n        '\\\\<uplus>'                : '\\U0000228e',\n        '\\\\<Uplus>'                : '\\U00002a04',\n        '\\\\<noteq>'                : '\\U00002260',\n        '\\\\<sim>'                  : '\\U0000223c',\n        '\\\\<doteq>'                : '\\U00002250',\n        '\\\\<simeq>'                : '\\U00002243',\n        '\\\\<approx>'               : '\\U00002248',\n        '\\\\<asymp>'                : '\\U0000224d',\n        '\\\\<cong>'                 : '\\U00002245',\n        '\\\\<smile>'                : '\\U00002323',\n        '\\\\<equiv>'                : '\\U00002261',\n        '\\\\<frown>'                : '\\U00002322',\n        '\\\\<Join>'                 : '\\U000022c8',\n        '\\\\<bowtie>'               : '\\U00002a1d',\n        '\\\\<prec>'                 : '\\U0000227a',\n        '\\\\<succ>'                 : '\\U0000227b',\n        '\\\\<preceq>'               : '\\U0000227c',\n        '\\\\<succeq>'               : '\\U0000227d',\n        '\\\\<parallel>'             : '\\U00002225',\n        '\\\\<bar>'                  : '\\U000000a6',\n        '\\\\<plusminus>'            : '\\U000000b1',\n        '\\\\<minusplus>'            : '\\U00002213',\n        '\\\\<times>'                : '\\U000000d7',\n        '\\\\<div>'                  : '\\U000000f7',\n        '\\\\<cdot>'                 : '\\U000022c5',\n        '\\\\<star>'                 : '\\U000022c6',\n        '\\\\<bullet>'               : '\\U00002219',\n        '\\\\<circ>'                 : '\\U00002218',\n        '\\\\<dagger>'               : '\\U00002020',\n        '\\\\<ddagger>'              : '\\U00002021',\n        '\\\\<lhd>'                  : '\\U000022b2',\n        '\\\\<rhd>'                  : '\\U000022b3',\n        '\\\\<unlhd>'                : '\\U000022b4',\n        '\\\\<unrhd>'                : '\\U000022b5',\n        '\\\\<triangleleft>'         : '\\U000025c3',\n        '\\\\<triangleright>'        : '\\U000025b9',\n        '\\\\<triangle>'             : '\\U000025b3',\n        '\\\\<triangleq>'            : '\\U0000225c',\n        '\\\\<oplus>'                : '\\U00002295',\n        '\\\\<Oplus>'                : '\\U00002a01',\n        '\\\\<otimes>'               : '\\U00002297',\n        '\\\\<Otimes>'               : '\\U00002a02',\n        '\\\\<odot>'                 : '\\U00002299',\n        '\\\\<Odot>'                 : '\\U00002a00',\n        '\\\\<ominus>'               : '\\U00002296',\n        '\\\\<oslash>'               : '\\U00002298',\n        '\\\\<dots>'                 : '\\U00002026',\n        '\\\\<cdots>'                : '\\U000022ef',\n        '\\\\<Sum>'                  : '\\U00002211',\n        '\\\\<Prod>'                 : '\\U0000220f',\n        '\\\\<Coprod>'               : '\\U00002210',\n        '\\\\<infinity>'             : '\\U0000221e',\n        '\\\\<integral>'             : '\\U0000222b',\n        '\\\\<ointegral>'            : '\\U0000222e',\n        '\\\\<clubsuit>'             : '\\U00002663',\n        '\\\\<diamondsuit>'          : '\\U00002662',\n        '\\\\<heartsuit>'            : '\\U00002661',\n        '\\\\<spadesuit>'            : '\\U00002660',\n        '\\\\<aleph>'                : '\\U00002135',\n        '\\\\<emptyset>'             : '\\U00002205',\n        '\\\\<nabla>'                : '\\U00002207',\n        '\\\\<partial>'              : '\\U00002202',\n        '\\\\<flat>'                 : '\\U0000266d',\n        '\\\\<natural>'              : '\\U0000266e',\n        '\\\\<sharp>'                : '\\U0000266f',\n        '\\\\<angle>'                : '\\U00002220',\n        '\\\\<copyright>'            : '\\U000000a9',\n        '\\\\<registered>'           : '\\U000000ae',\n        '\\\\<hyphen>'               : '\\U000000ad',\n        '\\\\<inverse>'              : '\\U000000af',\n        '\\\\<onequarter>'           : '\\U000000bc',\n        '\\\\<onehalf>'              : '\\U000000bd',\n        '\\\\<threequarters>'        : '\\U000000be',\n        '\\\\<ordfeminine>'          : '\\U000000aa',\n        '\\\\<ordmasculine>'         : '\\U000000ba',\n        '\\\\<section>'              : '\\U000000a7',\n        '\\\\<paragraph>'            : '\\U000000b6',\n        '\\\\<exclamdown>'           : '\\U000000a1',\n        '\\\\<questiondown>'         : '\\U000000bf',\n        '\\\\<euro>'                 : '\\U000020ac',\n        '\\\\<pounds>'               : '\\U000000a3',\n        '\\\\<yen>'                  : '\\U000000a5',\n        '\\\\<cent>'                 : '\\U000000a2',\n        '\\\\<currency>'             : '\\U000000a4',\n        '\\\\<degree>'               : '\\U000000b0',\n        '\\\\<amalg>'                : '\\U00002a3f',\n        '\\\\<mho>'                  : '\\U00002127',\n        '\\\\<lozenge>'              : '\\U000025ca',\n        '\\\\<wp>'                   : '\\U00002118',\n        '\\\\<wrong>'                : '\\U00002240',\n        '\\\\<struct>'               : '\\U000022c4',\n        '\\\\<acute>'                : '\\U000000b4',\n        '\\\\<index>'                : '\\U00000131',\n        '\\\\<dieresis>'             : '\\U000000a8',\n        '\\\\<cedilla>'              : '\\U000000b8',\n        '\\\\<hungarumlaut>'         : '\\U000002dd',\n        '\\\\<some>'                 : '\\U000003f5',\n        '\\\\<newline>'              : '\\U000023ce',\n        '\\\\<open>'                 : '\\U00002039',\n        '\\\\<close>'                : '\\U0000203a',\n        '\\\\<here>'                 : '\\U00002302',\n        '\\\\<^sub>'                 : '\\U000021e9',\n        '\\\\<^sup>'                 : '\\U000021e7',\n        '\\\\<^bold>'                : '\\U00002759',\n        '\\\\<^bsub>'                : '\\U000021d8',\n        '\\\\<^esub>'                : '\\U000021d9',\n        '\\\\<^bsup>'                : '\\U000021d7',\n        '\\\\<^esup>'                : '\\U000021d6',\n    }\n\n    lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols}\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        lang = get_choice_opt(options, 'lang',\n                              ['isabelle', 'latex'], 'isabelle')\n        self.symbols = self.lang_map[lang]\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if value in self.symbols:\n                yield ttype, self.symbols[value]\n            else:\n                yield ttype, value\n\n\nclass KeywordCaseFilter(Filter):\n    \"\"\"Convert keywords to lowercase or uppercase or capitalize them, which\n    means first letter uppercase, rest lowercase.\n\n    This can be useful e.g. if you highlight Pascal code and want to adapt the\n    code to your styleguide.\n\n    Options accepted:\n\n    `case` : string\n       The casing to convert keywords to. Must be one of ``'lower'``,\n       ``'upper'`` or ``'capitalize'``.  The default is ``'lower'``.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        case = get_choice_opt(options, 'case',\n                              ['lower', 'upper', 'capitalize'], 'lower')\n        self.convert = getattr(str, case)\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype in Keyword:\n                yield ttype, self.convert(value)\n            else:\n                yield ttype, value\n\n\nclass NameHighlightFilter(Filter):\n    \"\"\"Highlight a normal Name (and Name.*) token with a different token type.\n\n    Example::\n\n        filter = NameHighlightFilter(\n            names=['foo', 'bar', 'baz'],\n            tokentype=Name.Function,\n        )\n\n    This would highlight the names \"foo\", \"bar\" and \"baz\"\n    as functions. `Name.Function` is the default token type.\n\n    Options accepted:\n\n    `names` : list of strings\n      A list of names that should be given the different token type.\n      There is no default.\n    `tokentype` : TokenType or string\n      A token type or a string containing a token type name that is\n      used for highlighting the strings in `names`.  The default is\n      `Name.Function`.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.names = set(get_list_opt(options, 'names', []))\n        tokentype = options.get('tokentype')\n        if tokentype:\n            self.tokentype = string_to_tokentype(tokentype)\n        else:\n            self.tokentype = Name.Function\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype in Name and value in self.names:\n                yield self.tokentype, value\n            else:\n                yield ttype, value\n\n\nclass ErrorToken(Exception):\n    pass\n\n\nclass RaiseOnErrorTokenFilter(Filter):\n    \"\"\"Raise an exception when the lexer generates an error token.\n\n    Options accepted:\n\n    `excclass` : Exception class\n      The exception class to raise.\n      The default is `pygments.filters.ErrorToken`.\n\n    .. versionadded:: 0.8\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.exception = options.get('excclass', ErrorToken)\n        try:\n            # issubclass() will raise TypeError if first argument is not a class\n            if not issubclass(self.exception, Exception):\n                raise TypeError\n        except TypeError:\n            raise OptionError('excclass option is not an exception class')\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype is Error:\n                raise self.exception(value)\n            yield ttype, value\n\n\nclass VisibleWhitespaceFilter(Filter):\n    \"\"\"Convert tabs, newlines and/or spaces to visible characters.\n\n    Options accepted:\n\n    `spaces` : string or bool\n      If this is a one-character string, spaces will be replaces by this string.\n      If it is another true value, spaces will be replaced by ``·`` (unicode\n      MIDDLE DOT).  If it is a false value, spaces will not be replaced.  The\n      default is ``False``.\n    `tabs` : string or bool\n      The same as for `spaces`, but the default replacement character is ``»``\n      (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK).  The default value\n      is ``False``.  Note: this will not work if the `tabsize` option for the\n      lexer is nonzero, as tabs will already have been expanded then.\n    `tabsize` : int\n      If tabs are to be replaced by this filter (see the `tabs` option), this\n      is the total number of characters that a tab should be expanded to.\n      The default is ``8``.\n    `newlines` : string or bool\n      The same as for `spaces`, but the default replacement character is ``¶``\n      (unicode PILCROW SIGN).  The default value is ``False``.\n    `wstokentype` : bool\n      If true, give whitespace the special `Whitespace` token type.  This allows\n      styling the visible whitespace differently (e.g. greyed out), but it can\n      disrupt background colors.  The default is ``True``.\n\n    .. versionadded:: 0.8\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        for name, default in [('spaces',   '·'),\n                              ('tabs',     '»'),\n                              ('newlines', '¶')]:\n            opt = options.get(name, False)\n            if isinstance(opt, str) and len(opt) == 1:\n                setattr(self, name, opt)\n            else:\n                setattr(self, name, (opt and default or ''))\n        tabsize = get_int_opt(options, 'tabsize', 8)\n        if self.tabs:\n            self.tabs += ' ' * (tabsize - 1)\n        if self.newlines:\n            self.newlines += '\\n'\n        self.wstt = get_bool_opt(options, 'wstokentype', True)\n\n    def filter(self, lexer, stream):\n        if self.wstt:\n            spaces = self.spaces or ' '\n            tabs = self.tabs or '\\t'\n            newlines = self.newlines or '\\n'\n            regex = re.compile(r'\\s')\n\n            def replacefunc(wschar):\n                if wschar == ' ':\n                    return spaces\n                elif wschar == '\\t':\n                    return tabs\n                elif wschar == '\\n':\n                    return newlines\n                return wschar\n\n            for ttype, value in stream:\n                yield from _replace_special(ttype, value, regex, Whitespace,\n                                            replacefunc)\n        else:\n            spaces, tabs, newlines = self.spaces, self.tabs, self.newlines\n            # simpler processing\n            for ttype, value in stream:\n                if spaces:\n                    value = value.replace(' ', spaces)\n                if tabs:\n                    value = value.replace('\\t', tabs)\n                if newlines:\n                    value = value.replace('\\n', newlines)\n                yield ttype, value\n\n\nclass GobbleFilter(Filter):\n    \"\"\"Gobbles source code lines (eats initial characters).\n\n    This filter drops the first ``n`` characters off every line of code.  This\n    may be useful when the source code fed to the lexer is indented by a fixed\n    amount of space that isn't desired in the output.\n\n    Options accepted:\n\n    `n` : int\n       The number of characters to gobble.\n\n    .. versionadded:: 1.2\n    \"\"\"\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.n = get_int_opt(options, 'n', 0)\n\n    def gobble(self, value, left):\n        if left < len(value):\n            return value[left:], 0\n        else:\n            return '', left - len(value)\n\n    def filter(self, lexer, stream):\n        n = self.n\n        left = n  # How many characters left to gobble.\n        for ttype, value in stream:\n            # Remove ``left`` tokens from first line, ``n`` from all others.\n            parts = value.split('\\n')\n            (parts[0], left) = self.gobble(parts[0], left)\n            for i in range(1, len(parts)):\n                (parts[i], left) = self.gobble(parts[i], n)\n            value = '\\n'.join(parts)\n\n            if value != '':\n                yield ttype, value\n\n\nclass TokenMergeFilter(Filter):\n    \"\"\"Merges consecutive tokens with the same token type in the output\n    stream of a lexer.\n\n    .. versionadded:: 1.2\n    \"\"\"\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n\n    def filter(self, lexer, stream):\n        current_type = None\n        current_value = None\n        for ttype, value in stream:\n            if ttype is current_type:\n                current_value += value\n            else:\n                if current_type is not None:\n                    yield current_type, current_value\n                current_type = ttype\n                current_value = value\n        if current_type is not None:\n            yield current_type, current_value\n\n\nFILTERS = {\n    'codetagify':     CodeTagFilter,\n    'keywordcase':    KeywordCaseFilter,\n    'highlight':      NameHighlightFilter,\n    'raiseonerror':   RaiseOnErrorTokenFilter,\n    'whitespace':     VisibleWhitespaceFilter,\n    'gobble':         GobbleFilter,\n    'tokenmerge':     TokenMergeFilter,\n    'symbols':        SymbolFilter,\n}\n"
  },
  {
    "path": "src/pip/_vendor/pygments/formatter.py",
    "content": "\"\"\"\n    pygments.formatter\n    ~~~~~~~~~~~~~~~~~~\n\n    Base formatter class.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport codecs\n\nfrom pip._vendor.pygments.util import get_bool_opt\nfrom pip._vendor.pygments.styles import get_style_by_name\n\n__all__ = ['Formatter']\n\n\ndef _lookup_style(style):\n    if isinstance(style, str):\n        return get_style_by_name(style)\n    return style\n\n\nclass Formatter:\n    \"\"\"\n    Converts a token stream to text.\n\n    Formatters should have attributes to help selecting them. These\n    are similar to the corresponding :class:`~pygments.lexer.Lexer`\n    attributes.\n\n    .. autoattribute:: name\n       :no-value:\n\n    .. autoattribute:: aliases\n       :no-value:\n\n    .. autoattribute:: filenames\n       :no-value:\n\n    You can pass options as keyword arguments to the constructor.\n    All formatters accept these basic options:\n\n    ``style``\n        The style to use, can be a string or a Style subclass\n        (default: \"default\"). Not used by e.g. the\n        TerminalFormatter.\n    ``full``\n        Tells the formatter to output a \"full\" document, i.e.\n        a complete self-contained document. This doesn't have\n        any effect for some formatters (default: false).\n    ``title``\n        If ``full`` is true, the title that should be used to\n        caption the document (default: '').\n    ``encoding``\n        If given, must be an encoding name. This will be used to\n        convert the Unicode token strings to byte strings in the\n        output. If it is \"\" or None, Unicode strings will be written\n        to the output file, which most file-like objects do not\n        support (default: None).\n    ``outencoding``\n        Overrides ``encoding`` if given.\n\n    \"\"\"\n\n    #: Full name for the formatter, in human-readable form.\n    name = None\n\n    #: A list of short, unique identifiers that can be used to lookup\n    #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`.\n    aliases = []\n\n    #: A list of fnmatch patterns that match filenames for which this\n    #: formatter can produce output. The patterns in this list should be unique\n    #: among all formatters.\n    filenames = []\n\n    #: If True, this formatter outputs Unicode strings when no encoding\n    #: option is given.\n    unicodeoutput = True\n\n    def __init__(self, **options):\n        \"\"\"\n        As with lexers, this constructor takes arbitrary optional arguments,\n        and if you override it, you should first process your own options, then\n        call the base class implementation.\n        \"\"\"\n        self.style = _lookup_style(options.get('style', 'default'))\n        self.full = get_bool_opt(options, 'full', False)\n        self.title = options.get('title', '')\n        self.encoding = options.get('encoding', None) or None\n        if self.encoding in ('guess', 'chardet'):\n            # can happen for e.g. pygmentize -O encoding=guess\n            self.encoding = 'utf-8'\n        self.encoding = options.get('outencoding') or self.encoding\n        self.options = options\n\n    def get_style_defs(self, arg=''):\n        \"\"\"\n        This method must return statements or declarations suitable to define\n        the current style for subsequent highlighted text (e.g. CSS classes\n        in the `HTMLFormatter`).\n\n        The optional argument `arg` can be used to modify the generation and\n        is formatter dependent (it is standardized because it can be given on\n        the command line).\n\n        This method is called by the ``-S`` :doc:`command-line option <cmdline>`,\n        the `arg` is then given by the ``-a`` option.\n        \"\"\"\n        return ''\n\n    def format(self, tokensource, outfile):\n        \"\"\"\n        This method must format the tokens from the `tokensource` iterable and\n        write the formatted version to the file object `outfile`.\n\n        Formatter options can control how exactly the tokens are converted.\n        \"\"\"\n        if self.encoding:\n            # wrap the outfile in a StreamWriter\n            outfile = codecs.lookup(self.encoding)[3](outfile)\n        return self.format_unencoded(tokensource, outfile)\n\n    # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to\n    # Formatter. This helps when using third-party type stubs from typeshed.\n    def __class_getitem__(cls, name):\n        return cls\n"
  },
  {
    "path": "src/pip/_vendor/pygments/formatters/__init__.py",
    "content": "\"\"\"\n    pygments.formatters\n    ~~~~~~~~~~~~~~~~~~~\n\n    Pygments formatters.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport types\nimport fnmatch\nfrom os.path import basename\n\nfrom pip._vendor.pygments.formatters._mapping import FORMATTERS\nfrom pip._vendor.pygments.plugin import find_plugin_formatters\nfrom pip._vendor.pygments.util import ClassNotFound\n\n__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',\n           'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)\n\n_formatter_cache = {}  # classes by name\n_pattern_cache = {}\n\n\ndef _fn_matches(fn, glob):\n    \"\"\"Return whether the supplied file name fn matches pattern filename.\"\"\"\n    if glob not in _pattern_cache:\n        pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))\n        return pattern.match(fn)\n    return _pattern_cache[glob].match(fn)\n\n\ndef _load_formatters(module_name):\n    \"\"\"Load a formatter (and all others in the module too).\"\"\"\n    mod = __import__(module_name, None, None, ['__all__'])\n    for formatter_name in mod.__all__:\n        cls = getattr(mod, formatter_name)\n        _formatter_cache[cls.name] = cls\n\n\ndef get_all_formatters():\n    \"\"\"Return a generator for all formatter classes.\"\"\"\n    # NB: this returns formatter classes, not info like get_all_lexers().\n    for info in FORMATTERS.values():\n        if info[1] not in _formatter_cache:\n            _load_formatters(info[0])\n        yield _formatter_cache[info[1]]\n    for _, formatter in find_plugin_formatters():\n        yield formatter\n\n\ndef find_formatter_class(alias):\n    \"\"\"Lookup a formatter by alias.\n\n    Returns None if not found.\n    \"\"\"\n    for module_name, name, aliases, _, _ in FORMATTERS.values():\n        if alias in aliases:\n            if name not in _formatter_cache:\n                _load_formatters(module_name)\n            return _formatter_cache[name]\n    for _, cls in find_plugin_formatters():\n        if alias in cls.aliases:\n            return cls\n\n\ndef get_formatter_by_name(_alias, **options):\n    \"\"\"\n    Return an instance of a :class:`.Formatter` subclass that has `alias` in its\n    aliases list. The formatter is given the `options` at its instantiation.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that\n    alias is found.\n    \"\"\"\n    cls = find_formatter_class(_alias)\n    if cls is None:\n        raise ClassNotFound(f\"no formatter found for name {_alias!r}\")\n    return cls(**options)\n\n\ndef load_formatter_from_file(filename, formattername=\"CustomFormatter\", **options):\n    \"\"\"\n    Return a `Formatter` subclass instance loaded from the provided file, relative\n    to the current directory.\n\n    The file is expected to contain a Formatter class named ``formattername``\n    (by default, CustomFormatter). Users should be very careful with the input, because\n    this method is equivalent to running ``eval()`` on the input file. The formatter is\n    given the `options` at its instantiation.\n\n    :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading\n    the formatter.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    try:\n        # This empty dict will contain the namespace for the exec'd file\n        custom_namespace = {}\n        with open(filename, 'rb') as f:\n            exec(f.read(), custom_namespace)\n        # Retrieve the class `formattername` from that namespace\n        if formattername not in custom_namespace:\n            raise ClassNotFound(f'no valid {formattername} class found in {filename}')\n        formatter_class = custom_namespace[formattername]\n        # And finally instantiate it with the options\n        return formatter_class(**options)\n    except OSError as err:\n        raise ClassNotFound(f'cannot read {filename}: {err}')\n    except ClassNotFound:\n        raise\n    except Exception as err:\n        raise ClassNotFound(f'error when loading custom formatter: {err}')\n\n\ndef get_formatter_for_filename(fn, **options):\n    \"\"\"\n    Return a :class:`.Formatter` subclass instance that has a filename pattern\n    matching `fn`. The formatter is given the `options` at its instantiation.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename\n    is found.\n    \"\"\"\n    fn = basename(fn)\n    for modname, name, _, filenames, _ in FORMATTERS.values():\n        for filename in filenames:\n            if _fn_matches(fn, filename):\n                if name not in _formatter_cache:\n                    _load_formatters(modname)\n                return _formatter_cache[name](**options)\n    for _name, cls in find_plugin_formatters():\n        for filename in cls.filenames:\n            if _fn_matches(fn, filename):\n                return cls(**options)\n    raise ClassNotFound(f\"no formatter found for file name {fn!r}\")\n\n\nclass _automodule(types.ModuleType):\n    \"\"\"Automatically import formatters.\"\"\"\n\n    def __getattr__(self, name):\n        info = FORMATTERS.get(name)\n        if info:\n            _load_formatters(info[0])\n            cls = _formatter_cache[info[1]]\n            setattr(self, name, cls)\n            return cls\n        raise AttributeError(name)\n\n\noldmod = sys.modules[__name__]\nnewmod = _automodule(__name__)\nnewmod.__dict__.update(oldmod.__dict__)\nsys.modules[__name__] = newmod\ndel newmod.newmod, newmod.oldmod, newmod.sys, newmod.types\n"
  },
  {
    "path": "src/pip/_vendor/pygments/formatters/_mapping.py",
    "content": "# Automatically generated by scripts/gen_mapfiles.py.\n# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.\n\nFORMATTERS = {\n    'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'),\n    'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),\n    'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), \"Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option). The ``<div>``'s CSS class can be set by the `cssclass` option.\"),\n    'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),\n    'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),\n    'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),\n    'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),\n    'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),\n    'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'),\n    'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file.  This formatter is still experimental. Each line of code is a ``<text>`` element with explicit ``x`` and ``y`` coordinates containing ``<tspan>`` elements with the individual token styles.'),\n    'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console.  Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console.  Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'),\n}\n"
  },
  {
    "path": "src/pip/_vendor/pygments/lexer.py",
    "content": "\"\"\"\n    pygments.lexer\n    ~~~~~~~~~~~~~~\n\n    Base lexer classes.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport time\n\nfrom pip._vendor.pygments.filter import apply_filters, Filter\nfrom pip._vendor.pygments.filters import get_filter_by_name\nfrom pip._vendor.pygments.token import Error, Text, Other, Whitespace, _TokenType\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \\\n    make_analysator, Future, guess_decode\nfrom pip._vendor.pygments.regexopt import regex_opt\n\n__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer',\n           'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this',\n           'default', 'words', 'line_re']\n\nline_re = re.compile('.*?\\n')\n\n_encoding_map = [(b'\\xef\\xbb\\xbf', 'utf-8'),\n                 (b'\\xff\\xfe\\0\\0', 'utf-32'),\n                 (b'\\0\\0\\xfe\\xff', 'utf-32be'),\n                 (b'\\xff\\xfe', 'utf-16'),\n                 (b'\\xfe\\xff', 'utf-16be')]\n\n_default_analyse = staticmethod(lambda x: 0.0)\n\n\nclass LexerMeta(type):\n    \"\"\"\n    This metaclass automagically converts ``analyse_text`` methods into\n    static methods which always return float values.\n    \"\"\"\n\n    def __new__(mcs, name, bases, d):\n        if 'analyse_text' in d:\n            d['analyse_text'] = make_analysator(d['analyse_text'])\n        return type.__new__(mcs, name, bases, d)\n\n\nclass Lexer(metaclass=LexerMeta):\n    \"\"\"\n    Lexer for a specific language.\n\n    See also :doc:`lexerdevelopment`, a high-level guide to writing\n    lexers.\n\n    Lexer classes have attributes used for choosing the most appropriate\n    lexer based on various criteria.\n\n    .. autoattribute:: name\n       :no-value:\n    .. autoattribute:: aliases\n       :no-value:\n    .. autoattribute:: filenames\n       :no-value:\n    .. autoattribute:: alias_filenames\n    .. autoattribute:: mimetypes\n       :no-value:\n    .. autoattribute:: priority\n\n    Lexers included in Pygments should have two additional attributes:\n\n    .. autoattribute:: url\n       :no-value:\n    .. autoattribute:: version_added\n       :no-value:\n\n    Lexers included in Pygments may have additional attributes:\n\n    .. autoattribute:: _example\n       :no-value:\n\n    You can pass options to the constructor. The basic options recognized\n    by all lexers and processed by the base `Lexer` class are:\n\n    ``stripnl``\n        Strip leading and trailing newlines from the input (default: True).\n    ``stripall``\n        Strip all leading and trailing whitespace from the input\n        (default: False).\n    ``ensurenl``\n        Make sure that the input ends with a newline (default: True).  This\n        is required for some lexers that consume input linewise.\n\n        .. versionadded:: 1.3\n\n    ``tabsize``\n        If given and greater than 0, expand tabs in the input (default: 0).\n    ``encoding``\n        If given, must be an encoding name. This encoding will be used to\n        convert the input string to Unicode, if it is not already a Unicode\n        string (default: ``'guess'``, which uses a simple UTF-8 / Locale /\n        Latin1 detection.  Can also be ``'chardet'`` to use the chardet\n        library, if it is installed.\n    ``inencoding``\n        Overrides the ``encoding`` if given.\n    \"\"\"\n\n    #: Full name of the lexer, in human-readable form\n    name = None\n\n    #: A list of short, unique identifiers that can be used to look\n    #: up the lexer from a list, e.g., using `get_lexer_by_name()`.\n    aliases = []\n\n    #: A list of `fnmatch` patterns that match filenames which contain\n    #: content for this lexer. The patterns in this list should be unique among\n    #: all lexers.\n    filenames = []\n\n    #: A list of `fnmatch` patterns that match filenames which may or may not\n    #: contain content for this lexer. This list is used by the\n    #: :func:`.guess_lexer_for_filename()` function, to determine which lexers\n    #: are then included in guessing the correct one. That means that\n    #: e.g. every lexer for HTML and a template language should include\n    #: ``\\*.html`` in this list.\n    alias_filenames = []\n\n    #: A list of MIME types for content that can be lexed with this lexer.\n    mimetypes = []\n\n    #: Priority, should multiple lexers match and no content is provided\n    priority = 0\n\n    #: URL of the language specification/definition. Used in the Pygments\n    #: documentation. Set to an empty string to disable.\n    url = None\n\n    #: Version of Pygments in which the lexer was added.\n    version_added = None\n\n    #: Example file name. Relative to the ``tests/examplefiles`` directory.\n    #: This is used by the documentation generator to show an example.\n    _example = None\n\n    def __init__(self, **options):\n        \"\"\"\n        This constructor takes arbitrary options as keyword arguments.\n        Every subclass must first process its own options and then call\n        the `Lexer` constructor, since it processes the basic\n        options like `stripnl`.\n\n        An example looks like this:\n\n        .. sourcecode:: python\n\n           def __init__(self, **options):\n               self.compress = options.get('compress', '')\n               Lexer.__init__(self, **options)\n\n        As these options must all be specifiable as strings (due to the\n        command line usage), there are various utility functions\n        available to help with that, see `Utilities`_.\n        \"\"\"\n        self.options = options\n        self.stripnl = get_bool_opt(options, 'stripnl', True)\n        self.stripall = get_bool_opt(options, 'stripall', False)\n        self.ensurenl = get_bool_opt(options, 'ensurenl', True)\n        self.tabsize = get_int_opt(options, 'tabsize', 0)\n        self.encoding = options.get('encoding', 'guess')\n        self.encoding = options.get('inencoding') or self.encoding\n        self.filters = []\n        for filter_ in get_list_opt(options, 'filters', ()):\n            self.add_filter(filter_)\n\n    def __repr__(self):\n        if self.options:\n            return f'<pygments.lexers.{self.__class__.__name__} with {self.options!r}>'\n        else:\n            return f'<pygments.lexers.{self.__class__.__name__}>'\n\n    def add_filter(self, filter_, **options):\n        \"\"\"\n        Add a new stream filter to this lexer.\n        \"\"\"\n        if not isinstance(filter_, Filter):\n            filter_ = get_filter_by_name(filter_, **options)\n        self.filters.append(filter_)\n\n    def analyse_text(text):\n        \"\"\"\n        A static method which is called for lexer guessing.\n\n        It should analyse the text and return a float in the range\n        from ``0.0`` to ``1.0``.  If it returns ``0.0``, the lexer\n        will not be selected as the most probable one, if it returns\n        ``1.0``, it will be selected immediately.  This is used by\n        `guess_lexer`.\n\n        The `LexerMeta` metaclass automatically wraps this function so\n        that it works like a static method (no ``self`` or ``cls``\n        parameter) and the return value is automatically converted to\n        `float`. If the return value is an object that is boolean `False`\n        it's the same as if the return values was ``0.0``.\n        \"\"\"\n\n    def _preprocess_lexer_input(self, text):\n        \"\"\"Apply preprocessing such as decoding the input, removing BOM and normalizing newlines.\"\"\"\n\n        if not isinstance(text, str):\n            if self.encoding == 'guess':\n                text, _ = guess_decode(text)\n            elif self.encoding == 'chardet':\n                try:\n                    # pip vendoring note: this code is not reachable by pip,\n                    # removed import of chardet to make it clear.\n                    raise ImportError('chardet is not vendored by pip')\n                except ImportError as e:\n                    raise ImportError('To enable chardet encoding guessing, '\n                                      'please install the chardet library '\n                                      'from http://chardet.feedparser.org/') from e\n                # check for BOM first\n                decoded = None\n                for bom, encoding in _encoding_map:\n                    if text.startswith(bom):\n                        decoded = text[len(bom):].decode(encoding, 'replace')\n                        break\n                # no BOM found, so use chardet\n                if decoded is None:\n                    enc = chardet.detect(text[:1024])  # Guess using first 1KB\n                    decoded = text.decode(enc.get('encoding') or 'utf-8',\n                                          'replace')\n                text = decoded\n            else:\n                text = text.decode(self.encoding)\n                if text.startswith('\\ufeff'):\n                    text = text[len('\\ufeff'):]\n        else:\n            if text.startswith('\\ufeff'):\n                text = text[len('\\ufeff'):]\n\n        # text now *is* a unicode string\n        text = text.replace('\\r\\n', '\\n')\n        text = text.replace('\\r', '\\n')\n        if self.stripall:\n            text = text.strip()\n        elif self.stripnl:\n            text = text.strip('\\n')\n        if self.tabsize > 0:\n            text = text.expandtabs(self.tabsize)\n        if self.ensurenl and not text.endswith('\\n'):\n            text += '\\n'\n\n        return text\n\n    def get_tokens(self, text, unfiltered=False):\n        \"\"\"\n        This method is the basic interface of a lexer. It is called by\n        the `highlight()` function. It must process the text and return an\n        iterable of ``(tokentype, value)`` pairs from `text`.\n\n        Normally, you don't need to override this method. The default\n        implementation processes the options recognized by all lexers\n        (`stripnl`, `stripall` and so on), and then yields all tokens\n        from `get_tokens_unprocessed()`, with the ``index`` dropped.\n\n        If `unfiltered` is set to `True`, the filtering mechanism is\n        bypassed even if filters are defined.\n        \"\"\"\n        text = self._preprocess_lexer_input(text)\n\n        def streamer():\n            for _, t, v in self.get_tokens_unprocessed(text):\n                yield t, v\n        stream = streamer()\n        if not unfiltered:\n            stream = apply_filters(stream, self.filters, self)\n        return stream\n\n    def get_tokens_unprocessed(self, text):\n        \"\"\"\n        This method should process the text and return an iterable of\n        ``(index, tokentype, value)`` tuples where ``index`` is the starting\n        position of the token within the input text.\n\n        It must be overridden by subclasses. It is recommended to\n        implement it as a generator to maximize effectiveness.\n        \"\"\"\n        raise NotImplementedError\n\n\nclass DelegatingLexer(Lexer):\n    \"\"\"\n    This lexer takes two lexer as arguments. A root lexer and\n    a language lexer. First everything is scanned using the language\n    lexer, afterwards all ``Other`` tokens are lexed using the root\n    lexer.\n\n    The lexers from the ``template`` lexer package use this base lexer.\n    \"\"\"\n\n    def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options):\n        self.root_lexer = _root_lexer(**options)\n        self.language_lexer = _language_lexer(**options)\n        self.needle = _needle\n        Lexer.__init__(self, **options)\n\n    def get_tokens_unprocessed(self, text):\n        buffered = ''\n        insertions = []\n        lng_buffer = []\n        for i, t, v in self.language_lexer.get_tokens_unprocessed(text):\n            if t is self.needle:\n                if lng_buffer:\n                    insertions.append((len(buffered), lng_buffer))\n                    lng_buffer = []\n                buffered += v\n            else:\n                lng_buffer.append((i, t, v))\n        if lng_buffer:\n            insertions.append((len(buffered), lng_buffer))\n        return do_insertions(insertions,\n                             self.root_lexer.get_tokens_unprocessed(buffered))\n\n\n# ------------------------------------------------------------------------------\n# RegexLexer and ExtendedRegexLexer\n#\n\n\nclass include(str):  # pylint: disable=invalid-name\n    \"\"\"\n    Indicates that a state should include rules from another state.\n    \"\"\"\n    pass\n\n\nclass _inherit:\n    \"\"\"\n    Indicates the a state should inherit from its superclass.\n    \"\"\"\n    def __repr__(self):\n        return 'inherit'\n\ninherit = _inherit()  # pylint: disable=invalid-name\n\n\nclass combined(tuple):  # pylint: disable=invalid-name\n    \"\"\"\n    Indicates a state combined from multiple states.\n    \"\"\"\n\n    def __new__(cls, *args):\n        return tuple.__new__(cls, args)\n\n    def __init__(self, *args):\n        # tuple.__init__ doesn't do anything\n        pass\n\n\nclass _PseudoMatch:\n    \"\"\"\n    A pseudo match object constructed from a string.\n    \"\"\"\n\n    def __init__(self, start, text):\n        self._text = text\n        self._start = start\n\n    def start(self, arg=None):\n        return self._start\n\n    def end(self, arg=None):\n        return self._start + len(self._text)\n\n    def group(self, arg=None):\n        if arg:\n            raise IndexError('No such group')\n        return self._text\n\n    def groups(self):\n        return (self._text,)\n\n    def groupdict(self):\n        return {}\n\n\ndef bygroups(*args):\n    \"\"\"\n    Callback that yields multiple actions for each group in the match.\n    \"\"\"\n    def callback(lexer, match, ctx=None):\n        for i, action in enumerate(args):\n            if action is None:\n                continue\n            elif type(action) is _TokenType:\n                data = match.group(i + 1)\n                if data:\n                    yield match.start(i + 1), action, data\n            else:\n                data = match.group(i + 1)\n                if data is not None:\n                    if ctx:\n                        ctx.pos = match.start(i + 1)\n                    for item in action(lexer,\n                                       _PseudoMatch(match.start(i + 1), data), ctx):\n                        if item:\n                            yield item\n        if ctx:\n            ctx.pos = match.end()\n    return callback\n\n\nclass _This:\n    \"\"\"\n    Special singleton used for indicating the caller class.\n    Used by ``using``.\n    \"\"\"\n\nthis = _This()\n\n\ndef using(_other, **kwargs):\n    \"\"\"\n    Callback that processes the match with a different lexer.\n\n    The keyword arguments are forwarded to the lexer, except `state` which\n    is handled separately.\n\n    `state` specifies the state that the new lexer will start in, and can\n    be an enumerable such as ('root', 'inline', 'string') or a simple\n    string which is assumed to be on top of the root state.\n\n    Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.\n    \"\"\"\n    gt_kwargs = {}\n    if 'state' in kwargs:\n        s = kwargs.pop('state')\n        if isinstance(s, (list, tuple)):\n            gt_kwargs['stack'] = s\n        else:\n            gt_kwargs['stack'] = ('root', s)\n\n    if _other is this:\n        def callback(lexer, match, ctx=None):\n            # if keyword arguments are given the callback\n            # function has to create a new lexer instance\n            if kwargs:\n                # XXX: cache that somehow\n                kwargs.update(lexer.options)\n                lx = lexer.__class__(**kwargs)\n            else:\n                lx = lexer\n            s = match.start()\n            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):\n                yield i + s, t, v\n            if ctx:\n                ctx.pos = match.end()\n    else:\n        def callback(lexer, match, ctx=None):\n            # XXX: cache that somehow\n            kwargs.update(lexer.options)\n            lx = _other(**kwargs)\n\n            s = match.start()\n            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):\n                yield i + s, t, v\n            if ctx:\n                ctx.pos = match.end()\n    return callback\n\n\nclass default:\n    \"\"\"\n    Indicates a state or state action (e.g. #pop) to apply.\n    For example default('#pop') is equivalent to ('', Token, '#pop')\n    Note that state tuples may be used as well.\n\n    .. versionadded:: 2.0\n    \"\"\"\n    def __init__(self, state):\n        self.state = state\n\n\nclass words(Future):\n    \"\"\"\n    Indicates a list of literal words that is transformed into an optimized\n    regex that matches any of the words.\n\n    .. versionadded:: 2.0\n    \"\"\"\n    def __init__(self, words, prefix='', suffix=''):\n        self.words = words\n        self.prefix = prefix\n        self.suffix = suffix\n\n    def get(self):\n        return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)\n\n\nclass RegexLexerMeta(LexerMeta):\n    \"\"\"\n    Metaclass for RegexLexer, creates the self._tokens attribute from\n    self.tokens on the first instantiation.\n    \"\"\"\n\n    def _process_regex(cls, regex, rflags, state):\n        \"\"\"Preprocess the regular expression component of a token definition.\"\"\"\n        if isinstance(regex, Future):\n            regex = regex.get()\n        return re.compile(regex, rflags).match\n\n    def _process_token(cls, token):\n        \"\"\"Preprocess the token component of a token definition.\"\"\"\n        assert type(token) is _TokenType or callable(token), \\\n            f'token type must be simple type or callable, not {token!r}'\n        return token\n\n    def _process_new_state(cls, new_state, unprocessed, processed):\n        \"\"\"Preprocess the state transition action of a token definition.\"\"\"\n        if isinstance(new_state, str):\n            # an existing state\n            if new_state == '#pop':\n                return -1\n            elif new_state in unprocessed:\n                return (new_state,)\n            elif new_state == '#push':\n                return new_state\n            elif new_state[:5] == '#pop:':\n                return -int(new_state[5:])\n            else:\n                assert False, f'unknown new state {new_state!r}'\n        elif isinstance(new_state, combined):\n            # combine a new state from existing ones\n            tmp_state = '_tmp_%d' % cls._tmpname\n            cls._tmpname += 1\n            itokens = []\n            for istate in new_state:\n                assert istate != new_state, f'circular state ref {istate!r}'\n                itokens.extend(cls._process_state(unprocessed,\n                                                  processed, istate))\n            processed[tmp_state] = itokens\n            return (tmp_state,)\n        elif isinstance(new_state, tuple):\n            # push more than one state\n            for istate in new_state:\n                assert (istate in unprocessed or\n                        istate in ('#pop', '#push')), \\\n                    'unknown new state ' + istate\n            return new_state\n        else:\n            assert False, f'unknown new state def {new_state!r}'\n\n    def _process_state(cls, unprocessed, processed, state):\n        \"\"\"Preprocess a single state definition.\"\"\"\n        assert isinstance(state, str), f\"wrong state name {state!r}\"\n        assert state[0] != '#', f\"invalid state name {state!r}\"\n        if state in processed:\n            return processed[state]\n        tokens = processed[state] = []\n        rflags = cls.flags\n        for tdef in unprocessed[state]:\n            if isinstance(tdef, include):\n                # it's a state reference\n                assert tdef != state, f\"circular state reference {state!r}\"\n                tokens.extend(cls._process_state(unprocessed, processed,\n                                                 str(tdef)))\n                continue\n            if isinstance(tdef, _inherit):\n                # should be processed already, but may not in the case of:\n                # 1. the state has no counterpart in any parent\n                # 2. the state includes more than one 'inherit'\n                continue\n            if isinstance(tdef, default):\n                new_state = cls._process_new_state(tdef.state, unprocessed, processed)\n                tokens.append((re.compile('').match, None, new_state))\n                continue\n\n            assert type(tdef) is tuple, f\"wrong rule def {tdef!r}\"\n\n            try:\n                rex = cls._process_regex(tdef[0], rflags, state)\n            except Exception as err:\n                raise ValueError(f\"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}\") from err\n\n            token = cls._process_token(tdef[1])\n\n            if len(tdef) == 2:\n                new_state = None\n            else:\n                new_state = cls._process_new_state(tdef[2],\n                                                   unprocessed, processed)\n\n            tokens.append((rex, token, new_state))\n        return tokens\n\n    def process_tokendef(cls, name, tokendefs=None):\n        \"\"\"Preprocess a dictionary of token definitions.\"\"\"\n        processed = cls._all_tokens[name] = {}\n        tokendefs = tokendefs or cls.tokens[name]\n        for state in list(tokendefs):\n            cls._process_state(tokendefs, processed, state)\n        return processed\n\n    def get_tokendefs(cls):\n        \"\"\"\n        Merge tokens from superclasses in MRO order, returning a single tokendef\n        dictionary.\n\n        Any state that is not defined by a subclass will be inherited\n        automatically.  States that *are* defined by subclasses will, by\n        default, override that state in the superclass.  If a subclass wishes to\n        inherit definitions from a superclass, it can use the special value\n        \"inherit\", which will cause the superclass' state definition to be\n        included at that point in the state.\n        \"\"\"\n        tokens = {}\n        inheritable = {}\n        for c in cls.__mro__:\n            toks = c.__dict__.get('tokens', {})\n\n            for state, items in toks.items():\n                curitems = tokens.get(state)\n                if curitems is None:\n                    # N.b. because this is assigned by reference, sufficiently\n                    # deep hierarchies are processed incrementally (e.g. for\n                    # A(B), B(C), C(RegexLexer), B will be premodified so X(B)\n                    # will not see any inherits in B).\n                    tokens[state] = items\n                    try:\n                        inherit_ndx = items.index(inherit)\n                    except ValueError:\n                        continue\n                    inheritable[state] = inherit_ndx\n                    continue\n\n                inherit_ndx = inheritable.pop(state, None)\n                if inherit_ndx is None:\n                    continue\n\n                # Replace the \"inherit\" value with the items\n                curitems[inherit_ndx:inherit_ndx+1] = items\n                try:\n                    # N.b. this is the index in items (that is, the superclass\n                    # copy), so offset required when storing below.\n                    new_inh_ndx = items.index(inherit)\n                except ValueError:\n                    pass\n                else:\n                    inheritable[state] = inherit_ndx + new_inh_ndx\n\n        return tokens\n\n    def __call__(cls, *args, **kwds):\n        \"\"\"Instantiate cls after preprocessing its token definitions.\"\"\"\n        if '_tokens' not in cls.__dict__:\n            cls._all_tokens = {}\n            cls._tmpname = 0\n            if hasattr(cls, 'token_variants') and cls.token_variants:\n                # don't process yet\n                pass\n            else:\n                cls._tokens = cls.process_tokendef('', cls.get_tokendefs())\n\n        return type.__call__(cls, *args, **kwds)\n\n\nclass RegexLexer(Lexer, metaclass=RegexLexerMeta):\n    \"\"\"\n    Base for simple stateful regular expression-based lexers.\n    Simplifies the lexing process so that you need only\n    provide a list of states and regular expressions.\n    \"\"\"\n\n    #: Flags for compiling the regular expressions.\n    #: Defaults to MULTILINE.\n    flags = re.MULTILINE\n\n    #: At all time there is a stack of states. Initially, the stack contains\n    #: a single state 'root'. The top of the stack is called \"the current state\".\n    #:\n    #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}``\n    #:\n    #: ``new_state`` can be omitted to signify no state transition.\n    #: If ``new_state`` is a string, it is pushed on the stack. This ensure\n    #: the new current state is ``new_state``.\n    #: If ``new_state`` is a tuple of strings, all of those strings are pushed\n    #: on the stack and the current state will be the last element of the list.\n    #: ``new_state`` can also be ``combined('state1', 'state2', ...)``\n    #: to signify a new, anonymous state combined from the rules of two\n    #: or more existing ones.\n    #: Furthermore, it can be '#pop' to signify going back one step in\n    #: the state stack, or '#push' to push the current state on the stack\n    #: again. Note that if you push while in a combined state, the combined\n    #: state itself is pushed, and not only the state in which the rule is\n    #: defined.\n    #:\n    #: The tuple can also be replaced with ``include('state')``, in which\n    #: case the rules from the state named by the string are included in the\n    #: current one.\n    tokens = {}\n\n    def get_tokens_unprocessed(self, text, stack=('root',)):\n        \"\"\"\n        Split ``text`` into (tokentype, text) pairs.\n\n        ``stack`` is the initial stack (default: ``['root']``)\n        \"\"\"\n        pos = 0\n        tokendefs = self._tokens\n        statestack = list(stack)\n        statetokens = tokendefs[statestack[-1]]\n        while 1:\n            for rexmatch, action, new_state in statetokens:\n                m = rexmatch(text, pos)\n                if m:\n                    if action is not None:\n                        if type(action) is _TokenType:\n                            yield pos, action, m.group()\n                        else:\n                            yield from action(self, m)\n                    pos = m.end()\n                    if new_state is not None:\n                        # state transition\n                        if isinstance(new_state, tuple):\n                            for state in new_state:\n                                if state == '#pop':\n                                    if len(statestack) > 1:\n                                        statestack.pop()\n                                elif state == '#push':\n                                    statestack.append(statestack[-1])\n                                else:\n                                    statestack.append(state)\n                        elif isinstance(new_state, int):\n                            # pop, but keep at least one state on the stack\n                            # (random code leading to unexpected pops should\n                            # not allow exceptions)\n                            if abs(new_state) >= len(statestack):\n                                del statestack[1:]\n                            else:\n                                del statestack[new_state:]\n                        elif new_state == '#push':\n                            statestack.append(statestack[-1])\n                        else:\n                            assert False, f\"wrong state def: {new_state!r}\"\n                        statetokens = tokendefs[statestack[-1]]\n                    break\n            else:\n                # We are here only if all state tokens have been considered\n                # and there was not a match on any of them.\n                try:\n                    if text[pos] == '\\n':\n                        # at EOL, reset state to \"root\"\n                        statestack = ['root']\n                        statetokens = tokendefs['root']\n                        yield pos, Whitespace, '\\n'\n                        pos += 1\n                        continue\n                    yield pos, Error, text[pos]\n                    pos += 1\n                except IndexError:\n                    break\n\n\nclass LexerContext:\n    \"\"\"\n    A helper object that holds lexer position data.\n    \"\"\"\n\n    def __init__(self, text, pos, stack=None, end=None):\n        self.text = text\n        self.pos = pos\n        self.end = end or len(text)  # end=0 not supported ;-)\n        self.stack = stack or ['root']\n\n    def __repr__(self):\n        return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'\n\n\nclass ExtendedRegexLexer(RegexLexer):\n    \"\"\"\n    A RegexLexer that uses a context object to store its state.\n    \"\"\"\n\n    def get_tokens_unprocessed(self, text=None, context=None):\n        \"\"\"\n        Split ``text`` into (tokentype, text) pairs.\n        If ``context`` is given, use this lexer context instead.\n        \"\"\"\n        tokendefs = self._tokens\n        if not context:\n            ctx = LexerContext(text, 0)\n            statetokens = tokendefs['root']\n        else:\n            ctx = context\n            statetokens = tokendefs[ctx.stack[-1]]\n            text = ctx.text\n        while 1:\n            for rexmatch, action, new_state in statetokens:\n                m = rexmatch(text, ctx.pos, ctx.end)\n                if m:\n                    if action is not None:\n                        if type(action) is _TokenType:\n                            yield ctx.pos, action, m.group()\n                            ctx.pos = m.end()\n                        else:\n                            yield from action(self, m, ctx)\n                            if not new_state:\n                                # altered the state stack?\n                                statetokens = tokendefs[ctx.stack[-1]]\n                    # CAUTION: callback must set ctx.pos!\n                    if new_state is not None:\n                        # state transition\n                        if isinstance(new_state, tuple):\n                            for state in new_state:\n                                if state == '#pop':\n                                    if len(ctx.stack) > 1:\n                                        ctx.stack.pop()\n                                elif state == '#push':\n                                    ctx.stack.append(ctx.stack[-1])\n                                else:\n                                    ctx.stack.append(state)\n                        elif isinstance(new_state, int):\n                            # see RegexLexer for why this check is made\n                            if abs(new_state) >= len(ctx.stack):\n                                del ctx.stack[1:]\n                            else:\n                                del ctx.stack[new_state:]\n                        elif new_state == '#push':\n                            ctx.stack.append(ctx.stack[-1])\n                        else:\n                            assert False, f\"wrong state def: {new_state!r}\"\n                        statetokens = tokendefs[ctx.stack[-1]]\n                    break\n            else:\n                try:\n                    if ctx.pos >= ctx.end:\n                        break\n                    if text[ctx.pos] == '\\n':\n                        # at EOL, reset state to \"root\"\n                        ctx.stack = ['root']\n                        statetokens = tokendefs['root']\n                        yield ctx.pos, Text, '\\n'\n                        ctx.pos += 1\n                        continue\n                    yield ctx.pos, Error, text[ctx.pos]\n                    ctx.pos += 1\n                except IndexError:\n                    break\n\n\ndef do_insertions(insertions, tokens):\n    \"\"\"\n    Helper for lexers which must combine the results of several\n    sublexers.\n\n    ``insertions`` is a list of ``(index, itokens)`` pairs.\n    Each ``itokens`` iterable should be inserted at position\n    ``index`` into the token stream given by the ``tokens``\n    argument.\n\n    The result is a combined token stream.\n\n    TODO: clean up the code here.\n    \"\"\"\n    insertions = iter(insertions)\n    try:\n        index, itokens = next(insertions)\n    except StopIteration:\n        # no insertions\n        yield from tokens\n        return\n\n    realpos = None\n    insleft = True\n\n    # iterate over the token stream where we want to insert\n    # the tokens from the insertion list.\n    for i, t, v in tokens:\n        # first iteration. store the position of first item\n        if realpos is None:\n            realpos = i\n        oldi = 0\n        while insleft and i + len(v) >= index:\n            tmpval = v[oldi:index - i]\n            if tmpval:\n                yield realpos, t, tmpval\n                realpos += len(tmpval)\n            for it_index, it_token, it_value in itokens:\n                yield realpos, it_token, it_value\n                realpos += len(it_value)\n            oldi = index - i\n            try:\n                index, itokens = next(insertions)\n            except StopIteration:\n                insleft = False\n                break  # not strictly necessary\n        if oldi < len(v):\n            yield realpos, t, v[oldi:]\n            realpos += len(v) - oldi\n\n    # leftover tokens\n    while insleft:\n        # no normal tokens, set realpos to zero\n        realpos = realpos or 0\n        for p, t, v in itokens:\n            yield realpos, t, v\n            realpos += len(v)\n        try:\n            index, itokens = next(insertions)\n        except StopIteration:\n            insleft = False\n            break  # not strictly necessary\n\n\nclass ProfilingRegexLexerMeta(RegexLexerMeta):\n    \"\"\"Metaclass for ProfilingRegexLexer, collects regex timing info.\"\"\"\n\n    def _process_regex(cls, regex, rflags, state):\n        if isinstance(regex, words):\n            rex = regex_opt(regex.words, prefix=regex.prefix,\n                            suffix=regex.suffix)\n        else:\n            rex = regex\n        compiled = re.compile(rex, rflags)\n\n        def match_func(text, pos, endpos=sys.maxsize):\n            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])\n            t0 = time.time()\n            res = compiled.match(text, pos, endpos)\n            t1 = time.time()\n            info[0] += 1\n            info[1] += t1 - t0\n            return res\n        return match_func\n\n\nclass ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta):\n    \"\"\"Drop-in replacement for RegexLexer that does profiling of its regexes.\"\"\"\n\n    _prof_data = []\n    _prof_sort_index = 4  # defaults to time per call\n\n    def get_tokens_unprocessed(self, text, stack=('root',)):\n        # this needs to be a stack, since using(this) will produce nested calls\n        self.__class__._prof_data.append({})\n        yield from RegexLexer.get_tokens_unprocessed(self, text, stack)\n        rawdata = self.__class__._prof_data.pop()\n        data = sorted(((s, repr(r).strip('u\\'').replace('\\\\\\\\', '\\\\')[:65],\n                        n, 1000 * t, 1000 * t / n)\n                       for ((s, r), (n, t)) in rawdata.items()),\n                      key=lambda x: x[self._prof_sort_index],\n                      reverse=True)\n        sum_total = sum(x[3] for x in data)\n\n        print()\n        print('Profiling result for %s lexing %d chars in %.3f ms' %\n              (self.__class__.__name__, len(text), sum_total))\n        print('=' * 110)\n        print('%-20s %-64s ncalls  tottime  percall' % ('state', 'regex'))\n        print('-' * 110)\n        for d in data:\n            print('%-20s %-65s %5d %8.4f %8.4f' % d)\n        print('=' * 110)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/lexers/__init__.py",
    "content": "\"\"\"\n    pygments.lexers\n    ~~~~~~~~~~~~~~~\n\n    Pygments lexers.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport types\nimport fnmatch\nfrom os.path import basename\n\nfrom pip._vendor.pygments.lexers._mapping import LEXERS\nfrom pip._vendor.pygments.modeline import get_filetype_from_buffer\nfrom pip._vendor.pygments.plugin import find_plugin_lexers\nfrom pip._vendor.pygments.util import ClassNotFound, guess_decode\n\nCOMPAT = {\n    'Python3Lexer': 'PythonLexer',\n    'Python3TracebackLexer': 'PythonTracebackLexer',\n    'LeanLexer': 'Lean3Lexer',\n}\n\n__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',\n           'guess_lexer', 'load_lexer_from_file'] + list(LEXERS) + list(COMPAT)\n\n_lexer_cache = {}\n_pattern_cache = {}\n\n\ndef _fn_matches(fn, glob):\n    \"\"\"Return whether the supplied file name fn matches pattern filename.\"\"\"\n    if glob not in _pattern_cache:\n        pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))\n        return pattern.match(fn)\n    return _pattern_cache[glob].match(fn)\n\n\ndef _load_lexers(module_name):\n    \"\"\"Load a lexer (and all others in the module too).\"\"\"\n    mod = __import__(module_name, None, None, ['__all__'])\n    for lexer_name in mod.__all__:\n        cls = getattr(mod, lexer_name)\n        _lexer_cache[cls.name] = cls\n\n\ndef get_all_lexers(plugins=True):\n    \"\"\"Return a generator of tuples in the form ``(name, aliases,\n    filenames, mimetypes)`` of all know lexers.\n\n    If *plugins* is true (the default), plugin lexers supplied by entrypoints\n    are also returned.  Otherwise, only builtin ones are considered.\n    \"\"\"\n    for item in LEXERS.values():\n        yield item[1:]\n    if plugins:\n        for lexer in find_plugin_lexers():\n            yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes\n\n\ndef find_lexer_class(name):\n    \"\"\"\n    Return the `Lexer` subclass that with the *name* attribute as given by\n    the *name* argument.\n    \"\"\"\n    if name in _lexer_cache:\n        return _lexer_cache[name]\n    # lookup builtin lexers\n    for module_name, lname, aliases, _, _ in LEXERS.values():\n        if name == lname:\n            _load_lexers(module_name)\n            return _lexer_cache[name]\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if cls.name == name:\n            return cls\n\n\ndef find_lexer_class_by_name(_alias):\n    \"\"\"\n    Return the `Lexer` subclass that has `alias` in its aliases list, without\n    instantiating it.\n\n    Like `get_lexer_by_name`, but does not instantiate the class.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is\n    found.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    if not _alias:\n        raise ClassNotFound(f'no lexer for alias {_alias!r} found')\n    # lookup builtin lexers\n    for module_name, name, aliases, _, _ in LEXERS.values():\n        if _alias.lower() in aliases:\n            if name not in _lexer_cache:\n                _load_lexers(module_name)\n            return _lexer_cache[name]\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if _alias.lower() in cls.aliases:\n            return cls\n    raise ClassNotFound(f'no lexer for alias {_alias!r} found')\n\n\ndef get_lexer_by_name(_alias, **options):\n    \"\"\"\n    Return an instance of a `Lexer` subclass that has `alias` in its\n    aliases list. The lexer is given the `options` at its\n    instantiation.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is\n    found.\n    \"\"\"\n    if not _alias:\n        raise ClassNotFound(f'no lexer for alias {_alias!r} found')\n\n    # lookup builtin lexers\n    for module_name, name, aliases, _, _ in LEXERS.values():\n        if _alias.lower() in aliases:\n            if name not in _lexer_cache:\n                _load_lexers(module_name)\n            return _lexer_cache[name](**options)\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if _alias.lower() in cls.aliases:\n            return cls(**options)\n    raise ClassNotFound(f'no lexer for alias {_alias!r} found')\n\n\ndef load_lexer_from_file(filename, lexername=\"CustomLexer\", **options):\n    \"\"\"Load a lexer from a file.\n\n    This method expects a file located relative to the current working\n    directory, which contains a Lexer class. By default, it expects the\n    Lexer to be name CustomLexer; you can specify your own class name\n    as the second argument to this function.\n\n    Users should be very careful with the input, because this method\n    is equivalent to running eval on the input file.\n\n    Raises ClassNotFound if there are any problems importing the Lexer.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    try:\n        # This empty dict will contain the namespace for the exec'd file\n        custom_namespace = {}\n        with open(filename, 'rb') as f:\n            exec(f.read(), custom_namespace)\n        # Retrieve the class `lexername` from that namespace\n        if lexername not in custom_namespace:\n            raise ClassNotFound(f'no valid {lexername} class found in {filename}')\n        lexer_class = custom_namespace[lexername]\n        # And finally instantiate it with the options\n        return lexer_class(**options)\n    except OSError as err:\n        raise ClassNotFound(f'cannot read {filename}: {err}')\n    except ClassNotFound:\n        raise\n    except Exception as err:\n        raise ClassNotFound(f'error when loading custom lexer: {err}')\n\n\ndef find_lexer_class_for_filename(_fn, code=None):\n    \"\"\"Get a lexer for a filename.\n\n    If multiple lexers match the filename pattern, use ``analyse_text()`` to\n    figure out which one is more appropriate.\n\n    Returns None if not found.\n    \"\"\"\n    matches = []\n    fn = basename(_fn)\n    for modname, name, _, filenames, _ in LEXERS.values():\n        for filename in filenames:\n            if _fn_matches(fn, filename):\n                if name not in _lexer_cache:\n                    _load_lexers(modname)\n                matches.append((_lexer_cache[name], filename))\n    for cls in find_plugin_lexers():\n        for filename in cls.filenames:\n            if _fn_matches(fn, filename):\n                matches.append((cls, filename))\n\n    if isinstance(code, bytes):\n        # decode it, since all analyse_text functions expect unicode\n        code = guess_decode(code)\n\n    def get_rating(info):\n        cls, filename = info\n        # explicit patterns get a bonus\n        bonus = '*' not in filename and 0.5 or 0\n        # The class _always_ defines analyse_text because it's included in\n        # the Lexer class.  The default implementation returns None which\n        # gets turned into 0.0.  Run scripts/detect_missing_analyse_text.py\n        # to find lexers which need it overridden.\n        if code:\n            return cls.analyse_text(code) + bonus, cls.__name__\n        return cls.priority + bonus, cls.__name__\n\n    if matches:\n        matches.sort(key=get_rating)\n        # print \"Possible lexers, after sort:\", matches\n        return matches[-1][0]\n\n\ndef get_lexer_for_filename(_fn, code=None, **options):\n    \"\"\"Get a lexer for a filename.\n\n    Return a `Lexer` subclass instance that has a filename pattern\n    matching `fn`. The lexer is given the `options` at its\n    instantiation.\n\n    Raise :exc:`pygments.util.ClassNotFound` if no lexer for that filename\n    is found.\n\n    If multiple lexers match the filename pattern, use their ``analyse_text()``\n    methods to figure out which one is more appropriate.\n    \"\"\"\n    res = find_lexer_class_for_filename(_fn, code)\n    if not res:\n        raise ClassNotFound(f'no lexer for filename {_fn!r} found')\n    return res(**options)\n\n\ndef get_lexer_for_mimetype(_mime, **options):\n    \"\"\"\n    Return a `Lexer` subclass instance that has `mime` in its mimetype\n    list. The lexer is given the `options` at its instantiation.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if not lexer for that mimetype\n    is found.\n    \"\"\"\n    for modname, name, _, _, mimetypes in LEXERS.values():\n        if _mime in mimetypes:\n            if name not in _lexer_cache:\n                _load_lexers(modname)\n            return _lexer_cache[name](**options)\n    for cls in find_plugin_lexers():\n        if _mime in cls.mimetypes:\n            return cls(**options)\n    raise ClassNotFound(f'no lexer for mimetype {_mime!r} found')\n\n\ndef _iter_lexerclasses(plugins=True):\n    \"\"\"Return an iterator over all lexer classes.\"\"\"\n    for key in sorted(LEXERS):\n        module_name, name = LEXERS[key][:2]\n        if name not in _lexer_cache:\n            _load_lexers(module_name)\n        yield _lexer_cache[name]\n    if plugins:\n        yield from find_plugin_lexers()\n\n\ndef guess_lexer_for_filename(_fn, _text, **options):\n    \"\"\"\n    As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames`\n    or `alias_filenames` that matches `filename` are taken into consideration.\n\n    :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can\n    handle the content.\n    \"\"\"\n    fn = basename(_fn)\n    primary = {}\n    matching_lexers = set()\n    for lexer in _iter_lexerclasses():\n        for filename in lexer.filenames:\n            if _fn_matches(fn, filename):\n                matching_lexers.add(lexer)\n                primary[lexer] = True\n        for filename in lexer.alias_filenames:\n            if _fn_matches(fn, filename):\n                matching_lexers.add(lexer)\n                primary[lexer] = False\n    if not matching_lexers:\n        raise ClassNotFound(f'no lexer for filename {fn!r} found')\n    if len(matching_lexers) == 1:\n        return matching_lexers.pop()(**options)\n    result = []\n    for lexer in matching_lexers:\n        rv = lexer.analyse_text(_text)\n        if rv == 1.0:\n            return lexer(**options)\n        result.append((rv, lexer))\n\n    def type_sort(t):\n        # sort by:\n        # - analyse score\n        # - is primary filename pattern?\n        # - priority\n        # - last resort: class name\n        return (t[0], primary[t[1]], t[1].priority, t[1].__name__)\n    result.sort(key=type_sort)\n\n    return result[-1][1](**options)\n\n\ndef guess_lexer(_text, **options):\n    \"\"\"\n    Return a `Lexer` subclass instance that's guessed from the text in\n    `text`. For that, the :meth:`.analyse_text()` method of every known lexer\n    class is called with the text as argument, and the lexer which returned the\n    highest value will be instantiated and returned.\n\n    :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can\n    handle the content.\n    \"\"\"\n\n    if not isinstance(_text, str):\n        inencoding = options.get('inencoding', options.get('encoding'))\n        if inencoding:\n            _text = _text.decode(inencoding or 'utf8')\n        else:\n            _text, _ = guess_decode(_text)\n\n    # try to get a vim modeline first\n    ft = get_filetype_from_buffer(_text)\n\n    if ft is not None:\n        try:\n            return get_lexer_by_name(ft, **options)\n        except ClassNotFound:\n            pass\n\n    best_lexer = [0.0, None]\n    for lexer in _iter_lexerclasses():\n        rv = lexer.analyse_text(_text)\n        if rv == 1.0:\n            return lexer(**options)\n        if rv > best_lexer[0]:\n            best_lexer[:] = (rv, lexer)\n    if not best_lexer[0] or best_lexer[1] is None:\n        raise ClassNotFound('no lexer matching the text found')\n    return best_lexer[1](**options)\n\n\nclass _automodule(types.ModuleType):\n    \"\"\"Automatically import lexers.\"\"\"\n\n    def __getattr__(self, name):\n        info = LEXERS.get(name)\n        if info:\n            _load_lexers(info[0])\n            cls = _lexer_cache[info[1]]\n            setattr(self, name, cls)\n            return cls\n        if name in COMPAT:\n            return getattr(self, COMPAT[name])\n        raise AttributeError(name)\n\n\noldmod = sys.modules[__name__]\nnewmod = _automodule(__name__)\nnewmod.__dict__.update(oldmod.__dict__)\nsys.modules[__name__] = newmod\ndel newmod.newmod, newmod.oldmod, newmod.sys, newmod.types\n"
  },
  {
    "path": "src/pip/_vendor/pygments/lexers/_mapping.py",
    "content": "# Automatically generated by scripts/gen_mapfiles.py.\n# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.\n\nLEXERS = {\n    'ABAPLexer': ('pip._vendor.pygments.lexers.business', 'ABAP', ('abap',), ('*.abap', '*.ABAP'), ('text/x-abap',)),\n    'AMDGPULexer': ('pip._vendor.pygments.lexers.amdgpu', 'AMDGPU', ('amdgpu',), ('*.isa',), ()),\n    'APLLexer': ('pip._vendor.pygments.lexers.apl', 'APL', ('apl',), ('*.apl', '*.aplf', '*.aplo', '*.apln', '*.aplc', '*.apli', '*.dyalog'), ()),\n    'AbnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'ABNF', ('abnf',), ('*.abnf',), ('text/x-abnf',)),\n    'ActionScript3Lexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript 3', ('actionscript3', 'as3'), ('*.as',), ('application/x-actionscript3', 'text/x-actionscript3', 'text/actionscript3')),\n    'ActionScriptLexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript', ('actionscript', 'as'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')),\n    'AdaLexer': ('pip._vendor.pygments.lexers.ada', 'Ada', ('ada', 'ada95', 'ada2005'), ('*.adb', '*.ads', '*.ada'), ('text/x-ada',)),\n    'AdlLexer': ('pip._vendor.pygments.lexers.archetype', 'ADL', ('adl',), ('*.adl', '*.adls', '*.adlf', '*.adlx'), ()),\n    'AgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Agda', ('agda',), ('*.agda',), ('text/x-agda',)),\n    'AheuiLexer': ('pip._vendor.pygments.lexers.esoteric', 'Aheui', ('aheui',), ('*.aheui',), ()),\n    'AlloyLexer': ('pip._vendor.pygments.lexers.dsls', 'Alloy', ('alloy',), ('*.als',), ('text/x-alloy',)),\n    'AmbientTalkLexer': ('pip._vendor.pygments.lexers.ambient', 'AmbientTalk', ('ambienttalk', 'ambienttalk/2', 'at'), ('*.at',), ('text/x-ambienttalk',)),\n    'AmplLexer': ('pip._vendor.pygments.lexers.ampl', 'Ampl', ('ampl',), ('*.run',), ()),\n    'Angular2HtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML + Angular2', ('html+ng2',), ('*.ng2',), ()),\n    'Angular2Lexer': ('pip._vendor.pygments.lexers.templates', 'Angular2', ('ng2',), (), ()),\n    'AntlrActionScriptLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ActionScript Target', ('antlr-actionscript', 'antlr-as'), ('*.G', '*.g'), ()),\n    'AntlrCSharpLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With C# Target', ('antlr-csharp', 'antlr-c#'), ('*.G', '*.g'), ()),\n    'AntlrCppLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With CPP Target', ('antlr-cpp',), ('*.G', '*.g'), ()),\n    'AntlrJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Java Target', ('antlr-java',), ('*.G', '*.g'), ()),\n    'AntlrLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR', ('antlr',), (), ()),\n    'AntlrObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ObjectiveC Target', ('antlr-objc',), ('*.G', '*.g'), ()),\n    'AntlrPerlLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Perl Target', ('antlr-perl',), ('*.G', '*.g'), ()),\n    'AntlrPythonLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Python Target', ('antlr-python',), ('*.G', '*.g'), ()),\n    'AntlrRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Ruby Target', ('antlr-ruby', 'antlr-rb'), ('*.G', '*.g'), ()),\n    'ApacheConfLexer': ('pip._vendor.pygments.lexers.configs', 'ApacheConf', ('apacheconf', 'aconf', 'apache'), ('.htaccess', 'apache.conf', 'apache2.conf'), ('text/x-apacheconf',)),\n    'AppleScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'AppleScript', ('applescript',), ('*.applescript',), ()),\n    'ArduinoLexer': ('pip._vendor.pygments.lexers.c_like', 'Arduino', ('arduino',), ('*.ino',), ('text/x-arduino',)),\n    'ArrowLexer': ('pip._vendor.pygments.lexers.arrow', 'Arrow', ('arrow',), ('*.arw',), ()),\n    'ArturoLexer': ('pip._vendor.pygments.lexers.arturo', 'Arturo', ('arturo', 'art'), ('*.art',), ()),\n    'AscLexer': ('pip._vendor.pygments.lexers.asc', 'ASCII armored', ('asc', 'pem'), ('*.asc', '*.pem', 'id_dsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', 'id_ed25519_sk', 'id_rsa'), ('application/pgp-keys', 'application/pgp-encrypted', 'application/pgp-signature', 'application/pem-certificate-chain')),\n    'Asn1Lexer': ('pip._vendor.pygments.lexers.asn1', 'ASN.1', ('asn1',), ('*.asn1',), ()),\n    'AspectJLexer': ('pip._vendor.pygments.lexers.jvm', 'AspectJ', ('aspectj',), ('*.aj',), ('text/x-aspectj',)),\n    'AsymptoteLexer': ('pip._vendor.pygments.lexers.graphics', 'Asymptote', ('asymptote', 'asy'), ('*.asy',), ('text/x-asymptote',)),\n    'AugeasLexer': ('pip._vendor.pygments.lexers.configs', 'Augeas', ('augeas',), ('*.aug',), ()),\n    'AutoItLexer': ('pip._vendor.pygments.lexers.automation', 'AutoIt', ('autoit',), ('*.au3',), ('text/x-autoit',)),\n    'AutohotkeyLexer': ('pip._vendor.pygments.lexers.automation', 'autohotkey', ('autohotkey', 'ahk'), ('*.ahk', '*.ahkl'), ('text/x-autohotkey',)),\n    'AwkLexer': ('pip._vendor.pygments.lexers.textedit', 'Awk', ('awk', 'gawk', 'mawk', 'nawk'), ('*.awk',), ('application/x-awk',)),\n    'BBCBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BBC Basic', ('bbcbasic',), ('*.bbc',), ()),\n    'BBCodeLexer': ('pip._vendor.pygments.lexers.markup', 'BBCode', ('bbcode',), (), ('text/x-bbcode',)),\n    'BCLexer': ('pip._vendor.pygments.lexers.algebra', 'BC', ('bc',), ('*.bc',), ()),\n    'BQNLexer': ('pip._vendor.pygments.lexers.bqn', 'BQN', ('bqn',), ('*.bqn',), ()),\n    'BSTLexer': ('pip._vendor.pygments.lexers.bibtex', 'BST', ('bst', 'bst-pybtex'), ('*.bst',), ()),\n    'BareLexer': ('pip._vendor.pygments.lexers.bare', 'BARE', ('bare',), ('*.bare',), ()),\n    'BaseMakefileLexer': ('pip._vendor.pygments.lexers.make', 'Base Makefile', ('basemake',), (), ()),\n    'BashLexer': ('pip._vendor.pygments.lexers.shell', 'Bash', ('bash', 'sh', 'ksh', 'zsh', 'shell', 'openrc'), ('*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass', '*.exheres-0', '*.exlib', '*.zsh', '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc', '.kshrc', 'kshrc', 'PKGBUILD'), ('application/x-sh', 'application/x-shellscript', 'text/x-shellscript')),\n    'BashSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Bash Session', ('console', 'shell-session'), ('*.sh-session', '*.shell-session'), ('application/x-shell-session', 'application/x-sh-session')),\n    'BatchLexer': ('pip._vendor.pygments.lexers.shell', 'Batchfile', ('batch', 'bat', 'dosbatch', 'winbatch'), ('*.bat', '*.cmd'), ('application/x-dos-batch',)),\n    'BddLexer': ('pip._vendor.pygments.lexers.bdd', 'Bdd', ('bdd',), ('*.feature',), ('text/x-bdd',)),\n    'BefungeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Befunge', ('befunge',), ('*.befunge',), ('application/x-befunge',)),\n    'BerryLexer': ('pip._vendor.pygments.lexers.berry', 'Berry', ('berry', 'be'), ('*.be',), ('text/x-berry', 'application/x-berry')),\n    'BibTeXLexer': ('pip._vendor.pygments.lexers.bibtex', 'BibTeX', ('bibtex', 'bib'), ('*.bib',), ('text/x-bibtex',)),\n    'BlitzBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzBasic', ('blitzbasic', 'b3d', 'bplus'), ('*.bb', '*.decls'), ('text/x-bb',)),\n    'BlitzMaxLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzMax', ('blitzmax', 'bmax'), ('*.bmx',), ('text/x-bmx',)),\n    'BlueprintLexer': ('pip._vendor.pygments.lexers.blueprint', 'Blueprint', ('blueprint',), ('*.blp',), ('text/x-blueprint',)),\n    'BnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'BNF', ('bnf',), ('*.bnf',), ('text/x-bnf',)),\n    'BoaLexer': ('pip._vendor.pygments.lexers.boa', 'Boa', ('boa',), ('*.boa',), ()),\n    'BooLexer': ('pip._vendor.pygments.lexers.dotnet', 'Boo', ('boo',), ('*.boo',), ('text/x-boo',)),\n    'BoogieLexer': ('pip._vendor.pygments.lexers.verification', 'Boogie', ('boogie',), ('*.bpl',), ()),\n    'BrainfuckLexer': ('pip._vendor.pygments.lexers.esoteric', 'Brainfuck', ('brainfuck', 'bf'), ('*.bf', '*.b'), ('application/x-brainfuck',)),\n    'BugsLexer': ('pip._vendor.pygments.lexers.modeling', 'BUGS', ('bugs', 'winbugs', 'openbugs'), ('*.bug',), ()),\n    'CAmkESLexer': ('pip._vendor.pygments.lexers.esoteric', 'CAmkES', ('camkes', 'idl4'), ('*.camkes', '*.idl4'), ()),\n    'CLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C', ('c',), ('*.c', '*.h', '*.idc', '*.x[bp]m'), ('text/x-chdr', 'text/x-csrc', 'image/x-xbitmap', 'image/x-xpixmap')),\n    'CMakeLexer': ('pip._vendor.pygments.lexers.make', 'CMake', ('cmake',), ('*.cmake', 'CMakeLists.txt'), ('text/x-cmake',)),\n    'CObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('text/x-c-objdump',)),\n    'CPSALexer': ('pip._vendor.pygments.lexers.lisp', 'CPSA', ('cpsa',), ('*.cpsa',), ()),\n    'CSSUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'CSS+UL4', ('css+ul4',), ('*.cssul4',), ()),\n    'CSharpAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-cs', ('aspx-cs',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),\n    'CSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'C#', ('csharp', 'c#', 'cs'), ('*.cs',), ('text/x-csharp',)),\n    'Ca65Lexer': ('pip._vendor.pygments.lexers.asm', 'ca65 assembler', ('ca65',), ('*.s',), ()),\n    'CadlLexer': ('pip._vendor.pygments.lexers.archetype', 'cADL', ('cadl',), ('*.cadl',), ()),\n    'CapDLLexer': ('pip._vendor.pygments.lexers.esoteric', 'CapDL', ('capdl',), ('*.cdl',), ()),\n    'CapnProtoLexer': ('pip._vendor.pygments.lexers.capnproto', \"Cap'n Proto\", ('capnp',), ('*.capnp',), ()),\n    'CarbonLexer': ('pip._vendor.pygments.lexers.carbon', 'Carbon', ('carbon',), ('*.carbon',), ('text/x-carbon',)),\n    'CbmBasicV2Lexer': ('pip._vendor.pygments.lexers.basic', 'CBM BASIC V2', ('cbmbas',), ('*.bas',), ()),\n    'CddlLexer': ('pip._vendor.pygments.lexers.cddl', 'CDDL', ('cddl',), ('*.cddl',), ('text/x-cddl',)),\n    'CeylonLexer': ('pip._vendor.pygments.lexers.jvm', 'Ceylon', ('ceylon',), ('*.ceylon',), ('text/x-ceylon',)),\n    'Cfengine3Lexer': ('pip._vendor.pygments.lexers.configs', 'CFEngine3', ('cfengine3', 'cf3'), ('*.cf',), ()),\n    'ChaiscriptLexer': ('pip._vendor.pygments.lexers.scripting', 'ChaiScript', ('chaiscript', 'chai'), ('*.chai',), ('text/x-chaiscript', 'application/x-chaiscript')),\n    'ChapelLexer': ('pip._vendor.pygments.lexers.chapel', 'Chapel', ('chapel', 'chpl'), ('*.chpl',), ()),\n    'CharmciLexer': ('pip._vendor.pygments.lexers.c_like', 'Charmci', ('charmci',), ('*.ci',), ()),\n    'CheetahHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Cheetah', ('html+cheetah', 'html+spitfire', 'htmlcheetah'), (), ('text/html+cheetah', 'text/html+spitfire')),\n    'CheetahJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Cheetah', ('javascript+cheetah', 'js+cheetah', 'javascript+spitfire', 'js+spitfire'), (), ('application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire')),\n    'CheetahLexer': ('pip._vendor.pygments.lexers.templates', 'Cheetah', ('cheetah', 'spitfire'), ('*.tmpl', '*.spt'), ('application/x-cheetah', 'application/x-spitfire')),\n    'CheetahXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Cheetah', ('xml+cheetah', 'xml+spitfire'), (), ('application/xml+cheetah', 'application/xml+spitfire')),\n    'CirruLexer': ('pip._vendor.pygments.lexers.webmisc', 'Cirru', ('cirru',), ('*.cirru',), ('text/x-cirru',)),\n    'ClayLexer': ('pip._vendor.pygments.lexers.c_like', 'Clay', ('clay',), ('*.clay',), ('text/x-clay',)),\n    'CleanLexer': ('pip._vendor.pygments.lexers.clean', 'Clean', ('clean',), ('*.icl', '*.dcl'), ()),\n    'ClojureLexer': ('pip._vendor.pygments.lexers.jvm', 'Clojure', ('clojure', 'clj'), ('*.clj', '*.cljc'), ('text/x-clojure', 'application/x-clojure')),\n    'ClojureScriptLexer': ('pip._vendor.pygments.lexers.jvm', 'ClojureScript', ('clojurescript', 'cljs'), ('*.cljs',), ('text/x-clojurescript', 'application/x-clojurescript')),\n    'CobolFreeformatLexer': ('pip._vendor.pygments.lexers.business', 'COBOLFree', ('cobolfree',), ('*.cbl', '*.CBL'), ()),\n    'CobolLexer': ('pip._vendor.pygments.lexers.business', 'COBOL', ('cobol',), ('*.cob', '*.COB', '*.cpy', '*.CPY'), ('text/x-cobol',)),\n    'CodeQLLexer': ('pip._vendor.pygments.lexers.codeql', 'CodeQL', ('codeql', 'ql'), ('*.ql', '*.qll'), ()),\n    'CoffeeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'CoffeeScript', ('coffeescript', 'coffee-script', 'coffee'), ('*.coffee',), ('text/coffeescript',)),\n    'ColdfusionCFCLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion CFC', ('cfc',), ('*.cfc',), ()),\n    'ColdfusionHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion HTML', ('cfm',), ('*.cfm', '*.cfml'), ('application/x-coldfusion',)),\n    'ColdfusionLexer': ('pip._vendor.pygments.lexers.templates', 'cfstatement', ('cfs',), (), ()),\n    'Comal80Lexer': ('pip._vendor.pygments.lexers.comal', 'COMAL-80', ('comal', 'comal80'), ('*.cml', '*.comal'), ()),\n    'CommonLispLexer': ('pip._vendor.pygments.lexers.lisp', 'Common Lisp', ('common-lisp', 'cl', 'lisp'), ('*.cl', '*.lisp'), ('text/x-common-lisp',)),\n    'ComponentPascalLexer': ('pip._vendor.pygments.lexers.oberon', 'Component Pascal', ('componentpascal', 'cp'), ('*.cp', '*.cps'), ('text/x-component-pascal',)),\n    'CoqLexer': ('pip._vendor.pygments.lexers.theorem', 'Coq', ('coq',), ('*.v',), ('text/x-coq',)),\n    'CplintLexer': ('pip._vendor.pygments.lexers.cplint', 'cplint', ('cplint',), ('*.ecl', '*.prolog', '*.pro', '*.pl', '*.P', '*.lpad', '*.cpl'), ('text/x-cplint',)),\n    'CppLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C++', ('cpp', 'c++'), ('*.cpp', '*.hpp', '*.c++', '*.h++', '*.cc', '*.hh', '*.cxx', '*.hxx', '*.C', '*.H', '*.cp', '*.CPP', '*.tpp'), ('text/x-c++hdr', 'text/x-c++src')),\n    'CppObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'cpp-objdump', ('cpp-objdump', 'c++-objdumb', 'cxx-objdump'), ('*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'), ('text/x-cpp-objdump',)),\n    'CrmshLexer': ('pip._vendor.pygments.lexers.dsls', 'Crmsh', ('crmsh', 'pcmk'), ('*.crmsh', '*.pcmk'), ()),\n    'CrocLexer': ('pip._vendor.pygments.lexers.d', 'Croc', ('croc',), ('*.croc',), ('text/x-crocsrc',)),\n    'CryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Cryptol', ('cryptol', 'cry'), ('*.cry',), ('text/x-cryptol',)),\n    'CrystalLexer': ('pip._vendor.pygments.lexers.crystal', 'Crystal', ('cr', 'crystal'), ('*.cr',), ('text/x-crystal',)),\n    'CsoundDocumentLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Document', ('csound-document', 'csound-csd'), ('*.csd',), ()),\n    'CsoundOrchestraLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Orchestra', ('csound', 'csound-orc'), ('*.orc', '*.udo'), ()),\n    'CsoundScoreLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Score', ('csound-score', 'csound-sco'), ('*.sco',), ()),\n    'CssDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Django/Jinja', ('css+django', 'css+jinja'), ('*.css.j2', '*.css.jinja2'), ('text/css+django', 'text/css+jinja')),\n    'CssErbLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Ruby', ('css+ruby', 'css+erb'), (), ('text/css+ruby',)),\n    'CssGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Genshi Text', ('css+genshitext', 'css+genshi'), (), ('text/css+genshi',)),\n    'CssLexer': ('pip._vendor.pygments.lexers.css', 'CSS', ('css',), ('*.css',), ('text/css',)),\n    'CssPhpLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+PHP', ('css+php',), (), ('text/css+php',)),\n    'CssSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Smarty', ('css+smarty',), (), ('text/css+smarty',)),\n    'CudaLexer': ('pip._vendor.pygments.lexers.c_like', 'CUDA', ('cuda', 'cu'), ('*.cu', '*.cuh'), ('text/x-cuda',)),\n    'CypherLexer': ('pip._vendor.pygments.lexers.graph', 'Cypher', ('cypher',), ('*.cyp', '*.cypher'), ()),\n    'CythonLexer': ('pip._vendor.pygments.lexers.python', 'Cython', ('cython', 'pyx', 'pyrex'), ('*.pyx', '*.pxd', '*.pxi'), ('text/x-cython', 'application/x-cython')),\n    'DLexer': ('pip._vendor.pygments.lexers.d', 'D', ('d',), ('*.d', '*.di'), ('text/x-dsrc',)),\n    'DObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'd-objdump', ('d-objdump',), ('*.d-objdump',), ('text/x-d-objdump',)),\n    'DarcsPatchLexer': ('pip._vendor.pygments.lexers.diff', 'Darcs Patch', ('dpatch',), ('*.dpatch', '*.darcspatch'), ()),\n    'DartLexer': ('pip._vendor.pygments.lexers.javascript', 'Dart', ('dart',), ('*.dart',), ('text/x-dart',)),\n    'Dasm16Lexer': ('pip._vendor.pygments.lexers.asm', 'DASM16', ('dasm16',), ('*.dasm16', '*.dasm'), ('text/x-dasm16',)),\n    'DaxLexer': ('pip._vendor.pygments.lexers.dax', 'Dax', ('dax',), ('*.dax',), ()),\n    'DebianControlLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Control file', ('debcontrol', 'control'), ('control',), ()),\n    'DebianSourcesLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Sources file', ('debian.sources',), ('*.sources',), ()),\n    'DelphiLexer': ('pip._vendor.pygments.lexers.pascal', 'Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas', '*.dpr'), ('text/x-pascal',)),\n    'DesktopLexer': ('pip._vendor.pygments.lexers.configs', 'Desktop file', ('desktop',), ('*.desktop',), ('application/x-desktop',)),\n    'DevicetreeLexer': ('pip._vendor.pygments.lexers.devicetree', 'Devicetree', ('devicetree', 'dts'), ('*.dts', '*.dtsi'), ('text/x-c',)),\n    'DgLexer': ('pip._vendor.pygments.lexers.python', 'dg', ('dg',), ('*.dg',), ('text/x-dg',)),\n    'DiffLexer': ('pip._vendor.pygments.lexers.diff', 'Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')),\n    'DjangoLexer': ('pip._vendor.pygments.lexers.templates', 'Django/Jinja', ('django', 'jinja'), (), ('application/x-django-templating', 'application/x-jinja')),\n    'DnsZoneLexer': ('pip._vendor.pygments.lexers.dns', 'Zone', ('zone',), ('*.zone',), ('text/dns',)),\n    'DockerLexer': ('pip._vendor.pygments.lexers.configs', 'Docker', ('docker', 'dockerfile'), ('Dockerfile', '*.docker'), ('text/x-dockerfile-config',)),\n    'DtdLexer': ('pip._vendor.pygments.lexers.html', 'DTD', ('dtd',), ('*.dtd',), ('application/xml-dtd',)),\n    'DuelLexer': ('pip._vendor.pygments.lexers.webmisc', 'Duel', ('duel', 'jbst', 'jsonml+bst'), ('*.duel', '*.jbst'), ('text/x-duel', 'text/x-jbst')),\n    'DylanConsoleLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan session', ('dylan-console', 'dylan-repl'), ('*.dylan-console',), ('text/x-dylan-console',)),\n    'DylanLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan', ('dylan',), ('*.dylan', '*.dyl', '*.intr'), ('text/x-dylan',)),\n    'DylanLidLexer': ('pip._vendor.pygments.lexers.dylan', 'DylanLID', ('dylan-lid', 'lid'), ('*.lid', '*.hdp'), ('text/x-dylan-lid',)),\n    'ECLLexer': ('pip._vendor.pygments.lexers.ecl', 'ECL', ('ecl',), ('*.ecl',), ('application/x-ecl',)),\n    'ECLexer': ('pip._vendor.pygments.lexers.c_like', 'eC', ('ec',), ('*.ec', '*.eh'), ('text/x-echdr', 'text/x-ecsrc')),\n    'EarlGreyLexer': ('pip._vendor.pygments.lexers.javascript', 'Earl Grey', ('earl-grey', 'earlgrey', 'eg'), ('*.eg',), ('text/x-earl-grey',)),\n    'EasytrieveLexer': ('pip._vendor.pygments.lexers.scripting', 'Easytrieve', ('easytrieve',), ('*.ezt', '*.mac'), ('text/x-easytrieve',)),\n    'EbnfLexer': ('pip._vendor.pygments.lexers.parsers', 'EBNF', ('ebnf',), ('*.ebnf',), ('text/x-ebnf',)),\n    'EiffelLexer': ('pip._vendor.pygments.lexers.eiffel', 'Eiffel', ('eiffel',), ('*.e',), ('text/x-eiffel',)),\n    'ElixirConsoleLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir iex session', ('iex',), (), ('text/x-elixir-shellsession',)),\n    'ElixirLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir', ('elixir', 'ex', 'exs'), ('*.ex', '*.eex', '*.exs', '*.leex'), ('text/x-elixir',)),\n    'ElmLexer': ('pip._vendor.pygments.lexers.elm', 'Elm', ('elm',), ('*.elm',), ('text/x-elm',)),\n    'ElpiLexer': ('pip._vendor.pygments.lexers.elpi', 'Elpi', ('elpi',), ('*.elpi',), ('text/x-elpi',)),\n    'EmacsLispLexer': ('pip._vendor.pygments.lexers.lisp', 'EmacsLisp', ('emacs-lisp', 'elisp', 'emacs'), ('*.el',), ('text/x-elisp', 'application/x-elisp')),\n    'EmailLexer': ('pip._vendor.pygments.lexers.email', 'E-mail', ('email', 'eml'), ('*.eml',), ('message/rfc822',)),\n    'ErbLexer': ('pip._vendor.pygments.lexers.templates', 'ERB', ('erb',), (), ('application/x-ruby-templating',)),\n    'ErlangLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang', ('erlang',), ('*.erl', '*.hrl', '*.es', '*.escript'), ('text/x-erlang',)),\n    'ErlangShellLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang erl session', ('erl',), ('*.erl-sh',), ('text/x-erl-shellsession',)),\n    'EvoqueHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Evoque', ('html+evoque',), (), ('text/html+evoque',)),\n    'EvoqueLexer': ('pip._vendor.pygments.lexers.templates', 'Evoque', ('evoque',), ('*.evoque',), ('application/x-evoque',)),\n    'EvoqueXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Evoque', ('xml+evoque',), (), ('application/xml+evoque',)),\n    'ExeclineLexer': ('pip._vendor.pygments.lexers.shell', 'execline', ('execline',), ('*.exec',), ()),\n    'EzhilLexer': ('pip._vendor.pygments.lexers.ezhil', 'Ezhil', ('ezhil',), ('*.n',), ('text/x-ezhil',)),\n    'FSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'F#', ('fsharp', 'f#'), ('*.fs', '*.fsi', '*.fsx'), ('text/x-fsharp',)),\n    'FStarLexer': ('pip._vendor.pygments.lexers.ml', 'FStar', ('fstar',), ('*.fst', '*.fsti'), ('text/x-fstar',)),\n    'FactorLexer': ('pip._vendor.pygments.lexers.factor', 'Factor', ('factor',), ('*.factor',), ('text/x-factor',)),\n    'FancyLexer': ('pip._vendor.pygments.lexers.ruby', 'Fancy', ('fancy', 'fy'), ('*.fy', '*.fancypack'), ('text/x-fancysrc',)),\n    'FantomLexer': ('pip._vendor.pygments.lexers.fantom', 'Fantom', ('fan',), ('*.fan',), ('application/x-fantom',)),\n    'FelixLexer': ('pip._vendor.pygments.lexers.felix', 'Felix', ('felix', 'flx'), ('*.flx', '*.flxh'), ('text/x-felix',)),\n    'FennelLexer': ('pip._vendor.pygments.lexers.lisp', 'Fennel', ('fennel', 'fnl'), ('*.fnl',), ()),\n    'FiftLexer': ('pip._vendor.pygments.lexers.fift', 'Fift', ('fift', 'fif'), ('*.fif',), ()),\n    'FishShellLexer': ('pip._vendor.pygments.lexers.shell', 'Fish', ('fish', 'fishshell'), ('*.fish', '*.load'), ('application/x-fish',)),\n    'FlatlineLexer': ('pip._vendor.pygments.lexers.dsls', 'Flatline', ('flatline',), (), ('text/x-flatline',)),\n    'FloScriptLexer': ('pip._vendor.pygments.lexers.floscript', 'FloScript', ('floscript', 'flo'), ('*.flo',), ()),\n    'ForthLexer': ('pip._vendor.pygments.lexers.forth', 'Forth', ('forth',), ('*.frt', '*.fs'), ('application/x-forth',)),\n    'FortranFixedLexer': ('pip._vendor.pygments.lexers.fortran', 'FortranFixed', ('fortranfixed',), ('*.f', '*.F'), ()),\n    'FortranLexer': ('pip._vendor.pygments.lexers.fortran', 'Fortran', ('fortran', 'f90'), ('*.f03', '*.f90', '*.F03', '*.F90'), ('text/x-fortran',)),\n    'FoxProLexer': ('pip._vendor.pygments.lexers.foxpro', 'FoxPro', ('foxpro', 'vfp', 'clipper', 'xbase'), ('*.PRG', '*.prg'), ()),\n    'FreeFemLexer': ('pip._vendor.pygments.lexers.freefem', 'Freefem', ('freefem',), ('*.edp',), ('text/x-freefem',)),\n    'FuncLexer': ('pip._vendor.pygments.lexers.func', 'FunC', ('func', 'fc'), ('*.fc', '*.func'), ()),\n    'FutharkLexer': ('pip._vendor.pygments.lexers.futhark', 'Futhark', ('futhark',), ('*.fut',), ('text/x-futhark',)),\n    'GAPConsoleLexer': ('pip._vendor.pygments.lexers.algebra', 'GAP session', ('gap-console', 'gap-repl'), ('*.tst',), ()),\n    'GAPLexer': ('pip._vendor.pygments.lexers.algebra', 'GAP', ('gap',), ('*.g', '*.gd', '*.gi', '*.gap'), ()),\n    'GDScriptLexer': ('pip._vendor.pygments.lexers.gdscript', 'GDScript', ('gdscript', 'gd'), ('*.gd',), ('text/x-gdscript', 'application/x-gdscript')),\n    'GLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'GLSL', ('glsl',), ('*.vert', '*.frag', '*.geo'), ('text/x-glslsrc',)),\n    'GSQLLexer': ('pip._vendor.pygments.lexers.gsql', 'GSQL', ('gsql',), ('*.gsql',), ()),\n    'GasLexer': ('pip._vendor.pygments.lexers.asm', 'GAS', ('gas', 'asm'), ('*.s', '*.S'), ('text/x-gas',)),\n    'GcodeLexer': ('pip._vendor.pygments.lexers.gcodelexer', 'g-code', ('gcode',), ('*.gcode',), ()),\n    'GenshiLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi', ('genshi', 'kid', 'xml+genshi', 'xml+kid'), ('*.kid',), ('application/x-genshi', 'application/x-kid')),\n    'GenshiTextLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi Text', ('genshitext',), (), ('application/x-genshi-text', 'text/x-genshi')),\n    'GettextLexer': ('pip._vendor.pygments.lexers.textfmts', 'Gettext Catalog', ('pot', 'po'), ('*.pot', '*.po'), ('application/x-gettext', 'text/x-gettext', 'text/gettext')),\n    'GherkinLexer': ('pip._vendor.pygments.lexers.testing', 'Gherkin', ('gherkin', 'cucumber'), ('*.feature',), ('text/x-gherkin',)),\n    'GleamLexer': ('pip._vendor.pygments.lexers.gleam', 'Gleam', ('gleam',), ('*.gleam',), ('text/x-gleam',)),\n    'GnuplotLexer': ('pip._vendor.pygments.lexers.graphics', 'Gnuplot', ('gnuplot',), ('*.plot', '*.plt'), ('text/x-gnuplot',)),\n    'GoLexer': ('pip._vendor.pygments.lexers.go', 'Go', ('go', 'golang'), ('*.go',), ('text/x-gosrc',)),\n    'GoloLexer': ('pip._vendor.pygments.lexers.jvm', 'Golo', ('golo',), ('*.golo',), ()),\n    'GoodDataCLLexer': ('pip._vendor.pygments.lexers.business', 'GoodData-CL', ('gooddata-cl',), ('*.gdc',), ('text/x-gooddata-cl',)),\n    'GoogleSqlLexer': ('pip._vendor.pygments.lexers.sql', 'GoogleSQL', ('googlesql', 'zetasql'), ('*.googlesql', '*.googlesql.sql'), ('text/x-google-sql', 'text/x-google-sql-aux')),\n    'GosuLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu', ('gosu',), ('*.gs', '*.gsx', '*.gsp', '*.vark'), ('text/x-gosu',)),\n    'GosuTemplateLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu Template', ('gst',), ('*.gst',), ('text/x-gosu-template',)),\n    'GraphQLLexer': ('pip._vendor.pygments.lexers.graphql', 'GraphQL', ('graphql',), ('*.graphql',), ()),\n    'GraphvizLexer': ('pip._vendor.pygments.lexers.graphviz', 'Graphviz', ('graphviz', 'dot'), ('*.gv', '*.dot'), ('text/x-graphviz', 'text/vnd.graphviz')),\n    'GroffLexer': ('pip._vendor.pygments.lexers.markup', 'Groff', ('groff', 'nroff', 'man'), ('*.[1-9]', '*.man', '*.1p', '*.3pm'), ('application/x-troff', 'text/troff')),\n    'GroovyLexer': ('pip._vendor.pygments.lexers.jvm', 'Groovy', ('groovy',), ('*.groovy', '*.gradle'), ('text/x-groovy',)),\n    'HLSLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'HLSL', ('hlsl',), ('*.hlsl', '*.hlsli'), ('text/x-hlsl',)),\n    'HTMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'HTML+UL4', ('html+ul4',), ('*.htmlul4',), ()),\n    'HamlLexer': ('pip._vendor.pygments.lexers.html', 'Haml', ('haml',), ('*.haml',), ('text/x-haml',)),\n    'HandlebarsHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Handlebars', ('html+handlebars',), ('*.handlebars', '*.hbs'), ('text/html+handlebars', 'text/x-handlebars-template')),\n    'HandlebarsLexer': ('pip._vendor.pygments.lexers.templates', 'Handlebars', ('handlebars',), (), ()),\n    'HareLexer': ('pip._vendor.pygments.lexers.hare', 'Hare', ('hare',), ('*.ha',), ('text/x-hare',)),\n    'HaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Haskell', ('haskell', 'hs'), ('*.hs',), ('text/x-haskell',)),\n    'HaxeLexer': ('pip._vendor.pygments.lexers.haxe', 'Haxe', ('haxe', 'hxsl', 'hx'), ('*.hx', '*.hxsl'), ('text/haxe', 'text/x-haxe', 'text/x-hx')),\n    'HexdumpLexer': ('pip._vendor.pygments.lexers.hexdump', 'Hexdump', ('hexdump',), (), ()),\n    'HsailLexer': ('pip._vendor.pygments.lexers.asm', 'HSAIL', ('hsail', 'hsa'), ('*.hsail',), ('text/x-hsail',)),\n    'HspecLexer': ('pip._vendor.pygments.lexers.haskell', 'Hspec', ('hspec',), ('*Spec.hs',), ()),\n    'HtmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Django/Jinja', ('html+django', 'html+jinja', 'htmldjango'), ('*.html.j2', '*.htm.j2', '*.xhtml.j2', '*.html.jinja2', '*.htm.jinja2', '*.xhtml.jinja2'), ('text/html+django', 'text/html+jinja')),\n    'HtmlGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Genshi', ('html+genshi', 'html+kid'), (), ('text/html+genshi',)),\n    'HtmlLexer': ('pip._vendor.pygments.lexers.html', 'HTML', ('html',), ('*.html', '*.htm', '*.xhtml', '*.xslt'), ('text/html', 'application/xhtml+xml')),\n    'HtmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+PHP', ('html+php',), ('*.phtml',), ('application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5')),\n    'HtmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Smarty', ('html+smarty',), (), ('text/html+smarty',)),\n    'HttpLexer': ('pip._vendor.pygments.lexers.textfmts', 'HTTP', ('http',), (), ()),\n    'HxmlLexer': ('pip._vendor.pygments.lexers.haxe', 'Hxml', ('haxeml', 'hxml'), ('*.hxml',), ()),\n    'HyLexer': ('pip._vendor.pygments.lexers.lisp', 'Hy', ('hylang', 'hy'), ('*.hy',), ('text/x-hy', 'application/x-hy')),\n    'HybrisLexer': ('pip._vendor.pygments.lexers.scripting', 'Hybris', ('hybris',), ('*.hyb',), ('text/x-hybris', 'application/x-hybris')),\n    'IDLLexer': ('pip._vendor.pygments.lexers.idl', 'IDL', ('idl',), ('*.pro',), ('text/idl',)),\n    'IconLexer': ('pip._vendor.pygments.lexers.unicon', 'Icon', ('icon',), ('*.icon', '*.ICON'), ()),\n    'IdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Idris', ('idris', 'idr'), ('*.idr',), ('text/x-idris',)),\n    'IgorLexer': ('pip._vendor.pygments.lexers.igor', 'Igor', ('igor', 'igorpro'), ('*.ipf',), ('text/ipf',)),\n    'Inform6Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6', ('inform6', 'i6'), ('*.inf',), ()),\n    'Inform6TemplateLexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6 template', ('i6t',), ('*.i6t',), ()),\n    'Inform7Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 7', ('inform7', 'i7'), ('*.ni', '*.i7x'), ()),\n    'IniLexer': ('pip._vendor.pygments.lexers.configs', 'INI', ('ini', 'cfg', 'dosini'), ('*.ini', '*.cfg', '*.inf', '.editorconfig'), ('text/x-ini', 'text/inf')),\n    'IoLexer': ('pip._vendor.pygments.lexers.iolang', 'Io', ('io',), ('*.io',), ('text/x-iosrc',)),\n    'IokeLexer': ('pip._vendor.pygments.lexers.jvm', 'Ioke', ('ioke', 'ik'), ('*.ik',), ('text/x-iokesrc',)),\n    'IrcLogsLexer': ('pip._vendor.pygments.lexers.textfmts', 'IRC logs', ('irc',), ('*.weechatlog',), ('text/x-irclog',)),\n    'IsabelleLexer': ('pip._vendor.pygments.lexers.theorem', 'Isabelle', ('isabelle',), ('*.thy',), ('text/x-isabelle',)),\n    'JLexer': ('pip._vendor.pygments.lexers.j', 'J', ('j',), ('*.ijs',), ('text/x-j',)),\n    'JMESPathLexer': ('pip._vendor.pygments.lexers.jmespath', 'JMESPath', ('jmespath', 'jp'), ('*.jp',), ()),\n    'JSLTLexer': ('pip._vendor.pygments.lexers.jslt', 'JSLT', ('jslt',), ('*.jslt',), ('text/x-jslt',)),\n    'JagsLexer': ('pip._vendor.pygments.lexers.modeling', 'JAGS', ('jags',), ('*.jag', '*.bug'), ()),\n    'JanetLexer': ('pip._vendor.pygments.lexers.lisp', 'Janet', ('janet',), ('*.janet', '*.jdn'), ('text/x-janet', 'application/x-janet')),\n    'JasminLexer': ('pip._vendor.pygments.lexers.jvm', 'Jasmin', ('jasmin', 'jasminxt'), ('*.j',), ()),\n    'JavaLexer': ('pip._vendor.pygments.lexers.jvm', 'Java', ('java',), ('*.java',), ('text/x-java',)),\n    'JavascriptDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Django/Jinja', ('javascript+django', 'js+django', 'javascript+jinja', 'js+jinja'), ('*.js.j2', '*.js.jinja2'), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')),\n    'JavascriptErbLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Ruby', ('javascript+ruby', 'js+ruby', 'javascript+erb', 'js+erb'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')),\n    'JavascriptGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')),\n    'JavascriptLexer': ('pip._vendor.pygments.lexers.javascript', 'JavaScript', ('javascript', 'js'), ('*.js', '*.jsm', '*.mjs', '*.cjs'), ('application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript')),\n    'JavascriptPhpLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+PHP', ('javascript+php', 'js+php'), (), ('application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php')),\n    'JavascriptSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Smarty', ('javascript+smarty', 'js+smarty'), (), ('application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty')),\n    'JavascriptUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Javascript+UL4', ('js+ul4',), ('*.jsul4',), ()),\n    'JclLexer': ('pip._vendor.pygments.lexers.scripting', 'JCL', ('jcl',), ('*.jcl',), ('text/x-jcl',)),\n    'JsgfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'JSGF', ('jsgf',), ('*.jsgf',), ('application/jsgf', 'application/x-jsgf', 'text/jsgf')),\n    'Json5Lexer': ('pip._vendor.pygments.lexers.json5', 'JSON5', ('json5',), ('*.json5',), ()),\n    'JsonBareObjectLexer': ('pip._vendor.pygments.lexers.data', 'JSONBareObject', (), (), ()),\n    'JsonLdLexer': ('pip._vendor.pygments.lexers.data', 'JSON-LD', ('jsonld', 'json-ld'), ('*.jsonld',), ('application/ld+json',)),\n    'JsonLexer': ('pip._vendor.pygments.lexers.data', 'JSON', ('json', 'json-object'), ('*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock'), ('application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq')),\n    'JsonnetLexer': ('pip._vendor.pygments.lexers.jsonnet', 'Jsonnet', ('jsonnet',), ('*.jsonnet', '*.libsonnet'), ()),\n    'JspLexer': ('pip._vendor.pygments.lexers.templates', 'Java Server Page', ('jsp',), ('*.jsp',), ('application/x-jsp',)),\n    'JsxLexer': ('pip._vendor.pygments.lexers.jsx', 'JSX', ('jsx', 'react'), ('*.jsx', '*.react'), ('text/jsx', 'text/typescript-jsx')),\n    'JuliaConsoleLexer': ('pip._vendor.pygments.lexers.julia', 'Julia console', ('jlcon', 'julia-repl'), (), ()),\n    'JuliaLexer': ('pip._vendor.pygments.lexers.julia', 'Julia', ('julia', 'jl'), ('*.jl',), ('text/x-julia', 'application/x-julia')),\n    'JuttleLexer': ('pip._vendor.pygments.lexers.javascript', 'Juttle', ('juttle',), ('*.juttle',), ('application/juttle', 'application/x-juttle', 'text/x-juttle', 'text/juttle')),\n    'KLexer': ('pip._vendor.pygments.lexers.q', 'K', ('k',), ('*.k',), ()),\n    'KalLexer': ('pip._vendor.pygments.lexers.javascript', 'Kal', ('kal',), ('*.kal',), ('text/kal', 'application/kal')),\n    'KconfigLexer': ('pip._vendor.pygments.lexers.configs', 'Kconfig', ('kconfig', 'menuconfig', 'linux-config', 'kernel-config'), ('Kconfig*', '*Config.in*', 'external.in*', 'standard-modules.in'), ('text/x-kconfig',)),\n    'KernelLogLexer': ('pip._vendor.pygments.lexers.textfmts', 'Kernel log', ('kmsg', 'dmesg'), ('*.kmsg', '*.dmesg'), ()),\n    'KokaLexer': ('pip._vendor.pygments.lexers.haskell', 'Koka', ('koka',), ('*.kk', '*.kki'), ('text/x-koka',)),\n    'KotlinLexer': ('pip._vendor.pygments.lexers.jvm', 'Kotlin', ('kotlin',), ('*.kt', '*.kts'), ('text/x-kotlin',)),\n    'KuinLexer': ('pip._vendor.pygments.lexers.kuin', 'Kuin', ('kuin',), ('*.kn',), ()),\n    'KustoLexer': ('pip._vendor.pygments.lexers.kusto', 'Kusto', ('kql', 'kusto'), ('*.kql', '*.kusto', '.csl'), ()),\n    'LSLLexer': ('pip._vendor.pygments.lexers.scripting', 'LSL', ('lsl',), ('*.lsl',), ('text/x-lsl',)),\n    'LassoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Lasso', ('css+lasso',), (), ('text/css+lasso',)),\n    'LassoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Lasso', ('html+lasso',), (), ('text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]')),\n    'LassoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Lasso', ('javascript+lasso', 'js+lasso'), (), ('application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso')),\n    'LassoLexer': ('pip._vendor.pygments.lexers.javascript', 'Lasso', ('lasso', 'lassoscript'), ('*.lasso', '*.lasso[89]'), ('text/x-lasso',)),\n    'LassoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Lasso', ('xml+lasso',), (), ('application/xml+lasso',)),\n    'LdaprcLexer': ('pip._vendor.pygments.lexers.ldap', 'LDAP configuration file', ('ldapconf', 'ldaprc'), ('.ldaprc', 'ldaprc', 'ldap.conf'), ('text/x-ldapconf',)),\n    'LdifLexer': ('pip._vendor.pygments.lexers.ldap', 'LDIF', ('ldif',), ('*.ldif',), ('text/x-ldif',)),\n    'Lean3Lexer': ('pip._vendor.pygments.lexers.lean', 'Lean', ('lean', 'lean3'), ('*.lean',), ('text/x-lean', 'text/x-lean3')),\n    'Lean4Lexer': ('pip._vendor.pygments.lexers.lean', 'Lean4', ('lean4',), ('*.lean',), ('text/x-lean4',)),\n    'LessCssLexer': ('pip._vendor.pygments.lexers.css', 'LessCss', ('less',), ('*.less',), ('text/x-less-css',)),\n    'LighttpdConfLexer': ('pip._vendor.pygments.lexers.configs', 'Lighttpd configuration file', ('lighttpd', 'lighty'), ('lighttpd.conf',), ('text/x-lighttpd-conf',)),\n    'LilyPondLexer': ('pip._vendor.pygments.lexers.lilypond', 'LilyPond', ('lilypond',), ('*.ly',), ()),\n    'LimboLexer': ('pip._vendor.pygments.lexers.inferno', 'Limbo', ('limbo',), ('*.b',), ('text/limbo',)),\n    'LiquidLexer': ('pip._vendor.pygments.lexers.templates', 'liquid', ('liquid',), ('*.liquid',), ()),\n    'LiterateAgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Agda', ('literate-agda', 'lagda'), ('*.lagda',), ('text/x-literate-agda',)),\n    'LiterateCryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Cryptol', ('literate-cryptol', 'lcryptol', 'lcry'), ('*.lcry',), ('text/x-literate-cryptol',)),\n    'LiterateHaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Haskell', ('literate-haskell', 'lhaskell', 'lhs'), ('*.lhs',), ('text/x-literate-haskell',)),\n    'LiterateIdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Idris', ('literate-idris', 'lidris', 'lidr'), ('*.lidr',), ('text/x-literate-idris',)),\n    'LiveScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'LiveScript', ('livescript', 'live-script'), ('*.ls',), ('text/livescript',)),\n    'LlvmLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM', ('llvm',), ('*.ll',), ('text/x-llvm',)),\n    'LlvmMirBodyLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR Body', ('llvm-mir-body',), (), ()),\n    'LlvmMirLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR', ('llvm-mir',), ('*.mir',), ()),\n    'LogosLexer': ('pip._vendor.pygments.lexers.objective', 'Logos', ('logos',), ('*.x', '*.xi', '*.xm', '*.xmi'), ('text/x-logos',)),\n    'LogtalkLexer': ('pip._vendor.pygments.lexers.prolog', 'Logtalk', ('logtalk',), ('*.lgt', '*.logtalk'), ('text/x-logtalk',)),\n    'LuaLexer': ('pip._vendor.pygments.lexers.scripting', 'Lua', ('lua',), ('*.lua', '*.wlua'), ('text/x-lua', 'application/x-lua')),\n    'LuauLexer': ('pip._vendor.pygments.lexers.scripting', 'Luau', ('luau',), ('*.luau',), ()),\n    'MCFunctionLexer': ('pip._vendor.pygments.lexers.minecraft', 'MCFunction', ('mcfunction', 'mcf'), ('*.mcfunction',), ('text/mcfunction',)),\n    'MCSchemaLexer': ('pip._vendor.pygments.lexers.minecraft', 'MCSchema', ('mcschema',), ('*.mcschema',), ('text/mcschema',)),\n    'MIMELexer': ('pip._vendor.pygments.lexers.mime', 'MIME', ('mime',), (), ('multipart/mixed', 'multipart/related', 'multipart/alternative')),\n    'MIPSLexer': ('pip._vendor.pygments.lexers.mips', 'MIPS', ('mips',), ('*.mips', '*.MIPS'), ()),\n    'MOOCodeLexer': ('pip._vendor.pygments.lexers.scripting', 'MOOCode', ('moocode', 'moo'), ('*.moo',), ('text/x-moocode',)),\n    'MSDOSSessionLexer': ('pip._vendor.pygments.lexers.shell', 'MSDOS Session', ('doscon',), (), ()),\n    'Macaulay2Lexer': ('pip._vendor.pygments.lexers.macaulay2', 'Macaulay2', ('macaulay2',), ('*.m2',), ()),\n    'MakefileLexer': ('pip._vendor.pygments.lexers.make', 'Makefile', ('make', 'makefile', 'mf', 'bsdmake'), ('*.mak', '*.mk', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'), ('text/x-makefile',)),\n    'MakoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Mako', ('css+mako',), (), ('text/css+mako',)),\n    'MakoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Mako', ('html+mako',), (), ('text/html+mako',)),\n    'MakoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Mako', ('javascript+mako', 'js+mako'), (), ('application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako')),\n    'MakoLexer': ('pip._vendor.pygments.lexers.templates', 'Mako', ('mako',), ('*.mao',), ('application/x-mako',)),\n    'MakoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Mako', ('xml+mako',), (), ('application/xml+mako',)),\n    'MapleLexer': ('pip._vendor.pygments.lexers.maple', 'Maple', ('maple',), ('*.mpl', '*.mi', '*.mm'), ('text/x-maple',)),\n    'MaqlLexer': ('pip._vendor.pygments.lexers.business', 'MAQL', ('maql',), ('*.maql',), ('text/x-gooddata-maql', 'application/x-gooddata-maql')),\n    'MarkdownLexer': ('pip._vendor.pygments.lexers.markup', 'Markdown', ('markdown', 'md'), ('*.md', '*.markdown'), ('text/x-markdown',)),\n    'MaskLexer': ('pip._vendor.pygments.lexers.javascript', 'Mask', ('mask',), ('*.mask',), ('text/x-mask',)),\n    'MasonLexer': ('pip._vendor.pygments.lexers.templates', 'Mason', ('mason',), ('*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'), ('application/x-mason',)),\n    'MathematicaLexer': ('pip._vendor.pygments.lexers.algebra', 'Mathematica', ('mathematica', 'mma', 'nb'), ('*.nb', '*.cdf', '*.nbp', '*.ma'), ('application/mathematica', 'application/vnd.wolfram.mathematica', 'application/vnd.wolfram.mathematica.package', 'application/vnd.wolfram.cdf')),\n    'MatlabLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab', ('matlab',), ('*.m',), ('text/matlab',)),\n    'MatlabSessionLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab session', ('matlabsession',), (), ()),\n    'MaximaLexer': ('pip._vendor.pygments.lexers.maxima', 'Maxima', ('maxima', 'macsyma'), ('*.mac', '*.max'), ()),\n    'MesonLexer': ('pip._vendor.pygments.lexers.meson', 'Meson', ('meson', 'meson.build'), ('meson.build', 'meson_options.txt'), ('text/x-meson',)),\n    'MiniDLexer': ('pip._vendor.pygments.lexers.d', 'MiniD', ('minid',), (), ('text/x-minidsrc',)),\n    'MiniScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MiniScript', ('miniscript', 'ms'), ('*.ms',), ('text/x-minicript', 'application/x-miniscript')),\n    'ModelicaLexer': ('pip._vendor.pygments.lexers.modeling', 'Modelica', ('modelica',), ('*.mo',), ('text/x-modelica',)),\n    'Modula2Lexer': ('pip._vendor.pygments.lexers.modula2', 'Modula-2', ('modula2', 'm2'), ('*.def', '*.mod'), ('text/x-modula2',)),\n    'MoinWikiLexer': ('pip._vendor.pygments.lexers.markup', 'MoinMoin/Trac Wiki markup', ('trac-wiki', 'moin'), (), ('text/x-trac-wiki',)),\n    'MojoLexer': ('pip._vendor.pygments.lexers.mojo', 'Mojo', ('mojo', '🔥'), ('*.mojo', '*.🔥'), ('text/x-mojo', 'application/x-mojo')),\n    'MonkeyLexer': ('pip._vendor.pygments.lexers.basic', 'Monkey', ('monkey',), ('*.monkey',), ('text/x-monkey',)),\n    'MonteLexer': ('pip._vendor.pygments.lexers.monte', 'Monte', ('monte',), ('*.mt',), ()),\n    'MoonScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MoonScript', ('moonscript', 'moon'), ('*.moon',), ('text/x-moonscript', 'application/x-moonscript')),\n    'MoselLexer': ('pip._vendor.pygments.lexers.mosel', 'Mosel', ('mosel',), ('*.mos',), ()),\n    'MozPreprocCssLexer': ('pip._vendor.pygments.lexers.markup', 'CSS+mozpreproc', ('css+mozpreproc',), ('*.css.in',), ()),\n    'MozPreprocHashLexer': ('pip._vendor.pygments.lexers.markup', 'mozhashpreproc', ('mozhashpreproc',), (), ()),\n    'MozPreprocJavascriptLexer': ('pip._vendor.pygments.lexers.markup', 'Javascript+mozpreproc', ('javascript+mozpreproc',), ('*.js.in',), ()),\n    'MozPreprocPercentLexer': ('pip._vendor.pygments.lexers.markup', 'mozpercentpreproc', ('mozpercentpreproc',), (), ()),\n    'MozPreprocXulLexer': ('pip._vendor.pygments.lexers.markup', 'XUL+mozpreproc', ('xul+mozpreproc',), ('*.xul.in',), ()),\n    'MqlLexer': ('pip._vendor.pygments.lexers.c_like', 'MQL', ('mql', 'mq4', 'mq5', 'mql4', 'mql5'), ('*.mq4', '*.mq5', '*.mqh'), ('text/x-mql',)),\n    'MscgenLexer': ('pip._vendor.pygments.lexers.dsls', 'Mscgen', ('mscgen', 'msc'), ('*.msc',), ()),\n    'MuPADLexer': ('pip._vendor.pygments.lexers.algebra', 'MuPAD', ('mupad',), ('*.mu',), ()),\n    'MxmlLexer': ('pip._vendor.pygments.lexers.actionscript', 'MXML', ('mxml',), ('*.mxml',), ()),\n    'MySqlLexer': ('pip._vendor.pygments.lexers.sql', 'MySQL', ('mysql',), (), ('text/x-mysql',)),\n    'MyghtyCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Myghty', ('css+myghty',), (), ('text/css+myghty',)),\n    'MyghtyHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Myghty', ('html+myghty',), (), ('text/html+myghty',)),\n    'MyghtyJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Myghty', ('javascript+myghty', 'js+myghty'), (), ('application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy')),\n    'MyghtyLexer': ('pip._vendor.pygments.lexers.templates', 'Myghty', ('myghty',), ('*.myt', 'autodelegate'), ('application/x-myghty',)),\n    'MyghtyXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Myghty', ('xml+myghty',), (), ('application/xml+myghty',)),\n    'NCLLexer': ('pip._vendor.pygments.lexers.ncl', 'NCL', ('ncl',), ('*.ncl',), ('text/ncl',)),\n    'NSISLexer': ('pip._vendor.pygments.lexers.installers', 'NSIS', ('nsis', 'nsi', 'nsh'), ('*.nsi', '*.nsh'), ('text/x-nsis',)),\n    'NasmLexer': ('pip._vendor.pygments.lexers.asm', 'NASM', ('nasm',), ('*.asm', '*.ASM', '*.nasm'), ('text/x-nasm',)),\n    'NasmObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump-nasm', ('objdump-nasm',), ('*.objdump-intel',), ('text/x-nasm-objdump',)),\n    'NemerleLexer': ('pip._vendor.pygments.lexers.dotnet', 'Nemerle', ('nemerle',), ('*.n',), ('text/x-nemerle',)),\n    'NesCLexer': ('pip._vendor.pygments.lexers.c_like', 'nesC', ('nesc',), ('*.nc',), ('text/x-nescsrc',)),\n    'NestedTextLexer': ('pip._vendor.pygments.lexers.configs', 'NestedText', ('nestedtext', 'nt'), ('*.nt',), ()),\n    'NewLispLexer': ('pip._vendor.pygments.lexers.lisp', 'NewLisp', ('newlisp',), ('*.lsp', '*.nl', '*.kif'), ('text/x-newlisp', 'application/x-newlisp')),\n    'NewspeakLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Newspeak', ('newspeak',), ('*.ns2',), ('text/x-newspeak',)),\n    'NginxConfLexer': ('pip._vendor.pygments.lexers.configs', 'Nginx configuration file', ('nginx',), ('nginx.conf',), ('text/x-nginx-conf',)),\n    'NimrodLexer': ('pip._vendor.pygments.lexers.nimrod', 'Nimrod', ('nimrod', 'nim'), ('*.nim', '*.nimrod'), ('text/x-nim',)),\n    'NitLexer': ('pip._vendor.pygments.lexers.nit', 'Nit', ('nit',), ('*.nit',), ()),\n    'NixLexer': ('pip._vendor.pygments.lexers.nix', 'Nix', ('nixos', 'nix'), ('*.nix',), ('text/x-nix',)),\n    'NodeConsoleLexer': ('pip._vendor.pygments.lexers.javascript', 'Node.js REPL console session', ('nodejsrepl',), (), ('text/x-nodejsrepl',)),\n    'NotmuchLexer': ('pip._vendor.pygments.lexers.textfmts', 'Notmuch', ('notmuch',), (), ()),\n    'NuSMVLexer': ('pip._vendor.pygments.lexers.smv', 'NuSMV', ('nusmv',), ('*.smv',), ()),\n    'NumPyLexer': ('pip._vendor.pygments.lexers.python', 'NumPy', ('numpy',), (), ()),\n    'NumbaIRLexer': ('pip._vendor.pygments.lexers.numbair', 'Numba_IR', ('numba_ir', 'numbair'), ('*.numba_ir',), ('text/x-numba_ir', 'text/x-numbair')),\n    'ObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump', ('objdump',), ('*.objdump',), ('text/x-objdump',)),\n    'ObjectiveCLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)),\n    'ObjectiveCppLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)),\n    'ObjectiveJLexer': ('pip._vendor.pygments.lexers.javascript', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)),\n    'OcamlLexer': ('pip._vendor.pygments.lexers.ml', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),\n    'OctaveLexer': ('pip._vendor.pygments.lexers.matlab', 'Octave', ('octave',), ('*.m',), ('text/octave',)),\n    'OdinLexer': ('pip._vendor.pygments.lexers.archetype', 'ODIN', ('odin',), ('*.odin',), ('text/odin',)),\n    'OmgIdlLexer': ('pip._vendor.pygments.lexers.c_like', 'OMG Interface Definition Language', ('omg-idl',), ('*.idl', '*.pidl'), ()),\n    'OocLexer': ('pip._vendor.pygments.lexers.ooc', 'Ooc', ('ooc',), ('*.ooc',), ('text/x-ooc',)),\n    'OpaLexer': ('pip._vendor.pygments.lexers.ml', 'Opa', ('opa',), ('*.opa',), ('text/x-opa',)),\n    'OpenEdgeLexer': ('pip._vendor.pygments.lexers.business', 'OpenEdge ABL', ('openedge', 'abl', 'progress'), ('*.p', '*.cls'), ('text/x-openedge', 'application/x-openedge')),\n    'OpenScadLexer': ('pip._vendor.pygments.lexers.openscad', 'OpenSCAD', ('openscad',), ('*.scad',), ('application/x-openscad',)),\n    'OrgLexer': ('pip._vendor.pygments.lexers.markup', 'Org Mode', ('org', 'orgmode', 'org-mode'), ('*.org',), ('text/org',)),\n    'OutputLexer': ('pip._vendor.pygments.lexers.special', 'Text output', ('output',), (), ()),\n    'PacmanConfLexer': ('pip._vendor.pygments.lexers.configs', 'PacmanConf', ('pacmanconf',), ('pacman.conf',), ()),\n    'PanLexer': ('pip._vendor.pygments.lexers.dsls', 'Pan', ('pan',), ('*.pan',), ()),\n    'ParaSailLexer': ('pip._vendor.pygments.lexers.parasail', 'ParaSail', ('parasail',), ('*.psi', '*.psl'), ('text/x-parasail',)),\n    'PawnLexer': ('pip._vendor.pygments.lexers.pawn', 'Pawn', ('pawn',), ('*.p', '*.pwn', '*.inc'), ('text/x-pawn',)),\n    'PddlLexer': ('pip._vendor.pygments.lexers.pddl', 'PDDL', ('pddl',), ('*.pddl',), ()),\n    'PegLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'PEG', ('peg',), ('*.peg',), ('text/x-peg',)),\n    'Perl6Lexer': ('pip._vendor.pygments.lexers.perl', 'Perl6', ('perl6', 'pl6', 'raku'), ('*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod', '*.rakutest', '*.rakudoc'), ('text/x-perl6', 'application/x-perl6')),\n    'PerlLexer': ('pip._vendor.pygments.lexers.perl', 'Perl', ('perl', 'pl'), ('*.pl', '*.pm', '*.t', '*.perl'), ('text/x-perl', 'application/x-perl')),\n    'PhixLexer': ('pip._vendor.pygments.lexers.phix', 'Phix', ('phix',), ('*.exw',), ('text/x-phix',)),\n    'PhpLexer': ('pip._vendor.pygments.lexers.php', 'PHP', ('php', 'php3', 'php4', 'php5'), ('*.php', '*.php[345]', '*.inc'), ('text/x-php',)),\n    'PigLexer': ('pip._vendor.pygments.lexers.jvm', 'Pig', ('pig',), ('*.pig',), ('text/x-pig',)),\n    'PikeLexer': ('pip._vendor.pygments.lexers.c_like', 'Pike', ('pike',), ('*.pike', '*.pmod'), ('text/x-pike',)),\n    'PkgConfigLexer': ('pip._vendor.pygments.lexers.configs', 'PkgConfig', ('pkgconfig',), ('*.pc',), ()),\n    'PlPgsqlLexer': ('pip._vendor.pygments.lexers.sql', 'PL/pgSQL', ('plpgsql',), (), ('text/x-plpgsql',)),\n    'PointlessLexer': ('pip._vendor.pygments.lexers.pointless', 'Pointless', ('pointless',), ('*.ptls',), ()),\n    'PonyLexer': ('pip._vendor.pygments.lexers.pony', 'Pony', ('pony',), ('*.pony',), ()),\n    'PortugolLexer': ('pip._vendor.pygments.lexers.pascal', 'Portugol', ('portugol',), ('*.alg', '*.portugol'), ()),\n    'PostScriptLexer': ('pip._vendor.pygments.lexers.graphics', 'PostScript', ('postscript', 'postscr'), ('*.ps', '*.eps'), ('application/postscript',)),\n    'PostgresConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL console (psql)', ('psql', 'postgresql-console', 'postgres-console'), (), ('text/x-postgresql-psql',)),\n    'PostgresExplainLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL EXPLAIN dialect', ('postgres-explain',), ('*.explain',), ('text/x-postgresql-explain',)),\n    'PostgresLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL SQL dialect', ('postgresql', 'postgres'), (), ('text/x-postgresql',)),\n    'PovrayLexer': ('pip._vendor.pygments.lexers.graphics', 'POVRay', ('pov',), ('*.pov', '*.inc'), ('text/x-povray',)),\n    'PowerShellLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell', ('powershell', 'pwsh', 'posh', 'ps1', 'psm1'), ('*.ps1', '*.psm1'), ('text/x-powershell',)),\n    'PowerShellSessionLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell Session', ('pwsh-session', 'ps1con'), (), ()),\n    'PraatLexer': ('pip._vendor.pygments.lexers.praat', 'Praat', ('praat',), ('*.praat', '*.proc', '*.psc'), ()),\n    'ProcfileLexer': ('pip._vendor.pygments.lexers.procfile', 'Procfile', ('procfile',), ('Procfile',), ()),\n    'PrologLexer': ('pip._vendor.pygments.lexers.prolog', 'Prolog', ('prolog',), ('*.ecl', '*.prolog', '*.pro', '*.pl'), ('text/x-prolog',)),\n    'PromQLLexer': ('pip._vendor.pygments.lexers.promql', 'PromQL', ('promql',), ('*.promql',), ()),\n    'PromelaLexer': ('pip._vendor.pygments.lexers.c_like', 'Promela', ('promela',), ('*.pml', '*.prom', '*.prm', '*.promela', '*.pr', '*.pm'), ('text/x-promela',)),\n    'PropertiesLexer': ('pip._vendor.pygments.lexers.configs', 'Properties', ('properties', 'jproperties'), ('*.properties',), ('text/x-java-properties',)),\n    'ProtoBufLexer': ('pip._vendor.pygments.lexers.dsls', 'Protocol Buffer', ('protobuf', 'proto'), ('*.proto',), ()),\n    'PrqlLexer': ('pip._vendor.pygments.lexers.prql', 'PRQL', ('prql',), ('*.prql',), ('application/prql', 'application/x-prql')),\n    'PsyshConsoleLexer': ('pip._vendor.pygments.lexers.php', 'PsySH console session for PHP', ('psysh',), (), ()),\n    'PtxLexer': ('pip._vendor.pygments.lexers.ptx', 'PTX', ('ptx',), ('*.ptx',), ('text/x-ptx',)),\n    'PugLexer': ('pip._vendor.pygments.lexers.html', 'Pug', ('pug', 'jade'), ('*.pug', '*.jade'), ('text/x-pug', 'text/x-jade')),\n    'PuppetLexer': ('pip._vendor.pygments.lexers.dsls', 'Puppet', ('puppet',), ('*.pp',), ()),\n    'PyPyLogLexer': ('pip._vendor.pygments.lexers.console', 'PyPy Log', ('pypylog', 'pypy'), ('*.pypylog',), ('application/x-pypylog',)),\n    'Python2Lexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x', ('python2', 'py2'), (), ('text/x-python2', 'application/x-python2')),\n    'Python2TracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x Traceback', ('py2tb',), ('*.py2tb',), ('text/x-python2-traceback',)),\n    'PythonConsoleLexer': ('pip._vendor.pygments.lexers.python', 'Python console session', ('pycon', 'python-console'), (), ('text/x-python-doctest',)),\n    'PythonLexer': ('pip._vendor.pygments.lexers.python', 'Python', ('python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi'), ('*.py', '*.pyw', '*.pyi', '*.jy', '*.sage', '*.sc', 'SConstruct', 'SConscript', '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', '*.tac'), ('text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3')),\n    'PythonTracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python Traceback', ('pytb', 'py3tb'), ('*.pytb', '*.py3tb'), ('text/x-python-traceback', 'text/x-python3-traceback')),\n    'PythonUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Python+UL4', ('py+ul4',), ('*.pyul4',), ()),\n    'QBasicLexer': ('pip._vendor.pygments.lexers.basic', 'QBasic', ('qbasic', 'basic'), ('*.BAS', '*.bas'), ('text/basic',)),\n    'QLexer': ('pip._vendor.pygments.lexers.q', 'Q', ('q',), ('*.q',), ()),\n    'QVToLexer': ('pip._vendor.pygments.lexers.qvt', 'QVTO', ('qvto', 'qvt'), ('*.qvto',), ()),\n    'QlikLexer': ('pip._vendor.pygments.lexers.qlik', 'Qlik', ('qlik', 'qlikview', 'qliksense', 'qlikscript'), ('*.qvs', '*.qvw'), ()),\n    'QmlLexer': ('pip._vendor.pygments.lexers.webmisc', 'QML', ('qml', 'qbs'), ('*.qml', '*.qbs'), ('application/x-qml', 'application/x-qt.qbs+qml')),\n    'RConsoleLexer': ('pip._vendor.pygments.lexers.r', 'RConsole', ('rconsole', 'rout'), ('*.Rout',), ()),\n    'RNCCompactLexer': ('pip._vendor.pygments.lexers.rnc', 'Relax-NG Compact', ('rng-compact', 'rnc'), ('*.rnc',), ()),\n    'RPMSpecLexer': ('pip._vendor.pygments.lexers.installers', 'RPMSpec', ('spec',), ('*.spec',), ('text/x-rpm-spec',)),\n    'RacketLexer': ('pip._vendor.pygments.lexers.lisp', 'Racket', ('racket', 'rkt'), ('*.rkt', '*.rktd', '*.rktl'), ('text/x-racket', 'application/x-racket')),\n    'RagelCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in C Host', ('ragel-c',), ('*.rl',), ()),\n    'RagelCppLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in CPP Host', ('ragel-cpp',), ('*.rl',), ()),\n    'RagelDLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in D Host', ('ragel-d',), ('*.rl',), ()),\n    'RagelEmbeddedLexer': ('pip._vendor.pygments.lexers.parsers', 'Embedded Ragel', ('ragel-em',), ('*.rl',), ()),\n    'RagelJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Java Host', ('ragel-java',), ('*.rl',), ()),\n    'RagelLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel', ('ragel',), (), ()),\n    'RagelObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Objective C Host', ('ragel-objc',), ('*.rl',), ()),\n    'RagelRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Ruby Host', ('ragel-ruby', 'ragel-rb'), ('*.rl',), ()),\n    'RawTokenLexer': ('pip._vendor.pygments.lexers.special', 'Raw token data', (), (), ('application/x-pygments-tokens',)),\n    'RdLexer': ('pip._vendor.pygments.lexers.r', 'Rd', ('rd',), ('*.Rd',), ('text/x-r-doc',)),\n    'ReasonLexer': ('pip._vendor.pygments.lexers.ml', 'ReasonML', ('reasonml', 'reason'), ('*.re', '*.rei'), ('text/x-reasonml',)),\n    'RebolLexer': ('pip._vendor.pygments.lexers.rebol', 'REBOL', ('rebol',), ('*.r', '*.r3', '*.reb'), ('text/x-rebol',)),\n    'RedLexer': ('pip._vendor.pygments.lexers.rebol', 'Red', ('red', 'red/system'), ('*.red', '*.reds'), ('text/x-red', 'text/x-red-system')),\n    'RedcodeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Redcode', ('redcode',), ('*.cw',), ()),\n    'RegeditLexer': ('pip._vendor.pygments.lexers.configs', 'reg', ('registry',), ('*.reg',), ('text/x-windows-registry',)),\n    'RegoLexer': ('pip._vendor.pygments.lexers.rego', 'Rego', ('rego',), ('*.rego',), ('text/x-rego',)),\n    'ResourceLexer': ('pip._vendor.pygments.lexers.resource', 'ResourceBundle', ('resourcebundle', 'resource'), (), ()),\n    'RexxLexer': ('pip._vendor.pygments.lexers.scripting', 'Rexx', ('rexx', 'arexx'), ('*.rexx', '*.rex', '*.rx', '*.arexx'), ('text/x-rexx',)),\n    'RhtmlLexer': ('pip._vendor.pygments.lexers.templates', 'RHTML', ('rhtml', 'html+erb', 'html+ruby'), ('*.rhtml',), ('text/html+ruby',)),\n    'RideLexer': ('pip._vendor.pygments.lexers.ride', 'Ride', ('ride',), ('*.ride',), ('text/x-ride',)),\n    'RitaLexer': ('pip._vendor.pygments.lexers.rita', 'Rita', ('rita',), ('*.rita',), ('text/rita',)),\n    'RoboconfGraphLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Graph', ('roboconf-graph',), ('*.graph',), ()),\n    'RoboconfInstancesLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Instances', ('roboconf-instances',), ('*.instances',), ()),\n    'RobotFrameworkLexer': ('pip._vendor.pygments.lexers.robotframework', 'RobotFramework', ('robotframework',), ('*.robot', '*.resource'), ('text/x-robotframework',)),\n    'RqlLexer': ('pip._vendor.pygments.lexers.sql', 'RQL', ('rql',), ('*.rql',), ('text/x-rql',)),\n    'RslLexer': ('pip._vendor.pygments.lexers.dsls', 'RSL', ('rsl',), ('*.rsl',), ('text/rsl',)),\n    'RstLexer': ('pip._vendor.pygments.lexers.markup', 'reStructuredText', ('restructuredtext', 'rst', 'rest'), ('*.rst', '*.rest'), ('text/x-rst', 'text/prs.fallenstein.rst')),\n    'RtsLexer': ('pip._vendor.pygments.lexers.trafficscript', 'TrafficScript', ('trafficscript', 'rts'), ('*.rts',), ()),\n    'RubyConsoleLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby irb session', ('rbcon', 'irb'), (), ('text/x-ruby-shellsession',)),\n    'RubyLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby', ('ruby', 'rb', 'duby'), ('*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby', 'Gemfile', 'Vagrantfile'), ('text/x-ruby', 'application/x-ruby')),\n    'RustLexer': ('pip._vendor.pygments.lexers.rust', 'Rust', ('rust', 'rs'), ('*.rs', '*.rs.in'), ('text/rust', 'text/x-rust')),\n    'SASLexer': ('pip._vendor.pygments.lexers.sas', 'SAS', ('sas',), ('*.SAS', '*.sas'), ('text/x-sas', 'text/sas', 'application/x-sas')),\n    'SLexer': ('pip._vendor.pygments.lexers.r', 'S', ('splus', 's', 'r'), ('*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron'), ('text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile')),\n    'SMLLexer': ('pip._vendor.pygments.lexers.ml', 'Standard ML', ('sml',), ('*.sml', '*.sig', '*.fun'), ('text/x-standardml', 'application/x-standardml')),\n    'SNBTLexer': ('pip._vendor.pygments.lexers.minecraft', 'SNBT', ('snbt',), ('*.snbt',), ('text/snbt',)),\n    'SarlLexer': ('pip._vendor.pygments.lexers.jvm', 'SARL', ('sarl',), ('*.sarl',), ('text/x-sarl',)),\n    'SassLexer': ('pip._vendor.pygments.lexers.css', 'Sass', ('sass',), ('*.sass',), ('text/x-sass',)),\n    'SaviLexer': ('pip._vendor.pygments.lexers.savi', 'Savi', ('savi',), ('*.savi',), ()),\n    'ScalaLexer': ('pip._vendor.pygments.lexers.jvm', 'Scala', ('scala',), ('*.scala',), ('text/x-scala',)),\n    'ScamlLexer': ('pip._vendor.pygments.lexers.html', 'Scaml', ('scaml',), ('*.scaml',), ('text/x-scaml',)),\n    'ScdocLexer': ('pip._vendor.pygments.lexers.scdoc', 'scdoc', ('scdoc', 'scd'), ('*.scd', '*.scdoc'), ()),\n    'SchemeLexer': ('pip._vendor.pygments.lexers.lisp', 'Scheme', ('scheme', 'scm'), ('*.scm', '*.ss'), ('text/x-scheme', 'application/x-scheme')),\n    'ScilabLexer': ('pip._vendor.pygments.lexers.matlab', 'Scilab', ('scilab',), ('*.sci', '*.sce', '*.tst'), ('text/scilab',)),\n    'ScssLexer': ('pip._vendor.pygments.lexers.css', 'SCSS', ('scss',), ('*.scss',), ('text/x-scss',)),\n    'SedLexer': ('pip._vendor.pygments.lexers.textedit', 'Sed', ('sed', 'gsed', 'ssed'), ('*.sed', '*.[gs]sed'), ('text/x-sed',)),\n    'ShExCLexer': ('pip._vendor.pygments.lexers.rdf', 'ShExC', ('shexc', 'shex'), ('*.shex',), ('text/shex',)),\n    'ShenLexer': ('pip._vendor.pygments.lexers.lisp', 'Shen', ('shen',), ('*.shen',), ('text/x-shen', 'application/x-shen')),\n    'SieveLexer': ('pip._vendor.pygments.lexers.sieve', 'Sieve', ('sieve',), ('*.siv', '*.sieve'), ()),\n    'SilverLexer': ('pip._vendor.pygments.lexers.verification', 'Silver', ('silver',), ('*.sil', '*.vpr'), ()),\n    'SingularityLexer': ('pip._vendor.pygments.lexers.configs', 'Singularity', ('singularity',), ('*.def', 'Singularity'), ()),\n    'SlashLexer': ('pip._vendor.pygments.lexers.slash', 'Slash', ('slash',), ('*.sla',), ()),\n    'SlimLexer': ('pip._vendor.pygments.lexers.webmisc', 'Slim', ('slim',), ('*.slim',), ('text/x-slim',)),\n    'SlurmBashLexer': ('pip._vendor.pygments.lexers.shell', 'Slurm', ('slurm', 'sbatch'), ('*.sl',), ()),\n    'SmaliLexer': ('pip._vendor.pygments.lexers.dalvik', 'Smali', ('smali',), ('*.smali',), ('text/smali',)),\n    'SmalltalkLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Smalltalk', ('smalltalk', 'squeak', 'st'), ('*.st',), ('text/x-smalltalk',)),\n    'SmartGameFormatLexer': ('pip._vendor.pygments.lexers.sgf', 'SmartGameFormat', ('sgf',), ('*.sgf',), ()),\n    'SmartyLexer': ('pip._vendor.pygments.lexers.templates', 'Smarty', ('smarty',), ('*.tpl',), ('application/x-smarty',)),\n    'SmithyLexer': ('pip._vendor.pygments.lexers.smithy', 'Smithy', ('smithy',), ('*.smithy',), ()),\n    'SnobolLexer': ('pip._vendor.pygments.lexers.snobol', 'Snobol', ('snobol',), ('*.snobol',), ('text/x-snobol',)),\n    'SnowballLexer': ('pip._vendor.pygments.lexers.dsls', 'Snowball', ('snowball',), ('*.sbl',), ()),\n    'SolidityLexer': ('pip._vendor.pygments.lexers.solidity', 'Solidity', ('solidity',), ('*.sol',), ()),\n    'SoongLexer': ('pip._vendor.pygments.lexers.soong', 'Soong', ('androidbp', 'bp', 'soong'), ('Android.bp',), ()),\n    'SophiaLexer': ('pip._vendor.pygments.lexers.sophia', 'Sophia', ('sophia',), ('*.aes',), ()),\n    'SourcePawnLexer': ('pip._vendor.pygments.lexers.pawn', 'SourcePawn', ('sp',), ('*.sp',), ('text/x-sourcepawn',)),\n    'SourcesListLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Sourcelist', ('debsources', 'sourceslist', 'sources.list'), ('sources.list',), ()),\n    'SparqlLexer': ('pip._vendor.pygments.lexers.rdf', 'SPARQL', ('sparql',), ('*.rq', '*.sparql'), ('application/sparql-query',)),\n    'SpiceLexer': ('pip._vendor.pygments.lexers.spice', 'Spice', ('spice', 'spicelang'), ('*.spice',), ('text/x-spice',)),\n    'SqlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'SQL+Jinja', ('sql+jinja',), ('*.sql', '*.sql.j2', '*.sql.jinja2'), ()),\n    'SqlLexer': ('pip._vendor.pygments.lexers.sql', 'SQL', ('sql',), ('*.sql',), ('text/x-sql',)),\n    'SqliteConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'sqlite3con', ('sqlite3',), ('*.sqlite3-console',), ('text/x-sqlite3-console',)),\n    'SquidConfLexer': ('pip._vendor.pygments.lexers.configs', 'SquidConf', ('squidconf', 'squid.conf', 'squid'), ('squid.conf',), ('text/x-squidconf',)),\n    'SrcinfoLexer': ('pip._vendor.pygments.lexers.srcinfo', 'Srcinfo', ('srcinfo',), ('.SRCINFO',), ()),\n    'SspLexer': ('pip._vendor.pygments.lexers.templates', 'Scalate Server Page', ('ssp',), ('*.ssp',), ('application/x-ssp',)),\n    'StanLexer': ('pip._vendor.pygments.lexers.modeling', 'Stan', ('stan',), ('*.stan',), ()),\n    'StataLexer': ('pip._vendor.pygments.lexers.stata', 'Stata', ('stata', 'do'), ('*.do', '*.ado'), ('text/x-stata', 'text/stata', 'application/x-stata')),\n    'SuperColliderLexer': ('pip._vendor.pygments.lexers.supercollider', 'SuperCollider', ('supercollider', 'sc'), ('*.sc', '*.scd'), ('application/supercollider', 'text/supercollider')),\n    'SwiftLexer': ('pip._vendor.pygments.lexers.objective', 'Swift', ('swift',), ('*.swift',), ('text/x-swift',)),\n    'SwigLexer': ('pip._vendor.pygments.lexers.c_like', 'SWIG', ('swig',), ('*.swg', '*.i'), ('text/swig',)),\n    'SystemVerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'systemverilog', ('systemverilog', 'sv'), ('*.sv', '*.svh'), ('text/x-systemverilog',)),\n    'SystemdLexer': ('pip._vendor.pygments.lexers.configs', 'Systemd', ('systemd',), ('*.service', '*.socket', '*.device', '*.mount', '*.automount', '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope'), ()),\n    'TAPLexer': ('pip._vendor.pygments.lexers.testing', 'TAP', ('tap',), ('*.tap',), ()),\n    'TNTLexer': ('pip._vendor.pygments.lexers.tnt', 'Typographic Number Theory', ('tnt',), ('*.tnt',), ()),\n    'TOMLLexer': ('pip._vendor.pygments.lexers.configs', 'TOML', ('toml',), ('*.toml', 'Pipfile', 'poetry.lock'), ('application/toml',)),\n    'TableGenLexer': ('pip._vendor.pygments.lexers.tablegen', 'TableGen', ('tablegen', 'td'), ('*.td',), ()),\n    'TactLexer': ('pip._vendor.pygments.lexers.tact', 'Tact', ('tact',), ('*.tact',), ()),\n    'Tads3Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'TADS 3', ('tads3',), ('*.t',), ()),\n    'TalLexer': ('pip._vendor.pygments.lexers.tal', 'Tal', ('tal', 'uxntal'), ('*.tal',), ('text/x-uxntal',)),\n    'TasmLexer': ('pip._vendor.pygments.lexers.asm', 'TASM', ('tasm',), ('*.asm', '*.ASM', '*.tasm'), ('text/x-tasm',)),\n    'TclLexer': ('pip._vendor.pygments.lexers.tcl', 'Tcl', ('tcl',), ('*.tcl', '*.rvt'), ('text/x-tcl', 'text/x-script.tcl', 'application/x-tcl')),\n    'TcshLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh', ('tcsh', 'csh'), ('*.tcsh', '*.csh'), ('application/x-csh',)),\n    'TcshSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh Session', ('tcshcon',), (), ()),\n    'TeaTemplateLexer': ('pip._vendor.pygments.lexers.templates', 'Tea', ('tea',), ('*.tea',), ('text/x-tea',)),\n    'TealLexer': ('pip._vendor.pygments.lexers.teal', 'teal', ('teal',), ('*.teal',), ()),\n    'TeraTermLexer': ('pip._vendor.pygments.lexers.teraterm', 'Tera Term macro', ('teratermmacro', 'teraterm', 'ttl'), ('*.ttl',), ('text/x-teratermmacro',)),\n    'TermcapLexer': ('pip._vendor.pygments.lexers.configs', 'Termcap', ('termcap',), ('termcap', 'termcap.src'), ()),\n    'TerminfoLexer': ('pip._vendor.pygments.lexers.configs', 'Terminfo', ('terminfo',), ('terminfo', 'terminfo.src'), ()),\n    'TerraformLexer': ('pip._vendor.pygments.lexers.configs', 'Terraform', ('terraform', 'tf', 'hcl'), ('*.tf', '*.hcl'), ('application/x-tf', 'application/x-terraform')),\n    'TexLexer': ('pip._vendor.pygments.lexers.markup', 'TeX', ('tex', 'latex'), ('*.tex', '*.aux', '*.toc'), ('text/x-tex', 'text/x-latex')),\n    'TextLexer': ('pip._vendor.pygments.lexers.special', 'Text only', ('text',), ('*.txt',), ('text/plain',)),\n    'ThingsDBLexer': ('pip._vendor.pygments.lexers.thingsdb', 'ThingsDB', ('ti', 'thingsdb'), ('*.ti',), ()),\n    'ThriftLexer': ('pip._vendor.pygments.lexers.dsls', 'Thrift', ('thrift',), ('*.thrift',), ('application/x-thrift',)),\n    'TiddlyWiki5Lexer': ('pip._vendor.pygments.lexers.markup', 'tiddler', ('tid',), ('*.tid',), ('text/vnd.tiddlywiki',)),\n    'TlbLexer': ('pip._vendor.pygments.lexers.tlb', 'Tl-b', ('tlb',), ('*.tlb',), ()),\n    'TlsLexer': ('pip._vendor.pygments.lexers.tls', 'TLS Presentation Language', ('tls',), (), ()),\n    'TodotxtLexer': ('pip._vendor.pygments.lexers.textfmts', 'Todotxt', ('todotxt',), ('todo.txt', '*.todotxt'), ('text/x-todo',)),\n    'TransactSqlLexer': ('pip._vendor.pygments.lexers.sql', 'Transact-SQL', ('tsql', 't-sql'), ('*.sql',), ('text/x-tsql',)),\n    'TreetopLexer': ('pip._vendor.pygments.lexers.parsers', 'Treetop', ('treetop',), ('*.treetop', '*.tt'), ()),\n    'TsxLexer': ('pip._vendor.pygments.lexers.jsx', 'TSX', ('tsx',), ('*.tsx',), ('text/typescript-tsx',)),\n    'TurtleLexer': ('pip._vendor.pygments.lexers.rdf', 'Turtle', ('turtle',), ('*.ttl',), ('text/turtle', 'application/x-turtle')),\n    'TwigHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Twig', ('html+twig',), ('*.twig',), ('text/html+twig',)),\n    'TwigLexer': ('pip._vendor.pygments.lexers.templates', 'Twig', ('twig',), (), ('application/x-twig',)),\n    'TypeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'TypeScript', ('typescript', 'ts'), ('*.ts',), ('application/x-typescript', 'text/x-typescript')),\n    'TypoScriptCssDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptCssData', ('typoscriptcssdata',), (), ()),\n    'TypoScriptHtmlDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptHtmlData', ('typoscripthtmldata',), (), ()),\n    'TypoScriptLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScript', ('typoscript',), ('*.typoscript',), ('text/x-typoscript',)),\n    'TypstLexer': ('pip._vendor.pygments.lexers.typst', 'Typst', ('typst',), ('*.typ',), ('text/x-typst',)),\n    'UL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'UL4', ('ul4',), ('*.ul4',), ()),\n    'UcodeLexer': ('pip._vendor.pygments.lexers.unicon', 'ucode', ('ucode',), ('*.u', '*.u1', '*.u2'), ()),\n    'UniconLexer': ('pip._vendor.pygments.lexers.unicon', 'Unicon', ('unicon',), ('*.icn',), ('text/unicon',)),\n    'UnixConfigLexer': ('pip._vendor.pygments.lexers.configs', 'Unix/Linux config files', ('unixconfig', 'linuxconfig'), (), ()),\n    'UrbiscriptLexer': ('pip._vendor.pygments.lexers.urbi', 'UrbiScript', ('urbiscript',), ('*.u',), ('application/x-urbiscript',)),\n    'UrlEncodedLexer': ('pip._vendor.pygments.lexers.html', 'urlencoded', ('urlencoded',), (), ('application/x-www-form-urlencoded',)),\n    'UsdLexer': ('pip._vendor.pygments.lexers.usd', 'USD', ('usd', 'usda'), ('*.usd', '*.usda'), ()),\n    'VBScriptLexer': ('pip._vendor.pygments.lexers.basic', 'VBScript', ('vbscript',), ('*.vbs', '*.VBS'), ()),\n    'VCLLexer': ('pip._vendor.pygments.lexers.varnish', 'VCL', ('vcl',), ('*.vcl',), ('text/x-vclsrc',)),\n    'VCLSnippetLexer': ('pip._vendor.pygments.lexers.varnish', 'VCLSnippets', ('vclsnippets', 'vclsnippet'), (), ('text/x-vclsnippet',)),\n    'VCTreeStatusLexer': ('pip._vendor.pygments.lexers.console', 'VCTreeStatus', ('vctreestatus',), (), ()),\n    'VGLLexer': ('pip._vendor.pygments.lexers.dsls', 'VGL', ('vgl',), ('*.rpf',), ()),\n    'ValaLexer': ('pip._vendor.pygments.lexers.c_like', 'Vala', ('vala', 'vapi'), ('*.vala', '*.vapi'), ('text/x-vala',)),\n    'VbNetAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-vb', ('aspx-vb',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),\n    'VbNetLexer': ('pip._vendor.pygments.lexers.dotnet', 'VB.net', ('vb.net', 'vbnet', 'lobas', 'oobas', 'sobas', 'visual-basic', 'visualbasic'), ('*.vb', '*.bas'), ('text/x-vbnet', 'text/x-vba')),\n    'VelocityHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Velocity', ('html+velocity',), (), ('text/html+velocity',)),\n    'VelocityLexer': ('pip._vendor.pygments.lexers.templates', 'Velocity', ('velocity',), ('*.vm', '*.fhtml'), ()),\n    'VelocityXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Velocity', ('xml+velocity',), (), ('application/xml+velocity',)),\n    'VerifpalLexer': ('pip._vendor.pygments.lexers.verifpal', 'Verifpal', ('verifpal',), ('*.vp',), ('text/x-verifpal',)),\n    'VerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'verilog', ('verilog', 'v'), ('*.v',), ('text/x-verilog',)),\n    'VhdlLexer': ('pip._vendor.pygments.lexers.hdl', 'vhdl', ('vhdl',), ('*.vhdl', '*.vhd'), ('text/x-vhdl',)),\n    'VimLexer': ('pip._vendor.pygments.lexers.textedit', 'VimL', ('vim',), ('*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'), ('text/x-vim',)),\n    'VisualPrologGrammarLexer': ('pip._vendor.pygments.lexers.vip', 'Visual Prolog Grammar', ('visualprologgrammar',), ('*.vipgrm',), ()),\n    'VisualPrologLexer': ('pip._vendor.pygments.lexers.vip', 'Visual Prolog', ('visualprolog',), ('*.pro', '*.cl', '*.i', '*.pack', '*.ph'), ()),\n    'VueLexer': ('pip._vendor.pygments.lexers.html', 'Vue', ('vue',), ('*.vue',), ()),\n    'VyperLexer': ('pip._vendor.pygments.lexers.vyper', 'Vyper', ('vyper',), ('*.vy',), ()),\n    'WDiffLexer': ('pip._vendor.pygments.lexers.diff', 'WDiff', ('wdiff',), ('*.wdiff',), ()),\n    'WatLexer': ('pip._vendor.pygments.lexers.webassembly', 'WebAssembly', ('wast', 'wat'), ('*.wat', '*.wast'), ()),\n    'WebIDLLexer': ('pip._vendor.pygments.lexers.webidl', 'Web IDL', ('webidl',), ('*.webidl',), ()),\n    'WgslLexer': ('pip._vendor.pygments.lexers.wgsl', 'WebGPU Shading Language', ('wgsl',), ('*.wgsl',), ('text/wgsl',)),\n    'WhileyLexer': ('pip._vendor.pygments.lexers.whiley', 'Whiley', ('whiley',), ('*.whiley',), ('text/x-whiley',)),\n    'WikitextLexer': ('pip._vendor.pygments.lexers.markup', 'Wikitext', ('wikitext', 'mediawiki'), (), ('text/x-wiki',)),\n    'WoWTocLexer': ('pip._vendor.pygments.lexers.wowtoc', 'World of Warcraft TOC', ('wowtoc',), ('*.toc',), ()),\n    'WrenLexer': ('pip._vendor.pygments.lexers.wren', 'Wren', ('wren',), ('*.wren',), ()),\n    'X10Lexer': ('pip._vendor.pygments.lexers.x10', 'X10', ('x10', 'xten'), ('*.x10',), ('text/x-x10',)),\n    'XMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'XML+UL4', ('xml+ul4',), ('*.xmlul4',), ()),\n    'XQueryLexer': ('pip._vendor.pygments.lexers.webmisc', 'XQuery', ('xquery', 'xqy', 'xq', 'xql', 'xqm'), ('*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm'), ('text/xquery', 'application/xquery')),\n    'XmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Django/Jinja', ('xml+django', 'xml+jinja'), ('*.xml.j2', '*.xml.jinja2'), ('application/xml+django', 'application/xml+jinja')),\n    'XmlErbLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Ruby', ('xml+ruby', 'xml+erb'), (), ('application/xml+ruby',)),\n    'XmlLexer': ('pip._vendor.pygments.lexers.html', 'XML', ('xml',), ('*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl', '*.wsf'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml')),\n    'XmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'XML+PHP', ('xml+php',), (), ('application/xml+php',)),\n    'XmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Smarty', ('xml+smarty',), (), ('application/xml+smarty',)),\n    'XorgLexer': ('pip._vendor.pygments.lexers.xorg', 'Xorg', ('xorg.conf',), ('xorg.conf',), ()),\n    'XppLexer': ('pip._vendor.pygments.lexers.dotnet', 'X++', ('xpp', 'x++'), ('*.xpp',), ()),\n    'XsltLexer': ('pip._vendor.pygments.lexers.html', 'XSLT', ('xslt',), ('*.xsl', '*.xslt', '*.xpl'), ('application/xsl+xml', 'application/xslt+xml')),\n    'XtendLexer': ('pip._vendor.pygments.lexers.jvm', 'Xtend', ('xtend',), ('*.xtend',), ('text/x-xtend',)),\n    'XtlangLexer': ('pip._vendor.pygments.lexers.lisp', 'xtlang', ('extempore',), ('*.xtm',), ()),\n    'YamlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'YAML+Jinja', ('yaml+jinja', 'salt', 'sls'), ('*.sls', '*.yaml.j2', '*.yml.j2', '*.yaml.jinja2', '*.yml.jinja2'), ('text/x-yaml+jinja', 'text/x-sls')),\n    'YamlLexer': ('pip._vendor.pygments.lexers.data', 'YAML', ('yaml',), ('*.yaml', '*.yml'), ('text/x-yaml',)),\n    'YangLexer': ('pip._vendor.pygments.lexers.yang', 'YANG', ('yang',), ('*.yang',), ('application/yang',)),\n    'YaraLexer': ('pip._vendor.pygments.lexers.yara', 'YARA', ('yara', 'yar'), ('*.yar',), ('text/x-yara',)),\n    'ZeekLexer': ('pip._vendor.pygments.lexers.dsls', 'Zeek', ('zeek', 'bro'), ('*.zeek', '*.bro'), ()),\n    'ZephirLexer': ('pip._vendor.pygments.lexers.php', 'Zephir', ('zephir',), ('*.zep',), ()),\n    'ZigLexer': ('pip._vendor.pygments.lexers.zig', 'Zig', ('zig',), ('*.zig',), ('text/zig',)),\n    'apdlexer': ('pip._vendor.pygments.lexers.apdlexer', 'ANSYS parametric design language', ('ansys', 'apdl'), ('*.ans',), ()),\n}\n"
  },
  {
    "path": "src/pip/_vendor/pygments/lexers/python.py",
    "content": "\"\"\"\n    pygments.lexers.python\n    ~~~~~~~~~~~~~~~~~~~~~~\n\n    Lexers for Python and related languages.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport keyword\n\nfrom pip._vendor.pygments.lexer import DelegatingLexer, RegexLexer, include, \\\n    bygroups, using, default, words, combined, this\nfrom pip._vendor.pygments.util import get_bool_opt, shebang_matches\nfrom pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \\\n    Number, Punctuation, Generic, Other, Error, Whitespace\nfrom pip._vendor.pygments import unistring as uni\n\n__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer',\n           'Python2Lexer', 'Python2TracebackLexer',\n           'CythonLexer', 'DgLexer', 'NumPyLexer']\n\n\nclass PythonLexer(RegexLexer):\n    \"\"\"\n    For Python source code (version 3.x).\n\n    .. versionchanged:: 2.5\n       This is now the default ``PythonLexer``.  It is still available as the\n       alias ``Python3Lexer``.\n    \"\"\"\n\n    name = 'Python'\n    url = 'https://www.python.org'\n    aliases = ['python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi']\n    filenames = [\n        '*.py',\n        '*.pyw',\n        # Type stubs\n        '*.pyi',\n        # Jython\n        '*.jy',\n        # Sage\n        '*.sage',\n        # SCons\n        '*.sc',\n        'SConstruct',\n        'SConscript',\n        # Skylark/Starlark (used by Bazel, Buck, and Pants)\n        '*.bzl',\n        'BUCK',\n        'BUILD',\n        'BUILD.bazel',\n        'WORKSPACE',\n        # Twisted Application infrastructure\n        '*.tac',\n    ]\n    mimetypes = ['text/x-python', 'application/x-python',\n                 'text/x-python3', 'application/x-python3']\n    version_added = '0.10'\n\n    uni_name = f\"[{uni.xid_start}][{uni.xid_continue}]*\"\n\n    def innerstring_rules(ttype):\n        return [\n            # the old style '%s' % (...) string formatting (still valid in Py3)\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsaux%]', String.Interpol),\n            # the new style '{}'.format(...) string formatting\n            (r'\\{'\n             r'((\\w+)((\\.\\w+)|(\\[[^\\]]+\\]))*)?'  # field name\n             r'(\\![sra])?'                       # conversion\n             r'(\\:(.?[<>=\\^])?[-+ ]?#?0?(\\d+)?,?(\\.\\d+)?[E-GXb-gnosx%]?)?'\n             r'\\}', String.Interpol),\n\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"%{\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # unhandled string formatting sign\n            (r'%|(\\{{1,2})', ttype)\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    def fstring_rules(ttype):\n        return [\n            # Assuming that a '}' is the closing brace after format specifier.\n            # Sadly, this means that we won't detect syntax error. But it's\n            # more important to parse correct syntax correctly, than to\n            # highlight invalid syntax.\n            (r'\\}', String.Interpol),\n            (r'\\{', String.Interpol, 'expr-inside-fstring'),\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"{}\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    tokens = {\n        'root': [\n            (r'\\n', Whitespace),\n            (r'^(\\s*)([rRuUbB]{,2})(\"\"\"(?:.|\\n)*?\"\"\")',\n             bygroups(Whitespace, String.Affix, String.Doc)),\n            (r\"^(\\s*)([rRuUbB]{,2})('''(?:.|\\n)*?''')\",\n             bygroups(Whitespace, String.Affix, String.Doc)),\n            (r'\\A#!.+$', Comment.Hashbang),\n            (r'#.*$', Comment.Single),\n            (r'\\\\\\n', Text),\n            (r'\\\\', Text),\n            include('keywords'),\n            include('soft-keywords'),\n            (r'(def)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'),\n            (r'(class)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Whitespace), 'classname'),\n            (r'(from)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Whitespace),\n             'fromimport'),\n            (r'(import)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Whitespace),\n             'import'),\n            include('expr'),\n        ],\n        'expr': [\n            # raw f-strings\n            ('(?i)(rf|fr)(\"\"\")',\n             bygroups(String.Affix, String.Double),\n             combined('rfstringescape', 'tdqf')),\n            (\"(?i)(rf|fr)(''')\",\n             bygroups(String.Affix, String.Single),\n             combined('rfstringescape', 'tsqf')),\n            ('(?i)(rf|fr)(\")',\n             bygroups(String.Affix, String.Double),\n             combined('rfstringescape', 'dqf')),\n            (\"(?i)(rf|fr)(')\",\n             bygroups(String.Affix, String.Single),\n             combined('rfstringescape', 'sqf')),\n            # non-raw f-strings\n            ('([fF])(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('fstringescape', 'tdqf')),\n            (\"([fF])(''')\", bygroups(String.Affix, String.Single),\n             combined('fstringescape', 'tsqf')),\n            ('([fF])(\")', bygroups(String.Affix, String.Double),\n             combined('fstringescape', 'dqf')),\n            (\"([fF])(')\", bygroups(String.Affix, String.Single),\n             combined('fstringescape', 'sqf')),\n            # raw bytes and strings\n            ('(?i)(rb|br|r)(\"\"\")',\n             bygroups(String.Affix, String.Double), 'tdqs'),\n            (\"(?i)(rb|br|r)(''')\",\n             bygroups(String.Affix, String.Single), 'tsqs'),\n            ('(?i)(rb|br|r)(\")',\n             bygroups(String.Affix, String.Double), 'dqs'),\n            (\"(?i)(rb|br|r)(')\",\n             bygroups(String.Affix, String.Single), 'sqs'),\n            # non-raw strings\n            ('([uU]?)(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'tdqs')),\n            (\"([uU]?)(''')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'tsqs')),\n            ('([uU]?)(\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'dqs')),\n            (\"([uU]?)(')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'sqs')),\n            # non-raw bytes\n            ('([bB])(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('bytesescape', 'tdqs')),\n            (\"([bB])(''')\", bygroups(String.Affix, String.Single),\n             combined('bytesescape', 'tsqs')),\n            ('([bB])(\")', bygroups(String.Affix, String.Double),\n             combined('bytesescape', 'dqs')),\n            (\"([bB])(')\", bygroups(String.Affix, String.Single),\n             combined('bytesescape', 'sqs')),\n\n            (r'[^\\S\\n]+', Text),\n            include('numbers'),\n            (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            include('expr-keywords'),\n            include('builtins'),\n            include('magicfuncs'),\n            include('magicvars'),\n            include('name'),\n        ],\n        'expr-inside-fstring': [\n            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),\n            # without format specifier\n            (r'(=\\s*)?'         # debug (https://bugs.python.org/issue36817)\n             r'(\\![sraf])?'     # conversion\n             r'\\}', String.Interpol, '#pop'),\n            # with format specifier\n            # we'll catch the remaining '}' in the outer scope\n            (r'(=\\s*)?'         # debug (https://bugs.python.org/issue36817)\n             r'(\\![sraf])?'     # conversion\n             r':', String.Interpol, '#pop'),\n            (r'\\s+', Whitespace),  # allow new lines\n            include('expr'),\n        ],\n        'expr-inside-fstring-inner': [\n            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),\n            (r'[])}]', Punctuation, '#pop'),\n            (r'\\s+', Whitespace),  # allow new lines\n            include('expr'),\n        ],\n        'expr-keywords': [\n            # Based on https://docs.python.org/3/reference/expressions.html\n            (words((\n                'async for', 'await', 'else', 'for', 'if', 'lambda',\n                'yield', 'yield from'), suffix=r'\\b'),\n             Keyword),\n            (words(('True', 'False', 'None'), suffix=r'\\b'), Keyword.Constant),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'async', 'await', 'break', 'continue', 'del', 'elif',\n                'else', 'except', 'finally', 'for', 'global', 'if', 'lambda',\n                'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield',\n                'yield from', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n            (words(('True', 'False', 'None'), suffix=r'\\b'), Keyword.Constant),\n        ],\n        'soft-keywords': [\n            # `match`, `case` and `_` soft keywords\n            (r'(^[ \\t]*)'              # at beginning of line + possible indentation\n             r'(match|case)\\b'         # a possible keyword\n             r'(?![ \\t]*(?:'           # not followed by...\n             r'[:,;=^&|@~)\\]}]|(?:' +  # characters and keywords that mean this isn't\n                                       # pattern matching (but None/True/False is ok)\n             r'|'.join(k for k in keyword.kwlist if k[0].islower()) + r')\\b))',\n             bygroups(Text, Keyword), 'soft-keywords-inner'),\n        ],\n        'soft-keywords-inner': [\n            # optional `_` keyword\n            (r'(\\s+)([^\\n_]*)(_\\b)', bygroups(Whitespace, using(this), Keyword)),\n            default('#pop')\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray',\n                'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile',\n                'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',\n                'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',\n                'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance',\n                'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max',\n                'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow',\n                'print', 'property', 'range', 'repr', 'reversed', 'round', 'set',\n                'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',\n                'tuple', 'type', 'vars', 'zip'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|Ellipsis|NotImplemented|cls)\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning',\n                'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError',\n                'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n                'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',\n                'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',\n                'NotImplementedError', 'OSError', 'OverflowError',\n                'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning',\n                'RuntimeError', 'RuntimeWarning', 'StopIteration',\n                'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',\n                'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError',\n                'Warning', 'WindowsError', 'ZeroDivisionError',\n                # new builtin exceptions from PEP 3151\n                'BlockingIOError', 'ChildProcessError', 'ConnectionError',\n                'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError',\n                'ConnectionResetError', 'FileExistsError', 'FileNotFoundError',\n                'InterruptedError', 'IsADirectoryError', 'NotADirectoryError',\n                'PermissionError', 'ProcessLookupError', 'TimeoutError',\n                # others new in Python 3\n                'StopAsyncIteration', 'ModuleNotFoundError', 'RecursionError',\n                'EncodingWarning'),\n                prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'magicfuncs': [\n            (words((\n                '__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__',\n                '__and__', '__anext__', '__await__', '__bool__', '__bytes__',\n                '__call__', '__complex__', '__contains__', '__del__', '__delattr__',\n                '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__',\n                '__eq__', '__exit__', '__float__', '__floordiv__', '__format__',\n                '__ge__', '__get__', '__getattr__', '__getattribute__',\n                '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__',\n                '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__',\n                '__imul__', '__index__', '__init__', '__instancecheck__',\n                '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__',\n                '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__',\n                '__len__', '__length_hint__', '__lshift__', '__lt__', '__matmul__',\n                '__missing__', '__mod__', '__mul__', '__ne__', '__neg__',\n                '__new__', '__next__', '__or__', '__pos__', '__pow__',\n                '__prepare__', '__radd__', '__rand__', '__rdivmod__', '__repr__',\n                '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__',\n                '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__',\n                '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',\n                '__rxor__', '__set__', '__setattr__', '__setitem__', '__str__',\n                '__sub__', '__subclasscheck__', '__truediv__',\n                '__xor__'), suffix=r'\\b'),\n             Name.Function.Magic),\n        ],\n        'magicvars': [\n            (words((\n                '__annotations__', '__bases__', '__class__', '__closure__',\n                '__code__', '__defaults__', '__dict__', '__doc__', '__file__',\n                '__func__', '__globals__', '__kwdefaults__', '__module__',\n                '__mro__', '__name__', '__objclass__', '__qualname__',\n                '__self__', '__slots__', '__weakref__'), suffix=r'\\b'),\n             Name.Variable.Magic),\n        ],\n        'numbers': [\n            (r'(\\d(?:_?\\d)*\\.(?:\\d(?:_?\\d)*)?|(?:\\d(?:_?\\d)*)?\\.\\d(?:_?\\d)*)'\n             r'([eE][+-]?\\d(?:_?\\d)*)?', Number.Float),\n            (r'\\d(?:_?\\d)*[eE][+-]?\\d(?:_?\\d)*j?', Number.Float),\n            (r'0[oO](?:_?[0-7])+', Number.Oct),\n            (r'0[bB](?:_?[01])+', Number.Bin),\n            (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex),\n            (r'\\d(?:_?\\d)*', Number.Integer),\n        ],\n        'name': [\n            (r'@' + uni_name, Name.Decorator),\n            (r'@', Operator),  # new matrix multiplication operator\n            (uni_name, Name),\n        ],\n        'funcname': [\n            include('magicfuncs'),\n            (uni_name, Name.Function, '#pop'),\n            default('#pop'),\n        ],\n        'classname': [\n            (uni_name, Name.Class, '#pop'),\n        ],\n        'import': [\n            (r'(\\s+)(as)(\\s+)', bygroups(Whitespace, Keyword, Whitespace)),\n            (r'\\.', Name.Namespace),\n            (uni_name, Name.Namespace),\n            (r'(\\s*)(,)(\\s*)', bygroups(Whitespace, Operator, Whitespace)),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(\\s+)(import)\\b', bygroups(Whitespace, Keyword.Namespace), '#pop'),\n            (r'\\.', Name.Namespace),\n            # if None occurs here, it's \"raise x from None\", since None can\n            # never be a module name\n            (r'None\\b', Keyword.Constant, '#pop'),\n            (uni_name, Name.Namespace),\n            default('#pop'),\n        ],\n        'rfstringescape': [\n            (r'\\{\\{', String.Escape),\n            (r'\\}\\}', String.Escape),\n        ],\n        'fstringescape': [\n            include('rfstringescape'),\n            include('stringescape'),\n        ],\n        'bytesescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'stringescape': [\n            (r'\\\\(N\\{.*?\\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})', String.Escape),\n            include('bytesescape')\n        ],\n        'fstrings-single': fstring_rules(String.Single),\n        'fstrings-double': fstring_rules(String.Double),\n        'strings-single': innerstring_rules(String.Single),\n        'strings-double': innerstring_rules(String.Double),\n        'dqf': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('fstrings-double')\n        ],\n        'sqf': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('fstrings-single')\n        ],\n        'dqs': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('strings-double')\n        ],\n        'sqs': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('strings-single')\n        ],\n        'tdqf': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('fstrings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqf': [\n            (r\"'''\", String.Single, '#pop'),\n            include('fstrings-single'),\n            (r'\\n', String.Single)\n        ],\n        'tdqs': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('strings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqs': [\n            (r\"'''\", String.Single, '#pop'),\n            include('strings-single'),\n            (r'\\n', String.Single)\n        ],\n    }\n\n    def analyse_text(text):\n        return shebang_matches(text, r'pythonw?(3(\\.\\d)?)?') or \\\n            'import ' in text[:1000]\n\n\nPython3Lexer = PythonLexer\n\n\nclass Python2Lexer(RegexLexer):\n    \"\"\"\n    For Python 2.x source code.\n\n    .. versionchanged:: 2.5\n       This class has been renamed from ``PythonLexer``.  ``PythonLexer`` now\n       refers to the Python 3 variant.  File name patterns like ``*.py`` have\n       been moved to Python 3 as well.\n    \"\"\"\n\n    name = 'Python 2.x'\n    url = 'https://www.python.org'\n    aliases = ['python2', 'py2']\n    filenames = []  # now taken over by PythonLexer (3.x)\n    mimetypes = ['text/x-python2', 'application/x-python2']\n    version_added = ''\n\n    def innerstring_rules(ttype):\n        return [\n            # the old style '%s' % (...) string formatting\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"%\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # unhandled string formatting sign\n            (r'%', ttype),\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    tokens = {\n        'root': [\n            (r'\\n', Whitespace),\n            (r'^(\\s*)([rRuUbB]{,2})(\"\"\"(?:.|\\n)*?\"\"\")',\n             bygroups(Whitespace, String.Affix, String.Doc)),\n            (r\"^(\\s*)([rRuUbB]{,2})('''(?:.|\\n)*?''')\",\n             bygroups(Whitespace, String.Affix, String.Doc)),\n            (r'[^\\S\\n]+', Text),\n            (r'\\A#!.+$', Comment.Hashbang),\n            (r'#.*$', Comment.Single),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'\\\\\\n', Text),\n            (r'\\\\', Text),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator),\n            include('keywords'),\n            (r'(def)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'),\n            (r'(class)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Whitespace), 'classname'),\n            (r'(from)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Whitespace),\n             'fromimport'),\n            (r'(import)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Whitespace),\n             'import'),\n            include('builtins'),\n            include('magicfuncs'),\n            include('magicvars'),\n            include('backtick'),\n            ('([rR]|[uUbB][rR]|[rR][uUbB])(\"\"\")',\n             bygroups(String.Affix, String.Double), 'tdqs'),\n            (\"([rR]|[uUbB][rR]|[rR][uUbB])(''')\",\n             bygroups(String.Affix, String.Single), 'tsqs'),\n            ('([rR]|[uUbB][rR]|[rR][uUbB])(\")',\n             bygroups(String.Affix, String.Double), 'dqs'),\n            (\"([rR]|[uUbB][rR]|[rR][uUbB])(')\",\n             bygroups(String.Affix, String.Single), 'sqs'),\n            ('([uUbB]?)(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'tdqs')),\n            (\"([uUbB]?)(''')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'tsqs')),\n            ('([uUbB]?)(\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'dqs')),\n            (\"([uUbB]?)(')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'sqs')),\n            include('name'),\n            include('numbers'),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'break', 'continue', 'del', 'elif', 'else', 'except',\n                'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass',\n                'print', 'raise', 'return', 'try', 'while', 'yield',\n                'yield from', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin',\n                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod',\n                'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',\n                'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',\n                'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id',\n                'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',\n                'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object',\n                'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce',\n                'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n                'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',\n                'unichr', 'unicode', 'vars', 'xrange', 'zip'),\n                prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|None|Ellipsis|NotImplemented|False|True|cls'\n             r')\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',\n                'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',\n                'IOError', 'ImportError', 'ImportWarning', 'IndentationError',\n                'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n                'MemoryError', 'NameError',\n                'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',\n                'PendingDeprecationWarning', 'ReferenceError',\n                'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',\n                'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',\n                'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning',\n                'WindowsError', 'ZeroDivisionError'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'magicfuncs': [\n            (words((\n                '__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',\n                '__complex__', '__contains__', '__del__', '__delattr__', '__delete__',\n                '__delitem__', '__delslice__', '__div__', '__divmod__', '__enter__',\n                '__eq__', '__exit__', '__float__', '__floordiv__', '__ge__', '__get__',\n                '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',\n                '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__',\n                '__ilshift__', '__imod__', '__imul__', '__index__', '__init__',\n                '__instancecheck__', '__int__', '__invert__', '__iop__', '__ior__',\n                '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__',\n                '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__',\n                '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',\n                '__nonzero__', '__oct__', '__op__', '__or__', '__pos__', '__pow__',\n                '__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__repr__',\n                '__reversed__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',\n                '__rop__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',\n                '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__',\n                '__setslice__', '__str__', '__sub__', '__subclasscheck__', '__truediv__',\n                '__unicode__', '__xor__'), suffix=r'\\b'),\n             Name.Function.Magic),\n        ],\n        'magicvars': [\n            (words((\n                '__bases__', '__class__', '__closure__', '__code__', '__defaults__',\n                '__dict__', '__doc__', '__file__', '__func__', '__globals__',\n                '__metaclass__', '__module__', '__mro__', '__name__', '__self__',\n                '__slots__', '__weakref__'),\n                suffix=r'\\b'),\n             Name.Variable.Magic),\n        ],\n        'numbers': [\n            (r'(\\d+\\.\\d*|\\d*\\.\\d+)([eE][+-]?[0-9]+)?j?', Number.Float),\n            (r'\\d+[eE][+-]?[0-9]+j?', Number.Float),\n            (r'0[0-7]+j?', Number.Oct),\n            (r'0[bB][01]+', Number.Bin),\n            (r'0[xX][a-fA-F0-9]+', Number.Hex),\n            (r'\\d+L', Number.Integer.Long),\n            (r'\\d+j?', Number.Integer)\n        ],\n        'backtick': [\n            ('`.*?`', String.Backtick),\n        ],\n        'name': [\n            (r'@[\\w.]+', Name.Decorator),\n            (r'[a-zA-Z_]\\w*', Name),\n        ],\n        'funcname': [\n            include('magicfuncs'),\n            (r'[a-zA-Z_]\\w*', Name.Function, '#pop'),\n            default('#pop'),\n        ],\n        'classname': [\n            (r'[a-zA-Z_]\\w*', Name.Class, '#pop')\n        ],\n        'import': [\n            (r'(?:[ \\t]|\\\\\\n)+', Text),\n            (r'as\\b', Keyword.Namespace),\n            (r',', Operator),\n            (r'[a-zA-Z_][\\w.]*', Name.Namespace),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(?:[ \\t]|\\\\\\n)+', Text),\n            (r'import\\b', Keyword.Namespace, '#pop'),\n            # if None occurs here, it's \"raise x from None\", since None can\n            # never be a module name\n            (r'None\\b', Name.Builtin.Pseudo, '#pop'),\n            # sadly, in \"raise x from y\" y will be highlighted as namespace too\n            (r'[a-zA-Z_.][\\w.]*', Name.Namespace),\n            # anything else here also means \"raise x from y\" and is therefore\n            # not an error\n            default('#pop'),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'strings-single': innerstring_rules(String.Single),\n        'strings-double': innerstring_rules(String.Double),\n        'dqs': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('strings-double')\n        ],\n        'sqs': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('strings-single')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('strings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqs': [\n            (r\"'''\", String.Single, '#pop'),\n            include('strings-single'),\n            (r'\\n', String.Single)\n        ],\n    }\n\n    def analyse_text(text):\n        return shebang_matches(text, r'pythonw?2(\\.\\d)?')\n\n\nclass _PythonConsoleLexerBase(RegexLexer):\n    name = 'Python console session'\n    aliases = ['pycon', 'python-console']\n    mimetypes = ['text/x-python-doctest']\n\n    \"\"\"Auxiliary lexer for `PythonConsoleLexer`.\n\n    Code tokens are output as ``Token.Other.Code``, traceback tokens as\n    ``Token.Other.Traceback``.\n    \"\"\"\n    tokens = {\n        'root': [\n            (r'(>>> )(.*\\n)', bygroups(Generic.Prompt, Other.Code), 'continuations'),\n            # This happens, e.g., when tracebacks are embedded in documentation;\n            # trailing whitespaces are often stripped in such contexts.\n            (r'(>>>)(\\n)', bygroups(Generic.Prompt, Whitespace)),\n            (r'(\\^C)?Traceback \\(most recent call last\\):\\n', Other.Traceback, 'traceback'),\n            # SyntaxError starts with this\n            (r'  File \"[^\"]+\", line \\d+', Other.Traceback, 'traceback'),\n            (r'.*\\n', Generic.Output),\n        ],\n        'continuations': [\n            (r'(\\.\\.\\. )(.*\\n)', bygroups(Generic.Prompt, Other.Code)),\n            # See above.\n            (r'(\\.\\.\\.)(\\n)', bygroups(Generic.Prompt, Whitespace)),\n            default('#pop'),\n        ],\n        'traceback': [\n            # As soon as we see a traceback, consume everything until the next\n            # >>> prompt.\n            (r'(?=>>>( |$))', Text, '#pop'),\n            (r'(KeyboardInterrupt)(\\n)', bygroups(Name.Class, Whitespace)),\n            (r'.*\\n', Other.Traceback),\n        ],\n    }\n\n\nclass PythonConsoleLexer(DelegatingLexer):\n    \"\"\"\n    For Python console output or doctests, such as:\n\n    .. sourcecode:: pycon\n\n        >>> a = 'foo'\n        >>> print(a)\n        foo\n        >>> 1 / 0\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        ZeroDivisionError: integer division or modulo by zero\n\n    Additional options:\n\n    `python3`\n        Use Python 3 lexer for code.  Default is ``True``.\n\n        .. versionadded:: 1.0\n        .. versionchanged:: 2.5\n           Now defaults to ``True``.\n    \"\"\"\n\n    name = 'Python console session'\n    aliases = ['pycon', 'python-console']\n    mimetypes = ['text/x-python-doctest']\n    url = 'https://python.org'\n    version_added = ''\n\n    def __init__(self, **options):\n        python3 = get_bool_opt(options, 'python3', True)\n        if python3:\n            pylexer = PythonLexer\n            tblexer = PythonTracebackLexer\n        else:\n            pylexer = Python2Lexer\n            tblexer = Python2TracebackLexer\n        # We have two auxiliary lexers. Use DelegatingLexer twice with\n        # different tokens.  TODO: DelegatingLexer should support this\n        # directly, by accepting a tuplet of auxiliary lexers and a tuple of\n        # distinguishing tokens. Then we wouldn't need this intermediary\n        # class.\n        class _ReplaceInnerCode(DelegatingLexer):\n            def __init__(self, **options):\n                super().__init__(pylexer, _PythonConsoleLexerBase, Other.Code, **options)\n        super().__init__(tblexer, _ReplaceInnerCode, Other.Traceback, **options)\n\n\nclass PythonTracebackLexer(RegexLexer):\n    \"\"\"\n    For Python 3.x tracebacks, with support for chained exceptions.\n\n    .. versionchanged:: 2.5\n       This is now the default ``PythonTracebackLexer``.  It is still available\n       as the alias ``Python3TracebackLexer``.\n    \"\"\"\n\n    name = 'Python Traceback'\n    aliases = ['pytb', 'py3tb']\n    filenames = ['*.pytb', '*.py3tb']\n    mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback']\n    url = 'https://python.org'\n    version_added = '1.0'\n\n    tokens = {\n        'root': [\n            (r'\\n', Whitespace),\n            (r'^(\\^C)?Traceback \\(most recent call last\\):\\n', Generic.Traceback, 'intb'),\n            (r'^During handling of the above exception, another '\n             r'exception occurred:\\n\\n', Generic.Traceback),\n            (r'^The above exception was the direct cause of the '\n             r'following exception:\\n\\n', Generic.Traceback),\n            (r'^(?=  File \"[^\"]+\", line \\d+)', Generic.Traceback, 'intb'),\n            (r'^.*\\n', Other),\n        ],\n        'intb': [\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(, in )(.+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)),\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Whitespace)),\n            (r'^(    )(.+)(\\n)',\n             bygroups(Whitespace, using(PythonLexer), Whitespace), 'markers'),\n            (r'^([ \\t]*)(\\.\\.\\.)(\\n)',\n             bygroups(Whitespace, Comment, Whitespace)),  # for doctests...\n            (r'^([^:]+)(: )(.+)(\\n)',\n             bygroups(Generic.Error, Text, Name, Whitespace), '#pop'),\n            (r'^([a-zA-Z_][\\w.]*)(:?\\n)',\n             bygroups(Generic.Error, Whitespace), '#pop'),\n            default('#pop'),\n        ],\n        'markers': [\n            # Either `PEP 657 <https://www.python.org/dev/peps/pep-0657/>`\n            # error locations in Python 3.11+, or single-caret markers\n            # for syntax errors before that.\n            (r'^( {4,})([~^]+)(\\n)',\n             bygroups(Whitespace, Punctuation.Marker, Whitespace),\n             '#pop'),\n            default('#pop'),\n        ],\n    }\n\n\nPython3TracebackLexer = PythonTracebackLexer\n\n\nclass Python2TracebackLexer(RegexLexer):\n    \"\"\"\n    For Python tracebacks.\n\n    .. versionchanged:: 2.5\n       This class has been renamed from ``PythonTracebackLexer``.\n       ``PythonTracebackLexer`` now refers to the Python 3 variant.\n    \"\"\"\n\n    name = 'Python 2.x Traceback'\n    aliases = ['py2tb']\n    filenames = ['*.py2tb']\n    mimetypes = ['text/x-python2-traceback']\n    url = 'https://python.org'\n    version_added = '0.7'\n\n    tokens = {\n        'root': [\n            # Cover both (most recent call last) and (innermost last)\n            # The optional ^C allows us to catch keyboard interrupt signals.\n            (r'^(\\^C)?(Traceback.*\\n)',\n             bygroups(Text, Generic.Traceback), 'intb'),\n            # SyntaxError starts with this.\n            (r'^(?=  File \"[^\"]+\", line \\d+)', Generic.Traceback, 'intb'),\n            (r'^.*\\n', Other),\n        ],\n        'intb': [\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(, in )(.+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)),\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Whitespace)),\n            (r'^(    )(.+)(\\n)',\n             bygroups(Text, using(Python2Lexer), Whitespace), 'marker'),\n            (r'^([ \\t]*)(\\.\\.\\.)(\\n)',\n             bygroups(Text, Comment, Whitespace)),  # for doctests...\n            (r'^([^:]+)(: )(.+)(\\n)',\n             bygroups(Generic.Error, Text, Name, Whitespace), '#pop'),\n            (r'^([a-zA-Z_]\\w*)(:?\\n)',\n             bygroups(Generic.Error, Whitespace), '#pop')\n        ],\n        'marker': [\n            # For syntax errors.\n            (r'( {4,})(\\^)', bygroups(Text, Punctuation.Marker), '#pop'),\n            default('#pop'),\n        ],\n    }\n\n\nclass CythonLexer(RegexLexer):\n    \"\"\"\n    For Pyrex and Cython source code.\n    \"\"\"\n\n    name = 'Cython'\n    url = 'https://cython.org'\n    aliases = ['cython', 'pyx', 'pyrex']\n    filenames = ['*.pyx', '*.pxd', '*.pxi']\n    mimetypes = ['text/x-cython', 'application/x-cython']\n    version_added = '1.1'\n\n    tokens = {\n        'root': [\n            (r'\\n', Whitespace),\n            (r'^(\\s*)(\"\"\"(?:.|\\n)*?\"\"\")', bygroups(Whitespace, String.Doc)),\n            (r\"^(\\s*)('''(?:.|\\n)*?''')\", bygroups(Whitespace, String.Doc)),\n            (r'[^\\S\\n]+', Text),\n            (r'#.*$', Comment),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'\\\\\\n', Whitespace),\n            (r'\\\\', Text),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            (r'(<)([a-zA-Z0-9.?]+)(>)',\n             bygroups(Punctuation, Keyword.Type, Punctuation)),\n            (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator),\n            (r'(from)(\\d+)(<=)(\\s+)(<)(\\d+)(:)',\n             bygroups(Keyword, Number.Integer, Operator, Whitespace, Operator,\n                      Name, Punctuation)),\n            include('keywords'),\n            (r'(def|property)(\\s+)', bygroups(Keyword, Whitespace), 'funcname'),\n            (r'(cp?def)(\\s+)', bygroups(Keyword, Whitespace), 'cdef'),\n            # (should actually start a block with only cdefs)\n            (r'(cdef)(:)', bygroups(Keyword, Punctuation)),\n            (r'(class|struct)(\\s+)', bygroups(Keyword, Whitespace), 'classname'),\n            (r'(from)(\\s+)', bygroups(Keyword, Whitespace), 'fromimport'),\n            (r'(c?import)(\\s+)', bygroups(Keyword, Whitespace), 'import'),\n            include('builtins'),\n            include('backtick'),\n            ('(?:[rR]|[uU][rR]|[rR][uU])\"\"\"', String, 'tdqs'),\n            (\"(?:[rR]|[uU][rR]|[rR][uU])'''\", String, 'tsqs'),\n            ('(?:[rR]|[uU][rR]|[rR][uU])\"', String, 'dqs'),\n            (\"(?:[rR]|[uU][rR]|[rR][uU])'\", String, 'sqs'),\n            ('[uU]?\"\"\"', String, combined('stringescape', 'tdqs')),\n            (\"[uU]?'''\", String, combined('stringescape', 'tsqs')),\n            ('[uU]?\"', String, combined('stringescape', 'dqs')),\n            (\"[uU]?'\", String, combined('stringescape', 'sqs')),\n            include('name'),\n            include('numbers'),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', 'elif',\n                'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil',\n                'global', 'if', 'include', 'lambda', 'nogil', 'pass', 'print',\n                'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n            (r'(DEF|IF|ELIF|ELSE)\\b', Comment.Preproc),\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint',\n                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',\n                'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr',\n                'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit',\n                'file', 'filter', 'float', 'frozenset', 'getattr', 'globals',\n                'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance',\n                'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max',\n                'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'Py_ssize_t',\n                'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed',\n                'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod',\n                'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'unsigned',\n                'vars', 'xrange', 'zip'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|None|Ellipsis|NotImplemented|False|True|NULL'\n             r')\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',\n                'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',\n                'IOError', 'ImportError', 'ImportWarning', 'IndentationError',\n                'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n                'MemoryError', 'NameError', 'NotImplemented', 'NotImplementedError',\n                'OSError', 'OverflowError', 'OverflowWarning',\n                'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',\n                'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',\n                'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',\n                'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',\n                'ZeroDivisionError'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'numbers': [\n            (r'(\\d+\\.?\\d*|\\d*\\.\\d+)([eE][+-]?[0-9]+)?', Number.Float),\n            (r'0\\d+', Number.Oct),\n            (r'0[xX][a-fA-F0-9]+', Number.Hex),\n            (r'\\d+L', Number.Integer.Long),\n            (r'\\d+', Number.Integer)\n        ],\n        'backtick': [\n            ('`.*?`', String.Backtick),\n        ],\n        'name': [\n            (r'@\\w+', Name.Decorator),\n            (r'[a-zA-Z_]\\w*', Name),\n        ],\n        'funcname': [\n            (r'[a-zA-Z_]\\w*', Name.Function, '#pop')\n        ],\n        'cdef': [\n            (r'(public|readonly|extern|api|inline)\\b', Keyword.Reserved),\n            (r'(struct|enum|union|class)\\b', Keyword),\n            (r'([a-zA-Z_]\\w*)(\\s*)(?=[(:#=]|$)',\n             bygroups(Name.Function, Whitespace), '#pop'),\n            (r'([a-zA-Z_]\\w*)(\\s*)(,)',\n             bygroups(Name.Function, Whitespace, Punctuation)),\n            (r'from\\b', Keyword, '#pop'),\n            (r'as\\b', Keyword),\n            (r':', Punctuation, '#pop'),\n            (r'(?=[\"\\'])', Text, '#pop'),\n            (r'[a-zA-Z_]\\w*', Keyword.Type),\n            (r'.', Text),\n        ],\n        'classname': [\n            (r'[a-zA-Z_]\\w*', Name.Class, '#pop')\n        ],\n        'import': [\n            (r'(\\s+)(as)(\\s+)', bygroups(Whitespace, Keyword, Whitespace)),\n            (r'[a-zA-Z_][\\w.]*', Name.Namespace),\n            (r'(\\s*)(,)(\\s*)', bygroups(Whitespace, Operator, Whitespace)),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(\\s+)(c?import)\\b', bygroups(Whitespace, Keyword), '#pop'),\n            (r'[a-zA-Z_.][\\w.]*', Name.Namespace),\n            # ``cdef foo from \"header\"``, or ``for foo from 0 < i < 10``\n            default('#pop'),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'strings': [\n            (r'%(\\([a-zA-Z0-9]+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            (r'[^\\\\\\'\"%\\n]+', String),\n            # quotes, percents and backslashes must be parsed one at a time\n            (r'[\\'\"\\\\]', String),\n            # unhandled string formatting sign\n            (r'%', String)\n            # newlines are an error (use \"nl\" state)\n        ],\n        'nl': [\n            (r'\\n', String)\n        ],\n        'dqs': [\n            (r'\"', String, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here again for raw strings\n            include('strings')\n        ],\n        'sqs': [\n            (r\"'\", String, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here again for raw strings\n            include('strings')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String, '#pop'),\n            include('strings'),\n            include('nl')\n        ],\n        'tsqs': [\n            (r\"'''\", String, '#pop'),\n            include('strings'),\n            include('nl')\n        ],\n    }\n\n\nclass DgLexer(RegexLexer):\n    \"\"\"\n    Lexer for dg,\n    a functional and object-oriented programming language\n    running on the CPython 3 VM.\n    \"\"\"\n    name = 'dg'\n    aliases = ['dg']\n    filenames = ['*.dg']\n    mimetypes = ['text/x-dg']\n    url = 'http://pyos.github.io/dg'\n    version_added = '1.6'\n\n    tokens = {\n        'root': [\n            (r'\\s+', Text),\n            (r'#.*?$', Comment.Single),\n\n            (r'(?i)0b[01]+', Number.Bin),\n            (r'(?i)0o[0-7]+', Number.Oct),\n            (r'(?i)0x[0-9a-f]+', Number.Hex),\n            (r'(?i)[+-]?[0-9]+\\.[0-9]+(e[+-]?[0-9]+)?j?', Number.Float),\n            (r'(?i)[+-]?[0-9]+e[+-]?\\d+j?', Number.Float),\n            (r'(?i)[+-]?[0-9]+j?', Number.Integer),\n\n            (r\"(?i)(br|r?b?)'''\", String, combined('stringescape', 'tsqs', 'string')),\n            (r'(?i)(br|r?b?)\"\"\"', String, combined('stringescape', 'tdqs', 'string')),\n            (r\"(?i)(br|r?b?)'\", String, combined('stringescape', 'sqs', 'string')),\n            (r'(?i)(br|r?b?)\"', String, combined('stringescape', 'dqs', 'string')),\n\n            (r\"`\\w+'*`\", Operator),\n            (r'\\b(and|in|is|or|where)\\b', Operator.Word),\n            (r'[!$%&*+\\-./:<-@\\\\^|~;,]+', Operator),\n\n            (words((\n                'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'dict\\'',\n                'float', 'frozenset', 'int', 'list', 'list\\'', 'memoryview', 'object',\n                'property', 'range', 'set', 'set\\'', 'slice', 'staticmethod', 'str',\n                'super', 'tuple', 'tuple\\'', 'type'),\n                   prefix=r'(?<!\\.)', suffix=r'(?![\\'\\w])'),\n             Name.Builtin),\n            (words((\n                '__import__', 'abs', 'all', 'any', 'bin', 'bind', 'chr', 'cmp', 'compile',\n                'complex', 'delattr', 'dir', 'divmod', 'drop', 'dropwhile', 'enumerate',\n                'eval', 'exhaust', 'filter', 'flip', 'foldl1?', 'format', 'fst',\n                'getattr', 'globals', 'hasattr', 'hash', 'head', 'hex', 'id', 'init',\n                'input', 'isinstance', 'issubclass', 'iter', 'iterate', 'last', 'len',\n                'locals', 'map', 'max', 'min', 'next', 'oct', 'open', 'ord', 'pow',\n                'print', 'repr', 'reversed', 'round', 'setattr', 'scanl1?', 'snd',\n                'sorted', 'sum', 'tail', 'take', 'takewhile', 'vars', 'zip'),\n                   prefix=r'(?<!\\.)', suffix=r'(?![\\'\\w])'),\n             Name.Builtin),\n            (r\"(?<!\\.)(self|Ellipsis|NotImplemented|None|True|False)(?!['\\w])\",\n             Name.Builtin.Pseudo),\n\n            (r\"(?<!\\.)[A-Z]\\w*(Error|Exception|Warning)'*(?!['\\w])\",\n             Name.Exception),\n            (r\"(?<!\\.)(Exception|GeneratorExit|KeyboardInterrupt|StopIteration|\"\n             r\"SystemExit)(?!['\\w])\", Name.Exception),\n\n            (r\"(?<![\\w.])(except|finally|for|if|import|not|otherwise|raise|\"\n             r\"subclass|while|with|yield)(?!['\\w])\", Keyword.Reserved),\n\n            (r\"[A-Z_]+'*(?!['\\w])\", Name),\n            (r\"[A-Z]\\w+'*(?!['\\w])\", Keyword.Type),\n            (r\"\\w+'*\", Name),\n\n            (r'[()]', Punctuation),\n            (r'.', Error),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'string': [\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            (r'[^\\\\\\'\"%\\n]+', String),\n            # quotes, percents and backslashes must be parsed one at a time\n            (r'[\\'\"\\\\]', String),\n            # unhandled string formatting sign\n            (r'%', String),\n            (r'\\n', String)\n        ],\n        'dqs': [\n            (r'\"', String, '#pop')\n        ],\n        'sqs': [\n            (r\"'\", String, '#pop')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String, '#pop')\n        ],\n        'tsqs': [\n            (r\"'''\", String, '#pop')\n        ],\n    }\n\n\nclass NumPyLexer(PythonLexer):\n    \"\"\"\n    A Python lexer recognizing Numerical Python builtins.\n    \"\"\"\n\n    name = 'NumPy'\n    url = 'https://numpy.org/'\n    aliases = ['numpy']\n    version_added = '0.10'\n\n    # override the mimetypes to not inherit them from python\n    mimetypes = []\n    filenames = []\n\n    EXTRA_KEYWORDS = {\n        'abs', 'absolute', 'accumulate', 'add', 'alen', 'all', 'allclose',\n        'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append',\n        'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh',\n        'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin',\n        'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal',\n        'array_equiv', 'array_repr', 'array_split', 'array_str', 'arrayrange',\n        'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray',\n        'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'astype',\n        'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett',\n        'base_repr', 'beta', 'binary_repr', 'bincount', 'binomial',\n        'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman',\n        'bmat', 'broadcast', 'byte_bounds', 'bytes', 'byteswap', 'c_',\n        'can_cast', 'ceil', 'choose', 'clip', 'column_stack', 'common_type',\n        'compare_chararrays', 'compress', 'concatenate', 'conj', 'conjugate',\n        'convolve', 'copy', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov',\n        'cross', 'cumprod', 'cumproduct', 'cumsum', 'delete', 'deprecate',\n        'diag', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide',\n        'dot', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'empty',\n        'empty_like', 'equal', 'exp', 'expand_dims', 'expm1', 'extract', 'eye',\n        'fabs', 'fastCopyAndTranspose', 'fft', 'fftfreq', 'fftshift', 'fill',\n        'finfo', 'fix', 'flat', 'flatnonzero', 'flatten', 'fliplr', 'flipud',\n        'floor', 'floor_divide', 'fmod', 'frexp', 'fromarrays', 'frombuffer',\n        'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromstring',\n        'generic', 'get_array_wrap', 'get_include', 'get_numarray_include',\n        'get_numpy_include', 'get_printoptions', 'getbuffer', 'getbufsize',\n        'geterr', 'geterrcall', 'geterrobj', 'getfield', 'gradient', 'greater',\n        'greater_equal', 'gumbel', 'hamming', 'hanning', 'histogram',\n        'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0',\n        'identity', 'ifft', 'imag', 'index_exp', 'indices', 'inf', 'info',\n        'inner', 'insert', 'int_asbuffer', 'interp', 'intersect1d',\n        'intersect1d_nu', 'inv', 'invert', 'iscomplex', 'iscomplexobj',\n        'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf',\n        'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_',\n        'issubdtype', 'issubsctype', 'item', 'itemset', 'iterable', 'ix_',\n        'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort',\n        'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2',\n        'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace',\n        'lstsq', 'mat', 'matrix', 'max', 'maximum', 'maximum_sctype',\n        'may_share_memory', 'mean', 'median', 'meshgrid', 'mgrid', 'min',\n        'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan',\n        'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum',\n        'ndenumerate', 'ndim', 'ndindex', 'negative', 'newaxis', 'newbuffer',\n        'newbyteorder', 'nonzero', 'not_equal', 'obj2sctype', 'ogrid', 'ones',\n        'ones_like', 'outer', 'permutation', 'piecewise', 'pinv', 'pkgload',\n        'place', 'poisson', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv',\n        'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'prod',\n        'product', 'ptp', 'put', 'putmask', 'r_', 'randint', 'random_integers',\n        'random_sample', 'ranf', 'rank', 'ravel', 'real', 'real_if_close',\n        'recarray', 'reciprocal', 'reduce', 'remainder', 'repeat', 'require',\n        'reshape', 'resize', 'restoredot', 'right_shift', 'rint', 'roll',\n        'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_',\n        'sample', 'savetxt', 'sctype2char', 'searchsorted', 'seed', 'select',\n        'set_numeric_ops', 'set_printoptions', 'set_string_function',\n        'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj',\n        'setfield', 'setflags', 'setmember1d', 'setxor1d', 'shape',\n        'show_config', 'shuffle', 'sign', 'signbit', 'sin', 'sinc', 'sinh',\n        'size', 'slice', 'solve', 'sometrue', 'sort', 'sort_complex', 'source',\n        'split', 'sqrt', 'square', 'squeeze', 'standard_normal', 'std',\n        'subtract', 'sum', 'svd', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot',\n        'test', 'tile', 'tofile', 'tolist', 'tostring', 'trace', 'transpose',\n        'trapz', 'tri', 'tril', 'trim_zeros', 'triu', 'true_divide', 'typeDict',\n        'typename', 'uniform', 'union1d', 'unique', 'unique1d', 'unravel_index',\n        'unwrap', 'vander', 'var', 'vdot', 'vectorize', 'view', 'vonmises',\n        'vsplit', 'vstack', 'weibull', 'where', 'who', 'zeros', 'zeros_like'\n    }\n\n    def get_tokens_unprocessed(self, text):\n        for index, token, value in \\\n                PythonLexer.get_tokens_unprocessed(self, text):\n            if token is Name and value in self.EXTRA_KEYWORDS:\n                yield index, Keyword.Pseudo, value\n            else:\n                yield index, token, value\n\n    def analyse_text(text):\n        ltext = text[:1000]\n        return (shebang_matches(text, r'pythonw?(3(\\.\\d)?)?') or\n                'import ' in ltext) \\\n            and ('import numpy' in ltext or 'from numpy import' in ltext)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/modeline.py",
    "content": "\"\"\"\n    pygments.modeline\n    ~~~~~~~~~~~~~~~~~\n\n    A simple modeline parser (based on pymodeline).\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\n__all__ = ['get_filetype_from_buffer']\n\n\nmodeline_re = re.compile(r'''\n    (?: vi | vim | ex ) (?: [<=>]? \\d* )? :\n    .* (?: ft | filetype | syn | syntax ) = ( [^:\\s]+ )\n''', re.VERBOSE)\n\n\ndef get_filetype_from_line(l): # noqa: E741\n    m = modeline_re.search(l)\n    if m:\n        return m.group(1)\n\n\ndef get_filetype_from_buffer(buf, max_lines=5):\n    \"\"\"\n    Scan the buffer for modelines and return filetype if one is found.\n    \"\"\"\n    lines = buf.splitlines()\n    for line in lines[-1:-max_lines-1:-1]:\n        ret = get_filetype_from_line(line)\n        if ret:\n            return ret\n    for i in range(max_lines, -1, -1):\n        if i < len(lines):\n            ret = get_filetype_from_line(lines[i])\n            if ret:\n                return ret\n\n    return None\n"
  },
  {
    "path": "src/pip/_vendor/pygments/plugin.py",
    "content": "\"\"\"\n    pygments.plugin\n    ~~~~~~~~~~~~~~~\n\n    Pygments plugin interface.\n\n    lexer plugins::\n\n        [pygments.lexers]\n        yourlexer = yourmodule:YourLexer\n\n    formatter plugins::\n\n        [pygments.formatters]\n        yourformatter = yourformatter:YourFormatter\n        /.ext = yourformatter:YourFormatter\n\n    As you can see, you can define extensions for the formatter\n    with a leading slash.\n\n    syntax plugins::\n\n        [pygments.styles]\n        yourstyle = yourstyle:YourStyle\n\n    filter plugin::\n\n        [pygments.filter]\n        yourfilter = yourfilter:YourFilter\n\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\nfrom importlib.metadata import entry_points\n\nLEXER_ENTRY_POINT = 'pygments.lexers'\nFORMATTER_ENTRY_POINT = 'pygments.formatters'\nSTYLE_ENTRY_POINT = 'pygments.styles'\nFILTER_ENTRY_POINT = 'pygments.filters'\n\n\ndef iter_entry_points(group_name):\n    groups = entry_points()\n    if hasattr(groups, 'select'):\n        # New interface in Python 3.10 and newer versions of the\n        # importlib_metadata backport.\n        return groups.select(group=group_name)\n    else:\n        # Older interface, deprecated in Python 3.10 and recent\n        # importlib_metadata, but we need it in Python 3.8 and 3.9.\n        return groups.get(group_name, [])\n\n\ndef find_plugin_lexers():\n    for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):\n        yield entrypoint.load()\n\n\ndef find_plugin_formatters():\n    for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n\n\ndef find_plugin_styles():\n    for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n\n\ndef find_plugin_filters():\n    for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n"
  },
  {
    "path": "src/pip/_vendor/pygments/regexopt.py",
    "content": "\"\"\"\n    pygments.regexopt\n    ~~~~~~~~~~~~~~~~~\n\n    An algorithm that generates optimized regexes for matching long lists of\n    literal strings.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nfrom re import escape\nfrom os.path import commonprefix\nfrom itertools import groupby\nfrom operator import itemgetter\n\nCS_ESCAPE = re.compile(r'[\\[\\^\\\\\\-\\]]')\nFIRST_ELEMENT = itemgetter(0)\n\n\ndef make_charset(letters):\n    return '[' + CS_ESCAPE.sub(lambda m: '\\\\' + m.group(), ''.join(letters)) + ']'\n\n\ndef regex_opt_inner(strings, open_paren):\n    \"\"\"Return a regex that matches any string in the sorted list of strings.\"\"\"\n    close_paren = open_paren and ')' or ''\n    # print strings, repr(open_paren)\n    if not strings:\n        # print '-> nothing left'\n        return ''\n    first = strings[0]\n    if len(strings) == 1:\n        # print '-> only 1 string'\n        return open_paren + escape(first) + close_paren\n    if not first:\n        # print '-> first string empty'\n        return open_paren + regex_opt_inner(strings[1:], '(?:') \\\n            + '?' + close_paren\n    if len(first) == 1:\n        # multiple one-char strings? make a charset\n        oneletter = []\n        rest = []\n        for s in strings:\n            if len(s) == 1:\n                oneletter.append(s)\n            else:\n                rest.append(s)\n        if len(oneletter) > 1:  # do we have more than one oneletter string?\n            if rest:\n                # print '-> 1-character + rest'\n                return open_paren + regex_opt_inner(rest, '') + '|' \\\n                    + make_charset(oneletter) + close_paren\n            # print '-> only 1-character'\n            return open_paren + make_charset(oneletter) + close_paren\n    prefix = commonprefix(strings)\n    if prefix:\n        plen = len(prefix)\n        # we have a prefix for all strings\n        # print '-> prefix:', prefix\n        return open_paren + escape(prefix) \\\n            + regex_opt_inner([s[plen:] for s in strings], '(?:') \\\n            + close_paren\n    # is there a suffix?\n    strings_rev = [s[::-1] for s in strings]\n    suffix = commonprefix(strings_rev)\n    if suffix:\n        slen = len(suffix)\n        # print '-> suffix:', suffix[::-1]\n        return open_paren \\\n            + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \\\n            + escape(suffix[::-1]) + close_paren\n    # recurse on common 1-string prefixes\n    # print '-> last resort'\n    return open_paren + \\\n        '|'.join(regex_opt_inner(list(group[1]), '')\n                 for group in groupby(strings, lambda s: s[0] == first[0])) \\\n        + close_paren\n\n\ndef regex_opt(strings, prefix='', suffix=''):\n    \"\"\"Return a compiled regex that matches any string in the given list.\n\n    The strings to match must be literal strings, not regexes.  They will be\n    regex-escaped.\n\n    *prefix* and *suffix* are pre- and appended to the final regex.\n    \"\"\"\n    strings = sorted(strings)\n    return prefix + regex_opt_inner(strings, '(') + suffix\n"
  },
  {
    "path": "src/pip/_vendor/pygments/scanner.py",
    "content": "\"\"\"\n    pygments.scanner\n    ~~~~~~~~~~~~~~~~\n\n    This library implements a regex based scanner. Some languages\n    like Pascal are easy to parse but have some keywords that\n    depend on the context. Because of this it's impossible to lex\n    that just by using a regular expression lexer like the\n    `RegexLexer`.\n\n    Have a look at the `DelphiLexer` to get an idea of how to use\n    this scanner.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\nimport re\n\n\nclass EndOfText(RuntimeError):\n    \"\"\"\n    Raise if end of text is reached and the user\n    tried to call a match function.\n    \"\"\"\n\n\nclass Scanner:\n    \"\"\"\n    Simple scanner\n\n    All method patterns are regular expression strings (not\n    compiled expressions!)\n    \"\"\"\n\n    def __init__(self, text, flags=0):\n        \"\"\"\n        :param text:    The text which should be scanned\n        :param flags:   default regular expression flags\n        \"\"\"\n        self.data = text\n        self.data_length = len(text)\n        self.start_pos = 0\n        self.pos = 0\n        self.flags = flags\n        self.last = None\n        self.match = None\n        self._re_cache = {}\n\n    def eos(self):\n        \"\"\"`True` if the scanner reached the end of text.\"\"\"\n        return self.pos >= self.data_length\n    eos = property(eos, eos.__doc__)\n\n    def check(self, pattern):\n        \"\"\"\n        Apply `pattern` on the current position and return\n        the match object. (Doesn't touch pos). Use this for\n        lookahead.\n        \"\"\"\n        if self.eos:\n            raise EndOfText()\n        if pattern not in self._re_cache:\n            self._re_cache[pattern] = re.compile(pattern, self.flags)\n        return self._re_cache[pattern].match(self.data, self.pos)\n\n    def test(self, pattern):\n        \"\"\"Apply a pattern on the current position and check\n        if it patches. Doesn't touch pos.\n        \"\"\"\n        return self.check(pattern) is not None\n\n    def scan(self, pattern):\n        \"\"\"\n        Scan the text for the given pattern and update pos/match\n        and related fields. The return value is a boolean that\n        indicates if the pattern matched. The matched value is\n        stored on the instance as ``match``, the last value is\n        stored as ``last``. ``start_pos`` is the position of the\n        pointer before the pattern was matched, ``pos`` is the\n        end position.\n        \"\"\"\n        if self.eos:\n            raise EndOfText()\n        if pattern not in self._re_cache:\n            self._re_cache[pattern] = re.compile(pattern, self.flags)\n        self.last = self.match\n        m = self._re_cache[pattern].match(self.data, self.pos)\n        if m is None:\n            return False\n        self.start_pos = m.start()\n        self.pos = m.end()\n        self.match = m.group()\n        return True\n\n    def get_char(self):\n        \"\"\"Scan exactly one char.\"\"\"\n        self.scan('.')\n\n    def __repr__(self):\n        return '<%s %d/%d>' % (\n            self.__class__.__name__,\n            self.pos,\n            self.data_length\n        )\n"
  },
  {
    "path": "src/pip/_vendor/pygments/sphinxext.py",
    "content": "\"\"\"\n    pygments.sphinxext\n    ~~~~~~~~~~~~~~~~~~\n\n    Sphinx extension to generate automatic documentation of lexers,\n    formatters and filters.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport sys\n\nfrom docutils import nodes\nfrom docutils.statemachine import ViewList\nfrom docutils.parsers.rst import Directive\nfrom sphinx.util.nodes import nested_parse_with_titles\n\n\nMODULEDOC = '''\n.. module:: %s\n\n%s\n%s\n'''\n\nLEXERDOC = '''\n.. class:: %s\n\n    :Short names: %s\n    :Filenames:   %s\n    :MIME types:  %s\n\n    %s\n\n    %s\n\n'''\n\nFMTERDOC = '''\n.. class:: %s\n\n    :Short names: %s\n    :Filenames: %s\n\n    %s\n\n'''\n\nFILTERDOC = '''\n.. class:: %s\n\n    :Name: %s\n\n    %s\n\n'''\n\n\nclass PygmentsDoc(Directive):\n    \"\"\"\n    A directive to collect all lexers/formatters/filters and generate\n    autoclass directives for them.\n    \"\"\"\n    has_content = False\n    required_arguments = 1\n    optional_arguments = 0\n    final_argument_whitespace = False\n    option_spec = {}\n\n    def run(self):\n        self.filenames = set()\n        if self.arguments[0] == 'lexers':\n            out = self.document_lexers()\n        elif self.arguments[0] == 'formatters':\n            out = self.document_formatters()\n        elif self.arguments[0] == 'filters':\n            out = self.document_filters()\n        elif self.arguments[0] == 'lexers_overview':\n            out = self.document_lexers_overview()\n        else:\n            raise Exception('invalid argument for \"pygmentsdoc\" directive')\n        node = nodes.compound()\n        vl = ViewList(out.split('\\n'), source='')\n        nested_parse_with_titles(self.state, vl, node)\n        for fn in self.filenames:\n            self.state.document.settings.record_dependencies.add(fn)\n        return node.children\n\n    def document_lexers_overview(self):\n        \"\"\"Generate a tabular overview of all lexers.\n\n        The columns are the lexer name, the extensions handled by this lexer\n        (or \"None\"), the aliases and a link to the lexer class.\"\"\"\n        from pip._vendor.pygments.lexers._mapping import LEXERS\n        from pip._vendor.pygments.lexers import find_lexer_class\n        out = []\n\n        table = []\n\n        def format_link(name, url):\n            if url:\n                return f'`{name} <{url}>`_'\n            return name\n\n        for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()):\n            lexer_cls = find_lexer_class(data[1])\n            extensions = lexer_cls.filenames + lexer_cls.alias_filenames\n\n            table.append({\n                'name': format_link(data[1], lexer_cls.url),\n                'extensions': ', '.join(extensions).replace('*', '\\\\*').replace('_', '\\\\') or 'None',\n                'aliases': ', '.join(data[2]),\n                'class': f'{data[0]}.{classname}'\n            })\n\n        column_names = ['name', 'extensions', 'aliases', 'class']\n        column_lengths = [max([len(row[column]) for row in table if row[column]])\n                          for column in column_names]\n\n        def write_row(*columns):\n            \"\"\"Format a table row\"\"\"\n            out = []\n            for length, col in zip(column_lengths, columns):\n                if col:\n                    out.append(col.ljust(length))\n                else:\n                    out.append(' '*length)\n\n            return ' '.join(out)\n\n        def write_seperator():\n            \"\"\"Write a table separator row\"\"\"\n            sep = ['='*c for c in column_lengths]\n            return write_row(*sep)\n\n        out.append(write_seperator())\n        out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class'))\n        out.append(write_seperator())\n        for row in table:\n            out.append(write_row(\n                row['name'],\n                row['extensions'],\n                row['aliases'],\n                f':class:`~{row[\"class\"]}`'))\n        out.append(write_seperator())\n\n        return '\\n'.join(out)\n\n    def document_lexers(self):\n        from pip._vendor.pygments.lexers._mapping import LEXERS\n        from pip._vendor import pygments\n        import inspect\n        import pathlib\n\n        out = []\n        modules = {}\n        moduledocstrings = {}\n        for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]):\n            module = data[0]\n            mod = __import__(module, None, None, [classname])\n            self.filenames.add(mod.__file__)\n            cls = getattr(mod, classname)\n            if not cls.__doc__:\n                print(f\"Warning: {classname} does not have a docstring.\")\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n\n            example_file = getattr(cls, '_example', None)\n            if example_file:\n                p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\\\n                    'tests' / 'examplefiles' / example_file\n                content = p.read_text(encoding='utf-8')\n                if not content:\n                    raise Exception(\n                        f\"Empty example file '{example_file}' for lexer \"\n                        f\"{classname}\")\n\n                if data[2]:\n                    lexer_name = data[2][0]\n                    docstring += '\\n\\n    .. admonition:: Example\\n'\n                    docstring += f'\\n      .. code-block:: {lexer_name}\\n\\n'\n                    for line in content.splitlines():\n                        docstring += f'          {line}\\n'\n\n            if cls.version_added:\n                version_line = f'.. versionadded:: {cls.version_added}'\n            else:\n                version_line = ''\n\n            modules.setdefault(module, []).append((\n                classname,\n                ', '.join(data[2]) or 'None',\n                ', '.join(data[3]).replace('*', '\\\\*').replace('_', '\\\\') or 'None',\n                ', '.join(data[4]) or 'None',\n                docstring,\n                version_line))\n            if module not in moduledocstrings:\n                moddoc = mod.__doc__\n                if isinstance(moddoc, bytes):\n                    moddoc = moddoc.decode('utf8')\n                moduledocstrings[module] = moddoc\n\n        for module, lexers in sorted(modules.items(), key=lambda x: x[0]):\n            if moduledocstrings[module] is None:\n                raise Exception(f\"Missing docstring for {module}\")\n            heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.')\n            out.append(MODULEDOC % (module, heading, '-'*len(heading)))\n            for data in lexers:\n                out.append(LEXERDOC % data)\n\n        return ''.join(out)\n\n    def document_formatters(self):\n        from pip._vendor.pygments.formatters import FORMATTERS\n\n        out = []\n        for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]):\n            module = data[0]\n            mod = __import__(module, None, None, [classname])\n            self.filenames.add(mod.__file__)\n            cls = getattr(mod, classname)\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n            heading = cls.__name__\n            out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None',\n                                   ', '.join(data[3]).replace('*', '\\\\*') or 'None',\n                                   docstring))\n        return ''.join(out)\n\n    def document_filters(self):\n        from pip._vendor.pygments.filters import FILTERS\n\n        out = []\n        for name, cls in FILTERS.items():\n            self.filenames.add(sys.modules[cls.__module__].__file__)\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n            out.append(FILTERDOC % (cls.__name__, name, docstring))\n        return ''.join(out)\n\n\ndef setup(app):\n    app.add_directive('pygmentsdoc', PygmentsDoc)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/style.py",
    "content": "\"\"\"\n    pygments.style\n    ~~~~~~~~~~~~~~\n\n    Basic style object.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.token import Token, STANDARD_TYPES\n\n# Default mapping of ansixxx to RGB colors.\n_ansimap = {\n    # dark\n    'ansiblack': '000000',\n    'ansired': '7f0000',\n    'ansigreen': '007f00',\n    'ansiyellow': '7f7fe0',\n    'ansiblue': '00007f',\n    'ansimagenta': '7f007f',\n    'ansicyan': '007f7f',\n    'ansigray': 'e5e5e5',\n    # normal\n    'ansibrightblack': '555555',\n    'ansibrightred': 'ff0000',\n    'ansibrightgreen': '00ff00',\n    'ansibrightyellow': 'ffff00',\n    'ansibrightblue': '0000ff',\n    'ansibrightmagenta': 'ff00ff',\n    'ansibrightcyan': '00ffff',\n    'ansiwhite': 'ffffff',\n}\n# mapping of deprecated #ansixxx colors to new color names\n_deprecated_ansicolors = {\n    # dark\n    '#ansiblack': 'ansiblack',\n    '#ansidarkred': 'ansired',\n    '#ansidarkgreen': 'ansigreen',\n    '#ansibrown': 'ansiyellow',\n    '#ansidarkblue': 'ansiblue',\n    '#ansipurple': 'ansimagenta',\n    '#ansiteal': 'ansicyan',\n    '#ansilightgray': 'ansigray',\n    # normal\n    '#ansidarkgray': 'ansibrightblack',\n    '#ansired': 'ansibrightred',\n    '#ansigreen': 'ansibrightgreen',\n    '#ansiyellow': 'ansibrightyellow',\n    '#ansiblue': 'ansibrightblue',\n    '#ansifuchsia': 'ansibrightmagenta',\n    '#ansiturquoise': 'ansibrightcyan',\n    '#ansiwhite': 'ansiwhite',\n}\nansicolors = set(_ansimap)\n\n\nclass StyleMeta(type):\n\n    def __new__(mcs, name, bases, dct):\n        obj = type.__new__(mcs, name, bases, dct)\n        for token in STANDARD_TYPES:\n            if token not in obj.styles:\n                obj.styles[token] = ''\n\n        def colorformat(text):\n            if text in ansicolors:\n                return text\n            if text[0:1] == '#':\n                col = text[1:]\n                if len(col) == 6:\n                    return col\n                elif len(col) == 3:\n                    return col[0] * 2 + col[1] * 2 + col[2] * 2\n            elif text == '':\n                return ''\n            elif text.startswith('var') or text.startswith('calc'):\n                return text\n            assert False, f\"wrong color format {text!r}\"\n\n        _styles = obj._styles = {}\n\n        for ttype in obj.styles:\n            for token in ttype.split():\n                if token in _styles:\n                    continue\n                ndef = _styles.get(token.parent, None)\n                styledefs = obj.styles.get(token, '').split()\n                if not ndef or token is None:\n                    ndef = ['', 0, 0, 0, '', '', 0, 0, 0]\n                elif 'noinherit' in styledefs and token is not Token:\n                    ndef = _styles[Token][:]\n                else:\n                    ndef = ndef[:]\n                _styles[token] = ndef\n                for styledef in obj.styles.get(token, '').split():\n                    if styledef == 'noinherit':\n                        pass\n                    elif styledef == 'bold':\n                        ndef[1] = 1\n                    elif styledef == 'nobold':\n                        ndef[1] = 0\n                    elif styledef == 'italic':\n                        ndef[2] = 1\n                    elif styledef == 'noitalic':\n                        ndef[2] = 0\n                    elif styledef == 'underline':\n                        ndef[3] = 1\n                    elif styledef == 'nounderline':\n                        ndef[3] = 0\n                    elif styledef[:3] == 'bg:':\n                        ndef[4] = colorformat(styledef[3:])\n                    elif styledef[:7] == 'border:':\n                        ndef[5] = colorformat(styledef[7:])\n                    elif styledef == 'roman':\n                        ndef[6] = 1\n                    elif styledef == 'sans':\n                        ndef[7] = 1\n                    elif styledef == 'mono':\n                        ndef[8] = 1\n                    else:\n                        ndef[0] = colorformat(styledef)\n\n        return obj\n\n    def style_for_token(cls, token):\n        t = cls._styles[token]\n        ansicolor = bgansicolor = None\n        color = t[0]\n        if color in _deprecated_ansicolors:\n            color = _deprecated_ansicolors[color]\n        if color in ansicolors:\n            ansicolor = color\n            color = _ansimap[color]\n        bgcolor = t[4]\n        if bgcolor in _deprecated_ansicolors:\n            bgcolor = _deprecated_ansicolors[bgcolor]\n        if bgcolor in ansicolors:\n            bgansicolor = bgcolor\n            bgcolor = _ansimap[bgcolor]\n\n        return {\n            'color':        color or None,\n            'bold':         bool(t[1]),\n            'italic':       bool(t[2]),\n            'underline':    bool(t[3]),\n            'bgcolor':      bgcolor or None,\n            'border':       t[5] or None,\n            'roman':        bool(t[6]) or None,\n            'sans':         bool(t[7]) or None,\n            'mono':         bool(t[8]) or None,\n            'ansicolor':    ansicolor,\n            'bgansicolor':  bgansicolor,\n        }\n\n    def list_styles(cls):\n        return list(cls)\n\n    def styles_token(cls, ttype):\n        return ttype in cls._styles\n\n    def __iter__(cls):\n        for token in cls._styles:\n            yield token, cls.style_for_token(token)\n\n    def __len__(cls):\n        return len(cls._styles)\n\n\nclass Style(metaclass=StyleMeta):\n\n    #: overall background color (``None`` means transparent)\n    background_color = '#ffffff'\n\n    #: highlight background color\n    highlight_color = '#ffffcc'\n\n    #: line number font color\n    line_number_color = 'inherit'\n\n    #: line number background color\n    line_number_background_color = 'transparent'\n\n    #: special line number font color\n    line_number_special_color = '#000000'\n\n    #: special line number background color\n    line_number_special_background_color = '#ffffc0'\n\n    #: Style definitions for individual token types.\n    styles = {}\n\n    #: user-friendly style name (used when selecting the style, so this\n    # should be all-lowercase, no spaces, hyphens)\n    name = 'unnamed'\n\n    aliases = []\n\n    # Attribute for lexers defined within Pygments. If set\n    # to True, the style is not shown in the style gallery\n    # on the website. This is intended for language-specific\n    # styles.\n    web_style_gallery_exclude = False\n"
  },
  {
    "path": "src/pip/_vendor/pygments/styles/__init__.py",
    "content": "\"\"\"\n    pygments.styles\n    ~~~~~~~~~~~~~~~\n\n    Contains built-in styles.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.plugin import find_plugin_styles\nfrom pip._vendor.pygments.util import ClassNotFound\nfrom pip._vendor.pygments.styles._mapping import STYLES\n\n#: A dictionary of built-in styles, mapping style names to\n#: ``'submodule::classname'`` strings.\n#: This list is deprecated. Use `pygments.styles.STYLES` instead\nSTYLE_MAP = {v[1]: v[0].split('.')[-1] + '::' + k for k, v in STYLES.items()}\n\n#: Internal reverse mapping to make `get_style_by_name` more efficient\n_STYLE_NAME_TO_MODULE_MAP = {v[1]: (v[0], k) for k, v in STYLES.items()}\n\n\ndef get_style_by_name(name):\n    \"\"\"\n    Return a style class by its short name. The names of the builtin styles\n    are listed in :data:`pygments.styles.STYLE_MAP`.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is\n    found.\n    \"\"\"\n    if name in _STYLE_NAME_TO_MODULE_MAP:\n        mod, cls = _STYLE_NAME_TO_MODULE_MAP[name]\n        builtin = \"yes\"\n    else:\n        for found_name, style in find_plugin_styles():\n            if name == found_name:\n                return style\n        # perhaps it got dropped into our styles package\n        builtin = \"\"\n        mod = 'pygments.styles.' + name\n        cls = name.title() + \"Style\"\n\n    try:\n        mod = __import__(mod, None, None, [cls])\n    except ImportError:\n        raise ClassNotFound(f\"Could not find style module {mod!r}\" +\n                            (builtin and \", though it should be builtin\")\n                            + \".\")\n    try:\n        return getattr(mod, cls)\n    except AttributeError:\n        raise ClassNotFound(f\"Could not find style class {cls!r} in style module.\")\n\n\ndef get_all_styles():\n    \"\"\"Return a generator for all styles by name, both builtin and plugin.\"\"\"\n    for v in STYLES.values():\n        yield v[1]\n    for name, _ in find_plugin_styles():\n        yield name\n"
  },
  {
    "path": "src/pip/_vendor/pygments/styles/_mapping.py",
    "content": "# Automatically generated by scripts/gen_mapfiles.py.\n# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.\n\nSTYLES = {\n    'AbapStyle': ('pygments.styles.abap', 'abap', ()),\n    'AlgolStyle': ('pygments.styles.algol', 'algol', ()),\n    'Algol_NuStyle': ('pygments.styles.algol_nu', 'algol_nu', ()),\n    'ArduinoStyle': ('pygments.styles.arduino', 'arduino', ()),\n    'AutumnStyle': ('pygments.styles.autumn', 'autumn', ()),\n    'BlackWhiteStyle': ('pygments.styles.bw', 'bw', ()),\n    'BorlandStyle': ('pygments.styles.borland', 'borland', ()),\n    'CoffeeStyle': ('pygments.styles.coffee', 'coffee', ()),\n    'ColorfulStyle': ('pygments.styles.colorful', 'colorful', ()),\n    'DefaultStyle': ('pygments.styles.default', 'default', ()),\n    'DraculaStyle': ('pygments.styles.dracula', 'dracula', ()),\n    'EmacsStyle': ('pygments.styles.emacs', 'emacs', ()),\n    'FriendlyGrayscaleStyle': ('pygments.styles.friendly_grayscale', 'friendly_grayscale', ()),\n    'FriendlyStyle': ('pygments.styles.friendly', 'friendly', ()),\n    'FruityStyle': ('pygments.styles.fruity', 'fruity', ()),\n    'GhDarkStyle': ('pygments.styles.gh_dark', 'github-dark', ()),\n    'GruvboxDarkStyle': ('pygments.styles.gruvbox', 'gruvbox-dark', ()),\n    'GruvboxLightStyle': ('pygments.styles.gruvbox', 'gruvbox-light', ()),\n    'IgorStyle': ('pygments.styles.igor', 'igor', ()),\n    'InkPotStyle': ('pygments.styles.inkpot', 'inkpot', ()),\n    'LightbulbStyle': ('pygments.styles.lightbulb', 'lightbulb', ()),\n    'LilyPondStyle': ('pygments.styles.lilypond', 'lilypond', ()),\n    'LovelaceStyle': ('pygments.styles.lovelace', 'lovelace', ()),\n    'ManniStyle': ('pygments.styles.manni', 'manni', ()),\n    'MaterialStyle': ('pygments.styles.material', 'material', ()),\n    'MonokaiStyle': ('pygments.styles.monokai', 'monokai', ()),\n    'MurphyStyle': ('pygments.styles.murphy', 'murphy', ()),\n    'NativeStyle': ('pygments.styles.native', 'native', ()),\n    'NordDarkerStyle': ('pygments.styles.nord', 'nord-darker', ()),\n    'NordStyle': ('pygments.styles.nord', 'nord', ()),\n    'OneDarkStyle': ('pygments.styles.onedark', 'one-dark', ()),\n    'ParaisoDarkStyle': ('pygments.styles.paraiso_dark', 'paraiso-dark', ()),\n    'ParaisoLightStyle': ('pygments.styles.paraiso_light', 'paraiso-light', ()),\n    'PastieStyle': ('pygments.styles.pastie', 'pastie', ()),\n    'PerldocStyle': ('pygments.styles.perldoc', 'perldoc', ()),\n    'RainbowDashStyle': ('pygments.styles.rainbow_dash', 'rainbow_dash', ()),\n    'RrtStyle': ('pygments.styles.rrt', 'rrt', ()),\n    'SasStyle': ('pygments.styles.sas', 'sas', ()),\n    'SolarizedDarkStyle': ('pygments.styles.solarized', 'solarized-dark', ()),\n    'SolarizedLightStyle': ('pygments.styles.solarized', 'solarized-light', ()),\n    'StarofficeStyle': ('pygments.styles.staroffice', 'staroffice', ()),\n    'StataDarkStyle': ('pygments.styles.stata_dark', 'stata-dark', ()),\n    'StataLightStyle': ('pygments.styles.stata_light', 'stata-light', ()),\n    'TangoStyle': ('pygments.styles.tango', 'tango', ()),\n    'TracStyle': ('pygments.styles.trac', 'trac', ()),\n    'VimStyle': ('pygments.styles.vim', 'vim', ()),\n    'VisualStudioStyle': ('pygments.styles.vs', 'vs', ()),\n    'XcodeStyle': ('pygments.styles.xcode', 'xcode', ()),\n    'ZenburnStyle': ('pygments.styles.zenburn', 'zenburn', ()),\n}\n"
  },
  {
    "path": "src/pip/_vendor/pygments/token.py",
    "content": "\"\"\"\n    pygments.token\n    ~~~~~~~~~~~~~~\n\n    Basic token types and the standard tokens.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n\nclass _TokenType(tuple):\n    parent = None\n\n    def split(self):\n        buf = []\n        node = self\n        while node is not None:\n            buf.append(node)\n            node = node.parent\n        buf.reverse()\n        return buf\n\n    def __init__(self, *args):\n        # no need to call super.__init__\n        self.subtypes = set()\n\n    def __contains__(self, val):\n        return self is val or (\n            type(val) is self.__class__ and\n            val[:len(self)] == self\n        )\n\n    def __getattr__(self, val):\n        if not val or not val[0].isupper():\n            return tuple.__getattribute__(self, val)\n        new = _TokenType(self + (val,))\n        setattr(self, val, new)\n        self.subtypes.add(new)\n        new.parent = self\n        return new\n\n    def __repr__(self):\n        return 'Token' + (self and '.' or '') + '.'.join(self)\n\n    def __copy__(self):\n        # These instances are supposed to be singletons\n        return self\n\n    def __deepcopy__(self, memo):\n        # These instances are supposed to be singletons\n        return self\n\n\nToken = _TokenType()\n\n# Special token types\nText = Token.Text\nWhitespace = Text.Whitespace\nEscape = Token.Escape\nError = Token.Error\n# Text that doesn't belong to this lexer (e.g. HTML in PHP)\nOther = Token.Other\n\n# Common token types for source code\nKeyword = Token.Keyword\nName = Token.Name\nLiteral = Token.Literal\nString = Literal.String\nNumber = Literal.Number\nPunctuation = Token.Punctuation\nOperator = Token.Operator\nComment = Token.Comment\n\n# Generic types for non-source code\nGeneric = Token.Generic\n\n# String and some others are not direct children of Token.\n# alias them:\nToken.Token = Token\nToken.String = String\nToken.Number = Number\n\n\ndef is_token_subtype(ttype, other):\n    \"\"\"\n    Return True if ``ttype`` is a subtype of ``other``.\n\n    exists for backwards compatibility. use ``ttype in other`` now.\n    \"\"\"\n    return ttype in other\n\n\ndef string_to_tokentype(s):\n    \"\"\"\n    Convert a string into a token type::\n\n        >>> string_to_token('String.Double')\n        Token.Literal.String.Double\n        >>> string_to_token('Token.Literal.Number')\n        Token.Literal.Number\n        >>> string_to_token('')\n        Token\n\n    Tokens that are already tokens are returned unchanged:\n\n        >>> string_to_token(String)\n        Token.Literal.String\n    \"\"\"\n    if isinstance(s, _TokenType):\n        return s\n    if not s:\n        return Token\n    node = Token\n    for item in s.split('.'):\n        node = getattr(node, item)\n    return node\n\n\n# Map standard token types to short names, used in CSS class naming.\n# If you add a new item, please be sure to run this file to perform\n# a consistency check for duplicate values.\nSTANDARD_TYPES = {\n    Token:                         '',\n\n    Text:                          '',\n    Whitespace:                    'w',\n    Escape:                        'esc',\n    Error:                         'err',\n    Other:                         'x',\n\n    Keyword:                       'k',\n    Keyword.Constant:              'kc',\n    Keyword.Declaration:           'kd',\n    Keyword.Namespace:             'kn',\n    Keyword.Pseudo:                'kp',\n    Keyword.Reserved:              'kr',\n    Keyword.Type:                  'kt',\n\n    Name:                          'n',\n    Name.Attribute:                'na',\n    Name.Builtin:                  'nb',\n    Name.Builtin.Pseudo:           'bp',\n    Name.Class:                    'nc',\n    Name.Constant:                 'no',\n    Name.Decorator:                'nd',\n    Name.Entity:                   'ni',\n    Name.Exception:                'ne',\n    Name.Function:                 'nf',\n    Name.Function.Magic:           'fm',\n    Name.Property:                 'py',\n    Name.Label:                    'nl',\n    Name.Namespace:                'nn',\n    Name.Other:                    'nx',\n    Name.Tag:                      'nt',\n    Name.Variable:                 'nv',\n    Name.Variable.Class:           'vc',\n    Name.Variable.Global:          'vg',\n    Name.Variable.Instance:        'vi',\n    Name.Variable.Magic:           'vm',\n\n    Literal:                       'l',\n    Literal.Date:                  'ld',\n\n    String:                        's',\n    String.Affix:                  'sa',\n    String.Backtick:               'sb',\n    String.Char:                   'sc',\n    String.Delimiter:              'dl',\n    String.Doc:                    'sd',\n    String.Double:                 's2',\n    String.Escape:                 'se',\n    String.Heredoc:                'sh',\n    String.Interpol:               'si',\n    String.Other:                  'sx',\n    String.Regex:                  'sr',\n    String.Single:                 's1',\n    String.Symbol:                 'ss',\n\n    Number:                        'm',\n    Number.Bin:                    'mb',\n    Number.Float:                  'mf',\n    Number.Hex:                    'mh',\n    Number.Integer:                'mi',\n    Number.Integer.Long:           'il',\n    Number.Oct:                    'mo',\n\n    Operator:                      'o',\n    Operator.Word:                 'ow',\n\n    Punctuation:                   'p',\n    Punctuation.Marker:            'pm',\n\n    Comment:                       'c',\n    Comment.Hashbang:              'ch',\n    Comment.Multiline:             'cm',\n    Comment.Preproc:               'cp',\n    Comment.PreprocFile:           'cpf',\n    Comment.Single:                'c1',\n    Comment.Special:               'cs',\n\n    Generic:                       'g',\n    Generic.Deleted:               'gd',\n    Generic.Emph:                  'ge',\n    Generic.Error:                 'gr',\n    Generic.Heading:               'gh',\n    Generic.Inserted:              'gi',\n    Generic.Output:                'go',\n    Generic.Prompt:                'gp',\n    Generic.Strong:                'gs',\n    Generic.Subheading:            'gu',\n    Generic.EmphStrong:            'ges',\n    Generic.Traceback:             'gt',\n}\n"
  },
  {
    "path": "src/pip/_vendor/pygments/unistring.py",
    "content": "\"\"\"\n    pygments.unistring\n    ~~~~~~~~~~~~~~~~~~\n\n    Strings of all Unicode characters of a certain category.\n    Used for matching in Unicode-aware languages. Run to regenerate.\n\n    Inspired by chartypes_create.py from the MoinMoin project.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nCc = '\\x00-\\x1f\\x7f-\\x9f'\n\nCf = '\\xad\\u0600-\\u0605\\u061c\\u06dd\\u070f\\u08e2\\u180e\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2064\\u2066-\\u206f\\ufeff\\ufff9-\\ufffb\\U000110bd\\U000110cd\\U0001bca0-\\U0001bca3\\U0001d173-\\U0001d17a\\U000e0001\\U000e0020-\\U000e007f'\n\nCn = '\\u0378-\\u0379\\u0380-\\u0383\\u038b\\u038d\\u03a2\\u0530\\u0557-\\u0558\\u058b-\\u058c\\u0590\\u05c8-\\u05cf\\u05eb-\\u05ee\\u05f5-\\u05ff\\u061d\\u070e\\u074b-\\u074c\\u07b2-\\u07bf\\u07fb-\\u07fc\\u082e-\\u082f\\u083f\\u085c-\\u085d\\u085f\\u086b-\\u089f\\u08b5\\u08be-\\u08d2\\u0984\\u098d-\\u098e\\u0991-\\u0992\\u09a9\\u09b1\\u09b3-\\u09b5\\u09ba-\\u09bb\\u09c5-\\u09c6\\u09c9-\\u09ca\\u09cf-\\u09d6\\u09d8-\\u09db\\u09de\\u09e4-\\u09e5\\u09ff-\\u0a00\\u0a04\\u0a0b-\\u0a0e\\u0a11-\\u0a12\\u0a29\\u0a31\\u0a34\\u0a37\\u0a3a-\\u0a3b\\u0a3d\\u0a43-\\u0a46\\u0a49-\\u0a4a\\u0a4e-\\u0a50\\u0a52-\\u0a58\\u0a5d\\u0a5f-\\u0a65\\u0a77-\\u0a80\\u0a84\\u0a8e\\u0a92\\u0aa9\\u0ab1\\u0ab4\\u0aba-\\u0abb\\u0ac6\\u0aca\\u0ace-\\u0acf\\u0ad1-\\u0adf\\u0ae4-\\u0ae5\\u0af2-\\u0af8\\u0b00\\u0b04\\u0b0d-\\u0b0e\\u0b11-\\u0b12\\u0b29\\u0b31\\u0b34\\u0b3a-\\u0b3b\\u0b45-\\u0b46\\u0b49-\\u0b4a\\u0b4e-\\u0b55\\u0b58-\\u0b5b\\u0b5e\\u0b64-\\u0b65\\u0b78-\\u0b81\\u0b84\\u0b8b-\\u0b8d\\u0b91\\u0b96-\\u0b98\\u0b9b\\u0b9d\\u0ba0-\\u0ba2\\u0ba5-\\u0ba7\\u0bab-\\u0bad\\u0bba-\\u0bbd\\u0bc3-\\u0bc5\\u0bc9\\u0bce-\\u0bcf\\u0bd1-\\u0bd6\\u0bd8-\\u0be5\\u0bfb-\\u0bff\\u0c0d\\u0c11\\u0c29\\u0c3a-\\u0c3c\\u0c45\\u0c49\\u0c4e-\\u0c54\\u0c57\\u0c5b-\\u0c5f\\u0c64-\\u0c65\\u0c70-\\u0c77\\u0c8d\\u0c91\\u0ca9\\u0cb4\\u0cba-\\u0cbb\\u0cc5\\u0cc9\\u0cce-\\u0cd4\\u0cd7-\\u0cdd\\u0cdf\\u0ce4-\\u0ce5\\u0cf0\\u0cf3-\\u0cff\\u0d04\\u0d0d\\u0d11\\u0d45\\u0d49\\u0d50-\\u0d53\\u0d64-\\u0d65\\u0d80-\\u0d81\\u0d84\\u0d97-\\u0d99\\u0db2\\u0dbc\\u0dbe-\\u0dbf\\u0dc7-\\u0dc9\\u0dcb-\\u0dce\\u0dd5\\u0dd7\\u0de0-\\u0de5\\u0df0-\\u0df1\\u0df5-\\u0e00\\u0e3b-\\u0e3e\\u0e5c-\\u0e80\\u0e83\\u0e85-\\u0e86\\u0e89\\u0e8b-\\u0e8c\\u0e8e-\\u0e93\\u0e98\\u0ea0\\u0ea4\\u0ea6\\u0ea8-\\u0ea9\\u0eac\\u0eba\\u0ebe-\\u0ebf\\u0ec5\\u0ec7\\u0ece-\\u0ecf\\u0eda-\\u0edb\\u0ee0-\\u0eff\\u0f48\\u0f6d-\\u0f70\\u0f98\\u0fbd\\u0fcd\\u0fdb-\\u0fff\\u10c6\\u10c8-\\u10cc\\u10ce-\\u10cf\\u1249\\u124e-\\u124f\\u1257\\u1259\\u125e-\\u125f\\u1289\\u128e-\\u128f\\u12b1\\u12b6-\\u12b7\\u12bf\\u12c1\\u12c6-\\u12c7\\u12d7\\u1311\\u1316-\\u1317\\u135b-\\u135c\\u137d-\\u137f\\u139a-\\u139f\\u13f6-\\u13f7\\u13fe-\\u13ff\\u169d-\\u169f\\u16f9-\\u16ff\\u170d\\u1715-\\u171f\\u1737-\\u173f\\u1754-\\u175f\\u176d\\u1771\\u1774-\\u177f\\u17de-\\u17df\\u17ea-\\u17ef\\u17fa-\\u17ff\\u180f\\u181a-\\u181f\\u1879-\\u187f\\u18ab-\\u18af\\u18f6-\\u18ff\\u191f\\u192c-\\u192f\\u193c-\\u193f\\u1941-\\u1943\\u196e-\\u196f\\u1975-\\u197f\\u19ac-\\u19af\\u19ca-\\u19cf\\u19db-\\u19dd\\u1a1c-\\u1a1d\\u1a5f\\u1a7d-\\u1a7e\\u1a8a-\\u1a8f\\u1a9a-\\u1a9f\\u1aae-\\u1aaf\\u1abf-\\u1aff\\u1b4c-\\u1b4f\\u1b7d-\\u1b7f\\u1bf4-\\u1bfb\\u1c38-\\u1c3a\\u1c4a-\\u1c4c\\u1c89-\\u1c8f\\u1cbb-\\u1cbc\\u1cc8-\\u1ccf\\u1cfa-\\u1cff\\u1dfa\\u1f16-\\u1f17\\u1f1e-\\u1f1f\\u1f46-\\u1f47\\u1f4e-\\u1f4f\\u1f58\\u1f5a\\u1f5c\\u1f5e\\u1f7e-\\u1f7f\\u1fb5\\u1fc5\\u1fd4-\\u1fd5\\u1fdc\\u1ff0-\\u1ff1\\u1ff5\\u1fff\\u2065\\u2072-\\u2073\\u208f\\u209d-\\u209f\\u20c0-\\u20cf\\u20f1-\\u20ff\\u218c-\\u218f\\u2427-\\u243f\\u244b-\\u245f\\u2b74-\\u2b75\\u2b96-\\u2b97\\u2bc9\\u2bff\\u2c2f\\u2c5f\\u2cf4-\\u2cf8\\u2d26\\u2d28-\\u2d2c\\u2d2e-\\u2d2f\\u2d68-\\u2d6e\\u2d71-\\u2d7e\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf\\u2e4f-\\u2e7f\\u2e9a\\u2ef4-\\u2eff\\u2fd6-\\u2fef\\u2ffc-\\u2fff\\u3040\\u3097-\\u3098\\u3100-\\u3104\\u3130\\u318f\\u31bb-\\u31bf\\u31e4-\\u31ef\\u321f\\u32ff\\u4db6-\\u4dbf\\u9ff0-\\u9fff\\ua48d-\\ua48f\\ua4c7-\\ua4cf\\ua62c-\\ua63f\\ua6f8-\\ua6ff\\ua7ba-\\ua7f6\\ua82c-\\ua82f\\ua83a-\\ua83f\\ua878-\\ua87f\\ua8c6-\\ua8cd\\ua8da-\\ua8df\\ua954-\\ua95e\\ua97d-\\ua97f\\ua9ce\\ua9da-\\ua9dd\\ua9ff\\uaa37-\\uaa3f\\uaa4e-\\uaa4f\\uaa5a-\\uaa5b\\uaac3-\\uaada\\uaaf7-\\uab00\\uab07-\\uab08\\uab0f-\\uab10\\uab17-\\uab1f\\uab27\\uab2f\\uab66-\\uab6f\\uabee-\\uabef\\uabfa-\\uabff\\ud7a4-\\ud7af\\ud7c7-\\ud7ca\\ud7fc-\\ud7ff\\ufa6e-\\ufa6f\\ufada-\\ufaff\\ufb07-\\ufb12\\ufb18-\\ufb1c\\ufb37\\ufb3d\\ufb3f\\ufb42\\ufb45\\ufbc2-\\ufbd2\\ufd40-\\ufd4f\\ufd90-\\ufd91\\ufdc8-\\ufdef\\ufdfe-\\ufdff\\ufe1a-\\ufe1f\\ufe53\\ufe67\\ufe6c-\\ufe6f\\ufe75\\ufefd-\\ufefe\\uff00\\uffbf-\\uffc1\\uffc8-\\uffc9\\uffd0-\\uffd1\\uffd8-\\uffd9\\uffdd-\\uffdf\\uffe7\\uffef-\\ufff8\\ufffe-\\uffff\\U0001000c\\U00010027\\U0001003b\\U0001003e\\U0001004e-\\U0001004f\\U0001005e-\\U0001007f\\U000100fb-\\U000100ff\\U00010103-\\U00010106\\U00010134-\\U00010136\\U0001018f\\U0001019c-\\U0001019f\\U000101a1-\\U000101cf\\U000101fe-\\U0001027f\\U0001029d-\\U0001029f\\U000102d1-\\U000102df\\U000102fc-\\U000102ff\\U00010324-\\U0001032c\\U0001034b-\\U0001034f\\U0001037b-\\U0001037f\\U0001039e\\U000103c4-\\U000103c7\\U000103d6-\\U000103ff\\U0001049e-\\U0001049f\\U000104aa-\\U000104af\\U000104d4-\\U000104d7\\U000104fc-\\U000104ff\\U00010528-\\U0001052f\\U00010564-\\U0001056e\\U00010570-\\U000105ff\\U00010737-\\U0001073f\\U00010756-\\U0001075f\\U00010768-\\U000107ff\\U00010806-\\U00010807\\U00010809\\U00010836\\U00010839-\\U0001083b\\U0001083d-\\U0001083e\\U00010856\\U0001089f-\\U000108a6\\U000108b0-\\U000108df\\U000108f3\\U000108f6-\\U000108fa\\U0001091c-\\U0001091e\\U0001093a-\\U0001093e\\U00010940-\\U0001097f\\U000109b8-\\U000109bb\\U000109d0-\\U000109d1\\U00010a04\\U00010a07-\\U00010a0b\\U00010a14\\U00010a18\\U00010a36-\\U00010a37\\U00010a3b-\\U00010a3e\\U00010a49-\\U00010a4f\\U00010a59-\\U00010a5f\\U00010aa0-\\U00010abf\\U00010ae7-\\U00010aea\\U00010af7-\\U00010aff\\U00010b36-\\U00010b38\\U00010b56-\\U00010b57\\U00010b73-\\U00010b77\\U00010b92-\\U00010b98\\U00010b9d-\\U00010ba8\\U00010bb0-\\U00010bff\\U00010c49-\\U00010c7f\\U00010cb3-\\U00010cbf\\U00010cf3-\\U00010cf9\\U00010d28-\\U00010d2f\\U00010d3a-\\U00010e5f\\U00010e7f-\\U00010eff\\U00010f28-\\U00010f2f\\U00010f5a-\\U00010fff\\U0001104e-\\U00011051\\U00011070-\\U0001107e\\U000110c2-\\U000110cc\\U000110ce-\\U000110cf\\U000110e9-\\U000110ef\\U000110fa-\\U000110ff\\U00011135\\U00011147-\\U0001114f\\U00011177-\\U0001117f\\U000111ce-\\U000111cf\\U000111e0\\U000111f5-\\U000111ff\\U00011212\\U0001123f-\\U0001127f\\U00011287\\U00011289\\U0001128e\\U0001129e\\U000112aa-\\U000112af\\U000112eb-\\U000112ef\\U000112fa-\\U000112ff\\U00011304\\U0001130d-\\U0001130e\\U00011311-\\U00011312\\U00011329\\U00011331\\U00011334\\U0001133a\\U00011345-\\U00011346\\U00011349-\\U0001134a\\U0001134e-\\U0001134f\\U00011351-\\U00011356\\U00011358-\\U0001135c\\U00011364-\\U00011365\\U0001136d-\\U0001136f\\U00011375-\\U000113ff\\U0001145a\\U0001145c\\U0001145f-\\U0001147f\\U000114c8-\\U000114cf\\U000114da-\\U0001157f\\U000115b6-\\U000115b7\\U000115de-\\U000115ff\\U00011645-\\U0001164f\\U0001165a-\\U0001165f\\U0001166d-\\U0001167f\\U000116b8-\\U000116bf\\U000116ca-\\U000116ff\\U0001171b-\\U0001171c\\U0001172c-\\U0001172f\\U00011740-\\U000117ff\\U0001183c-\\U0001189f\\U000118f3-\\U000118fe\\U00011900-\\U000119ff\\U00011a48-\\U00011a4f\\U00011a84-\\U00011a85\\U00011aa3-\\U00011abf\\U00011af9-\\U00011bff\\U00011c09\\U00011c37\\U00011c46-\\U00011c4f\\U00011c6d-\\U00011c6f\\U00011c90-\\U00011c91\\U00011ca8\\U00011cb7-\\U00011cff\\U00011d07\\U00011d0a\\U00011d37-\\U00011d39\\U00011d3b\\U00011d3e\\U00011d48-\\U00011d4f\\U00011d5a-\\U00011d5f\\U00011d66\\U00011d69\\U00011d8f\\U00011d92\\U00011d99-\\U00011d9f\\U00011daa-\\U00011edf\\U00011ef9-\\U00011fff\\U0001239a-\\U000123ff\\U0001246f\\U00012475-\\U0001247f\\U00012544-\\U00012fff\\U0001342f-\\U000143ff\\U00014647-\\U000167ff\\U00016a39-\\U00016a3f\\U00016a5f\\U00016a6a-\\U00016a6d\\U00016a70-\\U00016acf\\U00016aee-\\U00016aef\\U00016af6-\\U00016aff\\U00016b46-\\U00016b4f\\U00016b5a\\U00016b62\\U00016b78-\\U00016b7c\\U00016b90-\\U00016e3f\\U00016e9b-\\U00016eff\\U00016f45-\\U00016f4f\\U00016f7f-\\U00016f8e\\U00016fa0-\\U00016fdf\\U00016fe2-\\U00016fff\\U000187f2-\\U000187ff\\U00018af3-\\U0001afff\\U0001b11f-\\U0001b16f\\U0001b2fc-\\U0001bbff\\U0001bc6b-\\U0001bc6f\\U0001bc7d-\\U0001bc7f\\U0001bc89-\\U0001bc8f\\U0001bc9a-\\U0001bc9b\\U0001bca4-\\U0001cfff\\U0001d0f6-\\U0001d0ff\\U0001d127-\\U0001d128\\U0001d1e9-\\U0001d1ff\\U0001d246-\\U0001d2df\\U0001d2f4-\\U0001d2ff\\U0001d357-\\U0001d35f\\U0001d379-\\U0001d3ff\\U0001d455\\U0001d49d\\U0001d4a0-\\U0001d4a1\\U0001d4a3-\\U0001d4a4\\U0001d4a7-\\U0001d4a8\\U0001d4ad\\U0001d4ba\\U0001d4bc\\U0001d4c4\\U0001d506\\U0001d50b-\\U0001d50c\\U0001d515\\U0001d51d\\U0001d53a\\U0001d53f\\U0001d545\\U0001d547-\\U0001d549\\U0001d551\\U0001d6a6-\\U0001d6a7\\U0001d7cc-\\U0001d7cd\\U0001da8c-\\U0001da9a\\U0001daa0\\U0001dab0-\\U0001dfff\\U0001e007\\U0001e019-\\U0001e01a\\U0001e022\\U0001e025\\U0001e02b-\\U0001e7ff\\U0001e8c5-\\U0001e8c6\\U0001e8d7-\\U0001e8ff\\U0001e94b-\\U0001e94f\\U0001e95a-\\U0001e95d\\U0001e960-\\U0001ec70\\U0001ecb5-\\U0001edff\\U0001ee04\\U0001ee20\\U0001ee23\\U0001ee25-\\U0001ee26\\U0001ee28\\U0001ee33\\U0001ee38\\U0001ee3a\\U0001ee3c-\\U0001ee41\\U0001ee43-\\U0001ee46\\U0001ee48\\U0001ee4a\\U0001ee4c\\U0001ee50\\U0001ee53\\U0001ee55-\\U0001ee56\\U0001ee58\\U0001ee5a\\U0001ee5c\\U0001ee5e\\U0001ee60\\U0001ee63\\U0001ee65-\\U0001ee66\\U0001ee6b\\U0001ee73\\U0001ee78\\U0001ee7d\\U0001ee7f\\U0001ee8a\\U0001ee9c-\\U0001eea0\\U0001eea4\\U0001eeaa\\U0001eebc-\\U0001eeef\\U0001eef2-\\U0001efff\\U0001f02c-\\U0001f02f\\U0001f094-\\U0001f09f\\U0001f0af-\\U0001f0b0\\U0001f0c0\\U0001f0d0\\U0001f0f6-\\U0001f0ff\\U0001f10d-\\U0001f10f\\U0001f16c-\\U0001f16f\\U0001f1ad-\\U0001f1e5\\U0001f203-\\U0001f20f\\U0001f23c-\\U0001f23f\\U0001f249-\\U0001f24f\\U0001f252-\\U0001f25f\\U0001f266-\\U0001f2ff\\U0001f6d5-\\U0001f6df\\U0001f6ed-\\U0001f6ef\\U0001f6fa-\\U0001f6ff\\U0001f774-\\U0001f77f\\U0001f7d9-\\U0001f7ff\\U0001f80c-\\U0001f80f\\U0001f848-\\U0001f84f\\U0001f85a-\\U0001f85f\\U0001f888-\\U0001f88f\\U0001f8ae-\\U0001f8ff\\U0001f90c-\\U0001f90f\\U0001f93f\\U0001f971-\\U0001f972\\U0001f977-\\U0001f979\\U0001f97b\\U0001f9a3-\\U0001f9af\\U0001f9ba-\\U0001f9bf\\U0001f9c3-\\U0001f9cf\\U0001fa00-\\U0001fa5f\\U0001fa6e-\\U0001ffff\\U0002a6d7-\\U0002a6ff\\U0002b735-\\U0002b73f\\U0002b81e-\\U0002b81f\\U0002cea2-\\U0002ceaf\\U0002ebe1-\\U0002f7ff\\U0002fa1e-\\U000e0000\\U000e0002-\\U000e001f\\U000e0080-\\U000e00ff\\U000e01f0-\\U000effff\\U000ffffe-\\U000fffff\\U0010fffe-\\U0010ffff'\n\nCo = '\\ue000-\\uf8ff\\U000f0000-\\U000ffffd\\U00100000-\\U0010fffd'\n\nCs = '\\ud800-\\udbff\\\\\\udc00\\udc01-\\udfff'\n\nLl = 'a-z\\xb5\\xdf-\\xf6\\xf8-\\xff\\u0101\\u0103\\u0105\\u0107\\u0109\\u010b\\u010d\\u010f\\u0111\\u0113\\u0115\\u0117\\u0119\\u011b\\u011d\\u011f\\u0121\\u0123\\u0125\\u0127\\u0129\\u012b\\u012d\\u012f\\u0131\\u0133\\u0135\\u0137-\\u0138\\u013a\\u013c\\u013e\\u0140\\u0142\\u0144\\u0146\\u0148-\\u0149\\u014b\\u014d\\u014f\\u0151\\u0153\\u0155\\u0157\\u0159\\u015b\\u015d\\u015f\\u0161\\u0163\\u0165\\u0167\\u0169\\u016b\\u016d\\u016f\\u0171\\u0173\\u0175\\u0177\\u017a\\u017c\\u017e-\\u0180\\u0183\\u0185\\u0188\\u018c-\\u018d\\u0192\\u0195\\u0199-\\u019b\\u019e\\u01a1\\u01a3\\u01a5\\u01a8\\u01aa-\\u01ab\\u01ad\\u01b0\\u01b4\\u01b6\\u01b9-\\u01ba\\u01bd-\\u01bf\\u01c6\\u01c9\\u01cc\\u01ce\\u01d0\\u01d2\\u01d4\\u01d6\\u01d8\\u01da\\u01dc-\\u01dd\\u01df\\u01e1\\u01e3\\u01e5\\u01e7\\u01e9\\u01eb\\u01ed\\u01ef-\\u01f0\\u01f3\\u01f5\\u01f9\\u01fb\\u01fd\\u01ff\\u0201\\u0203\\u0205\\u0207\\u0209\\u020b\\u020d\\u020f\\u0211\\u0213\\u0215\\u0217\\u0219\\u021b\\u021d\\u021f\\u0221\\u0223\\u0225\\u0227\\u0229\\u022b\\u022d\\u022f\\u0231\\u0233-\\u0239\\u023c\\u023f-\\u0240\\u0242\\u0247\\u0249\\u024b\\u024d\\u024f-\\u0293\\u0295-\\u02af\\u0371\\u0373\\u0377\\u037b-\\u037d\\u0390\\u03ac-\\u03ce\\u03d0-\\u03d1\\u03d5-\\u03d7\\u03d9\\u03db\\u03dd\\u03df\\u03e1\\u03e3\\u03e5\\u03e7\\u03e9\\u03eb\\u03ed\\u03ef-\\u03f3\\u03f5\\u03f8\\u03fb-\\u03fc\\u0430-\\u045f\\u0461\\u0463\\u0465\\u0467\\u0469\\u046b\\u046d\\u046f\\u0471\\u0473\\u0475\\u0477\\u0479\\u047b\\u047d\\u047f\\u0481\\u048b\\u048d\\u048f\\u0491\\u0493\\u0495\\u0497\\u0499\\u049b\\u049d\\u049f\\u04a1\\u04a3\\u04a5\\u04a7\\u04a9\\u04ab\\u04ad\\u04af\\u04b1\\u04b3\\u04b5\\u04b7\\u04b9\\u04bb\\u04bd\\u04bf\\u04c2\\u04c4\\u04c6\\u04c8\\u04ca\\u04cc\\u04ce-\\u04cf\\u04d1\\u04d3\\u04d5\\u04d7\\u04d9\\u04db\\u04dd\\u04df\\u04e1\\u04e3\\u04e5\\u04e7\\u04e9\\u04eb\\u04ed\\u04ef\\u04f1\\u04f3\\u04f5\\u04f7\\u04f9\\u04fb\\u04fd\\u04ff\\u0501\\u0503\\u0505\\u0507\\u0509\\u050b\\u050d\\u050f\\u0511\\u0513\\u0515\\u0517\\u0519\\u051b\\u051d\\u051f\\u0521\\u0523\\u0525\\u0527\\u0529\\u052b\\u052d\\u052f\\u0560-\\u0588\\u10d0-\\u10fa\\u10fd-\\u10ff\\u13f8-\\u13fd\\u1c80-\\u1c88\\u1d00-\\u1d2b\\u1d6b-\\u1d77\\u1d79-\\u1d9a\\u1e01\\u1e03\\u1e05\\u1e07\\u1e09\\u1e0b\\u1e0d\\u1e0f\\u1e11\\u1e13\\u1e15\\u1e17\\u1e19\\u1e1b\\u1e1d\\u1e1f\\u1e21\\u1e23\\u1e25\\u1e27\\u1e29\\u1e2b\\u1e2d\\u1e2f\\u1e31\\u1e33\\u1e35\\u1e37\\u1e39\\u1e3b\\u1e3d\\u1e3f\\u1e41\\u1e43\\u1e45\\u1e47\\u1e49\\u1e4b\\u1e4d\\u1e4f\\u1e51\\u1e53\\u1e55\\u1e57\\u1e59\\u1e5b\\u1e5d\\u1e5f\\u1e61\\u1e63\\u1e65\\u1e67\\u1e69\\u1e6b\\u1e6d\\u1e6f\\u1e71\\u1e73\\u1e75\\u1e77\\u1e79\\u1e7b\\u1e7d\\u1e7f\\u1e81\\u1e83\\u1e85\\u1e87\\u1e89\\u1e8b\\u1e8d\\u1e8f\\u1e91\\u1e93\\u1e95-\\u1e9d\\u1e9f\\u1ea1\\u1ea3\\u1ea5\\u1ea7\\u1ea9\\u1eab\\u1ead\\u1eaf\\u1eb1\\u1eb3\\u1eb5\\u1eb7\\u1eb9\\u1ebb\\u1ebd\\u1ebf\\u1ec1\\u1ec3\\u1ec5\\u1ec7\\u1ec9\\u1ecb\\u1ecd\\u1ecf\\u1ed1\\u1ed3\\u1ed5\\u1ed7\\u1ed9\\u1edb\\u1edd\\u1edf\\u1ee1\\u1ee3\\u1ee5\\u1ee7\\u1ee9\\u1eeb\\u1eed\\u1eef\\u1ef1\\u1ef3\\u1ef5\\u1ef7\\u1ef9\\u1efb\\u1efd\\u1eff-\\u1f07\\u1f10-\\u1f15\\u1f20-\\u1f27\\u1f30-\\u1f37\\u1f40-\\u1f45\\u1f50-\\u1f57\\u1f60-\\u1f67\\u1f70-\\u1f7d\\u1f80-\\u1f87\\u1f90-\\u1f97\\u1fa0-\\u1fa7\\u1fb0-\\u1fb4\\u1fb6-\\u1fb7\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fc7\\u1fd0-\\u1fd3\\u1fd6-\\u1fd7\\u1fe0-\\u1fe7\\u1ff2-\\u1ff4\\u1ff6-\\u1ff7\\u210a\\u210e-\\u210f\\u2113\\u212f\\u2134\\u2139\\u213c-\\u213d\\u2146-\\u2149\\u214e\\u2184\\u2c30-\\u2c5e\\u2c61\\u2c65-\\u2c66\\u2c68\\u2c6a\\u2c6c\\u2c71\\u2c73-\\u2c74\\u2c76-\\u2c7b\\u2c81\\u2c83\\u2c85\\u2c87\\u2c89\\u2c8b\\u2c8d\\u2c8f\\u2c91\\u2c93\\u2c95\\u2c97\\u2c99\\u2c9b\\u2c9d\\u2c9f\\u2ca1\\u2ca3\\u2ca5\\u2ca7\\u2ca9\\u2cab\\u2cad\\u2caf\\u2cb1\\u2cb3\\u2cb5\\u2cb7\\u2cb9\\u2cbb\\u2cbd\\u2cbf\\u2cc1\\u2cc3\\u2cc5\\u2cc7\\u2cc9\\u2ccb\\u2ccd\\u2ccf\\u2cd1\\u2cd3\\u2cd5\\u2cd7\\u2cd9\\u2cdb\\u2cdd\\u2cdf\\u2ce1\\u2ce3-\\u2ce4\\u2cec\\u2cee\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\ua641\\ua643\\ua645\\ua647\\ua649\\ua64b\\ua64d\\ua64f\\ua651\\ua653\\ua655\\ua657\\ua659\\ua65b\\ua65d\\ua65f\\ua661\\ua663\\ua665\\ua667\\ua669\\ua66b\\ua66d\\ua681\\ua683\\ua685\\ua687\\ua689\\ua68b\\ua68d\\ua68f\\ua691\\ua693\\ua695\\ua697\\ua699\\ua69b\\ua723\\ua725\\ua727\\ua729\\ua72b\\ua72d\\ua72f-\\ua731\\ua733\\ua735\\ua737\\ua739\\ua73b\\ua73d\\ua73f\\ua741\\ua743\\ua745\\ua747\\ua749\\ua74b\\ua74d\\ua74f\\ua751\\ua753\\ua755\\ua757\\ua759\\ua75b\\ua75d\\ua75f\\ua761\\ua763\\ua765\\ua767\\ua769\\ua76b\\ua76d\\ua76f\\ua771-\\ua778\\ua77a\\ua77c\\ua77f\\ua781\\ua783\\ua785\\ua787\\ua78c\\ua78e\\ua791\\ua793-\\ua795\\ua797\\ua799\\ua79b\\ua79d\\ua79f\\ua7a1\\ua7a3\\ua7a5\\ua7a7\\ua7a9\\ua7af\\ua7b5\\ua7b7\\ua7b9\\ua7fa\\uab30-\\uab5a\\uab60-\\uab65\\uab70-\\uabbf\\ufb00-\\ufb06\\ufb13-\\ufb17\\uff41-\\uff5a\\U00010428-\\U0001044f\\U000104d8-\\U000104fb\\U00010cc0-\\U00010cf2\\U000118c0-\\U000118df\\U00016e60-\\U00016e7f\\U0001d41a-\\U0001d433\\U0001d44e-\\U0001d454\\U0001d456-\\U0001d467\\U0001d482-\\U0001d49b\\U0001d4b6-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d4cf\\U0001d4ea-\\U0001d503\\U0001d51e-\\U0001d537\\U0001d552-\\U0001d56b\\U0001d586-\\U0001d59f\\U0001d5ba-\\U0001d5d3\\U0001d5ee-\\U0001d607\\U0001d622-\\U0001d63b\\U0001d656-\\U0001d66f\\U0001d68a-\\U0001d6a5\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6e1\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d71b\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d755\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d78f\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7c9\\U0001d7cb\\U0001e922-\\U0001e943'\n\nLm = '\\u02b0-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0374\\u037a\\u0559\\u0640\\u06e5-\\u06e6\\u07f4-\\u07f5\\u07fa\\u081a\\u0824\\u0828\\u0971\\u0e46\\u0ec6\\u10fc\\u17d7\\u1843\\u1aa7\\u1c78-\\u1c7d\\u1d2c-\\u1d6a\\u1d78\\u1d9b-\\u1dbf\\u2071\\u207f\\u2090-\\u209c\\u2c7c-\\u2c7d\\u2d6f\\u2e2f\\u3005\\u3031-\\u3035\\u303b\\u309d-\\u309e\\u30fc-\\u30fe\\ua015\\ua4f8-\\ua4fd\\ua60c\\ua67f\\ua69c-\\ua69d\\ua717-\\ua71f\\ua770\\ua788\\ua7f8-\\ua7f9\\ua9cf\\ua9e6\\uaa70\\uaadd\\uaaf3-\\uaaf4\\uab5c-\\uab5f\\uff70\\uff9e-\\uff9f\\U00016b40-\\U00016b43\\U00016f93-\\U00016f9f\\U00016fe0-\\U00016fe1'\n\nLo = '\\xaa\\xba\\u01bb\\u01c0-\\u01c3\\u0294\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u063f\\u0641-\\u064a\\u066e-\\u066f\\u0671-\\u06d3\\u06d5\\u06ee-\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u0800-\\u0815\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0972-\\u0980\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc-\\u09dd\\u09df-\\u09e1\\u09f0-\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0-\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c-\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60-\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0-\\u0ce1\\u0cf1-\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32-\\u0e33\\u0e40-\\u0e45\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb0\\u0eb2-\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065-\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u1100-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16f1-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17dc\\u1820-\\u1842\\u1844-\\u1878\\u1880-\\u1884\\u1887-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae-\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c77\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5-\\u1cf6\\u2135-\\u2138\\u2d30-\\u2d67\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3006\\u303c\\u3041-\\u3096\\u309f\\u30a1-\\u30fa\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua014\\ua016-\\ua48c\\ua4d0-\\ua4f7\\ua500-\\ua60b\\ua610-\\ua61f\\ua62a-\\ua62b\\ua66e\\ua6a0-\\ua6e5\\ua78f\\ua7f7\\ua7fb-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd-\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9e0-\\ua9e4\\ua9e7-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa6f\\uaa71-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5-\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadc\\uaae0-\\uaaea\\uaaf2\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff66-\\uff6f\\uff71-\\uff9d\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U00010300-\\U0001031f\\U0001032d-\\U00010340\\U00010342-\\U00010349\\U00010350-\\U00010375\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U00010450-\\U0001049d\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00\\U00010a10-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae4\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010d00-\\U00010d23\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f45\\U00011003-\\U00011037\\U00011083-\\U000110af\\U000110d0-\\U000110e8\\U00011103-\\U00011126\\U00011144\\U00011150-\\U00011172\\U00011176\\U00011183-\\U000111b2\\U000111c1-\\U000111c4\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U0001122b\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112de\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133d\\U00011350\\U0001135d-\\U00011361\\U00011400-\\U00011434\\U00011447-\\U0001144a\\U00011480-\\U000114af\\U000114c4-\\U000114c5\\U000114c7\\U00011580-\\U000115ae\\U000115d8-\\U000115db\\U00011600-\\U0001162f\\U00011644\\U00011680-\\U000116aa\\U00011700-\\U0001171a\\U00011800-\\U0001182b\\U000118ff\\U00011a00\\U00011a0b-\\U00011a32\\U00011a3a\\U00011a50\\U00011a5c-\\U00011a83\\U00011a86-\\U00011a89\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c2e\\U00011c40\\U00011c72-\\U00011c8f\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d30\\U00011d46\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d89\\U00011d98\\U00011ee0-\\U00011ef2\\U00012000-\\U00012399\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016ad0-\\U00016aed\\U00016b00-\\U00016b2f\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016f00-\\U00016f44\\U00016f50\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001e800-\\U0001e8c4\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d'\n\nLt = '\\u01c5\\u01c8\\u01cb\\u01f2\\u1f88-\\u1f8f\\u1f98-\\u1f9f\\u1fa8-\\u1faf\\u1fbc\\u1fcc\\u1ffc'\n\nLu = 'A-Z\\xc0-\\xd6\\xd8-\\xde\\u0100\\u0102\\u0104\\u0106\\u0108\\u010a\\u010c\\u010e\\u0110\\u0112\\u0114\\u0116\\u0118\\u011a\\u011c\\u011e\\u0120\\u0122\\u0124\\u0126\\u0128\\u012a\\u012c\\u012e\\u0130\\u0132\\u0134\\u0136\\u0139\\u013b\\u013d\\u013f\\u0141\\u0143\\u0145\\u0147\\u014a\\u014c\\u014e\\u0150\\u0152\\u0154\\u0156\\u0158\\u015a\\u015c\\u015e\\u0160\\u0162\\u0164\\u0166\\u0168\\u016a\\u016c\\u016e\\u0170\\u0172\\u0174\\u0176\\u0178-\\u0179\\u017b\\u017d\\u0181-\\u0182\\u0184\\u0186-\\u0187\\u0189-\\u018b\\u018e-\\u0191\\u0193-\\u0194\\u0196-\\u0198\\u019c-\\u019d\\u019f-\\u01a0\\u01a2\\u01a4\\u01a6-\\u01a7\\u01a9\\u01ac\\u01ae-\\u01af\\u01b1-\\u01b3\\u01b5\\u01b7-\\u01b8\\u01bc\\u01c4\\u01c7\\u01ca\\u01cd\\u01cf\\u01d1\\u01d3\\u01d5\\u01d7\\u01d9\\u01db\\u01de\\u01e0\\u01e2\\u01e4\\u01e6\\u01e8\\u01ea\\u01ec\\u01ee\\u01f1\\u01f4\\u01f6-\\u01f8\\u01fa\\u01fc\\u01fe\\u0200\\u0202\\u0204\\u0206\\u0208\\u020a\\u020c\\u020e\\u0210\\u0212\\u0214\\u0216\\u0218\\u021a\\u021c\\u021e\\u0220\\u0222\\u0224\\u0226\\u0228\\u022a\\u022c\\u022e\\u0230\\u0232\\u023a-\\u023b\\u023d-\\u023e\\u0241\\u0243-\\u0246\\u0248\\u024a\\u024c\\u024e\\u0370\\u0372\\u0376\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u038f\\u0391-\\u03a1\\u03a3-\\u03ab\\u03cf\\u03d2-\\u03d4\\u03d8\\u03da\\u03dc\\u03de\\u03e0\\u03e2\\u03e4\\u03e6\\u03e8\\u03ea\\u03ec\\u03ee\\u03f4\\u03f7\\u03f9-\\u03fa\\u03fd-\\u042f\\u0460\\u0462\\u0464\\u0466\\u0468\\u046a\\u046c\\u046e\\u0470\\u0472\\u0474\\u0476\\u0478\\u047a\\u047c\\u047e\\u0480\\u048a\\u048c\\u048e\\u0490\\u0492\\u0494\\u0496\\u0498\\u049a\\u049c\\u049e\\u04a0\\u04a2\\u04a4\\u04a6\\u04a8\\u04aa\\u04ac\\u04ae\\u04b0\\u04b2\\u04b4\\u04b6\\u04b8\\u04ba\\u04bc\\u04be\\u04c0-\\u04c1\\u04c3\\u04c5\\u04c7\\u04c9\\u04cb\\u04cd\\u04d0\\u04d2\\u04d4\\u04d6\\u04d8\\u04da\\u04dc\\u04de\\u04e0\\u04e2\\u04e4\\u04e6\\u04e8\\u04ea\\u04ec\\u04ee\\u04f0\\u04f2\\u04f4\\u04f6\\u04f8\\u04fa\\u04fc\\u04fe\\u0500\\u0502\\u0504\\u0506\\u0508\\u050a\\u050c\\u050e\\u0510\\u0512\\u0514\\u0516\\u0518\\u051a\\u051c\\u051e\\u0520\\u0522\\u0524\\u0526\\u0528\\u052a\\u052c\\u052e\\u0531-\\u0556\\u10a0-\\u10c5\\u10c7\\u10cd\\u13a0-\\u13f5\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1e00\\u1e02\\u1e04\\u1e06\\u1e08\\u1e0a\\u1e0c\\u1e0e\\u1e10\\u1e12\\u1e14\\u1e16\\u1e18\\u1e1a\\u1e1c\\u1e1e\\u1e20\\u1e22\\u1e24\\u1e26\\u1e28\\u1e2a\\u1e2c\\u1e2e\\u1e30\\u1e32\\u1e34\\u1e36\\u1e38\\u1e3a\\u1e3c\\u1e3e\\u1e40\\u1e42\\u1e44\\u1e46\\u1e48\\u1e4a\\u1e4c\\u1e4e\\u1e50\\u1e52\\u1e54\\u1e56\\u1e58\\u1e5a\\u1e5c\\u1e5e\\u1e60\\u1e62\\u1e64\\u1e66\\u1e68\\u1e6a\\u1e6c\\u1e6e\\u1e70\\u1e72\\u1e74\\u1e76\\u1e78\\u1e7a\\u1e7c\\u1e7e\\u1e80\\u1e82\\u1e84\\u1e86\\u1e88\\u1e8a\\u1e8c\\u1e8e\\u1e90\\u1e92\\u1e94\\u1e9e\\u1ea0\\u1ea2\\u1ea4\\u1ea6\\u1ea8\\u1eaa\\u1eac\\u1eae\\u1eb0\\u1eb2\\u1eb4\\u1eb6\\u1eb8\\u1eba\\u1ebc\\u1ebe\\u1ec0\\u1ec2\\u1ec4\\u1ec6\\u1ec8\\u1eca\\u1ecc\\u1ece\\u1ed0\\u1ed2\\u1ed4\\u1ed6\\u1ed8\\u1eda\\u1edc\\u1ede\\u1ee0\\u1ee2\\u1ee4\\u1ee6\\u1ee8\\u1eea\\u1eec\\u1eee\\u1ef0\\u1ef2\\u1ef4\\u1ef6\\u1ef8\\u1efa\\u1efc\\u1efe\\u1f08-\\u1f0f\\u1f18-\\u1f1d\\u1f28-\\u1f2f\\u1f38-\\u1f3f\\u1f48-\\u1f4d\\u1f59\\u1f5b\\u1f5d\\u1f5f\\u1f68-\\u1f6f\\u1fb8-\\u1fbb\\u1fc8-\\u1fcb\\u1fd8-\\u1fdb\\u1fe8-\\u1fec\\u1ff8-\\u1ffb\\u2102\\u2107\\u210b-\\u210d\\u2110-\\u2112\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u2130-\\u2133\\u213e-\\u213f\\u2145\\u2183\\u2c00-\\u2c2e\\u2c60\\u2c62-\\u2c64\\u2c67\\u2c69\\u2c6b\\u2c6d-\\u2c70\\u2c72\\u2c75\\u2c7e-\\u2c80\\u2c82\\u2c84\\u2c86\\u2c88\\u2c8a\\u2c8c\\u2c8e\\u2c90\\u2c92\\u2c94\\u2c96\\u2c98\\u2c9a\\u2c9c\\u2c9e\\u2ca0\\u2ca2\\u2ca4\\u2ca6\\u2ca8\\u2caa\\u2cac\\u2cae\\u2cb0\\u2cb2\\u2cb4\\u2cb6\\u2cb8\\u2cba\\u2cbc\\u2cbe\\u2cc0\\u2cc2\\u2cc4\\u2cc6\\u2cc8\\u2cca\\u2ccc\\u2cce\\u2cd0\\u2cd2\\u2cd4\\u2cd6\\u2cd8\\u2cda\\u2cdc\\u2cde\\u2ce0\\u2ce2\\u2ceb\\u2ced\\u2cf2\\ua640\\ua642\\ua644\\ua646\\ua648\\ua64a\\ua64c\\ua64e\\ua650\\ua652\\ua654\\ua656\\ua658\\ua65a\\ua65c\\ua65e\\ua660\\ua662\\ua664\\ua666\\ua668\\ua66a\\ua66c\\ua680\\ua682\\ua684\\ua686\\ua688\\ua68a\\ua68c\\ua68e\\ua690\\ua692\\ua694\\ua696\\ua698\\ua69a\\ua722\\ua724\\ua726\\ua728\\ua72a\\ua72c\\ua72e\\ua732\\ua734\\ua736\\ua738\\ua73a\\ua73c\\ua73e\\ua740\\ua742\\ua744\\ua746\\ua748\\ua74a\\ua74c\\ua74e\\ua750\\ua752\\ua754\\ua756\\ua758\\ua75a\\ua75c\\ua75e\\ua760\\ua762\\ua764\\ua766\\ua768\\ua76a\\ua76c\\ua76e\\ua779\\ua77b\\ua77d-\\ua77e\\ua780\\ua782\\ua784\\ua786\\ua78b\\ua78d\\ua790\\ua792\\ua796\\ua798\\ua79a\\ua79c\\ua79e\\ua7a0\\ua7a2\\ua7a4\\ua7a6\\ua7a8\\ua7aa-\\ua7ae\\ua7b0-\\ua7b4\\ua7b6\\ua7b8\\uff21-\\uff3a\\U00010400-\\U00010427\\U000104b0-\\U000104d3\\U00010c80-\\U00010cb2\\U000118a0-\\U000118bf\\U00016e40-\\U00016e5f\\U0001d400-\\U0001d419\\U0001d434-\\U0001d44d\\U0001d468-\\U0001d481\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b5\\U0001d4d0-\\U0001d4e9\\U0001d504-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d538-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d56c-\\U0001d585\\U0001d5a0-\\U0001d5b9\\U0001d5d4-\\U0001d5ed\\U0001d608-\\U0001d621\\U0001d63c-\\U0001d655\\U0001d670-\\U0001d689\\U0001d6a8-\\U0001d6c0\\U0001d6e2-\\U0001d6fa\\U0001d71c-\\U0001d734\\U0001d756-\\U0001d76e\\U0001d790-\\U0001d7a8\\U0001d7ca\\U0001e900-\\U0001e921'\n\nMc = '\\u0903\\u093b\\u093e-\\u0940\\u0949-\\u094c\\u094e-\\u094f\\u0982-\\u0983\\u09be-\\u09c0\\u09c7-\\u09c8\\u09cb-\\u09cc\\u09d7\\u0a03\\u0a3e-\\u0a40\\u0a83\\u0abe-\\u0ac0\\u0ac9\\u0acb-\\u0acc\\u0b02-\\u0b03\\u0b3e\\u0b40\\u0b47-\\u0b48\\u0b4b-\\u0b4c\\u0b57\\u0bbe-\\u0bbf\\u0bc1-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcc\\u0bd7\\u0c01-\\u0c03\\u0c41-\\u0c44\\u0c82-\\u0c83\\u0cbe\\u0cc0-\\u0cc4\\u0cc7-\\u0cc8\\u0cca-\\u0ccb\\u0cd5-\\u0cd6\\u0d02-\\u0d03\\u0d3e-\\u0d40\\u0d46-\\u0d48\\u0d4a-\\u0d4c\\u0d57\\u0d82-\\u0d83\\u0dcf-\\u0dd1\\u0dd8-\\u0ddf\\u0df2-\\u0df3\\u0f3e-\\u0f3f\\u0f7f\\u102b-\\u102c\\u1031\\u1038\\u103b-\\u103c\\u1056-\\u1057\\u1062-\\u1064\\u1067-\\u106d\\u1083-\\u1084\\u1087-\\u108c\\u108f\\u109a-\\u109c\\u17b6\\u17be-\\u17c5\\u17c7-\\u17c8\\u1923-\\u1926\\u1929-\\u192b\\u1930-\\u1931\\u1933-\\u1938\\u1a19-\\u1a1a\\u1a55\\u1a57\\u1a61\\u1a63-\\u1a64\\u1a6d-\\u1a72\\u1b04\\u1b35\\u1b3b\\u1b3d-\\u1b41\\u1b43-\\u1b44\\u1b82\\u1ba1\\u1ba6-\\u1ba7\\u1baa\\u1be7\\u1bea-\\u1bec\\u1bee\\u1bf2-\\u1bf3\\u1c24-\\u1c2b\\u1c34-\\u1c35\\u1ce1\\u1cf2-\\u1cf3\\u1cf7\\u302e-\\u302f\\ua823-\\ua824\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c3\\ua952-\\ua953\\ua983\\ua9b4-\\ua9b5\\ua9ba-\\ua9bb\\ua9bd-\\ua9c0\\uaa2f-\\uaa30\\uaa33-\\uaa34\\uaa4d\\uaa7b\\uaa7d\\uaaeb\\uaaee-\\uaaef\\uaaf5\\uabe3-\\uabe4\\uabe6-\\uabe7\\uabe9-\\uabea\\uabec\\U00011000\\U00011002\\U00011082\\U000110b0-\\U000110b2\\U000110b7-\\U000110b8\\U0001112c\\U00011145-\\U00011146\\U00011182\\U000111b3-\\U000111b5\\U000111bf-\\U000111c0\\U0001122c-\\U0001122e\\U00011232-\\U00011233\\U00011235\\U000112e0-\\U000112e2\\U00011302-\\U00011303\\U0001133e-\\U0001133f\\U00011341-\\U00011344\\U00011347-\\U00011348\\U0001134b-\\U0001134d\\U00011357\\U00011362-\\U00011363\\U00011435-\\U00011437\\U00011440-\\U00011441\\U00011445\\U000114b0-\\U000114b2\\U000114b9\\U000114bb-\\U000114be\\U000114c1\\U000115af-\\U000115b1\\U000115b8-\\U000115bb\\U000115be\\U00011630-\\U00011632\\U0001163b-\\U0001163c\\U0001163e\\U000116ac\\U000116ae-\\U000116af\\U000116b6\\U00011720-\\U00011721\\U00011726\\U0001182c-\\U0001182e\\U00011838\\U00011a39\\U00011a57-\\U00011a58\\U00011a97\\U00011c2f\\U00011c3e\\U00011ca9\\U00011cb1\\U00011cb4\\U00011d8a-\\U00011d8e\\U00011d93-\\U00011d94\\U00011d96\\U00011ef5-\\U00011ef6\\U00016f51-\\U00016f7e\\U0001d165-\\U0001d166\\U0001d16d-\\U0001d172'\n\nMe = '\\u0488-\\u0489\\u1abe\\u20dd-\\u20e0\\u20e2-\\u20e4\\ua670-\\ua672'\n\nMn = '\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065f\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7-\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u08d3-\\u08e1\\u08e3-\\u0902\\u093a\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0957\\u0962-\\u0963\\u0981\\u09bc\\u09c1-\\u09c4\\u09cd\\u09e2-\\u09e3\\u09fe\\u0a01-\\u0a02\\u0a3c\\u0a41-\\u0a42\\u0a47-\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70-\\u0a71\\u0a75\\u0a81-\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7-\\u0ac8\\u0acd\\u0ae2-\\u0ae3\\u0afa-\\u0aff\\u0b01\\u0b3c\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b62-\\u0b63\\u0b82\\u0bc0\\u0bcd\\u0c00\\u0c04\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55-\\u0c56\\u0c62-\\u0c63\\u0c81\\u0cbc\\u0cbf\\u0cc6\\u0ccc-\\u0ccd\\u0ce2-\\u0ce3\\u0d00-\\u0d01\\u0d3b-\\u0d3c\\u0d41-\\u0d44\\u0d4d\\u0d62-\\u0d63\\u0dca\\u0dd2-\\u0dd4\\u0dd6\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb-\\u0ebc\\u0ec8-\\u0ecd\\u0f18-\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039-\\u103a\\u103d-\\u103e\\u1058-\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085-\\u1086\\u108d\\u109d\\u135d-\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752-\\u1753\\u1772-\\u1773\\u17b4-\\u17b5\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u1885-\\u1886\\u18a9\\u1920-\\u1922\\u1927-\\u1928\\u1932\\u1939-\\u193b\\u1a17-\\u1a18\\u1a1b\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1ab0-\\u1abd\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80-\\u1b81\\u1ba2-\\u1ba5\\u1ba8-\\u1ba9\\u1bab-\\u1bad\\u1be6\\u1be8-\\u1be9\\u1bed\\u1bef-\\u1bf1\\u1c2c-\\u1c33\\u1c36-\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1cf4\\u1cf8-\\u1cf9\\u1dc0-\\u1df9\\u1dfb-\\u1dff\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302d\\u3099-\\u309a\\ua66f\\ua674-\\ua67d\\ua69e-\\ua69f\\ua6f0-\\ua6f1\\ua802\\ua806\\ua80b\\ua825-\\ua826\\ua8c4-\\ua8c5\\ua8e0-\\ua8f1\\ua8ff\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\ua9e5\\uaa29-\\uaa2e\\uaa31-\\uaa32\\uaa35-\\uaa36\\uaa43\\uaa4c\\uaa7c\\uaab0\\uaab2-\\uaab4\\uaab7-\\uaab8\\uaabe-\\uaabf\\uaac1\\uaaec-\\uaaed\\uaaf6\\uabe5\\uabe8\\uabed\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\U000101fd\\U000102e0\\U00010376-\\U0001037a\\U00010a01-\\U00010a03\\U00010a05-\\U00010a06\\U00010a0c-\\U00010a0f\\U00010a38-\\U00010a3a\\U00010a3f\\U00010ae5-\\U00010ae6\\U00010d24-\\U00010d27\\U00010f46-\\U00010f50\\U00011001\\U00011038-\\U00011046\\U0001107f-\\U00011081\\U000110b3-\\U000110b6\\U000110b9-\\U000110ba\\U00011100-\\U00011102\\U00011127-\\U0001112b\\U0001112d-\\U00011134\\U00011173\\U00011180-\\U00011181\\U000111b6-\\U000111be\\U000111c9-\\U000111cc\\U0001122f-\\U00011231\\U00011234\\U00011236-\\U00011237\\U0001123e\\U000112df\\U000112e3-\\U000112ea\\U00011300-\\U00011301\\U0001133b-\\U0001133c\\U00011340\\U00011366-\\U0001136c\\U00011370-\\U00011374\\U00011438-\\U0001143f\\U00011442-\\U00011444\\U00011446\\U0001145e\\U000114b3-\\U000114b8\\U000114ba\\U000114bf-\\U000114c0\\U000114c2-\\U000114c3\\U000115b2-\\U000115b5\\U000115bc-\\U000115bd\\U000115bf-\\U000115c0\\U000115dc-\\U000115dd\\U00011633-\\U0001163a\\U0001163d\\U0001163f-\\U00011640\\U000116ab\\U000116ad\\U000116b0-\\U000116b5\\U000116b7\\U0001171d-\\U0001171f\\U00011722-\\U00011725\\U00011727-\\U0001172b\\U0001182f-\\U00011837\\U00011839-\\U0001183a\\U00011a01-\\U00011a0a\\U00011a33-\\U00011a38\\U00011a3b-\\U00011a3e\\U00011a47\\U00011a51-\\U00011a56\\U00011a59-\\U00011a5b\\U00011a8a-\\U00011a96\\U00011a98-\\U00011a99\\U00011c30-\\U00011c36\\U00011c38-\\U00011c3d\\U00011c3f\\U00011c92-\\U00011ca7\\U00011caa-\\U00011cb0\\U00011cb2-\\U00011cb3\\U00011cb5-\\U00011cb6\\U00011d31-\\U00011d36\\U00011d3a\\U00011d3c-\\U00011d3d\\U00011d3f-\\U00011d45\\U00011d47\\U00011d90-\\U00011d91\\U00011d95\\U00011d97\\U00011ef3-\\U00011ef4\\U00016af0-\\U00016af4\\U00016b30-\\U00016b36\\U00016f8f-\\U00016f92\\U0001bc9d-\\U0001bc9e\\U0001d167-\\U0001d169\\U0001d17b-\\U0001d182\\U0001d185-\\U0001d18b\\U0001d1aa-\\U0001d1ad\\U0001d242-\\U0001d244\\U0001da00-\\U0001da36\\U0001da3b-\\U0001da6c\\U0001da75\\U0001da84\\U0001da9b-\\U0001da9f\\U0001daa1-\\U0001daaf\\U0001e000-\\U0001e006\\U0001e008-\\U0001e018\\U0001e01b-\\U0001e021\\U0001e023-\\U0001e024\\U0001e026-\\U0001e02a\\U0001e8d0-\\U0001e8d6\\U0001e944-\\U0001e94a\\U000e0100-\\U000e01ef'\n\nNd = '0-9\\u0660-\\u0669\\u06f0-\\u06f9\\u07c0-\\u07c9\\u0966-\\u096f\\u09e6-\\u09ef\\u0a66-\\u0a6f\\u0ae6-\\u0aef\\u0b66-\\u0b6f\\u0be6-\\u0bef\\u0c66-\\u0c6f\\u0ce6-\\u0cef\\u0d66-\\u0d6f\\u0de6-\\u0def\\u0e50-\\u0e59\\u0ed0-\\u0ed9\\u0f20-\\u0f29\\u1040-\\u1049\\u1090-\\u1099\\u17e0-\\u17e9\\u1810-\\u1819\\u1946-\\u194f\\u19d0-\\u19d9\\u1a80-\\u1a89\\u1a90-\\u1a99\\u1b50-\\u1b59\\u1bb0-\\u1bb9\\u1c40-\\u1c49\\u1c50-\\u1c59\\ua620-\\ua629\\ua8d0-\\ua8d9\\ua900-\\ua909\\ua9d0-\\ua9d9\\ua9f0-\\ua9f9\\uaa50-\\uaa59\\uabf0-\\uabf9\\uff10-\\uff19\\U000104a0-\\U000104a9\\U00010d30-\\U00010d39\\U00011066-\\U0001106f\\U000110f0-\\U000110f9\\U00011136-\\U0001113f\\U000111d0-\\U000111d9\\U000112f0-\\U000112f9\\U00011450-\\U00011459\\U000114d0-\\U000114d9\\U00011650-\\U00011659\\U000116c0-\\U000116c9\\U00011730-\\U00011739\\U000118e0-\\U000118e9\\U00011c50-\\U00011c59\\U00011d50-\\U00011d59\\U00011da0-\\U00011da9\\U00016a60-\\U00016a69\\U00016b50-\\U00016b59\\U0001d7ce-\\U0001d7ff\\U0001e950-\\U0001e959'\n\nNl = '\\u16ee-\\u16f0\\u2160-\\u2182\\u2185-\\u2188\\u3007\\u3021-\\u3029\\u3038-\\u303a\\ua6e6-\\ua6ef\\U00010140-\\U00010174\\U00010341\\U0001034a\\U000103d1-\\U000103d5\\U00012400-\\U0001246e'\n\nNo = '\\xb2-\\xb3\\xb9\\xbc-\\xbe\\u09f4-\\u09f9\\u0b72-\\u0b77\\u0bf0-\\u0bf2\\u0c78-\\u0c7e\\u0d58-\\u0d5e\\u0d70-\\u0d78\\u0f2a-\\u0f33\\u1369-\\u137c\\u17f0-\\u17f9\\u19da\\u2070\\u2074-\\u2079\\u2080-\\u2089\\u2150-\\u215f\\u2189\\u2460-\\u249b\\u24ea-\\u24ff\\u2776-\\u2793\\u2cfd\\u3192-\\u3195\\u3220-\\u3229\\u3248-\\u324f\\u3251-\\u325f\\u3280-\\u3289\\u32b1-\\u32bf\\ua830-\\ua835\\U00010107-\\U00010133\\U00010175-\\U00010178\\U0001018a-\\U0001018b\\U000102e1-\\U000102fb\\U00010320-\\U00010323\\U00010858-\\U0001085f\\U00010879-\\U0001087f\\U000108a7-\\U000108af\\U000108fb-\\U000108ff\\U00010916-\\U0001091b\\U000109bc-\\U000109bd\\U000109c0-\\U000109cf\\U000109d2-\\U000109ff\\U00010a40-\\U00010a48\\U00010a7d-\\U00010a7e\\U00010a9d-\\U00010a9f\\U00010aeb-\\U00010aef\\U00010b58-\\U00010b5f\\U00010b78-\\U00010b7f\\U00010ba9-\\U00010baf\\U00010cfa-\\U00010cff\\U00010e60-\\U00010e7e\\U00010f1d-\\U00010f26\\U00010f51-\\U00010f54\\U00011052-\\U00011065\\U000111e1-\\U000111f4\\U0001173a-\\U0001173b\\U000118ea-\\U000118f2\\U00011c5a-\\U00011c6c\\U00016b5b-\\U00016b61\\U00016e80-\\U00016e96\\U0001d2e0-\\U0001d2f3\\U0001d360-\\U0001d378\\U0001e8c7-\\U0001e8cf\\U0001ec71-\\U0001ecab\\U0001ecad-\\U0001ecaf\\U0001ecb1-\\U0001ecb4\\U0001f100-\\U0001f10c'\n\nPc = '_\\u203f-\\u2040\\u2054\\ufe33-\\ufe34\\ufe4d-\\ufe4f\\uff3f'\n\nPd = '\\\\-\\u058a\\u05be\\u1400\\u1806\\u2010-\\u2015\\u2e17\\u2e1a\\u2e3a-\\u2e3b\\u2e40\\u301c\\u3030\\u30a0\\ufe31-\\ufe32\\ufe58\\ufe63\\uff0d'\n\nPe = ')\\\\]}\\u0f3b\\u0f3d\\u169c\\u2046\\u207e\\u208e\\u2309\\u230b\\u232a\\u2769\\u276b\\u276d\\u276f\\u2771\\u2773\\u2775\\u27c6\\u27e7\\u27e9\\u27eb\\u27ed\\u27ef\\u2984\\u2986\\u2988\\u298a\\u298c\\u298e\\u2990\\u2992\\u2994\\u2996\\u2998\\u29d9\\u29db\\u29fd\\u2e23\\u2e25\\u2e27\\u2e29\\u3009\\u300b\\u300d\\u300f\\u3011\\u3015\\u3017\\u3019\\u301b\\u301e-\\u301f\\ufd3e\\ufe18\\ufe36\\ufe38\\ufe3a\\ufe3c\\ufe3e\\ufe40\\ufe42\\ufe44\\ufe48\\ufe5a\\ufe5c\\ufe5e\\uff09\\uff3d\\uff5d\\uff60\\uff63'\n\nPf = '\\xbb\\u2019\\u201d\\u203a\\u2e03\\u2e05\\u2e0a\\u2e0d\\u2e1d\\u2e21'\n\nPi = '\\xab\\u2018\\u201b-\\u201c\\u201f\\u2039\\u2e02\\u2e04\\u2e09\\u2e0c\\u2e1c\\u2e20'\n\nPo = \"!-#%-'*,.-/:-;?-@\\\\\\\\\\xa1\\xa7\\xb6-\\xb7\\xbf\\u037e\\u0387\\u055a-\\u055f\\u0589\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u166d-\\u166e\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u1805\\u1807-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2016-\\u2017\\u2020-\\u2027\\u2030-\\u2038\\u203b-\\u203e\\u2041-\\u2043\\u2047-\\u2051\\u2053\\u2055-\\u205e\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e01\\u2e06-\\u2e08\\u2e0b\\u2e0e-\\u2e16\\u2e18-\\u2e19\\u2e1b\\u2e1e-\\u2e1f\\u2e2a-\\u2e2e\\u2e30-\\u2e39\\u2e3c-\\u2e3f\\u2e41\\u2e43-\\u2e4e\\u3001-\\u3003\\u303d\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufe10-\\ufe16\\ufe19\\ufe30\\ufe45-\\ufe46\\ufe49-\\ufe4c\\ufe50-\\ufe52\\ufe54-\\ufe57\\ufe5f-\\ufe61\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff07\\uff0a\\uff0c\\uff0e-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3c\\uff61\\uff64-\\uff65\\U00010100-\\U00010102\\U0001039f\\U000103d0\\U0001056f\\U00010857\\U0001091f\\U0001093f\\U00010a50-\\U00010a58\\U00010a7f\\U00010af0-\\U00010af6\\U00010b39-\\U00010b3f\\U00010b99-\\U00010b9c\\U00010f55-\\U00010f59\\U00011047-\\U0001104d\\U000110bb-\\U000110bc\\U000110be-\\U000110c1\\U00011140-\\U00011143\\U00011174-\\U00011175\\U000111c5-\\U000111c8\\U000111cd\\U000111db\\U000111dd-\\U000111df\\U00011238-\\U0001123d\\U000112a9\\U0001144b-\\U0001144f\\U0001145b\\U0001145d\\U000114c6\\U000115c1-\\U000115d7\\U00011641-\\U00011643\\U00011660-\\U0001166c\\U0001173c-\\U0001173e\\U0001183b\\U00011a3f-\\U00011a46\\U00011a9a-\\U00011a9c\\U00011a9e-\\U00011aa2\\U00011c41-\\U00011c45\\U00011c70-\\U00011c71\\U00011ef7-\\U00011ef8\\U00012470-\\U00012474\\U00016a6e-\\U00016a6f\\U00016af5\\U00016b37-\\U00016b3b\\U00016b44\\U00016e97-\\U00016e9a\\U0001bc9f\\U0001da87-\\U0001da8b\\U0001e95e-\\U0001e95f\"\n\nPs = '(\\\\[{\\u0f3a\\u0f3c\\u169b\\u201a\\u201e\\u2045\\u207d\\u208d\\u2308\\u230a\\u2329\\u2768\\u276a\\u276c\\u276e\\u2770\\u2772\\u2774\\u27c5\\u27e6\\u27e8\\u27ea\\u27ec\\u27ee\\u2983\\u2985\\u2987\\u2989\\u298b\\u298d\\u298f\\u2991\\u2993\\u2995\\u2997\\u29d8\\u29da\\u29fc\\u2e22\\u2e24\\u2e26\\u2e28\\u2e42\\u3008\\u300a\\u300c\\u300e\\u3010\\u3014\\u3016\\u3018\\u301a\\u301d\\ufd3f\\ufe17\\ufe35\\ufe37\\ufe39\\ufe3b\\ufe3d\\ufe3f\\ufe41\\ufe43\\ufe47\\ufe59\\ufe5b\\ufe5d\\uff08\\uff3b\\uff5b\\uff5f\\uff62'\n\nSc = '$\\xa2-\\xa5\\u058f\\u060b\\u07fe-\\u07ff\\u09f2-\\u09f3\\u09fb\\u0af1\\u0bf9\\u0e3f\\u17db\\u20a0-\\u20bf\\ua838\\ufdfc\\ufe69\\uff04\\uffe0-\\uffe1\\uffe5-\\uffe6\\U0001ecb0'\n\nSk = '\\\\^`\\xa8\\xaf\\xb4\\xb8\\u02c2-\\u02c5\\u02d2-\\u02df\\u02e5-\\u02eb\\u02ed\\u02ef-\\u02ff\\u0375\\u0384-\\u0385\\u1fbd\\u1fbf-\\u1fc1\\u1fcd-\\u1fcf\\u1fdd-\\u1fdf\\u1fed-\\u1fef\\u1ffd-\\u1ffe\\u309b-\\u309c\\ua700-\\ua716\\ua720-\\ua721\\ua789-\\ua78a\\uab5b\\ufbb2-\\ufbc1\\uff3e\\uff40\\uffe3\\U0001f3fb-\\U0001f3ff'\n\nSm = '+<->|~\\xac\\xb1\\xd7\\xf7\\u03f6\\u0606-\\u0608\\u2044\\u2052\\u207a-\\u207c\\u208a-\\u208c\\u2118\\u2140-\\u2144\\u214b\\u2190-\\u2194\\u219a-\\u219b\\u21a0\\u21a3\\u21a6\\u21ae\\u21ce-\\u21cf\\u21d2\\u21d4\\u21f4-\\u22ff\\u2320-\\u2321\\u237c\\u239b-\\u23b3\\u23dc-\\u23e1\\u25b7\\u25c1\\u25f8-\\u25ff\\u266f\\u27c0-\\u27c4\\u27c7-\\u27e5\\u27f0-\\u27ff\\u2900-\\u2982\\u2999-\\u29d7\\u29dc-\\u29fb\\u29fe-\\u2aff\\u2b30-\\u2b44\\u2b47-\\u2b4c\\ufb29\\ufe62\\ufe64-\\ufe66\\uff0b\\uff1c-\\uff1e\\uff5c\\uff5e\\uffe2\\uffe9-\\uffec\\U0001d6c1\\U0001d6db\\U0001d6fb\\U0001d715\\U0001d735\\U0001d74f\\U0001d76f\\U0001d789\\U0001d7a9\\U0001d7c3\\U0001eef0-\\U0001eef1'\n\nSo = '\\xa6\\xa9\\xae\\xb0\\u0482\\u058d-\\u058e\\u060e-\\u060f\\u06de\\u06e9\\u06fd-\\u06fe\\u07f6\\u09fa\\u0b70\\u0bf3-\\u0bf8\\u0bfa\\u0c7f\\u0d4f\\u0d79\\u0f01-\\u0f03\\u0f13\\u0f15-\\u0f17\\u0f1a-\\u0f1f\\u0f34\\u0f36\\u0f38\\u0fbe-\\u0fc5\\u0fc7-\\u0fcc\\u0fce-\\u0fcf\\u0fd5-\\u0fd8\\u109e-\\u109f\\u1390-\\u1399\\u1940\\u19de-\\u19ff\\u1b61-\\u1b6a\\u1b74-\\u1b7c\\u2100-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2117\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u214a\\u214c-\\u214d\\u214f\\u218a-\\u218b\\u2195-\\u2199\\u219c-\\u219f\\u21a1-\\u21a2\\u21a4-\\u21a5\\u21a7-\\u21ad\\u21af-\\u21cd\\u21d0-\\u21d1\\u21d3\\u21d5-\\u21f3\\u2300-\\u2307\\u230c-\\u231f\\u2322-\\u2328\\u232b-\\u237b\\u237d-\\u239a\\u23b4-\\u23db\\u23e2-\\u2426\\u2440-\\u244a\\u249c-\\u24e9\\u2500-\\u25b6\\u25b8-\\u25c0\\u25c2-\\u25f7\\u2600-\\u266e\\u2670-\\u2767\\u2794-\\u27bf\\u2800-\\u28ff\\u2b00-\\u2b2f\\u2b45-\\u2b46\\u2b4d-\\u2b73\\u2b76-\\u2b95\\u2b98-\\u2bc8\\u2bca-\\u2bfe\\u2ce5-\\u2cea\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u2ffb\\u3004\\u3012-\\u3013\\u3020\\u3036-\\u3037\\u303e-\\u303f\\u3190-\\u3191\\u3196-\\u319f\\u31c0-\\u31e3\\u3200-\\u321e\\u322a-\\u3247\\u3250\\u3260-\\u327f\\u328a-\\u32b0\\u32c0-\\u32fe\\u3300-\\u33ff\\u4dc0-\\u4dff\\ua490-\\ua4c6\\ua828-\\ua82b\\ua836-\\ua837\\ua839\\uaa77-\\uaa79\\ufdfd\\uffe4\\uffe8\\uffed-\\uffee\\ufffc-\\ufffd\\U00010137-\\U0001013f\\U00010179-\\U00010189\\U0001018c-\\U0001018e\\U00010190-\\U0001019b\\U000101a0\\U000101d0-\\U000101fc\\U00010877-\\U00010878\\U00010ac8\\U0001173f\\U00016b3c-\\U00016b3f\\U00016b45\\U0001bc9c\\U0001d000-\\U0001d0f5\\U0001d100-\\U0001d126\\U0001d129-\\U0001d164\\U0001d16a-\\U0001d16c\\U0001d183-\\U0001d184\\U0001d18c-\\U0001d1a9\\U0001d1ae-\\U0001d1e8\\U0001d200-\\U0001d241\\U0001d245\\U0001d300-\\U0001d356\\U0001d800-\\U0001d9ff\\U0001da37-\\U0001da3a\\U0001da6d-\\U0001da74\\U0001da76-\\U0001da83\\U0001da85-\\U0001da86\\U0001ecac\\U0001f000-\\U0001f02b\\U0001f030-\\U0001f093\\U0001f0a0-\\U0001f0ae\\U0001f0b1-\\U0001f0bf\\U0001f0c1-\\U0001f0cf\\U0001f0d1-\\U0001f0f5\\U0001f110-\\U0001f16b\\U0001f170-\\U0001f1ac\\U0001f1e6-\\U0001f202\\U0001f210-\\U0001f23b\\U0001f240-\\U0001f248\\U0001f250-\\U0001f251\\U0001f260-\\U0001f265\\U0001f300-\\U0001f3fa\\U0001f400-\\U0001f6d4\\U0001f6e0-\\U0001f6ec\\U0001f6f0-\\U0001f6f9\\U0001f700-\\U0001f773\\U0001f780-\\U0001f7d8\\U0001f800-\\U0001f80b\\U0001f810-\\U0001f847\\U0001f850-\\U0001f859\\U0001f860-\\U0001f887\\U0001f890-\\U0001f8ad\\U0001f900-\\U0001f90b\\U0001f910-\\U0001f93e\\U0001f940-\\U0001f970\\U0001f973-\\U0001f976\\U0001f97a\\U0001f97c-\\U0001f9a2\\U0001f9b0-\\U0001f9b9\\U0001f9c0-\\U0001f9c2\\U0001f9d0-\\U0001f9ff\\U0001fa60-\\U0001fa6d'\n\nZl = '\\u2028'\n\nZp = '\\u2029'\n\nZs = ' \\xa0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000'\n\nxid_continue = '0-9A-Z_a-z\\xaa\\xb5\\xb7\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0300-\\u0374\\u0376-\\u0377\\u037b-\\u037d\\u037f\\u0386-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u0483-\\u0487\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u0591-\\u05bd\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0610-\\u061a\\u0620-\\u0669\\u066e-\\u06d3\\u06d5-\\u06dc\\u06df-\\u06e8\\u06ea-\\u06fc\\u06ff\\u0710-\\u074a\\u074d-\\u07b1\\u07c0-\\u07f5\\u07fa\\u07fd\\u0800-\\u082d\\u0840-\\u085b\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u08d3-\\u08e1\\u08e3-\\u0963\\u0966-\\u096f\\u0971-\\u0983\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bc-\\u09c4\\u09c7-\\u09c8\\u09cb-\\u09ce\\u09d7\\u09dc-\\u09dd\\u09df-\\u09e3\\u09e6-\\u09f1\\u09fc\\u09fe\\u0a01-\\u0a03\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a3c\\u0a3e-\\u0a42\\u0a47-\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a59-\\u0a5c\\u0a5e\\u0a66-\\u0a75\\u0a81-\\u0a83\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abc-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ad0\\u0ae0-\\u0ae3\\u0ae6-\\u0aef\\u0af9-\\u0aff\\u0b01-\\u0b03\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3c-\\u0b44\\u0b47-\\u0b48\\u0b4b-\\u0b4d\\u0b56-\\u0b57\\u0b5c-\\u0b5d\\u0b5f-\\u0b63\\u0b66-\\u0b6f\\u0b71\\u0b82-\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd0\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55-\\u0c56\\u0c58-\\u0c5a\\u0c60-\\u0c63\\u0c66-\\u0c6f\\u0c80-\\u0c83\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbc-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5-\\u0cd6\\u0cde\\u0ce0-\\u0ce3\\u0ce6-\\u0cef\\u0cf1-\\u0cf2\\u0d00-\\u0d03\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4e\\u0d54-\\u0d57\\u0d5f-\\u0d63\\u0d66-\\u0d6f\\u0d7a-\\u0d7f\\u0d82-\\u0d83\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2-\\u0df3\\u0e01-\\u0e3a\\u0e40-\\u0e4e\\u0e50-\\u0e59\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb9\\u0ebb-\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0edc-\\u0edf\\u0f00\\u0f18-\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e-\\u0f47\\u0f49-\\u0f6c\\u0f71-\\u0f84\\u0f86-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1049\\u1050-\\u109d\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u135d-\\u135f\\u1369-\\u1371\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176c\\u176e-\\u1770\\u1772-\\u1773\\u1780-\\u17d3\\u17d7\\u17dc-\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1820-\\u1878\\u1880-\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u19d0-\\u19da\\u1a00-\\u1a1b\\u1a20-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1aa7\\u1ab0-\\u1abd\\u1b00-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1bf3\\u1c00-\\u1c37\\u1c40-\\u1c49\\u1c4d-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1cd0-\\u1cd2\\u1cd4-\\u1cf9\\u1d00-\\u1df9\\u1dfb-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u203f-\\u2040\\u2054\\u2071\\u207f\\u2090-\\u209c\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d7f-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2de0-\\u2dff\\u3005-\\u3007\\u3021-\\u302f\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u3099-\\u309a\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua62b\\ua640-\\ua66f\\ua674-\\ua67d\\ua67f-\\ua6f1\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7b9\\ua7f7-\\ua827\\ua840-\\ua873\\ua880-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f7\\ua8fb\\ua8fd-\\ua92d\\ua930-\\ua953\\ua960-\\ua97c\\ua980-\\ua9c0\\ua9cf-\\ua9d9\\ua9e0-\\ua9fe\\uaa00-\\uaa36\\uaa40-\\uaa4d\\uaa50-\\uaa59\\uaa60-\\uaa76\\uaa7a-\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaef\\uaaf2-\\uaaf6\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab65\\uab70-\\uabea\\uabec-\\uabed\\uabf0-\\uabf9\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufc5d\\ufc64-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdf9\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33-\\ufe34\\ufe4d-\\ufe4f\\ufe71\\ufe73\\ufe77\\ufe79\\ufe7b\\ufe7d\\ufe7f-\\ufefc\\uff10-\\uff19\\uff21-\\uff3a\\uff3f\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010140-\\U00010174\\U000101fd\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U000102e0\\U00010300-\\U0001031f\\U0001032d-\\U0001034a\\U00010350-\\U0001037a\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U000103d1-\\U000103d5\\U00010400-\\U0001049d\\U000104a0-\\U000104a9\\U000104b0-\\U000104d3\\U000104d8-\\U000104fb\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00-\\U00010a03\\U00010a05-\\U00010a06\\U00010a0c-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a38-\\U00010a3a\\U00010a3f\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae6\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010c80-\\U00010cb2\\U00010cc0-\\U00010cf2\\U00010d00-\\U00010d27\\U00010d30-\\U00010d39\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f50\\U00011000-\\U00011046\\U00011066-\\U0001106f\\U0001107f-\\U000110ba\\U000110d0-\\U000110e8\\U000110f0-\\U000110f9\\U00011100-\\U00011134\\U00011136-\\U0001113f\\U00011144-\\U00011146\\U00011150-\\U00011173\\U00011176\\U00011180-\\U000111c4\\U000111c9-\\U000111cc\\U000111d0-\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U00011237\\U0001123e\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112ea\\U000112f0-\\U000112f9\\U00011300-\\U00011303\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133b-\\U00011344\\U00011347-\\U00011348\\U0001134b-\\U0001134d\\U00011350\\U00011357\\U0001135d-\\U00011363\\U00011366-\\U0001136c\\U00011370-\\U00011374\\U00011400-\\U0001144a\\U00011450-\\U00011459\\U0001145e\\U00011480-\\U000114c5\\U000114c7\\U000114d0-\\U000114d9\\U00011580-\\U000115b5\\U000115b8-\\U000115c0\\U000115d8-\\U000115dd\\U00011600-\\U00011640\\U00011644\\U00011650-\\U00011659\\U00011680-\\U000116b7\\U000116c0-\\U000116c9\\U00011700-\\U0001171a\\U0001171d-\\U0001172b\\U00011730-\\U00011739\\U00011800-\\U0001183a\\U000118a0-\\U000118e9\\U000118ff\\U00011a00-\\U00011a3e\\U00011a47\\U00011a50-\\U00011a83\\U00011a86-\\U00011a99\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c36\\U00011c38-\\U00011c40\\U00011c50-\\U00011c59\\U00011c72-\\U00011c8f\\U00011c92-\\U00011ca7\\U00011ca9-\\U00011cb6\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d36\\U00011d3a\\U00011d3c-\\U00011d3d\\U00011d3f-\\U00011d47\\U00011d50-\\U00011d59\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d8e\\U00011d90-\\U00011d91\\U00011d93-\\U00011d98\\U00011da0-\\U00011da9\\U00011ee0-\\U00011ef6\\U00012000-\\U00012399\\U00012400-\\U0001246e\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016a60-\\U00016a69\\U00016ad0-\\U00016aed\\U00016af0-\\U00016af4\\U00016b00-\\U00016b36\\U00016b40-\\U00016b43\\U00016b50-\\U00016b59\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016e40-\\U00016e7f\\U00016f00-\\U00016f44\\U00016f50-\\U00016f7e\\U00016f8f-\\U00016f9f\\U00016fe0-\\U00016fe1\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001bc9d-\\U0001bc9e\\U0001d165-\\U0001d169\\U0001d16d-\\U0001d172\\U0001d17b-\\U0001d182\\U0001d185-\\U0001d18b\\U0001d1aa-\\U0001d1ad\\U0001d242-\\U0001d244\\U0001d400-\\U0001d454\\U0001d456-\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d51e-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d552-\\U0001d6a5\\U0001d6a8-\\U0001d6c0\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6fa\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d734\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d76e\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d7a8\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7cb\\U0001d7ce-\\U0001d7ff\\U0001da00-\\U0001da36\\U0001da3b-\\U0001da6c\\U0001da75\\U0001da84\\U0001da9b-\\U0001da9f\\U0001daa1-\\U0001daaf\\U0001e000-\\U0001e006\\U0001e008-\\U0001e018\\U0001e01b-\\U0001e021\\U0001e023-\\U0001e024\\U0001e026-\\U0001e02a\\U0001e800-\\U0001e8c4\\U0001e8d0-\\U0001e8d6\\U0001e900-\\U0001e94a\\U0001e950-\\U0001e959\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d\\U000e0100-\\U000e01ef'\n\nxid_start = 'A-Z_a-z\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376-\\u0377\\u037b-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e-\\u066f\\u0671-\\u06d3\\u06d5\\u06e5-\\u06e6\\u06ee-\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4-\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc-\\u09dd\\u09df-\\u09e1\\u09f0-\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0-\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c-\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60-\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0-\\u0ce1\\u0cf1-\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e40-\\u0e46\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065-\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae-\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5-\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2-\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a-\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7b9\\ua7f7-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd-\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5-\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab65\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufc5d\\ufc64-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdf9\\ufe71\\ufe73\\ufe77\\ufe79\\ufe7b\\ufe7d\\ufe7f-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uff9d\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010140-\\U00010174\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U00010300-\\U0001031f\\U0001032d-\\U0001034a\\U00010350-\\U00010375\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U000103d1-\\U000103d5\\U00010400-\\U0001049d\\U000104b0-\\U000104d3\\U000104d8-\\U000104fb\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00\\U00010a10-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae4\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010c80-\\U00010cb2\\U00010cc0-\\U00010cf2\\U00010d00-\\U00010d23\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f45\\U00011003-\\U00011037\\U00011083-\\U000110af\\U000110d0-\\U000110e8\\U00011103-\\U00011126\\U00011144\\U00011150-\\U00011172\\U00011176\\U00011183-\\U000111b2\\U000111c1-\\U000111c4\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U0001122b\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112de\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133d\\U00011350\\U0001135d-\\U00011361\\U00011400-\\U00011434\\U00011447-\\U0001144a\\U00011480-\\U000114af\\U000114c4-\\U000114c5\\U000114c7\\U00011580-\\U000115ae\\U000115d8-\\U000115db\\U00011600-\\U0001162f\\U00011644\\U00011680-\\U000116aa\\U00011700-\\U0001171a\\U00011800-\\U0001182b\\U000118a0-\\U000118df\\U000118ff\\U00011a00\\U00011a0b-\\U00011a32\\U00011a3a\\U00011a50\\U00011a5c-\\U00011a83\\U00011a86-\\U00011a89\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c2e\\U00011c40\\U00011c72-\\U00011c8f\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d30\\U00011d46\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d89\\U00011d98\\U00011ee0-\\U00011ef2\\U00012000-\\U00012399\\U00012400-\\U0001246e\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016ad0-\\U00016aed\\U00016b00-\\U00016b2f\\U00016b40-\\U00016b43\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016e40-\\U00016e7f\\U00016f00-\\U00016f44\\U00016f50\\U00016f93-\\U00016f9f\\U00016fe0-\\U00016fe1\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001d400-\\U0001d454\\U0001d456-\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d51e-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d552-\\U0001d6a5\\U0001d6a8-\\U0001d6c0\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6fa\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d734\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d76e\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d7a8\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7cb\\U0001e800-\\U0001e8c4\\U0001e900-\\U0001e943\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d'\n\ncats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs']\n\n# Generated from unidata 11.0.0\n\ndef combine(*args):\n    return ''.join(globals()[cat] for cat in args)\n\n\ndef allexcept(*args):\n    newcats = cats[:]\n    for arg in args:\n        newcats.remove(arg)\n    return ''.join(globals()[cat] for cat in newcats)\n\n\ndef _handle_runs(char_list):  # pragma: no cover\n    buf = []\n    for c in char_list:\n        if len(c) == 1:\n            if buf and buf[-1][1] == chr(ord(c)-1):\n                buf[-1] = (buf[-1][0], c)\n            else:\n                buf.append((c, c))\n        else:\n            buf.append((c, c))\n    for a, b in buf:\n        if a == b:\n            yield a\n        else:\n            yield f'{a}-{b}'\n\n\nif __name__ == '__main__':  # pragma: no cover\n    import unicodedata\n\n    categories = {'xid_start': [], 'xid_continue': []}\n\n    with open(__file__, encoding='utf-8') as fp:\n        content = fp.read()\n\n    header = content[:content.find('Cc =')]\n    footer = content[content.find(\"def combine(\"):]\n\n    for code in range(0x110000):\n        c = chr(code)\n        cat = unicodedata.category(c)\n        if ord(c) == 0xdc00:\n            # Hack to avoid combining this combining with the preceding high\n            # surrogate, 0xdbff, when doing a repr.\n            c = '\\\\' + c\n        elif ord(c) in (0x2d, 0x5b, 0x5c, 0x5d, 0x5e):\n            # Escape regex metachars.\n            c = '\\\\' + c\n        categories.setdefault(cat, []).append(c)\n        # XID_START and XID_CONTINUE are special categories used for matching\n        # identifiers in Python 3.\n        if c.isidentifier():\n            categories['xid_start'].append(c)\n        if ('a' + c).isidentifier():\n            categories['xid_continue'].append(c)\n\n    with open(__file__, 'w', encoding='utf-8') as fp:\n        fp.write(header)\n\n        for cat in sorted(categories):\n            val = ''.join(_handle_runs(categories[cat]))\n            fp.write(f'{cat} = {val!a}\\n\\n')\n\n        cats = sorted(categories)\n        cats.remove('xid_start')\n        cats.remove('xid_continue')\n        fp.write(f'cats = {cats!r}\\n\\n')\n\n        fp.write(f'# Generated from unidata {unicodedata.unidata_version}\\n\\n')\n\n        fp.write(footer)\n"
  },
  {
    "path": "src/pip/_vendor/pygments/util.py",
    "content": "\"\"\"\n    pygments.util\n    ~~~~~~~~~~~~~\n\n    Utility functions.\n\n    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nfrom io import TextIOWrapper\n\n\nsplit_path_re = re.compile(r'[/\\\\ ]')\ndoctype_lookup_re = re.compile(r'''\n    <!DOCTYPE\\s+(\n     [a-zA-Z_][a-zA-Z0-9]*\n     (?: \\s+      # optional in HTML5\n     [a-zA-Z_][a-zA-Z0-9]*\\s+\n     \"[^\"]*\")?\n     )\n     [^>]*>\n''', re.DOTALL | re.MULTILINE | re.VERBOSE)\ntag_re = re.compile(r'<(.+?)(\\s.*?)?>.*?</.+?>',\n                    re.IGNORECASE | re.DOTALL | re.MULTILINE)\nxml_decl_re = re.compile(r'\\s*<\\?xml[^>]*\\?>', re.I)\n\n\nclass ClassNotFound(ValueError):\n    \"\"\"Raised if one of the lookup functions didn't find a matching class.\"\"\"\n\n\nclass OptionError(Exception):\n    \"\"\"\n    This exception will be raised by all option processing functions if\n    the type or value of the argument is not correct.\n    \"\"\"\n\ndef get_choice_opt(options, optname, allowed, default=None, normcase=False):\n    \"\"\"\n    If the key `optname` from the dictionary is not in the sequence\n    `allowed`, raise an error, otherwise return it.\n    \"\"\"\n    string = options.get(optname, default)\n    if normcase:\n        string = string.lower()\n    if string not in allowed:\n        raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed))))\n    return string\n\n\ndef get_bool_opt(options, optname, default=None):\n    \"\"\"\n    Intuitively, this is `options.get(optname, default)`, but restricted to\n    Boolean value. The Booleans can be represented as string, in order to accept\n    Boolean value from the command line arguments. If the key `optname` is\n    present in the dictionary `options` and is not associated with a Boolean,\n    raise an `OptionError`. If it is absent, `default` is returned instead.\n\n    The valid string values for ``True`` are ``1``, ``yes``, ``true`` and\n    ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off``\n    (matched case-insensitively).\n    \"\"\"\n    string = options.get(optname, default)\n    if isinstance(string, bool):\n        return string\n    elif isinstance(string, int):\n        return bool(string)\n    elif not isinstance(string, str):\n        raise OptionError(f'Invalid type {string!r} for option {optname}; use '\n                          '1/0, yes/no, true/false, on/off')\n    elif string.lower() in ('1', 'yes', 'true', 'on'):\n        return True\n    elif string.lower() in ('0', 'no', 'false', 'off'):\n        return False\n    else:\n        raise OptionError(f'Invalid value {string!r} for option {optname}; use '\n                          '1/0, yes/no, true/false, on/off')\n\n\ndef get_int_opt(options, optname, default=None):\n    \"\"\"As :func:`get_bool_opt`, but interpret the value as an integer.\"\"\"\n    string = options.get(optname, default)\n    try:\n        return int(string)\n    except TypeError:\n        raise OptionError(f'Invalid type {string!r} for option {optname}; you '\n                          'must give an integer value')\n    except ValueError:\n        raise OptionError(f'Invalid value {string!r} for option {optname}; you '\n                          'must give an integer value')\n\ndef get_list_opt(options, optname, default=None):\n    \"\"\"\n    If the key `optname` from the dictionary `options` is a string,\n    split it at whitespace and return it. If it is already a list\n    or a tuple, it is returned as a list.\n    \"\"\"\n    val = options.get(optname, default)\n    if isinstance(val, str):\n        return val.split()\n    elif isinstance(val, (list, tuple)):\n        return list(val)\n    else:\n        raise OptionError(f'Invalid type {val!r} for option {optname}; you '\n                          'must give a list value')\n\n\ndef docstring_headline(obj):\n    if not obj.__doc__:\n        return ''\n    res = []\n    for line in obj.__doc__.strip().splitlines():\n        if line.strip():\n            res.append(\" \" + line.strip())\n        else:\n            break\n    return ''.join(res).lstrip()\n\n\ndef make_analysator(f):\n    \"\"\"Return a static text analyser function that returns float values.\"\"\"\n    def text_analyse(text):\n        try:\n            rv = f(text)\n        except Exception:\n            return 0.0\n        if not rv:\n            return 0.0\n        try:\n            return min(1.0, max(0.0, float(rv)))\n        except (ValueError, TypeError):\n            return 0.0\n    text_analyse.__doc__ = f.__doc__\n    return staticmethod(text_analyse)\n\n\ndef shebang_matches(text, regex):\n    r\"\"\"Check if the given regular expression matches the last part of the\n    shebang if one exists.\n\n        >>> from pygments.util import shebang_matches\n        >>> shebang_matches('#!/usr/bin/env python', r'python(2\\.\\d)?')\n        True\n        >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\\.\\d)?')\n        True\n        >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\\.\\d)?')\n        False\n        >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\\.\\d)?')\n        False\n        >>> shebang_matches('#!/usr/bin/startsomethingwith python',\n        ...                 r'python(2\\.\\d)?')\n        True\n\n    It also checks for common windows executable file extensions::\n\n        >>> shebang_matches('#!C:\\\\Python2.4\\\\Python.exe', r'python(2\\.\\d)?')\n        True\n\n    Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does\n    the same as ``'perl -e'``)\n\n    Note that this method automatically searches the whole string (eg:\n    the regular expression is wrapped in ``'^$'``)\n    \"\"\"\n    index = text.find('\\n')\n    if index >= 0:\n        first_line = text[:index].lower()\n    else:\n        first_line = text.lower()\n    if first_line.startswith('#!'):\n        try:\n            found = [x for x in split_path_re.split(first_line[2:].strip())\n                     if x and not x.startswith('-')][-1]\n        except IndexError:\n            return False\n        regex = re.compile(rf'^{regex}(\\.(exe|cmd|bat|bin))?$', re.IGNORECASE)\n        if regex.search(found) is not None:\n            return True\n    return False\n\n\ndef doctype_matches(text, regex):\n    \"\"\"Check if the doctype matches a regular expression (if present).\n\n    Note that this method only checks the first part of a DOCTYPE.\n    eg: 'html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"'\n    \"\"\"\n    m = doctype_lookup_re.search(text)\n    if m is None:\n        return False\n    doctype = m.group(1)\n    return re.compile(regex, re.I).match(doctype.strip()) is not None\n\n\ndef html_doctype_matches(text):\n    \"\"\"Check if the file looks like it has a html doctype.\"\"\"\n    return doctype_matches(text, r'html')\n\n\n_looks_like_xml_cache = {}\n\n\ndef looks_like_xml(text):\n    \"\"\"Check if a doctype exists or if we have some tags.\"\"\"\n    if xml_decl_re.match(text):\n        return True\n    key = hash(text)\n    try:\n        return _looks_like_xml_cache[key]\n    except KeyError:\n        m = doctype_lookup_re.search(text)\n        if m is not None:\n            return True\n        rv = tag_re.search(text[:1000]) is not None\n        _looks_like_xml_cache[key] = rv\n        return rv\n\n\ndef surrogatepair(c):\n    \"\"\"Given a unicode character code with length greater than 16 bits,\n    return the two 16 bit surrogate pair.\n    \"\"\"\n    # From example D28 of:\n    # http://www.unicode.org/book/ch03.pdf\n    return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))\n\n\ndef format_lines(var_name, seq, raw=False, indent_level=0):\n    \"\"\"Formats a sequence of strings for output.\"\"\"\n    lines = []\n    base_indent = ' ' * indent_level * 4\n    inner_indent = ' ' * (indent_level + 1) * 4\n    lines.append(base_indent + var_name + ' = (')\n    if raw:\n        # These should be preformatted reprs of, say, tuples.\n        for i in seq:\n            lines.append(inner_indent + i + ',')\n    else:\n        for i in seq:\n            # Force use of single quotes\n            r = repr(i + '\"')\n            lines.append(inner_indent + r[:-2] + r[-1] + ',')\n    lines.append(base_indent + ')')\n    return '\\n'.join(lines)\n\n\ndef duplicates_removed(it, already_seen=()):\n    \"\"\"\n    Returns a list with duplicates removed from the iterable `it`.\n\n    Order is preserved.\n    \"\"\"\n    lst = []\n    seen = set()\n    for i in it:\n        if i in seen or i in already_seen:\n            continue\n        lst.append(i)\n        seen.add(i)\n    return lst\n\n\nclass Future:\n    \"\"\"Generic class to defer some work.\n\n    Handled specially in RegexLexerMeta, to support regex string construction at\n    first use.\n    \"\"\"\n    def get(self):\n        raise NotImplementedError\n\n\ndef guess_decode(text):\n    \"\"\"Decode *text* with guessed encoding.\n\n    First try UTF-8; this should fail for non-UTF-8 encodings.\n    Then try the preferred locale encoding.\n    Fall back to latin-1, which always works.\n    \"\"\"\n    try:\n        text = text.decode('utf-8')\n        return text, 'utf-8'\n    except UnicodeDecodeError:\n        try:\n            import locale\n            prefencoding = locale.getpreferredencoding()\n            text = text.decode()\n            return text, prefencoding\n        except (UnicodeDecodeError, LookupError):\n            text = text.decode('latin1')\n            return text, 'latin1'\n\n\ndef guess_decode_from_terminal(text, term):\n    \"\"\"Decode *text* coming from terminal *term*.\n\n    First try the terminal encoding, if given.\n    Then try UTF-8.  Then try the preferred locale encoding.\n    Fall back to latin-1, which always works.\n    \"\"\"\n    if getattr(term, 'encoding', None):\n        try:\n            text = text.decode(term.encoding)\n        except UnicodeDecodeError:\n            pass\n        else:\n            return text, term.encoding\n    return guess_decode(text)\n\n\ndef terminal_encoding(term):\n    \"\"\"Return our best guess of encoding for the given *term*.\"\"\"\n    if getattr(term, 'encoding', None):\n        return term.encoding\n    import locale\n    return locale.getpreferredencoding()\n\n\nclass UnclosingTextIOWrapper(TextIOWrapper):\n    # Don't close underlying buffer on destruction.\n    def close(self):\n        self.flush()\n"
  },
  {
    "path": "src/pip/_vendor/pygments.pyi",
    "content": "from pygments import *"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2017 Thomas Kluyver\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/__init__.py",
    "content": "\"\"\"Wrappers to call pyproject.toml-based build backend hooks.\n\"\"\"\n\nfrom typing import TYPE_CHECKING\n\nfrom ._impl import (\n    BackendUnavailable,\n    BuildBackendHookCaller,\n    HookMissing,\n    UnsupportedOperation,\n    default_subprocess_runner,\n    quiet_subprocess_runner,\n)\n\n__version__ = \"1.2.0\"\n__all__ = [\n    \"BackendUnavailable\",\n    \"BackendInvalid\",\n    \"HookMissing\",\n    \"UnsupportedOperation\",\n    \"default_subprocess_runner\",\n    \"quiet_subprocess_runner\",\n    \"BuildBackendHookCaller\",\n]\n\nBackendInvalid = BackendUnavailable  # Deprecated alias, previously a separate exception\n\nif TYPE_CHECKING:\n    from ._impl import SubprocessRunner\n\n    __all__ += [\"SubprocessRunner\"]\n"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/_impl.py",
    "content": "import json\nimport os\nimport sys\nimport tempfile\nfrom contextlib import contextmanager\nfrom os.path import abspath\nfrom os.path import join as pjoin\nfrom subprocess import STDOUT, check_call, check_output\nfrom typing import TYPE_CHECKING, Any, Iterator, Mapping, Optional, Sequence\n\nfrom ._in_process import _in_proc_script_path\n\nif TYPE_CHECKING:\n    from typing import Protocol\n\n    class SubprocessRunner(Protocol):\n        \"\"\"A protocol for the subprocess runner.\"\"\"\n\n        def __call__(\n            self,\n            cmd: Sequence[str],\n            cwd: Optional[str] = None,\n            extra_environ: Optional[Mapping[str, str]] = None,\n        ) -> None:\n            ...\n\n\ndef write_json(obj: Mapping[str, Any], path: str, **kwargs) -> None:\n    with open(path, \"w\", encoding=\"utf-8\") as f:\n        json.dump(obj, f, **kwargs)\n\n\ndef read_json(path: str) -> Mapping[str, Any]:\n    with open(path, encoding=\"utf-8\") as f:\n        return json.load(f)\n\n\nclass BackendUnavailable(Exception):\n    \"\"\"Will be raised if the backend cannot be imported in the hook process.\"\"\"\n\n    def __init__(\n        self,\n        traceback: str,\n        message: Optional[str] = None,\n        backend_name: Optional[str] = None,\n        backend_path: Optional[Sequence[str]] = None,\n    ) -> None:\n        # Preserving arg order for the sake of API backward compatibility.\n        self.backend_name = backend_name\n        self.backend_path = backend_path\n        self.traceback = traceback\n        super().__init__(message or \"Error while importing backend\")\n\n\nclass HookMissing(Exception):\n    \"\"\"Will be raised on missing hooks (if a fallback can't be used).\"\"\"\n\n    def __init__(self, hook_name: str) -> None:\n        super().__init__(hook_name)\n        self.hook_name = hook_name\n\n\nclass UnsupportedOperation(Exception):\n    \"\"\"May be raised by build_sdist if the backend indicates that it can't.\"\"\"\n\n    def __init__(self, traceback: str) -> None:\n        self.traceback = traceback\n\n\ndef default_subprocess_runner(\n    cmd: Sequence[str],\n    cwd: Optional[str] = None,\n    extra_environ: Optional[Mapping[str, str]] = None,\n) -> None:\n    \"\"\"The default method of calling the wrapper subprocess.\n\n    This uses :func:`subprocess.check_call` under the hood.\n    \"\"\"\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n\n    check_call(cmd, cwd=cwd, env=env)\n\n\ndef quiet_subprocess_runner(\n    cmd: Sequence[str],\n    cwd: Optional[str] = None,\n    extra_environ: Optional[Mapping[str, str]] = None,\n) -> None:\n    \"\"\"Call the subprocess while suppressing output.\n\n    This uses :func:`subprocess.check_output` under the hood.\n    \"\"\"\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n\n    check_output(cmd, cwd=cwd, env=env, stderr=STDOUT)\n\n\ndef norm_and_check(source_tree: str, requested: str) -> str:\n    \"\"\"Normalise and check a backend path.\n\n    Ensure that the requested backend path is specified as a relative path,\n    and resolves to a location under the given source tree.\n\n    Return an absolute version of the requested path.\n    \"\"\"\n    if os.path.isabs(requested):\n        raise ValueError(\"paths must be relative\")\n\n    abs_source = os.path.abspath(source_tree)\n    abs_requested = os.path.normpath(os.path.join(abs_source, requested))\n    # We have to use commonprefix for Python 2.7 compatibility. So we\n    # normalise case to avoid problems because commonprefix is a character\n    # based comparison :-(\n    norm_source = os.path.normcase(abs_source)\n    norm_requested = os.path.normcase(abs_requested)\n    if os.path.commonprefix([norm_source, norm_requested]) != norm_source:\n        raise ValueError(\"paths must be inside source tree\")\n\n    return abs_requested\n\n\nclass BuildBackendHookCaller:\n    \"\"\"A wrapper to call the build backend hooks for a source directory.\"\"\"\n\n    def __init__(\n        self,\n        source_dir: str,\n        build_backend: str,\n        backend_path: Optional[Sequence[str]] = None,\n        runner: Optional[\"SubprocessRunner\"] = None,\n        python_executable: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        :param source_dir: The source directory to invoke the build backend for\n        :param build_backend: The build backend spec\n        :param backend_path: Additional path entries for the build backend spec\n        :param runner: The :ref:`subprocess runner <Subprocess Runners>` to use\n        :param python_executable:\n            The Python executable used to invoke the build backend\n        \"\"\"\n        if runner is None:\n            runner = default_subprocess_runner\n\n        self.source_dir = abspath(source_dir)\n        self.build_backend = build_backend\n        if backend_path:\n            backend_path = [norm_and_check(self.source_dir, p) for p in backend_path]\n        self.backend_path = backend_path\n        self._subprocess_runner = runner\n        if not python_executable:\n            python_executable = sys.executable\n        self.python_executable = python_executable\n\n    @contextmanager\n    def subprocess_runner(self, runner: \"SubprocessRunner\") -> Iterator[None]:\n        \"\"\"A context manager for temporarily overriding the default\n        :ref:`subprocess runner <Subprocess Runners>`.\n\n        :param runner: The new subprocess runner to use within the context.\n\n        .. code-block:: python\n\n            hook_caller = BuildBackendHookCaller(...)\n            with hook_caller.subprocess_runner(quiet_subprocess_runner):\n                ...\n        \"\"\"\n        prev = self._subprocess_runner\n        self._subprocess_runner = runner\n        try:\n            yield\n        finally:\n            self._subprocess_runner = prev\n\n    def _supported_features(self) -> Sequence[str]:\n        \"\"\"Return the list of optional features supported by the backend.\"\"\"\n        return self._call_hook(\"_supported_features\", {})\n\n    def get_requires_for_build_wheel(\n        self,\n        config_settings: Optional[Mapping[str, Any]] = None,\n    ) -> Sequence[str]:\n        \"\"\"Get additional dependencies required for building a wheel.\n\n        :param config_settings: The configuration settings for the build backend\n        :returns: A list of :pep:`dependency specifiers <508>`.\n\n        .. admonition:: Fallback\n\n            If the build backend does not defined a hook with this name, an\n            empty list will be returned.\n        \"\"\"\n        return self._call_hook(\n            \"get_requires_for_build_wheel\", {\"config_settings\": config_settings}\n        )\n\n    def prepare_metadata_for_build_wheel(\n        self,\n        metadata_directory: str,\n        config_settings: Optional[Mapping[str, Any]] = None,\n        _allow_fallback: bool = True,\n    ) -> str:\n        \"\"\"Prepare a ``*.dist-info`` folder with metadata for this project.\n\n        :param metadata_directory: The directory to write the metadata to\n        :param config_settings: The configuration settings for the build backend\n        :param _allow_fallback:\n            Whether to allow the fallback to building a wheel and extracting\n            the metadata from it. Should be passed as a keyword argument only.\n\n        :returns: Name of the newly created subfolder within\n                  ``metadata_directory``, containing the metadata.\n\n        .. admonition:: Fallback\n\n            If the build backend does not define a hook with this name and\n            ``_allow_fallback`` is truthy, the backend will be asked to build a\n            wheel via the ``build_wheel`` hook and the dist-info extracted from\n            that will be returned.\n        \"\"\"\n        return self._call_hook(\n            \"prepare_metadata_for_build_wheel\",\n            {\n                \"metadata_directory\": abspath(metadata_directory),\n                \"config_settings\": config_settings,\n                \"_allow_fallback\": _allow_fallback,\n            },\n        )\n\n    def build_wheel(\n        self,\n        wheel_directory: str,\n        config_settings: Optional[Mapping[str, Any]] = None,\n        metadata_directory: Optional[str] = None,\n    ) -> str:\n        \"\"\"Build a wheel from this project.\n\n        :param wheel_directory: The directory to write the wheel to\n        :param config_settings: The configuration settings for the build backend\n        :param metadata_directory: The directory to reuse existing metadata from\n        :returns:\n            The name of the newly created wheel within ``wheel_directory``.\n\n        .. admonition:: Interaction with fallback\n\n            If the ``build_wheel`` hook was called in the fallback for\n            :meth:`prepare_metadata_for_build_wheel`, the build backend would\n            not be invoked. Instead, the previously built wheel will be copied\n            to ``wheel_directory`` and the name of that file will be returned.\n        \"\"\"\n        if metadata_directory is not None:\n            metadata_directory = abspath(metadata_directory)\n        return self._call_hook(\n            \"build_wheel\",\n            {\n                \"wheel_directory\": abspath(wheel_directory),\n                \"config_settings\": config_settings,\n                \"metadata_directory\": metadata_directory,\n            },\n        )\n\n    def get_requires_for_build_editable(\n        self,\n        config_settings: Optional[Mapping[str, Any]] = None,\n    ) -> Sequence[str]:\n        \"\"\"Get additional dependencies required for building an editable wheel.\n\n        :param config_settings: The configuration settings for the build backend\n        :returns: A list of :pep:`dependency specifiers <508>`.\n\n        .. admonition:: Fallback\n\n            If the build backend does not defined a hook with this name, an\n            empty list will be returned.\n        \"\"\"\n        return self._call_hook(\n            \"get_requires_for_build_editable\", {\"config_settings\": config_settings}\n        )\n\n    def prepare_metadata_for_build_editable(\n        self,\n        metadata_directory: str,\n        config_settings: Optional[Mapping[str, Any]] = None,\n        _allow_fallback: bool = True,\n    ) -> Optional[str]:\n        \"\"\"Prepare a ``*.dist-info`` folder with metadata for this project.\n\n        :param metadata_directory: The directory to write the metadata to\n        :param config_settings: The configuration settings for the build backend\n        :param _allow_fallback:\n            Whether to allow the fallback to building a wheel and extracting\n            the metadata from it. Should be passed as a keyword argument only.\n        :returns: Name of the newly created subfolder within\n                  ``metadata_directory``, containing the metadata.\n\n        .. admonition:: Fallback\n\n            If the build backend does not define a hook with this name and\n            ``_allow_fallback`` is truthy, the backend will be asked to build a\n            wheel via the ``build_editable`` hook and the dist-info\n            extracted from that will be returned.\n        \"\"\"\n        return self._call_hook(\n            \"prepare_metadata_for_build_editable\",\n            {\n                \"metadata_directory\": abspath(metadata_directory),\n                \"config_settings\": config_settings,\n                \"_allow_fallback\": _allow_fallback,\n            },\n        )\n\n    def build_editable(\n        self,\n        wheel_directory: str,\n        config_settings: Optional[Mapping[str, Any]] = None,\n        metadata_directory: Optional[str] = None,\n    ) -> str:\n        \"\"\"Build an editable wheel from this project.\n\n        :param wheel_directory: The directory to write the wheel to\n        :param config_settings: The configuration settings for the build backend\n        :param metadata_directory: The directory to reuse existing metadata from\n        :returns:\n            The name of the newly created wheel within ``wheel_directory``.\n\n        .. admonition:: Interaction with fallback\n\n            If the ``build_editable`` hook was called in the fallback for\n            :meth:`prepare_metadata_for_build_editable`, the build backend\n            would not be invoked. Instead, the previously built wheel will be\n            copied to ``wheel_directory`` and the name of that file will be\n            returned.\n        \"\"\"\n        if metadata_directory is not None:\n            metadata_directory = abspath(metadata_directory)\n        return self._call_hook(\n            \"build_editable\",\n            {\n                \"wheel_directory\": abspath(wheel_directory),\n                \"config_settings\": config_settings,\n                \"metadata_directory\": metadata_directory,\n            },\n        )\n\n    def get_requires_for_build_sdist(\n        self,\n        config_settings: Optional[Mapping[str, Any]] = None,\n    ) -> Sequence[str]:\n        \"\"\"Get additional dependencies required for building an sdist.\n\n        :returns: A list of :pep:`dependency specifiers <508>`.\n        \"\"\"\n        return self._call_hook(\n            \"get_requires_for_build_sdist\", {\"config_settings\": config_settings}\n        )\n\n    def build_sdist(\n        self,\n        sdist_directory: str,\n        config_settings: Optional[Mapping[str, Any]] = None,\n    ) -> str:\n        \"\"\"Build an sdist from this project.\n\n        :returns:\n            The name of the newly created sdist within ``wheel_directory``.\n        \"\"\"\n        return self._call_hook(\n            \"build_sdist\",\n            {\n                \"sdist_directory\": abspath(sdist_directory),\n                \"config_settings\": config_settings,\n            },\n        )\n\n    def _call_hook(self, hook_name: str, kwargs: Mapping[str, Any]) -> Any:\n        extra_environ = {\"_PYPROJECT_HOOKS_BUILD_BACKEND\": self.build_backend}\n\n        if self.backend_path:\n            backend_path = os.pathsep.join(self.backend_path)\n            extra_environ[\"_PYPROJECT_HOOKS_BACKEND_PATH\"] = backend_path\n\n        with tempfile.TemporaryDirectory() as td:\n            hook_input = {\"kwargs\": kwargs}\n            write_json(hook_input, pjoin(td, \"input.json\"), indent=2)\n\n            # Run the hook in a subprocess\n            with _in_proc_script_path() as script:\n                python = self.python_executable\n                self._subprocess_runner(\n                    [python, abspath(str(script)), hook_name, td],\n                    cwd=self.source_dir,\n                    extra_environ=extra_environ,\n                )\n\n            data = read_json(pjoin(td, \"output.json\"))\n            if data.get(\"unsupported\"):\n                raise UnsupportedOperation(data.get(\"traceback\", \"\"))\n            if data.get(\"no_backend\"):\n                raise BackendUnavailable(\n                    data.get(\"traceback\", \"\"),\n                    message=data.get(\"backend_error\", \"\"),\n                    backend_name=self.build_backend,\n                    backend_path=self.backend_path,\n                )\n            if data.get(\"hook_missing\"):\n                raise HookMissing(data.get(\"missing_hook_name\") or hook_name)\n            return data[\"return_val\"]\n"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/_in_process/__init__.py",
    "content": "\"\"\"This is a subpackage because the directory is on sys.path for _in_process.py\n\nThe subpackage should stay as empty as possible to avoid shadowing modules that\nthe backend might import.\n\"\"\"\n\nimport importlib.resources as resources\n\ntry:\n    resources.files\nexcept AttributeError:\n    # Python 3.8 compatibility\n    def _in_proc_script_path():\n        return resources.path(__package__, \"_in_process.py\")\n\nelse:\n\n    def _in_proc_script_path():\n        return resources.as_file(\n            resources.files(__package__).joinpath(\"_in_process.py\")\n        )\n"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/_in_process/_in_process.py",
    "content": "\"\"\"This is invoked in a subprocess to call the build backend hooks.\n\nIt expects:\n- Command line args: hook_name, control_dir\n- Environment variables:\n      _PYPROJECT_HOOKS_BUILD_BACKEND=entry.point:spec\n      _PYPROJECT_HOOKS_BACKEND_PATH=paths (separated with os.pathsep)\n- control_dir/input.json:\n  - {\"kwargs\": {...}}\n\nResults:\n- control_dir/output.json\n  - {\"return_val\": ...}\n\"\"\"\nimport json\nimport os\nimport os.path\nimport re\nimport shutil\nimport sys\nimport traceback\nfrom glob import glob\nfrom importlib import import_module\nfrom importlib.machinery import PathFinder\nfrom os.path import join as pjoin\n\n# This file is run as a script, and `import wrappers` is not zip-safe, so we\n# include write_json() and read_json() from wrappers.py.\n\n\ndef write_json(obj, path, **kwargs):\n    with open(path, \"w\", encoding=\"utf-8\") as f:\n        json.dump(obj, f, **kwargs)\n\n\ndef read_json(path):\n    with open(path, encoding=\"utf-8\") as f:\n        return json.load(f)\n\n\nclass BackendUnavailable(Exception):\n    \"\"\"Raised if we cannot import the backend\"\"\"\n\n    def __init__(self, message, traceback=None):\n        super().__init__(message)\n        self.message = message\n        self.traceback = traceback\n\n\nclass HookMissing(Exception):\n    \"\"\"Raised if a hook is missing and we are not executing the fallback\"\"\"\n\n    def __init__(self, hook_name=None):\n        super().__init__(hook_name)\n        self.hook_name = hook_name\n\n\ndef _build_backend():\n    \"\"\"Find and load the build backend\"\"\"\n    backend_path = os.environ.get(\"_PYPROJECT_HOOKS_BACKEND_PATH\")\n    ep = os.environ[\"_PYPROJECT_HOOKS_BUILD_BACKEND\"]\n    mod_path, _, obj_path = ep.partition(\":\")\n\n    if backend_path:\n        # Ensure in-tree backend directories have the highest priority when importing.\n        extra_pathitems = backend_path.split(os.pathsep)\n        sys.meta_path.insert(0, _BackendPathFinder(extra_pathitems, mod_path))\n\n    try:\n        obj = import_module(mod_path)\n    except ImportError:\n        msg = f\"Cannot import {mod_path!r}\"\n        raise BackendUnavailable(msg, traceback.format_exc())\n\n    if obj_path:\n        for path_part in obj_path.split(\".\"):\n            obj = getattr(obj, path_part)\n    return obj\n\n\nclass _BackendPathFinder:\n    \"\"\"Implements the MetaPathFinder interface to locate modules in ``backend-path``.\n\n    Since the environment provided by the frontend can contain all sorts of\n    MetaPathFinders, the only way to ensure the backend is loaded from the\n    right place is to prepend our own.\n    \"\"\"\n\n    def __init__(self, backend_path, backend_module):\n        self.backend_path = backend_path\n        self.backend_module = backend_module\n        self.backend_parent, _, _ = backend_module.partition(\".\")\n\n    def find_spec(self, fullname, _path, _target=None):\n        if \".\" in fullname:\n            # Rely on importlib to find nested modules based on parent's path\n            return None\n\n        # Ignore other items in _path or sys.path and use backend_path instead:\n        spec = PathFinder.find_spec(fullname, path=self.backend_path)\n        if spec is None and fullname == self.backend_parent:\n            # According to the spec, the backend MUST be loaded from backend-path.\n            # Therefore, we can halt the import machinery and raise a clean error.\n            msg = f\"Cannot find module {self.backend_module!r} in {self.backend_path!r}\"\n            raise BackendUnavailable(msg)\n\n        return spec\n\n    if sys.version_info >= (3, 8):\n\n        def find_distributions(self, context=None):\n            # Delayed import: Python 3.7 does not contain importlib.metadata\n            from importlib.metadata import DistributionFinder, MetadataPathFinder\n\n            context = DistributionFinder.Context(path=self.backend_path)\n            return MetadataPathFinder.find_distributions(context=context)\n\n\ndef _supported_features():\n    \"\"\"Return the list of options features supported by the backend.\n\n    Returns a list of strings.\n    The only possible value is 'build_editable'.\n    \"\"\"\n    backend = _build_backend()\n    features = []\n    if hasattr(backend, \"build_editable\"):\n        features.append(\"build_editable\")\n    return features\n\n\ndef get_requires_for_build_wheel(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_wheel hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_wheel\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\ndef get_requires_for_build_editable(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_editable hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_editable\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\ndef prepare_metadata_for_build_wheel(\n    metadata_directory, config_settings, _allow_fallback\n):\n    \"\"\"Invoke optional prepare_metadata_for_build_wheel\n\n    Implements a fallback by building a wheel if the hook isn't defined,\n    unless _allow_fallback is False in which case HookMissing is raised.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.prepare_metadata_for_build_wheel\n    except AttributeError:\n        if not _allow_fallback:\n            raise HookMissing()\n    else:\n        return hook(metadata_directory, config_settings)\n    # fallback to build_wheel outside the try block to avoid exception chaining\n    # which can be confusing to users and is not relevant\n    whl_basename = backend.build_wheel(metadata_directory, config_settings)\n    return _get_wheel_metadata_from_wheel(\n        whl_basename, metadata_directory, config_settings\n    )\n\n\ndef prepare_metadata_for_build_editable(\n    metadata_directory, config_settings, _allow_fallback\n):\n    \"\"\"Invoke optional prepare_metadata_for_build_editable\n\n    Implements a fallback by building an editable wheel if the hook isn't\n    defined, unless _allow_fallback is False in which case HookMissing is\n    raised.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.prepare_metadata_for_build_editable\n    except AttributeError:\n        if not _allow_fallback:\n            raise HookMissing()\n        try:\n            build_hook = backend.build_editable\n        except AttributeError:\n            raise HookMissing(hook_name=\"build_editable\")\n        else:\n            whl_basename = build_hook(metadata_directory, config_settings)\n            return _get_wheel_metadata_from_wheel(\n                whl_basename, metadata_directory, config_settings\n            )\n    else:\n        return hook(metadata_directory, config_settings)\n\n\nWHEEL_BUILT_MARKER = \"PYPROJECT_HOOKS_ALREADY_BUILT_WHEEL\"\n\n\ndef _dist_info_files(whl_zip):\n    \"\"\"Identify the .dist-info folder inside a wheel ZipFile.\"\"\"\n    res = []\n    for path in whl_zip.namelist():\n        m = re.match(r\"[^/\\\\]+-[^/\\\\]+\\.dist-info/\", path)\n        if m:\n            res.append(path)\n    if res:\n        return res\n    raise Exception(\"No .dist-info folder found in wheel\")\n\n\ndef _get_wheel_metadata_from_wheel(whl_basename, metadata_directory, config_settings):\n    \"\"\"Extract the metadata from a wheel.\n\n    Fallback for when the build backend does not\n    define the 'get_wheel_metadata' hook.\n    \"\"\"\n    from zipfile import ZipFile\n\n    with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), \"wb\"):\n        pass  # Touch marker file\n\n    whl_file = os.path.join(metadata_directory, whl_basename)\n    with ZipFile(whl_file) as zipf:\n        dist_info = _dist_info_files(zipf)\n        zipf.extractall(path=metadata_directory, members=dist_info)\n    return dist_info[0].split(\"/\")[0]\n\n\ndef _find_already_built_wheel(metadata_directory):\n    \"\"\"Check for a wheel already built during the get_wheel_metadata hook.\"\"\"\n    if not metadata_directory:\n        return None\n    metadata_parent = os.path.dirname(metadata_directory)\n    if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):\n        return None\n\n    whl_files = glob(os.path.join(metadata_parent, \"*.whl\"))\n    if not whl_files:\n        print(\"Found wheel built marker, but no .whl files\")\n        return None\n    if len(whl_files) > 1:\n        print(\n            \"Found multiple .whl files; unspecified behaviour. \"\n            \"Will call build_wheel.\"\n        )\n        return None\n\n    # Exactly one .whl file\n    return whl_files[0]\n\n\ndef build_wheel(wheel_directory, config_settings, metadata_directory=None):\n    \"\"\"Invoke the mandatory build_wheel hook.\n\n    If a wheel was already built in the\n    prepare_metadata_for_build_wheel fallback, this\n    will copy it rather than rebuilding the wheel.\n    \"\"\"\n    prebuilt_whl = _find_already_built_wheel(metadata_directory)\n    if prebuilt_whl:\n        shutil.copy2(prebuilt_whl, wheel_directory)\n        return os.path.basename(prebuilt_whl)\n\n    return _build_backend().build_wheel(\n        wheel_directory, config_settings, metadata_directory\n    )\n\n\ndef build_editable(wheel_directory, config_settings, metadata_directory=None):\n    \"\"\"Invoke the optional build_editable hook.\n\n    If a wheel was already built in the\n    prepare_metadata_for_build_editable fallback, this\n    will copy it rather than rebuilding the wheel.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.build_editable\n    except AttributeError:\n        raise HookMissing()\n    else:\n        prebuilt_whl = _find_already_built_wheel(metadata_directory)\n        if prebuilt_whl:\n            shutil.copy2(prebuilt_whl, wheel_directory)\n            return os.path.basename(prebuilt_whl)\n\n        return hook(wheel_directory, config_settings, metadata_directory)\n\n\ndef get_requires_for_build_sdist(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_wheel hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_sdist\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\nclass _DummyException(Exception):\n    \"\"\"Nothing should ever raise this exception\"\"\"\n\n\nclass GotUnsupportedOperation(Exception):\n    \"\"\"For internal use when backend raises UnsupportedOperation\"\"\"\n\n    def __init__(self, traceback):\n        self.traceback = traceback\n\n\ndef build_sdist(sdist_directory, config_settings):\n    \"\"\"Invoke the mandatory build_sdist hook.\"\"\"\n    backend = _build_backend()\n    try:\n        return backend.build_sdist(sdist_directory, config_settings)\n    except getattr(backend, \"UnsupportedOperation\", _DummyException):\n        raise GotUnsupportedOperation(traceback.format_exc())\n\n\nHOOK_NAMES = {\n    \"get_requires_for_build_wheel\",\n    \"prepare_metadata_for_build_wheel\",\n    \"build_wheel\",\n    \"get_requires_for_build_editable\",\n    \"prepare_metadata_for_build_editable\",\n    \"build_editable\",\n    \"get_requires_for_build_sdist\",\n    \"build_sdist\",\n    \"_supported_features\",\n}\n\n\ndef main():\n    if len(sys.argv) < 3:\n        sys.exit(\"Needs args: hook_name, control_dir\")\n    hook_name = sys.argv[1]\n    control_dir = sys.argv[2]\n    if hook_name not in HOOK_NAMES:\n        sys.exit(\"Unknown hook: %s\" % hook_name)\n\n    # Remove the parent directory from sys.path to avoid polluting the backend\n    # import namespace with this directory.\n    here = os.path.dirname(__file__)\n    if here in sys.path:\n        sys.path.remove(here)\n\n    hook = globals()[hook_name]\n\n    hook_input = read_json(pjoin(control_dir, \"input.json\"))\n\n    json_out = {\"unsupported\": False, \"return_val\": None}\n    try:\n        json_out[\"return_val\"] = hook(**hook_input[\"kwargs\"])\n    except BackendUnavailable as e:\n        json_out[\"no_backend\"] = True\n        json_out[\"traceback\"] = e.traceback\n        json_out[\"backend_error\"] = e.message\n    except GotUnsupportedOperation as e:\n        json_out[\"unsupported\"] = True\n        json_out[\"traceback\"] = e.traceback\n    except HookMissing as e:\n        json_out[\"hook_missing\"] = True\n        json_out[\"missing_hook_name\"] = e.hook_name or hook_name\n\n    write_json(json_out, pjoin(control_dir, \"output.json\"), indent=2)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/pyproject_hooks/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/requests/LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n"
  },
  {
    "path": "src/pip/_vendor/requests/__init__.py",
    "content": "#   __\n#  /__)  _  _     _   _ _/   _\n# / (   (- (/ (/ (- _)  /  _)\n#          /\n\n\"\"\"\nRequests HTTP Library\n~~~~~~~~~~~~~~~~~~~~~\n\nRequests is an HTTP library, written in Python, for human beings.\nBasic GET usage:\n\n   >>> import requests\n   >>> r = requests.get('https://www.python.org')\n   >>> r.status_code\n   200\n   >>> b'Python is a programming language' in r.content\n   True\n\n... or POST:\n\n   >>> payload = dict(key1='value1', key2='value2')\n   >>> r = requests.post('https://httpbin.org/post', data=payload)\n   >>> print(r.text)\n   {\n     ...\n     \"form\": {\n       \"key1\": \"value1\",\n       \"key2\": \"value2\"\n     },\n     ...\n   }\n\nThe other HTTP methods are supported - see `requests.api`. Full documentation\nis at <https://requests.readthedocs.io>.\n\n:copyright: (c) 2017 by Kenneth Reitz.\n:license: Apache 2.0, see LICENSE for more details.\n\"\"\"\n\nimport warnings\n\nfrom pip._vendor import urllib3\n\nfrom .exceptions import RequestsDependencyWarning\n\ncharset_normalizer_version = None\nchardet_version = None\n\n\ndef check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n    urllib3_version = urllib3_version.split(\".\")\n    assert urllib3_version != [\"dev\"]  # Verify urllib3 isn't installed from git.\n\n    # Sometimes, urllib3 only reports its version as 16.1.\n    if len(urllib3_version) == 2:\n        urllib3_version.append(\"0\")\n\n    # Check urllib3 for compatibility.\n    major, minor, patch = urllib3_version  # noqa: F811\n    major, minor, patch = int(major), int(minor), int(patch)\n    # urllib3 >= 1.21.1\n    assert major >= 1\n    if major == 1:\n        assert minor >= 21\n\n    # Check charset_normalizer for compatibility.\n    if chardet_version:\n        major, minor, patch = chardet_version.split(\".\")[:3]\n        major, minor, patch = int(major), int(minor), int(patch)\n        # chardet_version >= 3.0.2, < 6.0.0\n        assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)\n    elif charset_normalizer_version:\n        major, minor, patch = charset_normalizer_version.split(\".\")[:3]\n        major, minor, patch = int(major), int(minor), int(patch)\n        # charset_normalizer >= 2.0.0 < 4.0.0\n        assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)\n    else:\n        # pip does not need or use character detection\n        pass\n\n\ndef _check_cryptography(cryptography_version):\n    # cryptography < 1.3.4\n    try:\n        cryptography_version = list(map(int, cryptography_version.split(\".\")))\n    except ValueError:\n        return\n\n    if cryptography_version < [1, 3, 4]:\n        warning = \"Old version of cryptography ({}) may cause slowdown.\".format(\n            cryptography_version\n        )\n        warnings.warn(warning, RequestsDependencyWarning)\n\n\n# Check imported dependencies for compatibility.\ntry:\n    check_compatibility(\n        urllib3.__version__, chardet_version, charset_normalizer_version\n    )\nexcept (AssertionError, ValueError):\n    warnings.warn(\n        \"urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported \"\n        \"version!\".format(\n            urllib3.__version__, chardet_version, charset_normalizer_version\n        ),\n        RequestsDependencyWarning,\n    )\n\n# Attempt to enable urllib3's fallback for SNI support\n# if the standard library doesn't support SNI or the\n# 'ssl' library isn't available.\ntry:\n    # Note: This logic prevents upgrading cryptography on Windows, if imported\n    #       as part of pip.\n    from pip._internal.utils.compat import WINDOWS\n    if not WINDOWS:\n        raise ImportError(\"pip internals: don't import cryptography on Windows\")\n    try:\n        import ssl\n    except ImportError:\n        ssl = None\n\n    if not getattr(ssl, \"HAS_SNI\", False):\n        from pip._vendor.urllib3.contrib import pyopenssl\n\n        pyopenssl.inject_into_urllib3()\n\n        # Check cryptography version\n        from cryptography import __version__ as cryptography_version\n\n        _check_cryptography(cryptography_version)\nexcept ImportError:\n    pass\n\n# urllib3's DependencyWarnings should be silenced.\nfrom pip._vendor.urllib3.exceptions import DependencyWarning\n\nwarnings.simplefilter(\"ignore\", DependencyWarning)\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\nfrom logging import NullHandler\n\nfrom . import packages, utils\nfrom .__version__ import (\n    __author__,\n    __author_email__,\n    __build__,\n    __cake__,\n    __copyright__,\n    __description__,\n    __license__,\n    __title__,\n    __url__,\n    __version__,\n)\nfrom .api import delete, get, head, options, patch, post, put, request\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    FileModeWarning,\n    HTTPError,\n    JSONDecodeError,\n    ReadTimeout,\n    RequestException,\n    Timeout,\n    TooManyRedirects,\n    URLRequired,\n)\nfrom .models import PreparedRequest, Request, Response\nfrom .sessions import Session, session\nfrom .status_codes import codes\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n\n# FileModeWarnings go off per the default.\nwarnings.simplefilter(\"default\", FileModeWarning, append=True)\n"
  },
  {
    "path": "src/pip/_vendor/requests/__version__.py",
    "content": "# .-. .-. .-. . . .-. .-. .-. .-.\n# |(  |-  |.| | | |-  `-.  |  `-.\n# ' ' `-' `-`.`-' `-' `-'  '  `-'\n\n__title__ = \"requests\"\n__description__ = \"Python HTTP for Humans.\"\n__url__ = \"https://requests.readthedocs.io\"\n__version__ = \"2.32.5\"\n__build__ = 0x023205\n__author__ = \"Kenneth Reitz\"\n__author_email__ = \"me@kennethreitz.org\"\n__license__ = \"Apache-2.0\"\n__copyright__ = \"Copyright Kenneth Reitz\"\n__cake__ = \"\\u2728 \\U0001f370 \\u2728\"\n"
  },
  {
    "path": "src/pip/_vendor/requests/_internal_utils.py",
    "content": "\"\"\"\nrequests._internal_utils\n~~~~~~~~~~~~~~\n\nProvides utility functions that are consumed internally by Requests\nwhich depend on extremely few external helpers (such as compat)\n\"\"\"\nimport re\n\nfrom .compat import builtin_str\n\n_VALID_HEADER_NAME_RE_BYTE = re.compile(rb\"^[^:\\s][^:\\r\\n]*$\")\n_VALID_HEADER_NAME_RE_STR = re.compile(r\"^[^:\\s][^:\\r\\n]*$\")\n_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb\"^\\S[^\\r\\n]*$|^$\")\n_VALID_HEADER_VALUE_RE_STR = re.compile(r\"^\\S[^\\r\\n]*$|^$\")\n\n_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)\n_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)\nHEADER_VALIDATORS = {\n    bytes: _HEADER_VALIDATORS_BYTE,\n    str: _HEADER_VALIDATORS_STR,\n}\n\n\ndef to_native_string(string, encoding=\"ascii\"):\n    \"\"\"Given a string object, regardless of type, returns a representation of\n    that string in the native string type, encoding and decoding where\n    necessary. This assumes ASCII unless told otherwise.\n    \"\"\"\n    if isinstance(string, builtin_str):\n        out = string\n    else:\n        out = string.decode(encoding)\n\n    return out\n\n\ndef unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode(\"ascii\")\n        return True\n    except UnicodeEncodeError:\n        return False\n"
  },
  {
    "path": "src/pip/_vendor/requests/adapters.py",
    "content": "\"\"\"\nrequests.adapters\n~~~~~~~~~~~~~~~~~\n\nThis module contains the transport adapters that Requests uses to define\nand maintain connections.\n\"\"\"\n\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\n\nfrom pip._vendor.urllib3.exceptions import ClosedPoolError, ConnectTimeoutError\nfrom pip._vendor.urllib3.exceptions import HTTPError as _HTTPError\nfrom pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom pip._vendor.urllib3.exceptions import (\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n)\nfrom pip._vendor.urllib3.exceptions import ProxyError as _ProxyError\nfrom pip._vendor.urllib3.exceptions import ReadTimeoutError, ResponseError\nfrom pip._vendor.urllib3.exceptions import SSLError as _SSLError\nfrom pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url\nfrom pip._vendor.urllib3.util import Timeout as TimeoutSauce\nfrom pip._vendor.urllib3.util import parse_url\nfrom pip._vendor.urllib3.util.retry import Retry\n\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    extract_zipped_paths,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\n\ntry:\n    from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager\nexcept ImportError:\n\n    def SOCKSProxyManager(*args, **kwargs):\n        raise InvalidSchema(\"Missing dependencies for SOCKS support.\")\n\n\nif typing.TYPE_CHECKING:\n    from .models import PreparedRequest\n\n\nDEFAULT_POOLBLOCK = False\nDEFAULT_POOLSIZE = 10\nDEFAULT_RETRIES = 0\nDEFAULT_POOL_TIMEOUT = None\n\n\ndef _urllib3_request_context(\n    request: \"PreparedRequest\",\n    verify: \"bool | str | None\",\n    client_cert: \"typing.Tuple[str, str] | str | None\",\n    poolmanager: \"PoolManager\",\n) -> \"(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])\":\n    host_params = {}\n    pool_kwargs = {}\n    parsed_request_url = urlparse(request.url)\n    scheme = parsed_request_url.scheme.lower()\n    port = parsed_request_url.port\n\n    cert_reqs = \"CERT_REQUIRED\"\n    if verify is False:\n        cert_reqs = \"CERT_NONE\"\n    elif isinstance(verify, str):\n        if not os.path.isdir(verify):\n            pool_kwargs[\"ca_certs\"] = verify\n        else:\n            pool_kwargs[\"ca_cert_dir\"] = verify\n    pool_kwargs[\"cert_reqs\"] = cert_reqs\n    if client_cert is not None:\n        if isinstance(client_cert, tuple) and len(client_cert) == 2:\n            pool_kwargs[\"cert_file\"] = client_cert[0]\n            pool_kwargs[\"key_file\"] = client_cert[1]\n        else:\n            # According to our docs, we allow users to specify just the client\n            # cert path\n            pool_kwargs[\"cert_file\"] = client_cert\n    host_params = {\n        \"scheme\": scheme,\n        \"host\": parsed_request_url.hostname,\n        \"port\": port,\n    }\n    return host_params, pool_kwargs\n\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self):\n        super().__init__()\n\n    def send(\n        self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n    ):\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self):\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__ = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    def __init__(\n        self,\n        pool_connections=DEFAULT_POOLSIZE,\n        pool_maxsize=DEFAULT_POOLSIZE,\n        max_retries=DEFAULT_RETRIES,\n        pool_block=DEFAULT_POOLBLOCK,\n    ):\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self):\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state):\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs\n    ):\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy, **proxy_kwargs):\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(self, conn, url, verify, cert):\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req, resp):\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(self, request, verify, cert=None):\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedReqest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.ConnectionPool\n        \"\"\"\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(self, url, proxies=None):\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.ConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self):\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(self, request, proxies):\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n        if url.startswith(\"//\"):  # Don't confuse urllib3\n            url = f\"/{url.lstrip('/')}\"\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request, **kwargs):\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy):\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n    ):\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            pass\n        else:\n            timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,\n                headers=request.headers,\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n"
  },
  {
    "path": "src/pip/_vendor/requests/api.py",
    "content": "\"\"\"\nrequests.api\n~~~~~~~~~~~~\n\nThis module implements the Requests API.\n\n:copyright: (c) 2012 by Kenneth Reitz.\n:license: Apache2, see LICENSE for more details.\n\"\"\"\n\nfrom . import sessions\n\n\ndef request(method, url, **kwargs):\n    \"\"\"Constructs and sends a :class:`Request <Request>`.\n\n    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.\n    :param url: URL for the new :class:`Request` object.\n    :param params: (optional) Dictionary, list of tuples or bytes to send\n        in the query string for the :class:`Request`.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.\n    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.\n    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.\n        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``\n        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string\n        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers\n        to add for the file.\n    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.\n    :param timeout: (optional) How many seconds to wait for the server to send data\n        before giving up, as a float, or a :ref:`(connect timeout, read\n        timeout) <timeouts>` tuple.\n    :type timeout: float or tuple\n    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.\n    :type allow_redirects: bool\n    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.\n    :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``.\n    :param stream: (optional) if ``False``, the response content will be immediately downloaded.\n    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.request('GET', 'https://httpbin.org/get')\n      >>> req\n      <Response [200]>\n    \"\"\"\n\n    # By using the 'with' statement we are sure the session is closed, thus we\n    # avoid leaving sockets open which can trigger a ResourceWarning in some\n    # cases, and look like a memory leak in others.\n    with sessions.Session() as session:\n        return session.request(method=method, url=url, **kwargs)\n\n\ndef get(url, params=None, **kwargs):\n    r\"\"\"Sends a GET request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param params: (optional) Dictionary, list of tuples or bytes to send\n        in the query string for the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"get\", url, params=params, **kwargs)\n\n\ndef options(url, **kwargs):\n    r\"\"\"Sends an OPTIONS request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"options\", url, **kwargs)\n\n\ndef head(url, **kwargs):\n    r\"\"\"Sends a HEAD request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n        `allow_redirects` is not provided, it will be set to `False` (as\n        opposed to the default :meth:`request` behavior).\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    kwargs.setdefault(\"allow_redirects\", False)\n    return request(\"head\", url, **kwargs)\n\n\ndef post(url, data=None, json=None, **kwargs):\n    r\"\"\"Sends a POST request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"post\", url, data=data, json=json, **kwargs)\n\n\ndef put(url, data=None, **kwargs):\n    r\"\"\"Sends a PUT request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"put\", url, data=data, **kwargs)\n\n\ndef patch(url, data=None, **kwargs):\n    r\"\"\"Sends a PATCH request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"patch\", url, data=data, **kwargs)\n\n\ndef delete(url, **kwargs):\n    r\"\"\"Sends a DELETE request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"delete\", url, **kwargs)\n"
  },
  {
    "path": "src/pip/_vendor/requests/auth.py",
    "content": "\"\"\"\nrequests.auth\n~~~~~~~~~~~~~\n\nThis module contains the authentication handlers for Requests.\n\"\"\"\n\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\n\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nCONTENT_TYPE_FORM_URLENCODED = \"application/x-www-form-urlencoded\"\nCONTENT_TYPE_MULTI_PART = \"multipart/form-data\"\n\n\ndef _basic_auth_str(username, password):\n    \"\"\"Returns a Basic Auth string.\"\"\"\n\n    # \"I want us to put a big-ol' comment on top of it that\n    # says that this behaviour is dumb but we need to preserve\n    # it because people are relying on it.\"\n    #    - Lukasa\n    #\n    # These are here solely to maintain backwards compatibility\n    # for things like ints. This will be removed in 3.0.0.\n    if not isinstance(username, basestring):\n        warnings.warn(\n            \"Non-string usernames will no longer be supported in Requests \"\n            \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n            \"a string or bytes object in the near future to avoid \"\n            \"problems.\".format(username),\n            category=DeprecationWarning,\n        )\n        username = str(username)\n\n    if not isinstance(password, basestring):\n        warnings.warn(\n            \"Non-string passwords will no longer be supported in Requests \"\n            \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n            \"a string or bytes object in the near future to avoid \"\n            \"problems.\".format(type(password)),\n            category=DeprecationWarning,\n        )\n        password = str(password)\n    # -- End Removal --\n\n    if isinstance(username, str):\n        username = username.encode(\"latin1\")\n\n    if isinstance(password, str):\n        password = password.encode(\"latin1\")\n\n    authstr = \"Basic \" + to_native_string(\n        b64encode(b\":\".join((username, password))).strip()\n    )\n\n    return authstr\n\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r):\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    def __init__(self, username, password):\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other):\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __call__(self, r):\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r):\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    def __init__(self, username, password):\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self):\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method, url):\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        KD = lambda s, d: hash_utf8(f\"{s}:{d}\")  # noqa:E731\n\n        if hash_utf8 is None:\n            return None\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r, **kwargs):\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r, **kwargs):\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            r.request.body.seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            extract_cookies_to_jar(prep._cookies, r.request, r.raw)\n            prep.prepare_cookies(prep._cookies)\n\n            prep.headers[\"Authorization\"] = self.build_digest_header(\n                prep.method, prep.url\n            )\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r):\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            r.headers[\"Authorization\"] = self.build_digest_header(r.method, r.url)\n        try:\n            self._thread_local.pos = r.body.tell()\n        except AttributeError:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other):\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other):\n        return not self == other\n"
  },
  {
    "path": "src/pip/_vendor/requests/certs.py",
    "content": "#!/usr/bin/env python\n\n\"\"\"\nrequests.certs\n~~~~~~~~~~~~~~\n\nThis module returns the preferred default CA certificate bundle. There is\nonly one — the one from the certifi package.\n\nIf you are packaging Requests, e.g., for a Linux distribution or a managed\nenvironment, you can change the definition of where() to return a separately\npackaged CA bundle.\n\"\"\"\nfrom pip._vendor.certifi import where\n\nif __name__ == \"__main__\":\n    print(where())\n"
  },
  {
    "path": "src/pip/_vendor/requests/compat.py",
    "content": "\"\"\"\nrequests.compat\n~~~~~~~~~~~~~~~\n\nThis module previously handled import compatibility issues\nbetween Python 2 and Python 3. It remains for backwards\ncompatibility until the next major version.\n\"\"\"\n\nimport sys\n\n# -------\n# urllib3\n# -------\nfrom pip._vendor.urllib3 import __version__ as urllib3_version\n\n# Detect which major version of urllib3 is being used.\ntry:\n    is_urllib3_1 = int(urllib3_version.split(\".\")[0]) == 1\nexcept (TypeError, AttributeError):\n    # If we can't discern a version, prefer old functionality.\n    is_urllib3_1 = True\n\n# -------------------\n# Character Detection\n# -------------------\n\n\ndef _resolve_char_detection():\n    \"\"\"Find supported character detection libraries.\"\"\"\n    chardet = None\n    return chardet\n\n\nchardet = _resolve_char_detection()\n\n# -------\n# Pythons\n# -------\n\n# Syntax sugar.\n_ver = sys.version_info\n\n#: Python 2.x?\nis_py2 = _ver[0] == 2\n\n#: Python 3.x?\nis_py3 = _ver[0] == 3\n\n# Note: We've patched out simplejson support in pip because it prevents\n#       upgrading simplejson on Windows.\nimport json\nfrom json import JSONDecodeError\n\n# Keep OrderedDict for backwards compatibility.\nfrom collections import OrderedDict\nfrom collections.abc import Callable, Mapping, MutableMapping\nfrom http import cookiejar as cookielib\nfrom http.cookies import Morsel\nfrom io import StringIO\n\n# --------------\n# Legacy Imports\n# --------------\nfrom urllib.parse import (\n    quote,\n    quote_plus,\n    unquote,\n    unquote_plus,\n    urldefrag,\n    urlencode,\n    urljoin,\n    urlparse,\n    urlsplit,\n    urlunparse,\n)\nfrom urllib.request import (\n    getproxies,\n    getproxies_environment,\n    parse_http_list,\n    proxy_bypass,\n    proxy_bypass_environment,\n)\n\nbuiltin_str = str\nstr = str\nbytes = bytes\nbasestring = (str, bytes)\nnumeric_types = (int, float)\ninteger_types = (int,)\n"
  },
  {
    "path": "src/pip/_vendor/requests/cookies.py",
    "content": "\"\"\"\nrequests.cookies\n~~~~~~~~~~~~~~~~\n\nCompatibility code to be able to use `http.cookiejar.CookieJar` with requests.\n\nrequests.utils imports from here, so be careful with imports.\n\"\"\"\n\nimport calendar\nimport copy\nimport time\n\nfrom ._internal_utils import to_native_string\nfrom .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse\n\ntry:\n    import threading\nexcept ImportError:\n    import dummy_threading as threading\n\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.Request` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    def __init__(self, request):\n        self._r = request\n        self._new_headers = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self):\n        return self.type\n\n    def get_host(self):\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self):\n        return self.get_host()\n\n    def get_full_url(self):\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self):\n        return True\n\n    def has_header(self, name):\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name, default=None):\n        return self._r.headers.get(name, self._new_headers.get(name, default))\n\n    def add_header(self, key, val):\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name, value):\n        self._new_headers[name] = value\n\n    def get_new_headers(self):\n        return self._new_headers\n\n    @property\n    def unverifiable(self):\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self):\n        return self.get_origin_req_host()\n\n    @property\n    def host(self):\n        return self.get_host()\n\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers):\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self):\n        return self._headers\n\n    def getheaders(self, name):\n        self._headers.getheaders(name)\n\n\ndef extract_cookies_to_jar(jar, request, response):\n    \"\"\"Extract the cookies from the response into a CookieJar.\n\n    :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)\n    :param request: our own requests.Request object\n    :param response: urllib3.HTTPResponse object\n    \"\"\"\n    if not (hasattr(response, \"_original_response\") and response._original_response):\n        return\n    # the _original_response field is the wrapped httplib.HTTPResponse object,\n    req = MockRequest(request)\n    # pull out the HTTPMessage with the headers and put it in the mock:\n    res = MockResponse(response._original_response.msg)\n    jar.extract_cookies(res, req)\n\n\ndef get_cookie_header(jar, request):\n    \"\"\"\n    Produce an appropriate Cookie header string to be sent with `request`, or None.\n\n    :rtype: str\n    \"\"\"\n    r = MockRequest(request)\n    jar.add_cookie_header(r)\n    return r.get_new_headers().get(\"Cookie\")\n\n\ndef remove_cookie_by_name(cookiejar, name, domain=None, path=None):\n    \"\"\"Unsets a cookie by name, by default over all domains and paths.\n\n    Wraps CookieJar.clear(), is O(n).\n    \"\"\"\n    clearables = []\n    for cookie in cookiejar:\n        if cookie.name != name:\n            continue\n        if domain is not None and domain != cookie.domain:\n            continue\n        if path is not None and path != cookie.path:\n            continue\n        clearables.append((cookie.domain, cookie.path, cookie.name))\n\n    for domain, path, name in clearables:\n        cookiejar.clear(domain, path, name)\n\n\nclass CookieConflictError(RuntimeError):\n    \"\"\"There are two cookies that meet the criteria specified in the cookie jar.\n    Use .get and .set and include domain and path args in order to be more specific.\n    \"\"\"\n\n\nclass RequestsCookieJar(cookielib.CookieJar, MutableMapping):\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    def get(self, name, default=None, domain=None, path=None):\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(self, name, value, **kwargs):\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self):\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self):\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self):\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self):\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self):\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self):\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self):\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self):\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self):\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(self, domain=None, path=None):\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __contains__(self, name):\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name):\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(self, name, value):\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name):\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie, *args, **kwargs):\n        if (\n            hasattr(cookie.value, \"startswith\")\n            and cookie.value.startswith('\"')\n            and cookie.value.endswith('\"')\n        ):\n            cookie.value = cookie.value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(self, other):\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(self, name, domain=None, path=None):\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(self, name, domain=None, path=None):\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self):\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state):\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self):\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self):\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n\n\ndef _copy_cookie_jar(jar):\n    if jar is None:\n        return None\n\n    if hasattr(jar, \"copy\"):\n        # We're dealing with an instance of RequestsCookieJar\n        return jar.copy()\n    # We're dealing with a generic CookieJar instance\n    new_jar = copy.copy(jar)\n    new_jar.clear()\n    for cookie in jar:\n        new_jar.set_cookie(copy.copy(cookie))\n    return new_jar\n\n\ndef create_cookie(name, value, **kwargs):\n    \"\"\"Make a cookie from underspecified parameters.\n\n    By default, the pair of `name` and `value` will be set for the domain ''\n    and sent on every request (this is sometimes called a \"supercookie\").\n    \"\"\"\n    result = {\n        \"version\": 0,\n        \"name\": name,\n        \"value\": value,\n        \"port\": None,\n        \"domain\": \"\",\n        \"path\": \"/\",\n        \"secure\": False,\n        \"expires\": None,\n        \"discard\": True,\n        \"comment\": None,\n        \"comment_url\": None,\n        \"rest\": {\"HttpOnly\": None},\n        \"rfc2109\": False,\n    }\n\n    badargs = set(kwargs) - set(result)\n    if badargs:\n        raise TypeError(\n            f\"create_cookie() got unexpected keyword arguments: {list(badargs)}\"\n        )\n\n    result.update(kwargs)\n    result[\"port_specified\"] = bool(result[\"port\"])\n    result[\"domain_specified\"] = bool(result[\"domain\"])\n    result[\"domain_initial_dot\"] = result[\"domain\"].startswith(\".\")\n    result[\"path_specified\"] = bool(result[\"path\"])\n\n    return cookielib.Cookie(**result)\n\n\ndef morsel_to_cookie(morsel):\n    \"\"\"Convert a Morsel object into a Cookie containing the one k/v pair.\"\"\"\n\n    expires = None\n    if morsel[\"max-age\"]:\n        try:\n            expires = int(time.time() + int(morsel[\"max-age\"]))\n        except ValueError:\n            raise TypeError(f\"max-age: {morsel['max-age']} must be integer\")\n    elif morsel[\"expires\"]:\n        time_template = \"%a, %d-%b-%Y %H:%M:%S GMT\"\n        expires = calendar.timegm(time.strptime(morsel[\"expires\"], time_template))\n    return create_cookie(\n        comment=morsel[\"comment\"],\n        comment_url=bool(morsel[\"comment\"]),\n        discard=False,\n        domain=morsel[\"domain\"],\n        expires=expires,\n        name=morsel.key,\n        path=morsel[\"path\"],\n        port=None,\n        rest={\"HttpOnly\": morsel[\"httponly\"]},\n        rfc2109=False,\n        secure=bool(morsel[\"secure\"]),\n        value=morsel.value,\n        version=morsel[\"version\"] or 0,\n    )\n\n\ndef cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):\n    \"\"\"Returns a CookieJar from a key/value dictionary.\n\n    :param cookie_dict: Dict of key/values to insert into CookieJar.\n    :param cookiejar: (optional) A cookiejar to add the cookies to.\n    :param overwrite: (optional) If False, will not replace cookies\n        already in the jar with new ones.\n    :rtype: CookieJar\n    \"\"\"\n    if cookiejar is None:\n        cookiejar = RequestsCookieJar()\n\n    if cookie_dict is not None:\n        names_from_jar = [cookie.name for cookie in cookiejar]\n        for name in cookie_dict:\n            if overwrite or (name not in names_from_jar):\n                cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))\n\n    return cookiejar\n\n\ndef merge_cookies(cookiejar, cookies):\n    \"\"\"Add cookies to cookiejar and returns a merged CookieJar.\n\n    :param cookiejar: CookieJar object to add the cookies to.\n    :param cookies: Dictionary or CookieJar object to be added.\n    :rtype: CookieJar\n    \"\"\"\n    if not isinstance(cookiejar, cookielib.CookieJar):\n        raise ValueError(\"You can only merge into CookieJar\")\n\n    if isinstance(cookies, dict):\n        cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)\n    elif isinstance(cookies, cookielib.CookieJar):\n        try:\n            cookiejar.update(cookies)\n        except AttributeError:\n            for cookie_in_jar in cookies:\n                cookiejar.set_cookie(cookie_in_jar)\n\n    return cookiejar\n"
  },
  {
    "path": "src/pip/_vendor/requests/exceptions.py",
    "content": "\"\"\"\nrequests.exceptions\n~~~~~~~~~~~~~~~~~~~\n\nThis module contains the set of Requests' exceptions.\n\"\"\"\nfrom pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError\n\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = self.response.request\n        super().__init__(*args, **kwargs)\n\n\nclass InvalidJSONError(RequestException):\n    \"\"\"A JSON error occurred.\"\"\"\n\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self):\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n\n\nclass ConnectionError(RequestException):\n    \"\"\"A Connection error occurred.\"\"\"\n\n\nclass ProxyError(ConnectionError):\n    \"\"\"A proxy error occurred.\"\"\"\n\n\nclass SSLError(ConnectionError):\n    \"\"\"An SSL error occurred.\"\"\"\n\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n\n\nclass ReadTimeout(Timeout):\n    \"\"\"The server did not send any data in the allotted amount of time.\"\"\"\n\n\nclass URLRequired(RequestException):\n    \"\"\"A valid URL is required to make a request.\"\"\"\n\n\nclass TooManyRedirects(RequestException):\n    \"\"\"Too many redirects.\"\"\"\n\n\nclass MissingSchema(RequestException, ValueError):\n    \"\"\"The URL scheme (e.g. http or https) is missing.\"\"\"\n\n\nclass InvalidSchema(RequestException, ValueError):\n    \"\"\"The URL scheme provided is either invalid or unsupported.\"\"\"\n\n\nclass InvalidURL(RequestException, ValueError):\n    \"\"\"The URL provided was somehow invalid.\"\"\"\n\n\nclass InvalidHeader(RequestException, ValueError):\n    \"\"\"The header value provided was somehow invalid.\"\"\"\n\n\nclass InvalidProxyURL(InvalidURL):\n    \"\"\"The proxy URL provided is invalid.\"\"\"\n\n\nclass ChunkedEncodingError(RequestException):\n    \"\"\"The server declared chunked encoding but sent an invalid chunk.\"\"\"\n\n\nclass ContentDecodingError(RequestException, BaseHTTPError):\n    \"\"\"Failed to decode response content.\"\"\"\n\n\nclass StreamConsumedError(RequestException, TypeError):\n    \"\"\"The content for this response was already consumed.\"\"\"\n\n\nclass RetryError(RequestException):\n    \"\"\"Custom retries logic failed\"\"\"\n\n\nclass UnrewindableBodyError(RequestException):\n    \"\"\"Requests encountered an error when trying to rewind a body.\"\"\"\n\n\n# Warnings\n\n\nclass RequestsWarning(Warning):\n    \"\"\"Base warning for Requests.\"\"\"\n\n\nclass FileModeWarning(RequestsWarning, DeprecationWarning):\n    \"\"\"A file was opened in text mode, but Requests determined its binary length.\"\"\"\n\n\nclass RequestsDependencyWarning(RequestsWarning):\n    \"\"\"An imported dependency doesn't match the expected version range.\"\"\"\n"
  },
  {
    "path": "src/pip/_vendor/requests/help.py",
    "content": "\"\"\"Module containing bug report helper(s).\"\"\"\n\nimport json\nimport platform\nimport ssl\nimport sys\n\nfrom pip._vendor import idna\nfrom pip._vendor import urllib3\n\nfrom . import __version__ as requests_version\n\ncharset_normalizer = None\nchardet = None\n\ntry:\n    from pip._vendor.urllib3.contrib import pyopenssl\nexcept ImportError:\n    pyopenssl = None\n    OpenSSL = None\n    cryptography = None\nelse:\n    import cryptography\n    import OpenSSL\n\n\ndef _implementation():\n    \"\"\"Return a dict with the Python implementation and version.\n\n    Provide both the name and the version of the Python implementation\n    currently running. For example, on CPython 3.10.3 it will return\n    {'name': 'CPython', 'version': '3.10.3'}.\n\n    This function works best on CPython and PyPy: in particular, it probably\n    doesn't work for Jython or IronPython. Future investigation should be done\n    to work out the correct shape of the code for those platforms.\n    \"\"\"\n    implementation = platform.python_implementation()\n\n    if implementation == \"CPython\":\n        implementation_version = platform.python_version()\n    elif implementation == \"PyPy\":\n        implementation_version = \"{}.{}.{}\".format(\n            sys.pypy_version_info.major,\n            sys.pypy_version_info.minor,\n            sys.pypy_version_info.micro,\n        )\n        if sys.pypy_version_info.releaselevel != \"final\":\n            implementation_version = \"\".join(\n                [implementation_version, sys.pypy_version_info.releaselevel]\n            )\n    elif implementation == \"Jython\":\n        implementation_version = platform.python_version()  # Complete Guess\n    elif implementation == \"IronPython\":\n        implementation_version = platform.python_version()  # Complete Guess\n    else:\n        implementation_version = \"Unknown\"\n\n    return {\"name\": implementation, \"version\": implementation_version}\n\n\ndef info():\n    \"\"\"Generate information for a bug report.\"\"\"\n    try:\n        platform_info = {\n            \"system\": platform.system(),\n            \"release\": platform.release(),\n        }\n    except OSError:\n        platform_info = {\n            \"system\": \"Unknown\",\n            \"release\": \"Unknown\",\n        }\n\n    implementation_info = _implementation()\n    urllib3_info = {\"version\": urllib3.__version__}\n    charset_normalizer_info = {\"version\": None}\n    chardet_info = {\"version\": None}\n    if charset_normalizer:\n        charset_normalizer_info = {\"version\": charset_normalizer.__version__}\n    if chardet:\n        chardet_info = {\"version\": chardet.__version__}\n\n    pyopenssl_info = {\n        \"version\": None,\n        \"openssl_version\": \"\",\n    }\n    if OpenSSL:\n        pyopenssl_info = {\n            \"version\": OpenSSL.__version__,\n            \"openssl_version\": f\"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}\",\n        }\n    cryptography_info = {\n        \"version\": getattr(cryptography, \"__version__\", \"\"),\n    }\n    idna_info = {\n        \"version\": getattr(idna, \"__version__\", \"\"),\n    }\n\n    system_ssl = ssl.OPENSSL_VERSION_NUMBER\n    system_ssl_info = {\"version\": f\"{system_ssl:x}\" if system_ssl is not None else \"\"}\n\n    return {\n        \"platform\": platform_info,\n        \"implementation\": implementation_info,\n        \"system_ssl\": system_ssl_info,\n        \"using_pyopenssl\": pyopenssl is not None,\n        \"using_charset_normalizer\": chardet is None,\n        \"pyOpenSSL\": pyopenssl_info,\n        \"urllib3\": urllib3_info,\n        \"chardet\": chardet_info,\n        \"charset_normalizer\": charset_normalizer_info,\n        \"cryptography\": cryptography_info,\n        \"idna\": idna_info,\n        \"requests\": {\n            \"version\": requests_version,\n        },\n    }\n\n\ndef main():\n    \"\"\"Pretty-print the bug information as JSON.\"\"\"\n    print(json.dumps(info(), sort_keys=True, indent=2))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/pip/_vendor/requests/hooks.py",
    "content": "\"\"\"\nrequests.hooks\n~~~~~~~~~~~~~~\n\nThis module provides the capabilities for the Requests hooks system.\n\nAvailable hooks:\n\n``response``:\n    The response generated from a Request.\n\"\"\"\nHOOKS = [\"response\"]\n\n\ndef default_hooks():\n    return {event: [] for event in HOOKS}\n\n\n# TODO: response is the only one\n\n\ndef dispatch_hook(key, hooks, hook_data, **kwargs):\n    \"\"\"Dispatches a hook dictionary on a given piece of data.\"\"\"\n    hooks = hooks or {}\n    hooks = hooks.get(key)\n    if hooks:\n        if hasattr(hooks, \"__call__\"):\n            hooks = [hooks]\n        for hook in hooks:\n            _hook_data = hook(hook_data, **kwargs)\n            if _hook_data is not None:\n                hook_data = _hook_data\n    return hook_data\n"
  },
  {
    "path": "src/pip/_vendor/requests/models.py",
    "content": "\"\"\"\nrequests.models\n~~~~~~~~~~~~~~~\n\nThis module contains the primary objects that power Requests.\n\"\"\"\n\nimport datetime\n\n# Import encoding now, to avoid implicit import later.\n# Implicit import within threads may cause LookupError when standard library is in a ZIP,\n# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.\nimport encodings.idna  # noqa: F401\nfrom io import UnsupportedOperation\n\nfrom pip._vendor.urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom pip._vendor.urllib3.fields import RequestField\nfrom pip._vendor.urllib3.filepost import encode_multipart_formdata\nfrom pip._vendor.urllib3.util import parse_url\n\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    Callable,\n    JSONDecodeError,\n    Mapping,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n)\nfrom .compat import json as complexjson\nfrom .compat import urlencode, urlsplit, urlunparse\nfrom .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import MissingSchema\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .exceptions import StreamConsumedError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\n#: The set of HTTP status codes that indicate an automatically\n#: processable redirect.\nREDIRECT_STATI = (\n    codes.moved,  # 301\n    codes.found,  # 302\n    codes.other,  # 303\n    codes.temporary_redirect,  # 307\n    codes.permanent_redirect,  # 308\n)\n\nDEFAULT_REDIRECT_LIMIT = 30\nCONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n    @property\n    def path_url(self):\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url = []\n\n        p = urlsplit(self.url)\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @staticmethod\n    def _encode_params(data):\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif hasattr(data, \"read\"):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data\n\n    @staticmethod\n    def _encode_files(files, data):\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif hasattr(fp, \"read\"):\n                fdata = fp.read()\n            elif fp is None:\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n\n\nclass RequestHooksMixin:\n    def register_hook(self, event, hook):\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(h for h in hook if isinstance(h, Callable))\n\n    def deregister_hook(self, event, hook):\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    def __init__(\n        self,\n        method=None,\n        url=None,\n        headers=None,\n        files=None,\n        data=None,\n        params=None,\n        auth=None,\n        cookies=None,\n        hooks=None,\n        json=None,\n    ):\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self):\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self):\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    def __init__(self):\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method=None,\n        url=None,\n        headers=None,\n        files=None,\n        data=None,\n        params=None,\n        auth=None,\n        cookies=None,\n        hooks=None,\n        json=None,\n    ):\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self):\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self):\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method):\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host):\n        from pip._vendor import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(self, url, params):\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        enc_params = self._encode_params(params)\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))\n        self.url = url\n\n    def prepare_headers(self, headers):\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(self, data, files, json=None):\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        is_stream = all(\n            [\n                hasattr(data, \"__iter__\"),\n                not isinstance(data, (basestring, list, tuple, Mapping)),\n            ]\n        )\n\n        if is_stream:\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, data)\n            else:\n                if data:\n                    body = self._encode_params(data)\n                    if isinstance(data, basestring) or hasattr(data, \"read\"):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body\n\n    def prepare_content_length(self, body):\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(self, auth, url=\"\"):\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(self.url)\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:\n                # special-case basic HTTP auth\n                auth = HTTPBasicAuth(*auth)\n\n            # Allow auth to make its changes.\n            r = auth(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(self, cookies):\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookie_header = get_cookie_header(self._cookies, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks):\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or []\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    __attrs__ = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self):\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def __getstate__(self):\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state):\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self):\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self):\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self):\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self):\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self):\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self):\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    def iter_content(self, chunk_size=1, decode_unicode=False):\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using the best\n        available encoding based on the response.\n        \"\"\"\n\n        def generate():\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(chunk_size, int):\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n        # simulate reading small chunks of the content\n        reused_chunks = iter_slices(self._content, chunk_size)\n\n        stream_chunks = generate()\n\n        chunks = reused_chunks if self._content_consumed else stream_chunks\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    def iter_lines(\n        self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None\n    ):\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                chunk = pending + chunk\n\n            if delimiter:\n                lines = chunk.split(delimiter)\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self):\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content\n\n    @property\n    def text(self):\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding, errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs):\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self):\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self):\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self):\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n"
  },
  {
    "path": "src/pip/_vendor/requests/packages.py",
    "content": "import sys\n\nfrom .compat import chardet\n\n# This code exists for backwards compatibility reasons.\n# I don't like it either. Just look the other way. :)\n\nfor package in (\"urllib3\", \"idna\"):\n    vendored_package = \"pip._vendor.\" + package\n    locals()[package] = __import__(vendored_package)\n    # This traversal is apparently necessary such that the identities are\n    # preserved (requests.packages.urllib3.* is urllib3.*)\n    for mod in list(sys.modules):\n        if mod == vendored_package or mod.startswith(vendored_package + '.'):\n            unprefixed_mod = mod[len(\"pip._vendor.\"):]\n            sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod]\n\nif chardet is not None:\n    target = chardet.__name__\n    for mod in list(sys.modules):\n        if mod == target or mod.startswith(f\"{target}.\"):\n            imported_mod = sys.modules[mod]\n            sys.modules[f\"requests.packages.{mod}\"] = imported_mod\n            mod = mod.replace(target, \"chardet\")\n            sys.modules[f\"requests.packages.{mod}\"] = imported_mod\n"
  },
  {
    "path": "src/pip/_vendor/requests/sessions.py",
    "content": "\"\"\"\nrequests.sessions\n~~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\"\"\"\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom datetime import timedelta\n\nfrom ._internal_utils import to_native_string\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import Mapping, cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\n\n# formerly defined here, reexposed here for backward compatibility\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,\n    to_key_val_list,\n)\n\n# Preferred clock, based on which one is more accurate on a given system.\nif sys.platform == \"win32\":\n    preferred_clock = time.perf_counter\nelse:\n    preferred_clock = time.time\n\n\ndef merge_setting(request_setting, session_setting, dict_class=OrderedDict):\n    \"\"\"Determines appropriate setting for a given request, taking into account\n    the explicit setting on that request, and the setting in the session. If a\n    setting is a dictionary, they will be merged together using `dict_class`\n    \"\"\"\n\n    if session_setting is None:\n        return request_setting\n\n    if request_setting is None:\n        return session_setting\n\n    # Bypass if not a dictionary (e.g. verify)\n    if not (\n        isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)\n    ):\n        return request_setting\n\n    merged_setting = dict_class(to_key_val_list(session_setting))\n    merged_setting.update(to_key_val_list(request_setting))\n\n    # Remove keys that are set to None. Extract keys first to avoid altering\n    # the dictionary during iteration.\n    none_keys = [k for (k, v) in merged_setting.items() if v is None]\n    for key in none_keys:\n        del merged_setting[key]\n\n    return merged_setting\n\n\ndef merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):\n    \"\"\"Properly merges both requests and session hooks.\n\n    This is necessary because when request_hooks == {'response': []}, the\n    merge breaks Session hooks entirely.\n    \"\"\"\n    if session_hooks is None or session_hooks.get(\"response\") == []:\n        return request_hooks\n\n    if request_hooks is None or request_hooks.get(\"response\") == []:\n        return session_hooks\n\n    return merge_setting(request_hooks, session_hooks, dict_class)\n\n\nclass SessionRedirectMixin:\n    def get_redirect_target(self, resp):\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url, new_url):\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp,\n        req,\n        stream=False,\n        timeout=None,\n        verify=True,\n        cert=None,\n        proxies=None,\n        yield_requests=False,\n        **adapter_kwargs,\n    ):\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            # resp.history must ignore the original request in this loop\n            hist.append(resp)\n            resp.history = hist[1:]\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)\n            merge_cookies(prepared_request._cookies, self.cookies)\n            prepared_request.prepare_cookies(prepared_request._cookies)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(self, prepared_request, response):\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        headers = prepared_request.headers\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(\n            response.request.url, url\n        ):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(self, prepared_request, proxies):\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(self, prepared_request, response):\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    __attrs__ = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self):\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def prepare_request(self, request):\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(request.url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=request.method.upper(),\n            url=request.url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method,\n        url,\n        params=None,\n        data=None,\n        headers=None,\n        cookies=None,\n        files=None,\n        auth=None,\n        timeout=None,\n        allow_redirects=True,\n        proxies=None,\n        hooks=None,\n        stream=None,\n        verify=None,\n        cert=None,\n        json=None,\n    ):\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(self, url, **kwargs):\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, **kwargs)\n\n    def options(self, url, **kwargs):\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url, **kwargs):\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(self, url, data=None, json=None, **kwargs):\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(self, url, data=None, **kwargs):\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(self, url, data=None, **kwargs):\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url, **kwargs):\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request, **kwargs):\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(self, url, proxies, stream, verify, cert):\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            for k, v in env_proxies.items():\n                proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url):\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self):\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix, adapter):\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self):\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state):\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n\ndef session():\n    \"\"\"\n    Returns a :class:`Session` for context-management.\n\n    .. deprecated:: 1.0.0\n\n        This method has been deprecated since version 1.0.0 and is only kept for\n        backwards compatibility. New code should use :class:`~requests.sessions.Session`\n        to create a session. This may be removed at a future date.\n\n    :rtype: Session\n    \"\"\"\n    return Session()\n"
  },
  {
    "path": "src/pip/_vendor/requests/status_codes.py",
    "content": "r\"\"\"\nThe ``codes`` object defines a mapping from common names for HTTP statuses\nto their numerical codes, accessible either as attributes or as dictionary\nitems.\n\nExample::\n\n    >>> import requests\n    >>> requests.codes['temporary_redirect']\n    307\n    >>> requests.codes.teapot\n    418\n    >>> requests.codes['\\o/']\n    200\n\nSome codes have multiple names, and both upper- and lower-case versions of\nthe names are allowed. For example, ``codes.ok``, ``codes.OK``, and\n``codes.okay`` all correspond to the HTTP status code 200.\n\"\"\"\n\nfrom .structures import LookupDict\n\n_codes = {\n    # Informational.\n    100: (\"continue\",),\n    101: (\"switching_protocols\",),\n    102: (\"processing\", \"early-hints\"),\n    103: (\"checkpoint\",),\n    122: (\"uri_too_long\", \"request_uri_too_long\"),\n    200: (\"ok\", \"okay\", \"all_ok\", \"all_okay\", \"all_good\", \"\\\\o/\", \"✓\"),\n    201: (\"created\",),\n    202: (\"accepted\",),\n    203: (\"non_authoritative_info\", \"non_authoritative_information\"),\n    204: (\"no_content\",),\n    205: (\"reset_content\", \"reset\"),\n    206: (\"partial_content\", \"partial\"),\n    207: (\"multi_status\", \"multiple_status\", \"multi_stati\", \"multiple_stati\"),\n    208: (\"already_reported\",),\n    226: (\"im_used\",),\n    # Redirection.\n    300: (\"multiple_choices\",),\n    301: (\"moved_permanently\", \"moved\", \"\\\\o-\"),\n    302: (\"found\",),\n    303: (\"see_other\", \"other\"),\n    304: (\"not_modified\",),\n    305: (\"use_proxy\",),\n    306: (\"switch_proxy\",),\n    307: (\"temporary_redirect\", \"temporary_moved\", \"temporary\"),\n    308: (\n        \"permanent_redirect\",\n        \"resume_incomplete\",\n        \"resume\",\n    ),  # \"resume\" and \"resume_incomplete\" to be removed in 3.0\n    # Client Error.\n    400: (\"bad_request\", \"bad\"),\n    401: (\"unauthorized\",),\n    402: (\"payment_required\", \"payment\"),\n    403: (\"forbidden\",),\n    404: (\"not_found\", \"-o-\"),\n    405: (\"method_not_allowed\", \"not_allowed\"),\n    406: (\"not_acceptable\",),\n    407: (\"proxy_authentication_required\", \"proxy_auth\", \"proxy_authentication\"),\n    408: (\"request_timeout\", \"timeout\"),\n    409: (\"conflict\",),\n    410: (\"gone\",),\n    411: (\"length_required\",),\n    412: (\"precondition_failed\", \"precondition\"),\n    413: (\"request_entity_too_large\", \"content_too_large\"),\n    414: (\"request_uri_too_large\", \"uri_too_long\"),\n    415: (\"unsupported_media_type\", \"unsupported_media\", \"media_type\"),\n    416: (\n        \"requested_range_not_satisfiable\",\n        \"requested_range\",\n        \"range_not_satisfiable\",\n    ),\n    417: (\"expectation_failed\",),\n    418: (\"im_a_teapot\", \"teapot\", \"i_am_a_teapot\"),\n    421: (\"misdirected_request\",),\n    422: (\"unprocessable_entity\", \"unprocessable\", \"unprocessable_content\"),\n    423: (\"locked\",),\n    424: (\"failed_dependency\", \"dependency\"),\n    425: (\"unordered_collection\", \"unordered\", \"too_early\"),\n    426: (\"upgrade_required\", \"upgrade\"),\n    428: (\"precondition_required\", \"precondition\"),\n    429: (\"too_many_requests\", \"too_many\"),\n    431: (\"header_fields_too_large\", \"fields_too_large\"),\n    444: (\"no_response\", \"none\"),\n    449: (\"retry_with\", \"retry\"),\n    450: (\"blocked_by_windows_parental_controls\", \"parental_controls\"),\n    451: (\"unavailable_for_legal_reasons\", \"legal_reasons\"),\n    499: (\"client_closed_request\",),\n    # Server Error.\n    500: (\"internal_server_error\", \"server_error\", \"/o\\\\\", \"✗\"),\n    501: (\"not_implemented\",),\n    502: (\"bad_gateway\",),\n    503: (\"service_unavailable\", \"unavailable\"),\n    504: (\"gateway_timeout\",),\n    505: (\"http_version_not_supported\", \"http_version\"),\n    506: (\"variant_also_negotiates\",),\n    507: (\"insufficient_storage\",),\n    509: (\"bandwidth_limit_exceeded\", \"bandwidth\"),\n    510: (\"not_extended\",),\n    511: (\"network_authentication_required\", \"network_auth\", \"network_authentication\"),\n}\n\ncodes = LookupDict(name=\"status_codes\")\n\n\ndef _init():\n    for code, titles in _codes.items():\n        for title in titles:\n            setattr(codes, title, code)\n            if not title.startswith((\"\\\\\", \"/\")):\n                setattr(codes, title.upper(), code)\n\n    def doc(code):\n        names = \", \".join(f\"``{n}``\" for n in _codes[code])\n        return \"* %d: %s\" % (code, names)\n\n    global __doc__\n    __doc__ = (\n        __doc__ + \"\\n\" + \"\\n\".join(doc(code) for code in sorted(_codes))\n        if __doc__ is not None\n        else None\n    )\n\n\n_init()\n"
  },
  {
    "path": "src/pip/_vendor/requests/structures.py",
    "content": "\"\"\"\nrequests.structures\n~~~~~~~~~~~~~~~~~~~\n\nData structures that power Requests.\n\"\"\"\n\nfrom collections import OrderedDict\n\nfrom .compat import Mapping, MutableMapping\n\n\nclass CaseInsensitiveDict(MutableMapping):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    def __init__(self, data=None, **kwargs):\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key, value):\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key):\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key):\n        del self._store[key.lower()]\n\n    def __iter__(self):\n        return (casedkey for casedkey, mappedvalue in self._store.values())\n\n    def __len__(self):\n        return len(self._store)\n\n    def lower_items(self):\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other):\n        if isinstance(other, Mapping):\n            other = CaseInsensitiveDict(other)\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other.lower_items())\n\n    # Copy is required\n    def copy(self):\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self):\n        return str(dict(self.items()))\n\n\nclass LookupDict(dict):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    def __init__(self, name=None):\n        self.name = name\n        super().__init__()\n\n    def __repr__(self):\n        return f\"<lookup '{self.name}'>\"\n\n    def __getitem__(self, key):\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    def get(self, key, default=None):\n        return self.__dict__.get(key, default)\n"
  },
  {
    "path": "src/pip/_vendor/requests/utils.py",
    "content": "\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within Requests\nthat are also useful for external consumption.\n\"\"\"\n\nimport codecs\nimport contextlib\nimport io\nimport os\nimport re\nimport socket\nimport struct\nimport sys\nimport tempfile\nimport warnings\nimport zipfile\nfrom collections import OrderedDict\n\nfrom pip._vendor.urllib3.util import make_headers, parse_url\n\nfrom . import certs\nfrom .__version__ import __version__\n\n# to_native_string is unused here, but imported here for backwards compatibility\nfrom ._internal_utils import (  # noqa: F401\n    _HEADER_VALIDATORS_BYTE,\n    _HEADER_VALIDATORS_STR,\n    HEADER_VALIDATORS,\n    to_native_string,\n)\nfrom .compat import (\n    Mapping,\n    basestring,\n    bytes,\n    getproxies,\n    getproxies_environment,\n    integer_types,\n    is_urllib3_1,\n)\nfrom .compat import parse_http_list as _parse_list_header\nfrom .compat import (\n    proxy_bypass,\n    proxy_bypass_environment,\n    quote,\n    str,\n    unquote,\n    urlparse,\n    urlunparse,\n)\nfrom .cookies import cookiejar_from_dict\nfrom .exceptions import (\n    FileModeWarning,\n    InvalidHeader,\n    InvalidURL,\n    UnrewindableBodyError,\n)\nfrom .structures import CaseInsensitiveDict\n\nNETRC_FILES = (\".netrc\", \"_netrc\")\n\nDEFAULT_CA_BUNDLE_PATH = certs.where()\n\nDEFAULT_PORTS = {\"http\": 80, \"https\": 443}\n\n# Ensure that ', ' is used to preserve previous delimiter behavior.\nDEFAULT_ACCEPT_ENCODING = \", \".join(\n    re.split(r\",\\s*\", make_headers(accept_encoding=True)[\"accept-encoding\"])\n)\n\n\nif sys.platform == \"win32\":\n    # provide a proxy_bypass version on Windows without DNS lookups\n\n    def proxy_bypass_registry(host):\n        try:\n            import winreg\n        except ImportError:\n            return False\n\n        try:\n            internetSettings = winreg.OpenKey(\n                winreg.HKEY_CURRENT_USER,\n                r\"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\",\n            )\n            # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it\n            proxyEnable = int(winreg.QueryValueEx(internetSettings, \"ProxyEnable\")[0])\n            # ProxyOverride is almost always a string\n            proxyOverride = winreg.QueryValueEx(internetSettings, \"ProxyOverride\")[0]\n        except (OSError, ValueError):\n            return False\n        if not proxyEnable or not proxyOverride:\n            return False\n\n        # make a check value list from the registry entry: replace the\n        # '<local>' string by the localhost entry and the corresponding\n        # canonical entry.\n        proxyOverride = proxyOverride.split(\";\")\n        # filter out empty strings to avoid re.match return true in the following code.\n        proxyOverride = filter(None, proxyOverride)\n        # now check if we match one of the registry values.\n        for test in proxyOverride:\n            if test == \"<local>\":\n                if \".\" not in host:\n                    return True\n            test = test.replace(\".\", r\"\\.\")  # mask dots\n            test = test.replace(\"*\", r\".*\")  # change glob sequence\n            test = test.replace(\"?\", r\".\")  # change glob char\n            if re.match(test, host, re.I):\n                return True\n        return False\n\n    def proxy_bypass(host):  # noqa\n        \"\"\"Return True, if the host should be bypassed.\n\n        Checks proxy settings gathered from the environment, if specified,\n        or the registry.\n        \"\"\"\n        if getproxies_environment():\n            return proxy_bypass_environment(host)\n        else:\n            return proxy_bypass_registry(host)\n\n\ndef dict_to_sequence(d):\n    \"\"\"Returns an internal sequence dictionary update.\"\"\"\n\n    if hasattr(d, \"items\"):\n        d = d.items()\n\n    return d\n\n\ndef super_len(o):\n    total_length = None\n    current_position = 0\n\n    if not is_urllib3_1 and isinstance(o, str):\n        # urllib3 2.x+ treats all strings as utf-8 instead\n        # of latin-1 (iso-8859-1) like http.client.\n        o = o.encode(\"utf-8\")\n\n    if hasattr(o, \"__len__\"):\n        total_length = len(o)\n\n    elif hasattr(o, \"len\"):\n        total_length = o.len\n\n    elif hasattr(o, \"fileno\"):\n        try:\n            fileno = o.fileno()\n        except (io.UnsupportedOperation, AttributeError):\n            # AttributeError is a surprising exception, seeing as how we've just checked\n            # that `hasattr(o, 'fileno')`.  It happens for objects obtained via\n            # `Tarfile.extractfile()`, per issue 5229.\n            pass\n        else:\n            total_length = os.fstat(fileno).st_size\n\n            # Having used fstat to determine the file length, we need to\n            # confirm that this file was opened up in binary mode.\n            if \"b\" not in o.mode:\n                warnings.warn(\n                    (\n                        \"Requests has determined the content-length for this \"\n                        \"request using the binary size of the file: however, the \"\n                        \"file has been opened in text mode (i.e. without the 'b' \"\n                        \"flag in the mode). This may lead to an incorrect \"\n                        \"content-length. In Requests 3.0, support will be removed \"\n                        \"for files in text mode.\"\n                    ),\n                    FileModeWarning,\n                )\n\n    if hasattr(o, \"tell\"):\n        try:\n            current_position = o.tell()\n        except OSError:\n            # This can happen in some weird situations, such as when the file\n            # is actually a special file descriptor like stdin. In this\n            # instance, we don't know what the length is, so set it to zero and\n            # let requests chunk it instead.\n            if total_length is not None:\n                current_position = total_length\n        else:\n            if hasattr(o, \"seek\") and total_length is None:\n                # StringIO and BytesIO have seek but no usable fileno\n                try:\n                    # seek to end of file\n                    o.seek(0, 2)\n                    total_length = o.tell()\n\n                    # seek back to current position to support\n                    # partially read file-like objects\n                    o.seek(current_position or 0)\n                except OSError:\n                    total_length = 0\n\n    if total_length is None:\n        total_length = 0\n\n    return max(0, total_length - current_position)\n\n\ndef get_netrc_auth(url, raise_errors=False):\n    \"\"\"Returns the Requests tuple auth for a given url from netrc.\"\"\"\n\n    netrc_file = os.environ.get(\"NETRC\")\n    if netrc_file is not None:\n        netrc_locations = (netrc_file,)\n    else:\n        netrc_locations = (f\"~/{f}\" for f in NETRC_FILES)\n\n    try:\n        from netrc import NetrcParseError, netrc\n\n        netrc_path = None\n\n        for f in netrc_locations:\n            loc = os.path.expanduser(f)\n            if os.path.exists(loc):\n                netrc_path = loc\n                break\n\n        # Abort early if there isn't one.\n        if netrc_path is None:\n            return\n\n        ri = urlparse(url)\n        host = ri.hostname\n\n        try:\n            _netrc = netrc(netrc_path).authenticators(host)\n            if _netrc:\n                # Return with login / password\n                login_i = 0 if _netrc[0] else 1\n                return (_netrc[login_i], _netrc[2])\n        except (NetrcParseError, OSError):\n            # If there was a parsing error or a permissions issue reading the file,\n            # we'll just skip netrc auth unless explicitly asked to raise errors.\n            if raise_errors:\n                raise\n\n    # App Engine hackiness.\n    except (ImportError, AttributeError):\n        pass\n\n\ndef guess_filename(obj):\n    \"\"\"Tries to guess the filename of the given object.\"\"\"\n    name = getattr(obj, \"name\", None)\n    if name and isinstance(name, basestring) and name[0] != \"<\" and name[-1] != \">\":\n        return os.path.basename(name)\n\n\ndef extract_zipped_paths(path):\n    \"\"\"Replace nonexistent paths that look like they refer to a member of a zip\n    archive with the location of an extracted copy of the target, or else\n    just return the provided path unchanged.\n    \"\"\"\n    if os.path.exists(path):\n        # this is already a valid path, no need to do anything further\n        return path\n\n    # find the first valid part of the provided path and treat that as a zip archive\n    # assume the rest of the path is the name of a member in the archive\n    archive, member = os.path.split(path)\n    while archive and not os.path.exists(archive):\n        archive, prefix = os.path.split(archive)\n        if not prefix:\n            # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),\n            # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users\n            break\n        member = \"/\".join([prefix, member])\n\n    if not zipfile.is_zipfile(archive):\n        return path\n\n    zip_file = zipfile.ZipFile(archive)\n    if member not in zip_file.namelist():\n        return path\n\n    # we have a valid zip archive and a valid member of that archive\n    tmp = tempfile.gettempdir()\n    extracted_path = os.path.join(tmp, member.split(\"/\")[-1])\n    if not os.path.exists(extracted_path):\n        # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition\n        with atomic_open(extracted_path) as file_handler:\n            file_handler.write(zip_file.read(member))\n    return extracted_path\n\n\n@contextlib.contextmanager\ndef atomic_open(filename):\n    \"\"\"Write a file to the disk in an atomic fashion\"\"\"\n    tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))\n    try:\n        with os.fdopen(tmp_descriptor, \"wb\") as tmp_handler:\n            yield tmp_handler\n        os.replace(tmp_name, filename)\n    except BaseException:\n        os.remove(tmp_name)\n        raise\n\n\ndef from_key_val_list(value):\n    \"\"\"Take an object and test to see if it can be represented as a\n    dictionary. Unless it can not be represented as such, return an\n    OrderedDict, e.g.,\n\n    ::\n\n        >>> from_key_val_list([('key', 'val')])\n        OrderedDict([('key', 'val')])\n        >>> from_key_val_list('string')\n        Traceback (most recent call last):\n        ...\n        ValueError: cannot encode objects that are not 2-tuples\n        >>> from_key_val_list({'key': 'val'})\n        OrderedDict([('key', 'val')])\n\n    :rtype: OrderedDict\n    \"\"\"\n    if value is None:\n        return None\n\n    if isinstance(value, (str, bytes, bool, int)):\n        raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n    return OrderedDict(value)\n\n\ndef to_key_val_list(value):\n    \"\"\"Take an object and test to see if it can be represented as a\n    dictionary. If it can be, return a list of tuples, e.g.,\n\n    ::\n\n        >>> to_key_val_list([('key', 'val')])\n        [('key', 'val')]\n        >>> to_key_val_list({'key': 'val'})\n        [('key', 'val')]\n        >>> to_key_val_list('string')\n        Traceback (most recent call last):\n        ...\n        ValueError: cannot encode objects that are not 2-tuples\n\n    :rtype: list\n    \"\"\"\n    if value is None:\n        return None\n\n    if isinstance(value, (str, bytes, bool, int)):\n        raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n    if isinstance(value, Mapping):\n        value = value.items()\n\n    return list(value)\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef parse_list_header(value):\n    \"\"\"Parse lists as described by RFC 2068 Section 2.\n\n    In particular, parse comma-separated lists where the elements of\n    the list may include quoted-strings.  A quoted-string could\n    contain a comma.  A non-quoted string could have quotes in the\n    middle.  Quotes are removed automatically after parsing.\n\n    It basically works like :func:`parse_set_header` just that items\n    may appear multiple times and case sensitivity is preserved.\n\n    The return value is a standard :class:`list`:\n\n    >>> parse_list_header('token, \"quoted value\"')\n    ['token', 'quoted value']\n\n    To create a header from the :class:`list` again, use the\n    :func:`dump_header` function.\n\n    :param value: a string with a list header.\n    :return: :class:`list`\n    :rtype: list\n    \"\"\"\n    result = []\n    for item in _parse_list_header(value):\n        if item[:1] == item[-1:] == '\"':\n            item = unquote_header_value(item[1:-1])\n        result.append(item)\n    return result\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef parse_dict_header(value):\n    \"\"\"Parse lists of key, value pairs as described by RFC 2068 Section 2 and\n    convert them into a python dict:\n\n    >>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')\n    >>> type(d) is dict\n    True\n    >>> sorted(d.items())\n    [('bar', 'as well'), ('foo', 'is a fish')]\n\n    If there is no value for a key it will be `None`:\n\n    >>> parse_dict_header('key_without_value')\n    {'key_without_value': None}\n\n    To create a header from the :class:`dict` again, use the\n    :func:`dump_header` function.\n\n    :param value: a string with a dict header.\n    :return: :class:`dict`\n    :rtype: dict\n    \"\"\"\n    result = {}\n    for item in _parse_list_header(value):\n        if \"=\" not in item:\n            result[item] = None\n            continue\n        name, value = item.split(\"=\", 1)\n        if value[:1] == value[-1:] == '\"':\n            value = unquote_header_value(value[1:-1])\n        result[name] = value\n    return result\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef unquote_header_value(value, is_filename=False):\n    r\"\"\"Unquotes a header value.  (Reversal of :func:`quote_header_value`).\n    This does not use the real unquoting but what browsers are actually\n    using for quoting.\n\n    :param value: the header value to unquote.\n    :rtype: str\n    \"\"\"\n    if value and value[0] == value[-1] == '\"':\n        # this is not the real unquoting, but fixing this so that the\n        # RFC is met will result in bugs with internet explorer and\n        # probably some other browsers as well.  IE for example is\n        # uploading files with \"C:\\foo\\bar.txt\" as filename\n        value = value[1:-1]\n\n        # if this is a filename and the starting characters look like\n        # a UNC path, then just return the value without quotes.  Using the\n        # replace sequence below on a UNC path has the effect of turning\n        # the leading double slash into a single slash and then\n        # _fix_ie_filename() doesn't work correctly.  See #458.\n        if not is_filename or value[:2] != \"\\\\\\\\\":\n            return value.replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"')\n    return value\n\n\ndef dict_from_cookiejar(cj):\n    \"\"\"Returns a key/value dictionary from a CookieJar.\n\n    :param cj: CookieJar object to extract cookies from.\n    :rtype: dict\n    \"\"\"\n\n    cookie_dict = {cookie.name: cookie.value for cookie in cj}\n    return cookie_dict\n\n\ndef add_dict_to_cookiejar(cj, cookie_dict):\n    \"\"\"Returns a CookieJar from a key/value dictionary.\n\n    :param cj: CookieJar to insert cookies into.\n    :param cookie_dict: Dict of key/values to insert into CookieJar.\n    :rtype: CookieJar\n    \"\"\"\n\n    return cookiejar_from_dict(cookie_dict, cj)\n\n\ndef get_encodings_from_content(content):\n    \"\"\"Returns encodings from given content string.\n\n    :param content: bytestring to extract encodings from.\n    \"\"\"\n    warnings.warn(\n        (\n            \"In requests 3.0, get_encodings_from_content will be removed. For \"\n            \"more information, please see the discussion on issue #2266. (This\"\n            \" warning should only appear once.)\"\n        ),\n        DeprecationWarning,\n    )\n\n    charset_re = re.compile(r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]', flags=re.I)\n    pragma_re = re.compile(r'<meta.*?content=[\"\\']*;?charset=(.+?)[\"\\'>]', flags=re.I)\n    xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n\n    return (\n        charset_re.findall(content)\n        + pragma_re.findall(content)\n        + xml_re.findall(content)\n    )\n\n\ndef _parse_content_type_header(header):\n    \"\"\"Returns content type and parameters from given header\n\n    :param header: string\n    :return: tuple containing content type and dictionary of\n         parameters\n    \"\"\"\n\n    tokens = header.split(\";\")\n    content_type, params = tokens[0].strip(), tokens[1:]\n    params_dict = {}\n    items_to_strip = \"\\\"' \"\n\n    for param in params:\n        param = param.strip()\n        if param:\n            key, value = param, True\n            index_of_equals = param.find(\"=\")\n            if index_of_equals != -1:\n                key = param[:index_of_equals].strip(items_to_strip)\n                value = param[index_of_equals + 1 :].strip(items_to_strip)\n            params_dict[key.lower()] = value\n    return content_type, params_dict\n\n\ndef get_encoding_from_headers(headers):\n    \"\"\"Returns encodings from given HTTP Header Dict.\n\n    :param headers: dictionary to extract encoding from.\n    :rtype: str\n    \"\"\"\n\n    content_type = headers.get(\"content-type\")\n\n    if not content_type:\n        return None\n\n    content_type, params = _parse_content_type_header(content_type)\n\n    if \"charset\" in params:\n        return params[\"charset\"].strip(\"'\\\"\")\n\n    if \"text\" in content_type:\n        return \"ISO-8859-1\"\n\n    if \"application/json\" in content_type:\n        # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset\n        return \"utf-8\"\n\n\ndef stream_decode_response_unicode(iterator, r):\n    \"\"\"Stream decodes an iterator.\"\"\"\n\n    if r.encoding is None:\n        yield from iterator\n        return\n\n    decoder = codecs.getincrementaldecoder(r.encoding)(errors=\"replace\")\n    for chunk in iterator:\n        rv = decoder.decode(chunk)\n        if rv:\n            yield rv\n    rv = decoder.decode(b\"\", final=True)\n    if rv:\n        yield rv\n\n\ndef iter_slices(string, slice_length):\n    \"\"\"Iterate over slices of a string.\"\"\"\n    pos = 0\n    if slice_length is None or slice_length <= 0:\n        slice_length = len(string)\n    while pos < len(string):\n        yield string[pos : pos + slice_length]\n        pos += slice_length\n\n\ndef get_unicode_from_response(r):\n    \"\"\"Returns the requested content back in unicode.\n\n    :param r: Response object to get unicode content from.\n\n    Tried:\n\n    1. charset from content-type\n    2. fall back and replace all unicode characters\n\n    :rtype: str\n    \"\"\"\n    warnings.warn(\n        (\n            \"In requests 3.0, get_unicode_from_response will be removed. For \"\n            \"more information, please see the discussion on issue #2266. (This\"\n            \" warning should only appear once.)\"\n        ),\n        DeprecationWarning,\n    )\n\n    tried_encodings = []\n\n    # Try charset from content-type\n    encoding = get_encoding_from_headers(r.headers)\n\n    if encoding:\n        try:\n            return str(r.content, encoding)\n        except UnicodeError:\n            tried_encodings.append(encoding)\n\n    # Fall back:\n    try:\n        return str(r.content, encoding, errors=\"replace\")\n    except TypeError:\n        return r.content\n\n\n# The unreserved URI characters (RFC 3986)\nUNRESERVED_SET = frozenset(\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\" + \"0123456789-._~\"\n)\n\n\ndef unquote_unreserved(uri):\n    \"\"\"Un-escape any percent-escape sequences in a URI that are unreserved\n    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.\n\n    :rtype: str\n    \"\"\"\n    parts = uri.split(\"%\")\n    for i in range(1, len(parts)):\n        h = parts[i][0:2]\n        if len(h) == 2 and h.isalnum():\n            try:\n                c = chr(int(h, 16))\n            except ValueError:\n                raise InvalidURL(f\"Invalid percent-escape sequence: '{h}'\")\n\n            if c in UNRESERVED_SET:\n                parts[i] = c + parts[i][2:]\n            else:\n                parts[i] = f\"%{parts[i]}\"\n        else:\n            parts[i] = f\"%{parts[i]}\"\n    return \"\".join(parts)\n\n\ndef requote_uri(uri):\n    \"\"\"Re-quote the given URI.\n\n    This function passes the given URI through an unquote/quote cycle to\n    ensure that it is fully and consistently quoted.\n\n    :rtype: str\n    \"\"\"\n    safe_with_percent = \"!#$%&'()*+,/:;=?@[]~\"\n    safe_without_percent = \"!#$&'()*+,/:;=?@[]~\"\n    try:\n        # Unquote only the unreserved characters\n        # Then quote only illegal characters (do not quote reserved,\n        # unreserved, or '%')\n        return quote(unquote_unreserved(uri), safe=safe_with_percent)\n    except InvalidURL:\n        # We couldn't unquote the given URI, so let's try quoting it, but\n        # there may be unquoted '%'s in the URI. We need to make sure they're\n        # properly quoted so they do not cause issues elsewhere.\n        return quote(uri, safe=safe_without_percent)\n\n\ndef address_in_network(ip, net):\n    \"\"\"This function allows you to check if an IP belongs to a network subnet\n\n    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n    :rtype: bool\n    \"\"\"\n    ipaddr = struct.unpack(\"=L\", socket.inet_aton(ip))[0]\n    netaddr, bits = net.split(\"/\")\n    netmask = struct.unpack(\"=L\", socket.inet_aton(dotted_netmask(int(bits))))[0]\n    network = struct.unpack(\"=L\", socket.inet_aton(netaddr))[0] & netmask\n    return (ipaddr & netmask) == (network & netmask)\n\n\ndef dotted_netmask(mask):\n    \"\"\"Converts mask from /xx format to xxx.xxx.xxx.xxx\n\n    Example: if mask is 24 function returns 255.255.255.0\n\n    :rtype: str\n    \"\"\"\n    bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1\n    return socket.inet_ntoa(struct.pack(\">I\", bits))\n\n\ndef is_ipv4_address(string_ip):\n    \"\"\"\n    :rtype: bool\n    \"\"\"\n    try:\n        socket.inet_aton(string_ip)\n    except OSError:\n        return False\n    return True\n\n\ndef is_valid_cidr(string_network):\n    \"\"\"\n    Very simple check of the cidr format in no_proxy variable.\n\n    :rtype: bool\n    \"\"\"\n    if string_network.count(\"/\") == 1:\n        try:\n            mask = int(string_network.split(\"/\")[1])\n        except ValueError:\n            return False\n\n        if mask < 1 or mask > 32:\n            return False\n\n        try:\n            socket.inet_aton(string_network.split(\"/\")[0])\n        except OSError:\n            return False\n    else:\n        return False\n    return True\n\n\n@contextlib.contextmanager\ndef set_environ(env_name, value):\n    \"\"\"Set the environment variable 'env_name' to 'value'\n\n    Save previous value, yield, and then restore the previous value stored in\n    the environment variable 'env_name'.\n\n    If 'value' is None, do nothing\"\"\"\n    value_changed = value is not None\n    if value_changed:\n        old_value = os.environ.get(env_name)\n        os.environ[env_name] = value\n    try:\n        yield\n    finally:\n        if value_changed:\n            if old_value is None:\n                del os.environ[env_name]\n            else:\n                os.environ[env_name] = old_value\n\n\ndef should_bypass_proxies(url, no_proxy):\n    \"\"\"\n    Returns whether we should bypass proxies or not.\n\n    :rtype: bool\n    \"\"\"\n\n    # Prioritize lowercase environment variables over uppercase\n    # to keep a consistent behaviour with other http projects (curl, wget).\n    def get_proxy(key):\n        return os.environ.get(key) or os.environ.get(key.upper())\n\n    # First check whether no_proxy is defined. If it is, check that the URL\n    # we're getting isn't in the no_proxy list.\n    no_proxy_arg = no_proxy\n    if no_proxy is None:\n        no_proxy = get_proxy(\"no_proxy\")\n    parsed = urlparse(url)\n\n    if parsed.hostname is None:\n        # URLs don't always have hostnames, e.g. file:/// urls.\n        return True\n\n    if no_proxy:\n        # We need to check whether we match here. We need to see if we match\n        # the end of the hostname, both with and without the port.\n        no_proxy = (host for host in no_proxy.replace(\" \", \"\").split(\",\") if host)\n\n        if is_ipv4_address(parsed.hostname):\n            for proxy_ip in no_proxy:\n                if is_valid_cidr(proxy_ip):\n                    if address_in_network(parsed.hostname, proxy_ip):\n                        return True\n                elif parsed.hostname == proxy_ip:\n                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &\n                    # matches the IP of the index\n                    return True\n        else:\n            host_with_port = parsed.hostname\n            if parsed.port:\n                host_with_port += f\":{parsed.port}\"\n\n            for host in no_proxy:\n                if parsed.hostname.endswith(host) or host_with_port.endswith(host):\n                    # The URL does match something in no_proxy, so we don't want\n                    # to apply the proxies on this URL.\n                    return True\n\n    with set_environ(\"no_proxy\", no_proxy_arg):\n        # parsed.hostname can be `None` in cases such as a file URI.\n        try:\n            bypass = proxy_bypass(parsed.hostname)\n        except (TypeError, socket.gaierror):\n            bypass = False\n\n    if bypass:\n        return True\n\n    return False\n\n\ndef get_environ_proxies(url, no_proxy=None):\n    \"\"\"\n    Return a dict of environment proxies.\n\n    :rtype: dict\n    \"\"\"\n    if should_bypass_proxies(url, no_proxy=no_proxy):\n        return {}\n    else:\n        return getproxies()\n\n\ndef select_proxy(url, proxies):\n    \"\"\"Select a proxy for the url, if applicable.\n\n    :param url: The url being for the request\n    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n    \"\"\"\n    proxies = proxies or {}\n    urlparts = urlparse(url)\n    if urlparts.hostname is None:\n        return proxies.get(urlparts.scheme, proxies.get(\"all\"))\n\n    proxy_keys = [\n        urlparts.scheme + \"://\" + urlparts.hostname,\n        urlparts.scheme,\n        \"all://\" + urlparts.hostname,\n        \"all\",\n    ]\n    proxy = None\n    for proxy_key in proxy_keys:\n        if proxy_key in proxies:\n            proxy = proxies[proxy_key]\n            break\n\n    return proxy\n\n\ndef resolve_proxies(request, proxies, trust_env=True):\n    \"\"\"This method takes proxy information from a request and configuration\n    input to resolve a mapping of target proxies. This will consider settings\n    such as NO_PROXY to strip proxy configurations.\n\n    :param request: Request or PreparedRequest\n    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n    :param trust_env: Boolean declaring whether to trust environment configs\n\n    :rtype: dict\n    \"\"\"\n    proxies = proxies if proxies is not None else {}\n    url = request.url\n    scheme = urlparse(url).scheme\n    no_proxy = proxies.get(\"no_proxy\")\n    new_proxies = proxies.copy()\n\n    if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):\n        environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n\n        proxy = environ_proxies.get(scheme, environ_proxies.get(\"all\"))\n\n        if proxy:\n            new_proxies.setdefault(scheme, proxy)\n    return new_proxies\n\n\ndef default_user_agent(name=\"python-requests\"):\n    \"\"\"\n    Return a string representing the default user agent.\n\n    :rtype: str\n    \"\"\"\n    return f\"{name}/{__version__}\"\n\n\ndef default_headers():\n    \"\"\"\n    :rtype: requests.structures.CaseInsensitiveDict\n    \"\"\"\n    return CaseInsensitiveDict(\n        {\n            \"User-Agent\": default_user_agent(),\n            \"Accept-Encoding\": DEFAULT_ACCEPT_ENCODING,\n            \"Accept\": \"*/*\",\n            \"Connection\": \"keep-alive\",\n        }\n    )\n\n\ndef parse_header_links(value):\n    \"\"\"Return a list of parsed link headers proxies.\n\n    i.e. Link: <http:/.../front.jpeg>; rel=front; type=\"image/jpeg\",<http://.../back.jpeg>; rel=back;type=\"image/jpeg\"\n\n    :rtype: list\n    \"\"\"\n\n    links = []\n\n    replace_chars = \" '\\\"\"\n\n    value = value.strip(replace_chars)\n    if not value:\n        return links\n\n    for val in re.split(\", *<\", value):\n        try:\n            url, params = val.split(\";\", 1)\n        except ValueError:\n            url, params = val, \"\"\n\n        link = {\"url\": url.strip(\"<> '\\\"\")}\n\n        for param in params.split(\";\"):\n            try:\n                key, value = param.split(\"=\")\n            except ValueError:\n                break\n\n            link[key.strip(replace_chars)] = value.strip(replace_chars)\n\n        links.append(link)\n\n    return links\n\n\n# Null bytes; no need to recreate these on each call to guess_json_utf\n_null = \"\\x00\".encode(\"ascii\")  # encoding to ASCII for Python 3\n_null2 = _null * 2\n_null3 = _null * 3\n\n\ndef guess_json_utf(data):\n    \"\"\"\n    :rtype: str\n    \"\"\"\n    # JSON always starts with two ASCII characters, so detection is as\n    # easy as counting the nulls and from their location and count\n    # determine the encoding. Also detect a BOM, if present.\n    sample = data[:4]\n    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):\n        return \"utf-32\"  # BOM included\n    if sample[:3] == codecs.BOM_UTF8:\n        return \"utf-8-sig\"  # BOM included, MS style (discouraged)\n    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n        return \"utf-16\"  # BOM included\n    nullcount = sample.count(_null)\n    if nullcount == 0:\n        return \"utf-8\"\n    if nullcount == 2:\n        if sample[::2] == _null2:  # 1st and 3rd are null\n            return \"utf-16-be\"\n        if sample[1::2] == _null2:  # 2nd and 4th are null\n            return \"utf-16-le\"\n        # Did not detect 2 valid UTF-16 ascii-range characters\n    if nullcount == 3:\n        if sample[:3] == _null3:\n            return \"utf-32-be\"\n        if sample[1:] == _null3:\n            return \"utf-32-le\"\n        # Did not detect a valid UTF-32 ascii-range character\n    return None\n\n\ndef prepend_scheme_if_needed(url, new_scheme):\n    \"\"\"Given a URL that may or may not have a scheme, prepend the given scheme.\n    Does not replace a present scheme with the one provided as an argument.\n\n    :rtype: str\n    \"\"\"\n    parsed = parse_url(url)\n    scheme, auth, host, port, path, query, fragment = parsed\n\n    # A defect in urlparse determines that there isn't a netloc present in some\n    # urls. We previously assumed parsing was overly cautious, and swapped the\n    # netloc and path. Due to a lack of tests on the original defect, this is\n    # maintained with parse_url for backwards compatibility.\n    netloc = parsed.netloc\n    if not netloc:\n        netloc, path = path, netloc\n\n    if auth:\n        # parse_url doesn't provide the netloc with auth\n        # so we'll add it ourselves.\n        netloc = \"@\".join([auth, netloc])\n    if scheme is None:\n        scheme = new_scheme\n    if path is None:\n        path = \"\"\n\n    return urlunparse((scheme, netloc, path, \"\", query, fragment))\n\n\ndef get_auth_from_url(url):\n    \"\"\"Given a url with authentication components, extract them into a tuple of\n    username,password.\n\n    :rtype: (str,str)\n    \"\"\"\n    parsed = urlparse(url)\n\n    try:\n        auth = (unquote(parsed.username), unquote(parsed.password))\n    except (AttributeError, TypeError):\n        auth = (\"\", \"\")\n\n    return auth\n\n\ndef check_header_validity(header):\n    \"\"\"Verifies that header parts don't contain leading whitespace\n    reserved characters, or return characters.\n\n    :param header: tuple, in the format (name, value).\n    \"\"\"\n    name, value = header\n    _validate_header_part(header, name, 0)\n    _validate_header_part(header, value, 1)\n\n\ndef _validate_header_part(header, header_part, header_validator_index):\n    if isinstance(header_part, str):\n        validator = _HEADER_VALIDATORS_STR[header_validator_index]\n    elif isinstance(header_part, bytes):\n        validator = _HEADER_VALIDATORS_BYTE[header_validator_index]\n    else:\n        raise InvalidHeader(\n            f\"Header part ({header_part!r}) from {header} \"\n            f\"must be of type str or bytes, not {type(header_part)}\"\n        )\n\n    if not validator.match(header_part):\n        header_kind = \"name\" if header_validator_index == 0 else \"value\"\n        raise InvalidHeader(\n            f\"Invalid leading whitespace, reserved character(s), or return \"\n            f\"character(s) in header {header_kind}: {header_part!r}\"\n        )\n\n\ndef urldefragauth(url):\n    \"\"\"\n    Given a url remove the fragment and the authentication part.\n\n    :rtype: str\n    \"\"\"\n    scheme, netloc, path, params, query, fragment = urlparse(url)\n\n    # see func:`prepend_scheme_if_needed`\n    if not netloc:\n        netloc, path = path, netloc\n\n    netloc = netloc.rsplit(\"@\", 1)[-1]\n\n    return urlunparse((scheme, netloc, path, params, query, \"\"))\n\n\ndef rewind_body(prepared_request):\n    \"\"\"Move file pointer back to its recorded starting position\n    so it can be read again on redirect.\n    \"\"\"\n    body_seek = getattr(prepared_request.body, \"seek\", None)\n    if body_seek is not None and isinstance(\n        prepared_request._body_position, integer_types\n    ):\n        try:\n            body_seek(prepared_request._body_position)\n        except OSError:\n            raise UnrewindableBodyError(\n                \"An error occurred when rewinding request body for redirect.\"\n            )\n    else:\n        raise UnrewindableBodyError(\"Unable to rewind request body for redirect.\")\n"
  },
  {
    "path": "src/pip/_vendor/requests.pyi",
    "content": "from requests import *"
  },
  {
    "path": "src/pip/_vendor/resolvelib/LICENSE",
    "content": "Copyright (c) 2018, Tzu-ping Chung <uranusjr@gmail.com>\n\nPermission to use, copy, modify, and distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/__init__.py",
    "content": "__all__ = [\n    \"AbstractProvider\",\n    \"AbstractResolver\",\n    \"BaseReporter\",\n    \"InconsistentCandidate\",\n    \"RequirementsConflicted\",\n    \"ResolutionError\",\n    \"ResolutionImpossible\",\n    \"ResolutionTooDeep\",\n    \"Resolver\",\n    \"__version__\",\n]\n\n__version__ = \"1.2.1\"\n\n\nfrom .providers import AbstractProvider\nfrom .reporters import BaseReporter\nfrom .resolvers import (\n    AbstractResolver,\n    InconsistentCandidate,\n    RequirementsConflicted,\n    ResolutionError,\n    ResolutionImpossible,\n    ResolutionTooDeep,\n    Resolver,\n)\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/providers.py",
    "content": "from __future__ import annotations\n\nfrom typing import (\n    TYPE_CHECKING,\n    Generic,\n    Iterable,\n    Iterator,\n    Mapping,\n    Sequence,\n)\n\nfrom .structs import CT, KT, RT, Matches, RequirementInformation\n\nif TYPE_CHECKING:\n    from typing import Any, Protocol\n\n    class Preference(Protocol):\n        def __lt__(self, __other: Any) -> bool: ...\n\n\nclass AbstractProvider(Generic[RT, CT, KT]):\n    \"\"\"Delegate class to provide the required interface for the resolver.\"\"\"\n\n    def identify(self, requirement_or_candidate: RT | CT) -> KT:\n        \"\"\"Given a requirement or candidate, return an identifier for it.\n\n        This is used to identify, e.g. whether two requirements\n        should have their specifier parts merged or a candidate matches a\n        requirement via ``find_matches()``.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_preference(\n        self,\n        identifier: KT,\n        resolutions: Mapping[KT, CT],\n        candidates: Mapping[KT, Iterator[CT]],\n        information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],\n        backtrack_causes: Sequence[RequirementInformation[RT, CT]],\n    ) -> Preference:\n        \"\"\"Produce a sort key for given requirement based on preference.\n\n        As this is a sort key it will be called O(n) times per backtrack\n        step, where n is the number of `identifier`s, if you have a check\n        which is expensive in some sense. E.g. It needs to make O(n) checks\n        per call or takes significant wall clock time, consider using\n        `narrow_requirement_selection` to filter the `identifier`s, which\n        is applied before this sort key is called.\n\n        The preference is defined as \"I think this requirement should be\n        resolved first\". The lower the return value is, the more preferred\n        this group of arguments is.\n\n        :param identifier: An identifier as returned by ``identify()``. This\n            identifies the requirement being considered.\n        :param resolutions: Mapping of candidates currently pinned by the\n            resolver. Each key is an identifier, and the value is a candidate.\n            The candidate may conflict with requirements from ``information``.\n        :param candidates: Mapping of each dependency's possible candidates.\n            Each value is an iterator of candidates.\n        :param information: Mapping of requirement information of each package.\n            Each value is an iterator of *requirement information*.\n        :param backtrack_causes: Sequence of *requirement information* that are\n            the requirements that caused the resolver to most recently\n            backtrack.\n\n        A *requirement information* instance is a named tuple with two members:\n\n        * ``requirement`` specifies a requirement contributing to the current\n          list of candidates.\n        * ``parent`` specifies the candidate that provides (depended on) the\n          requirement, or ``None`` to indicate a root requirement.\n\n        The preference could depend on various issues, including (not\n        necessarily in this order):\n\n        * Is this package pinned in the current resolution result?\n        * How relaxed is the requirement? Stricter ones should probably be\n          worked on first? (I don't know, actually.)\n        * How many possibilities are there to satisfy this requirement? Those\n          with few left should likely be worked on first, I guess?\n        * Are there any known conflicts for this requirement? We should\n          probably work on those with the most known conflicts.\n\n        A sortable value should be returned (this will be used as the ``key``\n        parameter of the built-in sorting function). The smaller the value is,\n        the more preferred this requirement is (i.e. the sorting function\n        is called with ``reverse=False``).\n        \"\"\"\n        raise NotImplementedError\n\n    def find_matches(\n        self,\n        identifier: KT,\n        requirements: Mapping[KT, Iterator[RT]],\n        incompatibilities: Mapping[KT, Iterator[CT]],\n    ) -> Matches[CT]:\n        \"\"\"Find all possible candidates that satisfy the given constraints.\n\n        :param identifier: An identifier as returned by ``identify()``. All\n            candidates returned by this method should produce the same\n            identifier.\n        :param requirements: A mapping of requirements that all returned\n            candidates must satisfy. Each key is an identifier, and the value\n            an iterator of requirements for that dependency.\n        :param incompatibilities: A mapping of known incompatibile candidates of\n            each dependency. Each key is an identifier, and the value an\n            iterator of incompatibilities known to the resolver. All\n            incompatibilities *must* be excluded from the return value.\n\n        This should try to get candidates based on the requirements' types.\n        For VCS, local, and archive requirements, the one-and-only match is\n        returned, and for a \"named\" requirement, the index(es) should be\n        consulted to find concrete candidates for this requirement.\n\n        The return value should produce candidates ordered by preference; the\n        most preferred candidate should come first. The return type may be one\n        of the following:\n\n        * A callable that returns an iterator that yields candidates.\n        * An collection of candidates.\n        * An iterable of candidates. This will be consumed immediately into a\n          list of candidates.\n        \"\"\"\n        raise NotImplementedError\n\n    def is_satisfied_by(self, requirement: RT, candidate: CT) -> bool:\n        \"\"\"Whether the given requirement can be satisfied by a candidate.\n\n        The candidate is guaranteed to have been generated from the\n        requirement.\n\n        A boolean should be returned to indicate whether ``candidate`` is a\n        viable solution to the requirement.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_dependencies(self, candidate: CT) -> Iterable[RT]:\n        \"\"\"Get dependencies of a candidate.\n\n        This should return a collection of requirements that `candidate`\n        specifies as its dependencies.\n        \"\"\"\n        raise NotImplementedError\n\n    def narrow_requirement_selection(\n        self,\n        identifiers: Iterable[KT],\n        resolutions: Mapping[KT, CT],\n        candidates: Mapping[KT, Iterator[CT]],\n        information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],\n        backtrack_causes: Sequence[RequirementInformation[RT, CT]],\n    ) -> Iterable[KT]:\n        \"\"\"\n        An optional method to narrow the selection of requirements being\n        considered during resolution. This method is called O(1) time per\n        backtrack step.\n\n        :param identifiers: An iterable of `identifiers` as returned by\n            ``identify()``. These identify all requirements currently being\n            considered.\n        :param resolutions: A mapping of candidates currently pinned by the\n            resolver. Each key is an identifier, and the value is a candidate\n            that may conflict with requirements from ``information``.\n        :param candidates: A mapping of each dependency's possible candidates.\n            Each value is an iterator of candidates.\n        :param information: A mapping of requirement information for each package.\n            Each value is an iterator of *requirement information*.\n        :param backtrack_causes: A sequence of *requirement information* that are\n            the requirements causing the resolver to most recently\n            backtrack.\n\n        A *requirement information* instance is a named tuple with two members:\n\n        * ``requirement`` specifies a requirement contributing to the current\n          list of candidates.\n        * ``parent`` specifies the candidate that provides (is depended on for)\n          the requirement, or ``None`` to indicate a root requirement.\n\n        Must return a non-empty subset of `identifiers`, with the default\n        implementation being to return `identifiers` unchanged. Those `identifiers`\n        will then be passed to the sort key `get_preference` to pick the most\n        prefered requirement to attempt to pin, unless `narrow_requirement_selection`\n        returns only 1 requirement, in which case that will be used without\n        calling the sort key `get_preference`.\n\n        This method is designed to be used by the provider to optimize the\n        dependency resolution, e.g. if a check cost is O(m) and it can be done\n        against all identifiers at once then filtering the requirement selection\n        here will cost O(m) but making it part of the sort key in `get_preference`\n        will cost O(m*n), where n is the number of `identifiers`.\n\n        Returns:\n            Iterable[KT]: A non-empty subset of `identifiers`.\n        \"\"\"\n        return identifiers\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/resolvelib/reporters.py",
    "content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Collection, Generic\n\nfrom .structs import CT, KT, RT, RequirementInformation, State\n\nif TYPE_CHECKING:\n    from .resolvers import Criterion\n\n\nclass BaseReporter(Generic[RT, CT, KT]):\n    \"\"\"Delegate class to provide progress reporting for the resolver.\"\"\"\n\n    def starting(self) -> None:\n        \"\"\"Called before the resolution actually starts.\"\"\"\n\n    def starting_round(self, index: int) -> None:\n        \"\"\"Called before each round of resolution starts.\n\n        The index is zero-based.\n        \"\"\"\n\n    def ending_round(self, index: int, state: State[RT, CT, KT]) -> None:\n        \"\"\"Called before each round of resolution ends.\n\n        This is NOT called if the resolution ends at this round. Use `ending`\n        if you want to report finalization. The index is zero-based.\n        \"\"\"\n\n    def ending(self, state: State[RT, CT, KT]) -> None:\n        \"\"\"Called before the resolution ends successfully.\"\"\"\n\n    def adding_requirement(self, requirement: RT, parent: CT | None) -> None:\n        \"\"\"Called when adding a new requirement into the resolve criteria.\n\n        :param requirement: The additional requirement to be applied to filter\n            the available candidaites.\n        :param parent: The candidate that requires ``requirement`` as a\n            dependency, or None if ``requirement`` is one of the root\n            requirements passed in from ``Resolver.resolve()``.\n        \"\"\"\n\n    def resolving_conflicts(\n        self, causes: Collection[RequirementInformation[RT, CT]]\n    ) -> None:\n        \"\"\"Called when starting to attempt requirement conflict resolution.\n\n        :param causes: The information on the collision that caused the backtracking.\n        \"\"\"\n\n    def rejecting_candidate(self, criterion: Criterion[RT, CT], candidate: CT) -> None:\n        \"\"\"Called when rejecting a candidate during backtracking.\"\"\"\n\n    def pinning(self, candidate: CT) -> None:\n        \"\"\"Called when adding a candidate to the potential solution.\"\"\"\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/resolvers/__init__.py",
    "content": "from ..structs import RequirementInformation\nfrom .abstract import AbstractResolver, Result\nfrom .criterion import Criterion\nfrom .exceptions import (\n    InconsistentCandidate,\n    RequirementsConflicted,\n    ResolutionError,\n    ResolutionImpossible,\n    ResolutionTooDeep,\n    ResolverException,\n)\nfrom .resolution import Resolution, Resolver\n\n__all__ = [\n    \"AbstractResolver\",\n    \"Criterion\",\n    \"InconsistentCandidate\",\n    \"RequirementInformation\",\n    \"RequirementsConflicted\",\n    \"Resolution\",\n    \"ResolutionError\",\n    \"ResolutionImpossible\",\n    \"ResolutionTooDeep\",\n    \"Resolver\",\n    \"ResolverException\",\n    \"Result\",\n]\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/resolvers/abstract.py",
    "content": "from __future__ import annotations\n\nimport collections\nfrom typing import TYPE_CHECKING, Any, Generic, Iterable, NamedTuple\n\nfrom ..structs import CT, KT, RT, DirectedGraph\n\nif TYPE_CHECKING:\n    from ..providers import AbstractProvider\n    from ..reporters import BaseReporter\n    from .criterion import Criterion\n\n    class Result(NamedTuple, Generic[RT, CT, KT]):\n        mapping: dict[KT, CT]\n        graph: DirectedGraph[KT | None]\n        criteria: dict[KT, Criterion[RT, CT]]\n\nelse:\n    Result = collections.namedtuple(\"Result\", [\"mapping\", \"graph\", \"criteria\"])\n\n\nclass AbstractResolver(Generic[RT, CT, KT]):\n    \"\"\"The thing that performs the actual resolution work.\"\"\"\n\n    base_exception = Exception\n\n    def __init__(\n        self,\n        provider: AbstractProvider[RT, CT, KT],\n        reporter: BaseReporter[RT, CT, KT],\n    ) -> None:\n        self.provider = provider\n        self.reporter = reporter\n\n    def resolve(self, requirements: Iterable[RT], **kwargs: Any) -> Result[RT, CT, KT]:\n        \"\"\"Take a collection of constraints, spit out the resolution result.\n\n        This returns a representation of the final resolution state, with one\n        guarenteed attribute ``mapping`` that contains resolved candidates as\n        values. The keys are their respective identifiers.\n\n        :param requirements: A collection of constraints.\n        :param kwargs: Additional keyword arguments that subclasses may accept.\n\n        :raises: ``self.base_exception`` or its subclass.\n        \"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/resolvers/criterion.py",
    "content": "from __future__ import annotations\n\nfrom typing import Collection, Generic, Iterable, Iterator\n\nfrom ..structs import CT, RT, RequirementInformation\n\n\nclass Criterion(Generic[RT, CT]):\n    \"\"\"Representation of possible resolution results of a package.\n\n    This holds three attributes:\n\n    * `information` is a collection of `RequirementInformation` pairs.\n      Each pair is a requirement contributing to this criterion, and the\n      candidate that provides the requirement.\n    * `incompatibilities` is a collection of all known not-to-work candidates\n      to exclude from consideration.\n    * `candidates` is a collection containing all possible candidates deducted\n      from the union of contributing requirements and known incompatibilities.\n      It should never be empty, except when the criterion is an attribute of a\n      raised `RequirementsConflicted` (in which case it is always empty).\n\n    .. note::\n        This class is intended to be externally immutable. **Do not** mutate\n        any of its attribute containers.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates: Iterable[CT],\n        information: Collection[RequirementInformation[RT, CT]],\n        incompatibilities: Collection[CT],\n    ) -> None:\n        self.candidates = candidates\n        self.information = information\n        self.incompatibilities = incompatibilities\n\n    def __repr__(self) -> str:\n        requirements = \", \".join(\n            f\"({req!r}, via={parent!r})\" for req, parent in self.information\n        )\n        return f\"Criterion({requirements})\"\n\n    def iter_requirement(self) -> Iterator[RT]:\n        return (i.requirement for i in self.information)\n\n    def iter_parent(self) -> Iterator[CT | None]:\n        return (i.parent for i in self.information)\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/resolvers/exceptions.py",
    "content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Collection, Generic\n\nfrom ..structs import CT, RT, RequirementInformation\n\nif TYPE_CHECKING:\n    from .criterion import Criterion\n\n\nclass ResolverException(Exception):\n    \"\"\"A base class for all exceptions raised by this module.\n\n    Exceptions derived by this class should all be handled in this module. Any\n    bubbling pass the resolver should be treated as a bug.\n    \"\"\"\n\n\nclass RequirementsConflicted(ResolverException, Generic[RT, CT]):\n    def __init__(self, criterion: Criterion[RT, CT]) -> None:\n        super().__init__(criterion)\n        self.criterion = criterion\n\n    def __str__(self) -> str:\n        return \"Requirements conflict: {}\".format(\n            \", \".join(repr(r) for r in self.criterion.iter_requirement()),\n        )\n\n\nclass InconsistentCandidate(ResolverException, Generic[RT, CT]):\n    def __init__(self, candidate: CT, criterion: Criterion[RT, CT]):\n        super().__init__(candidate, criterion)\n        self.candidate = candidate\n        self.criterion = criterion\n\n    def __str__(self) -> str:\n        return \"Provided candidate {!r} does not satisfy {}\".format(\n            self.candidate,\n            \", \".join(repr(r) for r in self.criterion.iter_requirement()),\n        )\n\n\nclass ResolutionError(ResolverException):\n    pass\n\n\nclass ResolutionImpossible(ResolutionError, Generic[RT, CT]):\n    def __init__(self, causes: Collection[RequirementInformation[RT, CT]]):\n        super().__init__(causes)\n        # causes is a list of RequirementInformation objects\n        self.causes = causes\n\n\nclass ResolutionTooDeep(ResolutionError):\n    def __init__(self, round_count: int) -> None:\n        super().__init__(round_count)\n        self.round_count = round_count\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/resolvers/resolution.py",
    "content": "from __future__ import annotations\n\nimport collections\nimport itertools\nimport operator\nfrom typing import TYPE_CHECKING, Generic\n\nfrom ..structs import (\n    CT,\n    KT,\n    RT,\n    DirectedGraph,\n    IterableView,\n    IteratorMapping,\n    RequirementInformation,\n    State,\n    build_iter_view,\n)\nfrom .abstract import AbstractResolver, Result\nfrom .criterion import Criterion\nfrom .exceptions import (\n    InconsistentCandidate,\n    RequirementsConflicted,\n    ResolutionImpossible,\n    ResolutionTooDeep,\n    ResolverException,\n)\n\nif TYPE_CHECKING:\n    from collections.abc import Collection, Iterable, Mapping\n\n    from ..providers import AbstractProvider, Preference\n    from ..reporters import BaseReporter\n\n_OPTIMISTIC_BACKJUMPING_RATIO: float = 0.1\n\n\ndef _build_result(state: State[RT, CT, KT]) -> Result[RT, CT, KT]:\n    mapping = state.mapping\n    all_keys: dict[int, KT | None] = {id(v): k for k, v in mapping.items()}\n    all_keys[id(None)] = None\n\n    graph: DirectedGraph[KT | None] = DirectedGraph()\n    graph.add(None)  # Sentinel as root dependencies' parent.\n\n    connected: set[KT | None] = {None}\n    for key, criterion in state.criteria.items():\n        if not _has_route_to_root(state.criteria, key, all_keys, connected):\n            continue\n        if key not in graph:\n            graph.add(key)\n        for p in criterion.iter_parent():\n            try:\n                pkey = all_keys[id(p)]\n            except KeyError:\n                continue\n            if pkey not in graph:\n                graph.add(pkey)\n            graph.connect(pkey, key)\n\n    return Result(\n        mapping={k: v for k, v in mapping.items() if k in connected},\n        graph=graph,\n        criteria=state.criteria,\n    )\n\n\nclass Resolution(Generic[RT, CT, KT]):\n    \"\"\"Stateful resolution object.\n\n    This is designed as a one-off object that holds information to kick start\n    the resolution process, and holds the results afterwards.\n    \"\"\"\n\n    def __init__(\n        self,\n        provider: AbstractProvider[RT, CT, KT],\n        reporter: BaseReporter[RT, CT, KT],\n    ) -> None:\n        self._p = provider\n        self._r = reporter\n        self._states: list[State[RT, CT, KT]] = []\n\n        # Optimistic backjumping variables\n        self._optimistic_backjumping_ratio = _OPTIMISTIC_BACKJUMPING_RATIO\n        self._save_states: list[State[RT, CT, KT]] | None = None\n        self._optimistic_start_round: int | None = None\n\n    @property\n    def state(self) -> State[RT, CT, KT]:\n        try:\n            return self._states[-1]\n        except IndexError as e:\n            raise AttributeError(\"state\") from e\n\n    def _push_new_state(self) -> None:\n        \"\"\"Push a new state into history.\n\n        This new state will be used to hold resolution results of the next\n        coming round.\n        \"\"\"\n        base = self._states[-1]\n        state = State(\n            mapping=base.mapping.copy(),\n            criteria=base.criteria.copy(),\n            backtrack_causes=base.backtrack_causes[:],\n        )\n        self._states.append(state)\n\n    def _add_to_criteria(\n        self,\n        criteria: dict[KT, Criterion[RT, CT]],\n        requirement: RT,\n        parent: CT | None,\n    ) -> None:\n        self._r.adding_requirement(requirement=requirement, parent=parent)\n\n        identifier = self._p.identify(requirement_or_candidate=requirement)\n        criterion = criteria.get(identifier)\n        if criterion:\n            incompatibilities = list(criterion.incompatibilities)\n        else:\n            incompatibilities = []\n\n        matches = self._p.find_matches(\n            identifier=identifier,\n            requirements=IteratorMapping(\n                criteria,\n                operator.methodcaller(\"iter_requirement\"),\n                {identifier: [requirement]},\n            ),\n            incompatibilities=IteratorMapping(\n                criteria,\n                operator.attrgetter(\"incompatibilities\"),\n                {identifier: incompatibilities},\n            ),\n        )\n\n        if criterion:\n            information = list(criterion.information)\n            information.append(RequirementInformation(requirement, parent))\n        else:\n            information = [RequirementInformation(requirement, parent)]\n\n        criterion = Criterion(\n            candidates=build_iter_view(matches),\n            information=information,\n            incompatibilities=incompatibilities,\n        )\n        if not criterion.candidates:\n            raise RequirementsConflicted(criterion)\n        criteria[identifier] = criterion\n\n    def _remove_information_from_criteria(\n        self, criteria: dict[KT, Criterion[RT, CT]], parents: Collection[KT]\n    ) -> None:\n        \"\"\"Remove information from parents of criteria.\n\n        Concretely, removes all values from each criterion's ``information``\n        field that have one of ``parents`` as provider of the requirement.\n\n        :param criteria: The criteria to update.\n        :param parents: Identifiers for which to remove information from all criteria.\n        \"\"\"\n        if not parents:\n            return\n        for key, criterion in criteria.items():\n            criteria[key] = Criterion(\n                criterion.candidates,\n                [\n                    information\n                    for information in criterion.information\n                    if (\n                        information.parent is None\n                        or self._p.identify(information.parent) not in parents\n                    )\n                ],\n                criterion.incompatibilities,\n            )\n\n    def _get_preference(self, name: KT) -> Preference:\n        return self._p.get_preference(\n            identifier=name,\n            resolutions=self.state.mapping,\n            candidates=IteratorMapping(\n                self.state.criteria,\n                operator.attrgetter(\"candidates\"),\n            ),\n            information=IteratorMapping(\n                self.state.criteria,\n                operator.attrgetter(\"information\"),\n            ),\n            backtrack_causes=self.state.backtrack_causes,\n        )\n\n    def _is_current_pin_satisfying(\n        self, name: KT, criterion: Criterion[RT, CT]\n    ) -> bool:\n        try:\n            current_pin = self.state.mapping[name]\n        except KeyError:\n            return False\n        return all(\n            self._p.is_satisfied_by(requirement=r, candidate=current_pin)\n            for r in criterion.iter_requirement()\n        )\n\n    def _get_updated_criteria(self, candidate: CT) -> dict[KT, Criterion[RT, CT]]:\n        criteria = self.state.criteria.copy()\n        for requirement in self._p.get_dependencies(candidate=candidate):\n            self._add_to_criteria(criteria, requirement, parent=candidate)\n        return criteria\n\n    def _attempt_to_pin_criterion(self, name: KT) -> list[Criterion[RT, CT]]:\n        criterion = self.state.criteria[name]\n\n        causes: list[Criterion[RT, CT]] = []\n        for candidate in criterion.candidates:\n            try:\n                criteria = self._get_updated_criteria(candidate)\n            except RequirementsConflicted as e:\n                self._r.rejecting_candidate(e.criterion, candidate)\n                causes.append(e.criterion)\n                continue\n\n            # Check the newly-pinned candidate actually works. This should\n            # always pass under normal circumstances, but in the case of a\n            # faulty provider, we will raise an error to notify the implementer\n            # to fix find_matches() and/or is_satisfied_by().\n            satisfied = all(\n                self._p.is_satisfied_by(requirement=r, candidate=candidate)\n                for r in criterion.iter_requirement()\n            )\n            if not satisfied:\n                raise InconsistentCandidate(candidate, criterion)\n\n            self._r.pinning(candidate=candidate)\n            self.state.criteria.update(criteria)\n\n            # Put newly-pinned candidate at the end. This is essential because\n            # backtracking looks at this mapping to get the last pin.\n            self.state.mapping.pop(name, None)\n            self.state.mapping[name] = candidate\n\n            return []\n\n        # All candidates tried, nothing works. This criterion is a dead\n        # end, signal for backtracking.\n        return causes\n\n    def _patch_criteria(\n        self, incompatibilities_from_broken: list[tuple[KT, list[CT]]]\n    ) -> bool:\n        # Create a new state from the last known-to-work one, and apply\n        # the previously gathered incompatibility information.\n        for k, incompatibilities in incompatibilities_from_broken:\n            if not incompatibilities:\n                continue\n            try:\n                criterion = self.state.criteria[k]\n            except KeyError:\n                continue\n            matches = self._p.find_matches(\n                identifier=k,\n                requirements=IteratorMapping(\n                    self.state.criteria,\n                    operator.methodcaller(\"iter_requirement\"),\n                ),\n                incompatibilities=IteratorMapping(\n                    self.state.criteria,\n                    operator.attrgetter(\"incompatibilities\"),\n                    {k: incompatibilities},\n                ),\n            )\n            candidates: IterableView[CT] = build_iter_view(matches)\n            if not candidates:\n                return False\n            incompatibilities.extend(criterion.incompatibilities)\n            self.state.criteria[k] = Criterion(\n                candidates=candidates,\n                information=list(criterion.information),\n                incompatibilities=incompatibilities,\n            )\n        return True\n\n    def _save_state(self) -> None:\n        \"\"\"Save states for potential rollback if optimistic backjumping fails.\"\"\"\n        if self._save_states is None:\n            self._save_states = [\n                State(\n                    mapping=s.mapping.copy(),\n                    criteria=s.criteria.copy(),\n                    backtrack_causes=s.backtrack_causes[:],\n                )\n                for s in self._states\n            ]\n\n    def _rollback_states(self) -> None:\n        \"\"\"Rollback states and disable optimistic backjumping.\"\"\"\n        self._optimistic_backjumping_ratio = 0.0\n        if self._save_states:\n            self._states = self._save_states\n            self._save_states = None\n\n    def _backjump(self, causes: list[RequirementInformation[RT, CT]]) -> bool:\n        \"\"\"Perform backjumping.\n\n        When we enter here, the stack is like this::\n\n            [ state Z ]\n            [ state Y ]\n            [ state X ]\n            .... earlier states are irrelevant.\n\n        1. No pins worked for Z, so it does not have a pin.\n        2. We want to reset state Y to unpinned, and pin another candidate.\n        3. State X holds what state Y was before the pin, but does not\n           have the incompatibility information gathered in state Y.\n\n        Each iteration of the loop will:\n\n        1.  Identify Z. The incompatibility is not always caused by the latest\n            state. For example, given three requirements A, B and C, with\n            dependencies A1, B1 and C1, where A1 and B1 are incompatible: the\n            last state might be related to C, so we want to discard the\n            previous state.\n        2.  Discard Z.\n        3.  Discard Y but remember its incompatibility information gathered\n            previously, and the failure we're dealing with right now.\n        4.  Push a new state Y' based on X, and apply the incompatibility\n            information from Y to Y'.\n        5a. If this causes Y' to conflict, we need to backtrack again. Make Y'\n            the new Z and go back to step 2.\n        5b. If the incompatibilities apply cleanly, end backtracking.\n        \"\"\"\n        incompatible_reqs: Iterable[CT | RT] = itertools.chain(\n            (c.parent for c in causes if c.parent is not None),\n            (c.requirement for c in causes),\n        )\n        incompatible_deps = {self._p.identify(r) for r in incompatible_reqs}\n        while len(self._states) >= 3:\n            # Remove the state that triggered backtracking.\n            del self._states[-1]\n\n            # Optimistically backtrack to a state that caused the incompatibility\n            broken_state = self.state\n            while True:\n                # Retrieve the last candidate pin and known incompatibilities.\n                try:\n                    broken_state = self._states.pop()\n                    name, candidate = broken_state.mapping.popitem()\n                except (IndexError, KeyError):\n                    raise ResolutionImpossible(causes) from None\n\n                if (\n                    not self._optimistic_backjumping_ratio\n                    and name not in incompatible_deps\n                ):\n                    # For safe backjumping only backjump if the current dependency\n                    # is not the same as the incompatible dependency\n                    break\n\n                # On the first time a non-safe backjump is done the state\n                # is saved so we can restore it later if the resolution fails\n                if (\n                    self._optimistic_backjumping_ratio\n                    and self._save_states is None\n                    and name not in incompatible_deps\n                ):\n                    self._save_state()\n\n                # If the current dependencies and the incompatible dependencies\n                # are overlapping then we have likely found a cause of the\n                # incompatibility\n                current_dependencies = {\n                    self._p.identify(d) for d in self._p.get_dependencies(candidate)\n                }\n                if not current_dependencies.isdisjoint(incompatible_deps):\n                    break\n\n                # Fallback: We should not backtrack to the point where\n                # broken_state.mapping is empty, so stop backtracking for\n                # a chance for the resolution to recover\n                if not broken_state.mapping:\n                    break\n\n                # Guard: We need at least two state to remain to both\n                # backtrack and push a new state\n                if len(self._states) <= 1:\n                    raise ResolutionImpossible(causes)\n\n            incompatibilities_from_broken = [\n                (k, list(v.incompatibilities)) for k, v in broken_state.criteria.items()\n            ]\n\n            # Also mark the newly known incompatibility.\n            incompatibilities_from_broken.append((name, [candidate]))\n\n            self._push_new_state()\n            success = self._patch_criteria(incompatibilities_from_broken)\n\n            # It works! Let's work on this new state.\n            if success:\n                return True\n\n            # State does not work after applying known incompatibilities.\n            # Try the still previous state.\n\n        # No way to backtrack anymore.\n        return False\n\n    def _extract_causes(\n        self, criteron: list[Criterion[RT, CT]]\n    ) -> list[RequirementInformation[RT, CT]]:\n        \"\"\"Extract causes from list of criterion and deduplicate\"\"\"\n        return list({id(i): i for c in criteron for i in c.information}.values())\n\n    def resolve(self, requirements: Iterable[RT], max_rounds: int) -> State[RT, CT, KT]:\n        if self._states:\n            raise RuntimeError(\"already resolved\")\n\n        self._r.starting()\n\n        # Initialize the root state.\n        self._states = [\n            State(\n                mapping=collections.OrderedDict(),\n                criteria={},\n                backtrack_causes=[],\n            )\n        ]\n        for r in requirements:\n            try:\n                self._add_to_criteria(self.state.criteria, r, parent=None)\n            except RequirementsConflicted as e:\n                raise ResolutionImpossible(e.criterion.information) from e\n\n        # The root state is saved as a sentinel so the first ever pin can have\n        # something to backtrack to if it fails. The root state is basically\n        # pinning the virtual \"root\" package in the graph.\n        self._push_new_state()\n\n        # Variables for optimistic backjumping\n        optimistic_rounds_cutoff: int | None = None\n        optimistic_backjumping_start_round: int | None = None\n\n        for round_index in range(max_rounds):\n            self._r.starting_round(index=round_index)\n\n            # Handle if optimistic backjumping has been running for too long\n            if self._optimistic_backjumping_ratio and self._save_states is not None:\n                if optimistic_backjumping_start_round is None:\n                    optimistic_backjumping_start_round = round_index\n                    optimistic_rounds_cutoff = int(\n                        (max_rounds - round_index) * self._optimistic_backjumping_ratio\n                    )\n\n                    if optimistic_rounds_cutoff <= 0:\n                        self._rollback_states()\n                        continue\n                elif optimistic_rounds_cutoff is not None:\n                    if (\n                        round_index - optimistic_backjumping_start_round\n                        >= optimistic_rounds_cutoff\n                    ):\n                        self._rollback_states()\n                        continue\n\n            unsatisfied_names = [\n                key\n                for key, criterion in self.state.criteria.items()\n                if not self._is_current_pin_satisfying(key, criterion)\n            ]\n\n            # All criteria are accounted for. Nothing more to pin, we are done!\n            if not unsatisfied_names:\n                self._r.ending(state=self.state)\n                return self.state\n\n            # keep track of satisfied names to calculate diff after pinning\n            satisfied_names = set(self.state.criteria.keys()) - set(unsatisfied_names)\n\n            if len(unsatisfied_names) > 1:\n                narrowed_unstatisfied_names = list(\n                    self._p.narrow_requirement_selection(\n                        identifiers=unsatisfied_names,\n                        resolutions=self.state.mapping,\n                        candidates=IteratorMapping(\n                            self.state.criteria,\n                            operator.attrgetter(\"candidates\"),\n                        ),\n                        information=IteratorMapping(\n                            self.state.criteria,\n                            operator.attrgetter(\"information\"),\n                        ),\n                        backtrack_causes=self.state.backtrack_causes,\n                    )\n                )\n            else:\n                narrowed_unstatisfied_names = unsatisfied_names\n\n            # If there are no unsatisfied names use unsatisfied names\n            if not narrowed_unstatisfied_names:\n                raise RuntimeError(\"narrow_requirement_selection returned 0 names\")\n\n            # If there is only 1 unsatisfied name skip calling self._get_preference\n            if len(narrowed_unstatisfied_names) > 1:\n                # Choose the most preferred unpinned criterion to try.\n                name = min(narrowed_unstatisfied_names, key=self._get_preference)\n            else:\n                name = narrowed_unstatisfied_names[0]\n\n            failure_criterion = self._attempt_to_pin_criterion(name)\n\n            if failure_criterion:\n                causes = self._extract_causes(failure_criterion)\n                # Backjump if pinning fails. The backjump process puts us in\n                # an unpinned state, so we can work on it in the next round.\n                self._r.resolving_conflicts(causes=causes)\n\n                try:\n                    success = self._backjump(causes)\n                except ResolutionImpossible:\n                    if self._optimistic_backjumping_ratio and self._save_states:\n                        failed_optimistic_backjumping = True\n                    else:\n                        raise\n                else:\n                    failed_optimistic_backjumping = bool(\n                        not success\n                        and self._optimistic_backjumping_ratio\n                        and self._save_states\n                    )\n\n                if failed_optimistic_backjumping and self._save_states:\n                    self._rollback_states()\n                else:\n                    self.state.backtrack_causes[:] = causes\n\n                    # Dead ends everywhere. Give up.\n                    if not success:\n                        raise ResolutionImpossible(self.state.backtrack_causes)\n            else:\n                # discard as information sources any invalidated names\n                # (unsatisfied names that were previously satisfied)\n                newly_unsatisfied_names = {\n                    key\n                    for key, criterion in self.state.criteria.items()\n                    if key in satisfied_names\n                    and not self._is_current_pin_satisfying(key, criterion)\n                }\n                self._remove_information_from_criteria(\n                    self.state.criteria, newly_unsatisfied_names\n                )\n                # Pinning was successful. Push a new state to do another pin.\n                self._push_new_state()\n\n            self._r.ending_round(index=round_index, state=self.state)\n\n        raise ResolutionTooDeep(max_rounds)\n\n\nclass Resolver(AbstractResolver[RT, CT, KT]):\n    \"\"\"The thing that performs the actual resolution work.\"\"\"\n\n    base_exception = ResolverException\n\n    def resolve(  # type: ignore[override]\n        self,\n        requirements: Iterable[RT],\n        max_rounds: int = 100,\n    ) -> Result[RT, CT, KT]:\n        \"\"\"Take a collection of constraints, spit out the resolution result.\n\n        The return value is a representation to the final resolution result. It\n        is a tuple subclass with three public members:\n\n        * `mapping`: A dict of resolved candidates. Each key is an identifier\n            of a requirement (as returned by the provider's `identify` method),\n            and the value is the resolved candidate.\n        * `graph`: A `DirectedGraph` instance representing the dependency tree.\n            The vertices are keys of `mapping`, and each edge represents *why*\n            a particular package is included. A special vertex `None` is\n            included to represent parents of user-supplied requirements.\n        * `criteria`: A dict of \"criteria\" that hold detailed information on\n            how edges in the graph are derived. Each key is an identifier of a\n            requirement, and the value is a `Criterion` instance.\n\n        The following exceptions may be raised if a resolution cannot be found:\n\n        * `ResolutionImpossible`: A resolution cannot be found for the given\n            combination of requirements. The `causes` attribute of the\n            exception is a list of (requirement, parent), giving the\n            requirements that could not be satisfied.\n        * `ResolutionTooDeep`: The dependency tree is too deeply nested and\n            the resolver gave up. This is usually caused by a circular\n            dependency, but you can try to resolve this by increasing the\n            `max_rounds` argument.\n        \"\"\"\n        resolution = Resolution(self.provider, self.reporter)\n        state = resolution.resolve(requirements, max_rounds=max_rounds)\n        return _build_result(state)\n\n\ndef _has_route_to_root(\n    criteria: Mapping[KT, Criterion[RT, CT]],\n    key: KT | None,\n    all_keys: dict[int, KT | None],\n    connected: set[KT | None],\n) -> bool:\n    if key in connected:\n        return True\n    if key not in criteria:\n        return False\n    assert key is not None\n    for p in criteria[key].iter_parent():\n        try:\n            pkey = all_keys[id(p)]\n        except KeyError:\n            continue\n        if pkey in connected:\n            connected.add(key)\n            return True\n        if _has_route_to_root(criteria, pkey, all_keys, connected):\n            connected.add(key)\n            return True\n    return False\n"
  },
  {
    "path": "src/pip/_vendor/resolvelib/structs.py",
    "content": "from __future__ import annotations\n\nimport itertools\nfrom collections import namedtuple\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Generic,\n    Iterable,\n    Iterator,\n    Mapping,\n    NamedTuple,\n    Sequence,\n    TypeVar,\n    Union,\n)\n\nKT = TypeVar(\"KT\")  # Identifier.\nRT = TypeVar(\"RT\")  # Requirement.\nCT = TypeVar(\"CT\")  # Candidate.\n\nMatches = Union[Iterable[CT], Callable[[], Iterable[CT]]]\n\nif TYPE_CHECKING:\n    from .resolvers.criterion import Criterion\n\n    class RequirementInformation(NamedTuple, Generic[RT, CT]):\n        requirement: RT\n        parent: CT | None\n\n    class State(NamedTuple, Generic[RT, CT, KT]):\n        \"\"\"Resolution state in a round.\"\"\"\n\n        mapping: dict[KT, CT]\n        criteria: dict[KT, Criterion[RT, CT]]\n        backtrack_causes: list[RequirementInformation[RT, CT]]\n\nelse:\n    RequirementInformation = namedtuple(\n        \"RequirementInformation\", [\"requirement\", \"parent\"]\n    )\n    State = namedtuple(\"State\", [\"mapping\", \"criteria\", \"backtrack_causes\"])\n\n\nclass DirectedGraph(Generic[KT]):\n    \"\"\"A graph structure with directed edges.\"\"\"\n\n    def __init__(self) -> None:\n        self._vertices: set[KT] = set()\n        self._forwards: dict[KT, set[KT]] = {}  # <key> -> Set[<key>]\n        self._backwards: dict[KT, set[KT]] = {}  # <key> -> Set[<key>]\n\n    def __iter__(self) -> Iterator[KT]:\n        return iter(self._vertices)\n\n    def __len__(self) -> int:\n        return len(self._vertices)\n\n    def __contains__(self, key: KT) -> bool:\n        return key in self._vertices\n\n    def copy(self) -> DirectedGraph[KT]:\n        \"\"\"Return a shallow copy of this graph.\"\"\"\n        other = type(self)()\n        other._vertices = set(self._vertices)\n        other._forwards = {k: set(v) for k, v in self._forwards.items()}\n        other._backwards = {k: set(v) for k, v in self._backwards.items()}\n        return other\n\n    def add(self, key: KT) -> None:\n        \"\"\"Add a new vertex to the graph.\"\"\"\n        if key in self._vertices:\n            raise ValueError(\"vertex exists\")\n        self._vertices.add(key)\n        self._forwards[key] = set()\n        self._backwards[key] = set()\n\n    def remove(self, key: KT) -> None:\n        \"\"\"Remove a vertex from the graph, disconnecting all edges from/to it.\"\"\"\n        self._vertices.remove(key)\n        for f in self._forwards.pop(key):\n            self._backwards[f].remove(key)\n        for t in self._backwards.pop(key):\n            self._forwards[t].remove(key)\n\n    def connected(self, f: KT, t: KT) -> bool:\n        return f in self._backwards[t] and t in self._forwards[f]\n\n    def connect(self, f: KT, t: KT) -> None:\n        \"\"\"Connect two existing vertices.\n\n        Nothing happens if the vertices are already connected.\n        \"\"\"\n        if t not in self._vertices:\n            raise KeyError(t)\n        self._forwards[f].add(t)\n        self._backwards[t].add(f)\n\n    def iter_edges(self) -> Iterator[tuple[KT, KT]]:\n        for f, children in self._forwards.items():\n            for t in children:\n                yield f, t\n\n    def iter_children(self, key: KT) -> Iterator[KT]:\n        return iter(self._forwards[key])\n\n    def iter_parents(self, key: KT) -> Iterator[KT]:\n        return iter(self._backwards[key])\n\n\nclass IteratorMapping(Mapping[KT, Iterator[CT]], Generic[RT, CT, KT]):\n    def __init__(\n        self,\n        mapping: Mapping[KT, RT],\n        accessor: Callable[[RT], Iterable[CT]],\n        appends: Mapping[KT, Iterable[CT]] | None = None,\n    ) -> None:\n        self._mapping = mapping\n        self._accessor = accessor\n        self._appends: Mapping[KT, Iterable[CT]] = appends or {}\n\n    def __repr__(self) -> str:\n        return \"IteratorMapping({!r}, {!r}, {!r})\".format(\n            self._mapping,\n            self._accessor,\n            self._appends,\n        )\n\n    def __bool__(self) -> bool:\n        return bool(self._mapping or self._appends)\n\n    def __contains__(self, key: object) -> bool:\n        return key in self._mapping or key in self._appends\n\n    def __getitem__(self, k: KT) -> Iterator[CT]:\n        try:\n            v = self._mapping[k]\n        except KeyError:\n            return iter(self._appends[k])\n        return itertools.chain(self._accessor(v), self._appends.get(k, ()))\n\n    def __iter__(self) -> Iterator[KT]:\n        more = (k for k in self._appends if k not in self._mapping)\n        return itertools.chain(self._mapping, more)\n\n    def __len__(self) -> int:\n        more = sum(1 for k in self._appends if k not in self._mapping)\n        return len(self._mapping) + more\n\n\nclass _FactoryIterableView(Iterable[RT]):\n    \"\"\"Wrap an iterator factory returned by `find_matches()`.\n\n    Calling `iter()` on this class would invoke the underlying iterator\n    factory, making it a \"collection with ordering\" that can be iterated\n    through multiple times, but lacks random access methods presented in\n    built-in Python sequence types.\n    \"\"\"\n\n    def __init__(self, factory: Callable[[], Iterable[RT]]) -> None:\n        self._factory = factory\n        self._iterable: Iterable[RT] | None = None\n\n    def __repr__(self) -> str:\n        return f\"{type(self).__name__}({list(self)})\"\n\n    def __bool__(self) -> bool:\n        try:\n            next(iter(self))\n        except StopIteration:\n            return False\n        return True\n\n    def __iter__(self) -> Iterator[RT]:\n        iterable = self._factory() if self._iterable is None else self._iterable\n        self._iterable, current = itertools.tee(iterable)\n        return current\n\n\nclass _SequenceIterableView(Iterable[RT]):\n    \"\"\"Wrap an iterable returned by find_matches().\n\n    This is essentially just a proxy to the underlying sequence that provides\n    the same interface as `_FactoryIterableView`.\n    \"\"\"\n\n    def __init__(self, sequence: Sequence[RT]):\n        self._sequence = sequence\n\n    def __repr__(self) -> str:\n        return f\"{type(self).__name__}({self._sequence})\"\n\n    def __bool__(self) -> bool:\n        return bool(self._sequence)\n\n    def __iter__(self) -> Iterator[RT]:\n        return iter(self._sequence)\n\n\ndef build_iter_view(matches: Matches[CT]) -> Iterable[CT]:\n    \"\"\"Build an iterable view from the value returned by `find_matches()`.\"\"\"\n    if callable(matches):\n        return _FactoryIterableView(matches)\n    if not isinstance(matches, Sequence):\n        matches = list(matches)\n    return _SequenceIterableView(matches)\n\n\nIterableView = Iterable\n"
  },
  {
    "path": "src/pip/_vendor/rich/LICENSE",
    "content": "Copyright (c) 2020 Will McGugan\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/rich/__init__.py",
    "content": "\"\"\"Rich text and beautiful formatting in the terminal.\"\"\"\n\nimport os\nfrom typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union\n\nfrom ._extension import load_ipython_extension  # noqa: F401\n\n__all__ = [\"get_console\", \"reconfigure\", \"print\", \"inspect\", \"print_json\"]\n\nif TYPE_CHECKING:\n    from .console import Console\n\n# Global console used by alternative print\n_console: Optional[\"Console\"] = None\n\ntry:\n    _IMPORT_CWD = os.path.abspath(os.getcwd())\nexcept FileNotFoundError:\n    # Can happen if the cwd has been deleted\n    _IMPORT_CWD = \"\"\n\n\ndef get_console() -> \"Console\":\n    \"\"\"Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,\n    and hasn't been explicitly given one.\n\n    Returns:\n        Console: A console instance.\n    \"\"\"\n    global _console\n    if _console is None:\n        from .console import Console\n\n        _console = Console()\n\n    return _console\n\n\ndef reconfigure(*args: Any, **kwargs: Any) -> None:\n    \"\"\"Reconfigures the global console by replacing it with another.\n\n    Args:\n        *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.\n        **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.\n    \"\"\"\n    from pip._vendor.rich.console import Console\n\n    new_console = Console(*args, **kwargs)\n    _console = get_console()\n    _console.__dict__ = new_console.__dict__\n\n\ndef print(\n    *objects: Any,\n    sep: str = \" \",\n    end: str = \"\\n\",\n    file: Optional[IO[str]] = None,\n    flush: bool = False,\n) -> None:\n    r\"\"\"Print object(s) supplied via positional arguments.\n    This function has an identical signature to the built-in print.\n    For more advanced features, see the :class:`~rich.console.Console` class.\n\n    Args:\n        sep (str, optional): Separator between printed objects. Defaults to \" \".\n        end (str, optional): Character to write at end of output. Defaults to \"\\\\n\".\n        file (IO[str], optional): File to write to, or None for stdout. Defaults to None.\n        flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.\n\n    \"\"\"\n    from .console import Console\n\n    write_console = get_console() if file is None else Console(file=file)\n    return write_console.print(*objects, sep=sep, end=end)\n\n\ndef print_json(\n    json: Optional[str] = None,\n    *,\n    data: Any = None,\n    indent: Union[None, int, str] = 2,\n    highlight: bool = True,\n    skip_keys: bool = False,\n    ensure_ascii: bool = False,\n    check_circular: bool = True,\n    allow_nan: bool = True,\n    default: Optional[Callable[[Any], Any]] = None,\n    sort_keys: bool = False,\n) -> None:\n    \"\"\"Pretty prints JSON. Output will be valid JSON.\n\n    Args:\n        json (str): A string containing JSON.\n        data (Any): If json is not supplied, then encode this data.\n        indent (int, optional): Number of spaces to indent. Defaults to 2.\n        highlight (bool, optional): Enable highlighting of output: Defaults to True.\n        skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n        ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n        check_circular (bool, optional): Check for circular references. Defaults to True.\n        allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n        default (Callable, optional): A callable that converts values that can not be encoded\n            in to something that can be JSON encoded. Defaults to None.\n        sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n    \"\"\"\n\n    get_console().print_json(\n        json,\n        data=data,\n        indent=indent,\n        highlight=highlight,\n        skip_keys=skip_keys,\n        ensure_ascii=ensure_ascii,\n        check_circular=check_circular,\n        allow_nan=allow_nan,\n        default=default,\n        sort_keys=sort_keys,\n    )\n\n\ndef inspect(\n    obj: Any,\n    *,\n    console: Optional[\"Console\"] = None,\n    title: Optional[str] = None,\n    help: bool = False,\n    methods: bool = False,\n    docs: bool = True,\n    private: bool = False,\n    dunder: bool = False,\n    sort: bool = True,\n    all: bool = False,\n    value: bool = True,\n) -> None:\n    \"\"\"Inspect any Python object.\n\n    * inspect(<OBJECT>) to see summarized info.\n    * inspect(<OBJECT>, methods=True) to see methods.\n    * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help.\n    * inspect(<OBJECT>, private=True) to see private attributes (single underscore).\n    * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore.\n    * inspect(<OBJECT>, all=True) to see all attributes.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value. Defaults to True.\n    \"\"\"\n    _console = console or get_console()\n    from pip._vendor.rich._inspect import Inspect\n\n    # Special case for inspect(inspect)\n    is_inspect = obj is inspect\n\n    _inspect = Inspect(\n        obj,\n        title=title,\n        help=is_inspect or help,\n        methods=is_inspect or methods,\n        docs=is_inspect or docs,\n        private=private,\n        dunder=dunder,\n        sort=sort,\n        all=all,\n        value=value,\n    )\n    _console.print(_inspect)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    print(\"Hello, **World**\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/__main__.py",
    "content": "import colorsys\nimport io\nfrom time import process_time\n\nfrom pip._vendor.rich import box\nfrom pip._vendor.rich.color import Color\nfrom pip._vendor.rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult\nfrom pip._vendor.rich.markdown import Markdown\nfrom pip._vendor.rich.measure import Measurement\nfrom pip._vendor.rich.pretty import Pretty\nfrom pip._vendor.rich.segment import Segment\nfrom pip._vendor.rich.style import Style\nfrom pip._vendor.rich.syntax import Syntax\nfrom pip._vendor.rich.table import Table\nfrom pip._vendor.rich.text import Text\n\n\nclass ColorBox:\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        for y in range(0, 5):\n            for x in range(options.max_width):\n                h = x / options.max_width\n                l = 0.1 + ((y / 5) * 0.7)\n                r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)\n                r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)\n                bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)\n                color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)\n                yield Segment(\"▄\", Style(color=color, bgcolor=bgcolor))\n            yield Segment.line()\n\n    def __rich_measure__(\n        self, console: \"Console\", options: ConsoleOptions\n    ) -> Measurement:\n        return Measurement(1, options.max_width)\n\n\ndef make_test_card() -> Table:\n    \"\"\"Get a renderable that demonstrates a number of features.\"\"\"\n    table = Table.grid(padding=1, pad_edge=True)\n    table.title = \"Rich features\"\n    table.add_column(\"Feature\", no_wrap=True, justify=\"center\", style=\"bold red\")\n    table.add_column(\"Demonstration\")\n\n    color_table = Table(\n        box=None,\n        expand=False,\n        show_header=False,\n        show_edge=False,\n        pad_edge=False,\n    )\n    color_table.add_row(\n        (\n            \"✓ [bold green]4-bit color[/]\\n\"\n            \"✓ [bold blue]8-bit color[/]\\n\"\n            \"✓ [bold magenta]Truecolor (16.7 million)[/]\\n\"\n            \"✓ [bold yellow]Dumb terminals[/]\\n\"\n            \"✓ [bold cyan]Automatic color conversion\"\n        ),\n        ColorBox(),\n    )\n\n    table.add_row(\"Colors\", color_table)\n\n    table.add_row(\n        \"Styles\",\n        \"All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].\",\n    )\n\n    lorem = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus.\"\n    lorem_table = Table.grid(padding=1, collapse_padding=True)\n    lorem_table.pad_edge = False\n    lorem_table.add_row(\n        Text(lorem, justify=\"left\", style=\"green\"),\n        Text(lorem, justify=\"center\", style=\"yellow\"),\n        Text(lorem, justify=\"right\", style=\"blue\"),\n        Text(lorem, justify=\"full\", style=\"red\"),\n    )\n    table.add_row(\n        \"Text\",\n        Group(\n            Text.from_markup(\n                \"\"\"Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\\n\"\"\"\n            ),\n            lorem_table,\n        ),\n    )\n\n    def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:\n        table = Table(show_header=False, pad_edge=False, box=None, expand=True)\n        table.add_column(\"1\", ratio=1)\n        table.add_column(\"2\", ratio=1)\n        table.add_row(renderable1, renderable2)\n        return table\n\n    table.add_row(\n        \"Asian\\nlanguage\\nsupport\",\n        \":flag_for_china:  该库支持中文，日文和韩文文本！\\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다\",\n    )\n\n    markup_example = (\n        \"[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! \"\n        \":+1: :apple: :ant: :bear: :baguette_bread: :bus: \"\n    )\n    table.add_row(\"Markup\", markup_example)\n\n    example_table = Table(\n        show_edge=False,\n        show_header=True,\n        expand=False,\n        row_styles=[\"none\", \"dim\"],\n        box=box.SIMPLE,\n    )\n    example_table.add_column(\"[green]Date\", style=\"green\", no_wrap=True)\n    example_table.add_column(\"[blue]Title\", style=\"blue\")\n    example_table.add_column(\n        \"[cyan]Production Budget\",\n        style=\"cyan\",\n        justify=\"right\",\n        no_wrap=True,\n    )\n    example_table.add_column(\n        \"[magenta]Box Office\",\n        style=\"magenta\",\n        justify=\"right\",\n        no_wrap=True,\n    )\n    example_table.add_row(\n        \"Dec 20, 2019\",\n        \"Star Wars: The Rise of Skywalker\",\n        \"$275,000,000\",\n        \"$375,126,118\",\n    )\n    example_table.add_row(\n        \"May 25, 2018\",\n        \"[b]Solo[/]: A Star Wars Story\",\n        \"$275,000,000\",\n        \"$393,151,347\",\n    )\n    example_table.add_row(\n        \"Dec 15, 2017\",\n        \"Star Wars Ep. VIII: The Last Jedi\",\n        \"$262,000,000\",\n        \"[bold]$1,332,539,889[/bold]\",\n    )\n    example_table.add_row(\n        \"May 19, 1999\",\n        \"Star Wars Ep. [b]I[/b]: [i]The phantom Menace\",\n        \"$115,000,000\",\n        \"$1,027,044,677\",\n    )\n\n    table.add_row(\"Tables\", example_table)\n\n    code = '''\\\ndef iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value'''\n\n    pretty_data = {\n        \"foo\": [\n            3.1427,\n            (\n                \"Paul Atreides\",\n                \"Vladimir Harkonnen\",\n                \"Thufir Hawat\",\n            ),\n        ],\n        \"atomic\": (False, True, None),\n    }\n    table.add_row(\n        \"Syntax\\nhighlighting\\n&\\npretty\\nprinting\",\n        comparison(\n            Syntax(code, \"python3\", line_numbers=True, indent_guides=True),\n            Pretty(pretty_data, indent_guides=True),\n        ),\n    )\n\n    markdown_example = \"\"\"\\\n# Markdown\n\nSupports much of the *markdown* __syntax__!\n\n- Headers\n- Basic formatting: **bold**, *italic*, `code`\n- Block quotes\n- Lists, and more...\n    \"\"\"\n    table.add_row(\n        \"Markdown\", comparison(\"[cyan]\" + markdown_example, Markdown(markdown_example))\n    )\n\n    table.add_row(\n        \"+more!\",\n        \"\"\"Progress bars, columns, styled logging handler, tracebacks, etc...\"\"\",\n    )\n    return table\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.panel import Panel\n\n    console = Console(\n        file=io.StringIO(),\n        force_terminal=True,\n    )\n    test_card = make_test_card()\n\n    # Print once to warm cache\n    start = process_time()\n    console.print(test_card)\n    pre_cache_taken = round((process_time() - start) * 1000.0, 1)\n\n    console.file = io.StringIO()\n\n    start = process_time()\n    console.print(test_card)\n    taken = round((process_time() - start) * 1000.0, 1)\n\n    c = Console(record=True)\n    c.print(test_card)\n\n    console = Console()\n    console.print(f\"[dim]rendered in [not dim]{pre_cache_taken}ms[/] (cold cache)\")\n    console.print(f\"[dim]rendered in [not dim]{taken}ms[/] (warm cache)\")\n    console.print()\n    console.print(\n        Panel.fit(\n            \"[b magenta]Hope you enjoy using Rich![/]\\n\\n\"\n            \"Please consider sponsoring me if you get value from my work.\\n\\n\"\n            \"Even the price of a ☕ can brighten my day!\\n\\n\"\n            \"https://github.com/sponsors/willmcgugan\",\n            border_style=\"red\",\n            title=\"Help ensure Rich is maintained\",\n        )\n    )\n"
  },
  {
    "path": "src/pip/_vendor/rich/_cell_widths.py",
    "content": "# Auto generated by make_terminal_widths.py\n\nCELL_WIDTHS = [\n    (0, 0, 0),\n    (1, 31, -1),\n    (127, 159, -1),\n    (173, 173, 0),\n    (768, 879, 0),\n    (1155, 1161, 0),\n    (1425, 1469, 0),\n    (1471, 1471, 0),\n    (1473, 1474, 0),\n    (1476, 1477, 0),\n    (1479, 1479, 0),\n    (1536, 1541, 0),\n    (1552, 1562, 0),\n    (1564, 1564, 0),\n    (1611, 1631, 0),\n    (1648, 1648, 0),\n    (1750, 1757, 0),\n    (1759, 1764, 0),\n    (1767, 1768, 0),\n    (1770, 1773, 0),\n    (1807, 1807, 0),\n    (1809, 1809, 0),\n    (1840, 1866, 0),\n    (1958, 1968, 0),\n    (2027, 2035, 0),\n    (2045, 2045, 0),\n    (2070, 2073, 0),\n    (2075, 2083, 0),\n    (2085, 2087, 0),\n    (2089, 2093, 0),\n    (2137, 2139, 0),\n    (2192, 2193, 0),\n    (2200, 2207, 0),\n    (2250, 2307, 0),\n    (2362, 2364, 0),\n    (2366, 2383, 0),\n    (2385, 2391, 0),\n    (2402, 2403, 0),\n    (2433, 2435, 0),\n    (2492, 2492, 0),\n    (2494, 2500, 0),\n    (2503, 2504, 0),\n    (2507, 2509, 0),\n    (2519, 2519, 0),\n    (2530, 2531, 0),\n    (2558, 2558, 0),\n    (2561, 2563, 0),\n    (2620, 2620, 0),\n    (2622, 2626, 0),\n    (2631, 2632, 0),\n    (2635, 2637, 0),\n    (2641, 2641, 0),\n    (2672, 2673, 0),\n    (2677, 2677, 0),\n    (2689, 2691, 0),\n    (2748, 2748, 0),\n    (2750, 2757, 0),\n    (2759, 2761, 0),\n    (2763, 2765, 0),\n    (2786, 2787, 0),\n    (2810, 2815, 0),\n    (2817, 2819, 0),\n    (2876, 2876, 0),\n    (2878, 2884, 0),\n    (2887, 2888, 0),\n    (2891, 2893, 0),\n    (2901, 2903, 0),\n    (2914, 2915, 0),\n    (2946, 2946, 0),\n    (3006, 3010, 0),\n    (3014, 3016, 0),\n    (3018, 3021, 0),\n    (3031, 3031, 0),\n    (3072, 3076, 0),\n    (3132, 3132, 0),\n    (3134, 3140, 0),\n    (3142, 3144, 0),\n    (3146, 3149, 0),\n    (3157, 3158, 0),\n    (3170, 3171, 0),\n    (3201, 3203, 0),\n    (3260, 3260, 0),\n    (3262, 3268, 0),\n    (3270, 3272, 0),\n    (3274, 3277, 0),\n    (3285, 3286, 0),\n    (3298, 3299, 0),\n    (3315, 3315, 0),\n    (3328, 3331, 0),\n    (3387, 3388, 0),\n    (3390, 3396, 0),\n    (3398, 3400, 0),\n    (3402, 3405, 0),\n    (3415, 3415, 0),\n    (3426, 3427, 0),\n    (3457, 3459, 0),\n    (3530, 3530, 0),\n    (3535, 3540, 0),\n    (3542, 3542, 0),\n    (3544, 3551, 0),\n    (3570, 3571, 0),\n    (3633, 3633, 0),\n    (3636, 3642, 0),\n    (3655, 3662, 0),\n    (3761, 3761, 0),\n    (3764, 3772, 0),\n    (3784, 3790, 0),\n    (3864, 3865, 0),\n    (3893, 3893, 0),\n    (3895, 3895, 0),\n    (3897, 3897, 0),\n    (3902, 3903, 0),\n    (3953, 3972, 0),\n    (3974, 3975, 0),\n    (3981, 3991, 0),\n    (3993, 4028, 0),\n    (4038, 4038, 0),\n    (4139, 4158, 0),\n    (4182, 4185, 0),\n    (4190, 4192, 0),\n    (4194, 4196, 0),\n    (4199, 4205, 0),\n    (4209, 4212, 0),\n    (4226, 4237, 0),\n    (4239, 4239, 0),\n    (4250, 4253, 0),\n    (4352, 4447, 2),\n    (4448, 4607, 0),\n    (4957, 4959, 0),\n    (5906, 5909, 0),\n    (5938, 5940, 0),\n    (5970, 5971, 0),\n    (6002, 6003, 0),\n    (6068, 6099, 0),\n    (6109, 6109, 0),\n    (6155, 6159, 0),\n    (6277, 6278, 0),\n    (6313, 6313, 0),\n    (6432, 6443, 0),\n    (6448, 6459, 0),\n    (6679, 6683, 0),\n    (6741, 6750, 0),\n    (6752, 6780, 0),\n    (6783, 6783, 0),\n    (6832, 6862, 0),\n    (6912, 6916, 0),\n    (6964, 6980, 0),\n    (7019, 7027, 0),\n    (7040, 7042, 0),\n    (7073, 7085, 0),\n    (7142, 7155, 0),\n    (7204, 7223, 0),\n    (7376, 7378, 0),\n    (7380, 7400, 0),\n    (7405, 7405, 0),\n    (7412, 7412, 0),\n    (7415, 7417, 0),\n    (7616, 7679, 0),\n    (8203, 8207, 0),\n    (8232, 8238, 0),\n    (8288, 8292, 0),\n    (8294, 8303, 0),\n    (8400, 8432, 0),\n    (8986, 8987, 2),\n    (9001, 9002, 2),\n    (9193, 9196, 2),\n    (9200, 9200, 2),\n    (9203, 9203, 2),\n    (9725, 9726, 2),\n    (9748, 9749, 2),\n    (9800, 9811, 2),\n    (9855, 9855, 2),\n    (9875, 9875, 2),\n    (9889, 9889, 2),\n    (9898, 9899, 2),\n    (9917, 9918, 2),\n    (9924, 9925, 2),\n    (9934, 9934, 2),\n    (9940, 9940, 2),\n    (9962, 9962, 2),\n    (9970, 9971, 2),\n    (9973, 9973, 2),\n    (9978, 9978, 2),\n    (9981, 9981, 2),\n    (9989, 9989, 2),\n    (9994, 9995, 2),\n    (10024, 10024, 2),\n    (10060, 10060, 2),\n    (10062, 10062, 2),\n    (10067, 10069, 2),\n    (10071, 10071, 2),\n    (10133, 10135, 2),\n    (10160, 10160, 2),\n    (10175, 10175, 2),\n    (11035, 11036, 2),\n    (11088, 11088, 2),\n    (11093, 11093, 2),\n    (11503, 11505, 0),\n    (11647, 11647, 0),\n    (11744, 11775, 0),\n    (11904, 11929, 2),\n    (11931, 12019, 2),\n    (12032, 12245, 2),\n    (12272, 12329, 2),\n    (12330, 12335, 0),\n    (12336, 12350, 2),\n    (12353, 12438, 2),\n    (12441, 12442, 0),\n    (12443, 12543, 2),\n    (12549, 12591, 2),\n    (12593, 12686, 2),\n    (12688, 12771, 2),\n    (12783, 12830, 2),\n    (12832, 12871, 2),\n    (12880, 19903, 2),\n    (19968, 42124, 2),\n    (42128, 42182, 2),\n    (42607, 42610, 0),\n    (42612, 42621, 0),\n    (42654, 42655, 0),\n    (42736, 42737, 0),\n    (43010, 43010, 0),\n    (43014, 43014, 0),\n    (43019, 43019, 0),\n    (43043, 43047, 0),\n    (43052, 43052, 0),\n    (43136, 43137, 0),\n    (43188, 43205, 0),\n    (43232, 43249, 0),\n    (43263, 43263, 0),\n    (43302, 43309, 0),\n    (43335, 43347, 0),\n    (43360, 43388, 2),\n    (43392, 43395, 0),\n    (43443, 43456, 0),\n    (43493, 43493, 0),\n    (43561, 43574, 0),\n    (43587, 43587, 0),\n    (43596, 43597, 0),\n    (43643, 43645, 0),\n    (43696, 43696, 0),\n    (43698, 43700, 0),\n    (43703, 43704, 0),\n    (43710, 43711, 0),\n    (43713, 43713, 0),\n    (43755, 43759, 0),\n    (43765, 43766, 0),\n    (44003, 44010, 0),\n    (44012, 44013, 0),\n    (44032, 55203, 2),\n    (55216, 55295, 0),\n    (63744, 64255, 2),\n    (64286, 64286, 0),\n    (65024, 65039, 0),\n    (65040, 65049, 2),\n    (65056, 65071, 0),\n    (65072, 65106, 2),\n    (65108, 65126, 2),\n    (65128, 65131, 2),\n    (65279, 65279, 0),\n    (65281, 65376, 2),\n    (65504, 65510, 2),\n    (65529, 65531, 0),\n    (66045, 66045, 0),\n    (66272, 66272, 0),\n    (66422, 66426, 0),\n    (68097, 68099, 0),\n    (68101, 68102, 0),\n    (68108, 68111, 0),\n    (68152, 68154, 0),\n    (68159, 68159, 0),\n    (68325, 68326, 0),\n    (68900, 68903, 0),\n    (69291, 69292, 0),\n    (69373, 69375, 0),\n    (69446, 69456, 0),\n    (69506, 69509, 0),\n    (69632, 69634, 0),\n    (69688, 69702, 0),\n    (69744, 69744, 0),\n    (69747, 69748, 0),\n    (69759, 69762, 0),\n    (69808, 69818, 0),\n    (69821, 69821, 0),\n    (69826, 69826, 0),\n    (69837, 69837, 0),\n    (69888, 69890, 0),\n    (69927, 69940, 0),\n    (69957, 69958, 0),\n    (70003, 70003, 0),\n    (70016, 70018, 0),\n    (70067, 70080, 0),\n    (70089, 70092, 0),\n    (70094, 70095, 0),\n    (70188, 70199, 0),\n    (70206, 70206, 0),\n    (70209, 70209, 0),\n    (70367, 70378, 0),\n    (70400, 70403, 0),\n    (70459, 70460, 0),\n    (70462, 70468, 0),\n    (70471, 70472, 0),\n    (70475, 70477, 0),\n    (70487, 70487, 0),\n    (70498, 70499, 0),\n    (70502, 70508, 0),\n    (70512, 70516, 0),\n    (70709, 70726, 0),\n    (70750, 70750, 0),\n    (70832, 70851, 0),\n    (71087, 71093, 0),\n    (71096, 71104, 0),\n    (71132, 71133, 0),\n    (71216, 71232, 0),\n    (71339, 71351, 0),\n    (71453, 71467, 0),\n    (71724, 71738, 0),\n    (71984, 71989, 0),\n    (71991, 71992, 0),\n    (71995, 71998, 0),\n    (72000, 72000, 0),\n    (72002, 72003, 0),\n    (72145, 72151, 0),\n    (72154, 72160, 0),\n    (72164, 72164, 0),\n    (72193, 72202, 0),\n    (72243, 72249, 0),\n    (72251, 72254, 0),\n    (72263, 72263, 0),\n    (72273, 72283, 0),\n    (72330, 72345, 0),\n    (72751, 72758, 0),\n    (72760, 72767, 0),\n    (72850, 72871, 0),\n    (72873, 72886, 0),\n    (73009, 73014, 0),\n    (73018, 73018, 0),\n    (73020, 73021, 0),\n    (73023, 73029, 0),\n    (73031, 73031, 0),\n    (73098, 73102, 0),\n    (73104, 73105, 0),\n    (73107, 73111, 0),\n    (73459, 73462, 0),\n    (73472, 73473, 0),\n    (73475, 73475, 0),\n    (73524, 73530, 0),\n    (73534, 73538, 0),\n    (78896, 78912, 0),\n    (78919, 78933, 0),\n    (92912, 92916, 0),\n    (92976, 92982, 0),\n    (94031, 94031, 0),\n    (94033, 94087, 0),\n    (94095, 94098, 0),\n    (94176, 94179, 2),\n    (94180, 94180, 0),\n    (94192, 94193, 0),\n    (94208, 100343, 2),\n    (100352, 101589, 2),\n    (101632, 101640, 2),\n    (110576, 110579, 2),\n    (110581, 110587, 2),\n    (110589, 110590, 2),\n    (110592, 110882, 2),\n    (110898, 110898, 2),\n    (110928, 110930, 2),\n    (110933, 110933, 2),\n    (110948, 110951, 2),\n    (110960, 111355, 2),\n    (113821, 113822, 0),\n    (113824, 113827, 0),\n    (118528, 118573, 0),\n    (118576, 118598, 0),\n    (119141, 119145, 0),\n    (119149, 119170, 0),\n    (119173, 119179, 0),\n    (119210, 119213, 0),\n    (119362, 119364, 0),\n    (121344, 121398, 0),\n    (121403, 121452, 0),\n    (121461, 121461, 0),\n    (121476, 121476, 0),\n    (121499, 121503, 0),\n    (121505, 121519, 0),\n    (122880, 122886, 0),\n    (122888, 122904, 0),\n    (122907, 122913, 0),\n    (122915, 122916, 0),\n    (122918, 122922, 0),\n    (123023, 123023, 0),\n    (123184, 123190, 0),\n    (123566, 123566, 0),\n    (123628, 123631, 0),\n    (124140, 124143, 0),\n    (125136, 125142, 0),\n    (125252, 125258, 0),\n    (126980, 126980, 2),\n    (127183, 127183, 2),\n    (127374, 127374, 2),\n    (127377, 127386, 2),\n    (127488, 127490, 2),\n    (127504, 127547, 2),\n    (127552, 127560, 2),\n    (127568, 127569, 2),\n    (127584, 127589, 2),\n    (127744, 127776, 2),\n    (127789, 127797, 2),\n    (127799, 127868, 2),\n    (127870, 127891, 2),\n    (127904, 127946, 2),\n    (127951, 127955, 2),\n    (127968, 127984, 2),\n    (127988, 127988, 2),\n    (127992, 127994, 2),\n    (127995, 127999, 0),\n    (128000, 128062, 2),\n    (128064, 128064, 2),\n    (128066, 128252, 2),\n    (128255, 128317, 2),\n    (128331, 128334, 2),\n    (128336, 128359, 2),\n    (128378, 128378, 2),\n    (128405, 128406, 2),\n    (128420, 128420, 2),\n    (128507, 128591, 2),\n    (128640, 128709, 2),\n    (128716, 128716, 2),\n    (128720, 128722, 2),\n    (128725, 128727, 2),\n    (128732, 128735, 2),\n    (128747, 128748, 2),\n    (128756, 128764, 2),\n    (128992, 129003, 2),\n    (129008, 129008, 2),\n    (129292, 129338, 2),\n    (129340, 129349, 2),\n    (129351, 129535, 2),\n    (129648, 129660, 2),\n    (129664, 129672, 2),\n    (129680, 129725, 2),\n    (129727, 129733, 2),\n    (129742, 129755, 2),\n    (129760, 129768, 2),\n    (129776, 129784, 2),\n    (131072, 196605, 2),\n    (196608, 262141, 2),\n    (917505, 917505, 0),\n    (917536, 917631, 0),\n    (917760, 917999, 0),\n]\n"
  },
  {
    "path": "src/pip/_vendor/rich/_emoji_codes.py",
    "content": "EMOJI = {\n    \"1st_place_medal\": \"🥇\",\n    \"2nd_place_medal\": \"🥈\",\n    \"3rd_place_medal\": \"🥉\",\n    \"ab_button_(blood_type)\": \"🆎\",\n    \"atm_sign\": \"🏧\",\n    \"a_button_(blood_type)\": \"🅰\",\n    \"afghanistan\": \"🇦🇫\",\n    \"albania\": \"🇦🇱\",\n    \"algeria\": \"🇩🇿\",\n    \"american_samoa\": \"🇦🇸\",\n    \"andorra\": \"🇦🇩\",\n    \"angola\": \"🇦🇴\",\n    \"anguilla\": \"🇦🇮\",\n    \"antarctica\": \"🇦🇶\",\n    \"antigua_&_barbuda\": \"🇦🇬\",\n    \"aquarius\": \"♒\",\n    \"argentina\": \"🇦🇷\",\n    \"aries\": \"♈\",\n    \"armenia\": \"🇦🇲\",\n    \"aruba\": \"🇦🇼\",\n    \"ascension_island\": \"🇦🇨\",\n    \"australia\": \"🇦🇺\",\n    \"austria\": \"🇦🇹\",\n    \"azerbaijan\": \"🇦🇿\",\n    \"back_arrow\": \"🔙\",\n    \"b_button_(blood_type)\": \"🅱\",\n    \"bahamas\": \"🇧🇸\",\n    \"bahrain\": \"🇧🇭\",\n    \"bangladesh\": \"🇧🇩\",\n    \"barbados\": \"🇧🇧\",\n    \"belarus\": \"🇧🇾\",\n    \"belgium\": \"🇧🇪\",\n    \"belize\": \"🇧🇿\",\n    \"benin\": \"🇧🇯\",\n    \"bermuda\": \"🇧🇲\",\n    \"bhutan\": \"🇧🇹\",\n    \"bolivia\": \"🇧🇴\",\n    \"bosnia_&_herzegovina\": \"🇧🇦\",\n    \"botswana\": \"🇧🇼\",\n    \"bouvet_island\": \"🇧🇻\",\n    \"brazil\": \"🇧🇷\",\n    \"british_indian_ocean_territory\": \"🇮🇴\",\n    \"british_virgin_islands\": \"🇻🇬\",\n    \"brunei\": \"🇧🇳\",\n    \"bulgaria\": \"🇧🇬\",\n    \"burkina_faso\": \"🇧🇫\",\n    \"burundi\": \"🇧🇮\",\n    \"cl_button\": \"🆑\",\n    \"cool_button\": \"🆒\",\n    \"cambodia\": \"🇰🇭\",\n    \"cameroon\": \"🇨🇲\",\n    \"canada\": \"🇨🇦\",\n    \"canary_islands\": \"🇮🇨\",\n    \"cancer\": \"♋\",\n    \"cape_verde\": \"🇨🇻\",\n    \"capricorn\": \"♑\",\n    \"caribbean_netherlands\": \"🇧🇶\",\n    \"cayman_islands\": \"🇰🇾\",\n    \"central_african_republic\": \"🇨🇫\",\n    \"ceuta_&_melilla\": \"🇪🇦\",\n    \"chad\": \"🇹🇩\",\n    \"chile\": \"🇨🇱\",\n    \"china\": \"🇨🇳\",\n    \"christmas_island\": \"🇨🇽\",\n    \"christmas_tree\": \"🎄\",\n    \"clipperton_island\": \"🇨🇵\",\n    \"cocos_(keeling)_islands\": \"🇨🇨\",\n    \"colombia\": \"🇨🇴\",\n    \"comoros\": \"🇰🇲\",\n    \"congo_-_brazzaville\": \"🇨🇬\",\n    \"congo_-_kinshasa\": \"🇨🇩\",\n    \"cook_islands\": \"🇨🇰\",\n    \"costa_rica\": \"🇨🇷\",\n    \"croatia\": \"🇭🇷\",\n    \"cuba\": \"🇨🇺\",\n    \"curaçao\": \"🇨🇼\",\n    \"cyprus\": \"🇨🇾\",\n    \"czechia\": \"🇨🇿\",\n    \"côte_d’ivoire\": \"🇨🇮\",\n    \"denmark\": \"🇩🇰\",\n    \"diego_garcia\": \"🇩🇬\",\n    \"djibouti\": \"🇩🇯\",\n    \"dominica\": \"🇩🇲\",\n    \"dominican_republic\": \"🇩🇴\",\n    \"end_arrow\": \"🔚\",\n    \"ecuador\": \"🇪🇨\",\n    \"egypt\": \"🇪🇬\",\n    \"el_salvador\": \"🇸🇻\",\n    \"england\": \"🏴\\U000e0067\\U000e0062\\U000e0065\\U000e006e\\U000e0067\\U000e007f\",\n    \"equatorial_guinea\": \"🇬🇶\",\n    \"eritrea\": \"🇪🇷\",\n    \"estonia\": \"🇪🇪\",\n    \"ethiopia\": \"🇪🇹\",\n    \"european_union\": \"🇪🇺\",\n    \"free_button\": \"🆓\",\n    \"falkland_islands\": \"🇫🇰\",\n    \"faroe_islands\": \"🇫🇴\",\n    \"fiji\": \"🇫🇯\",\n    \"finland\": \"🇫🇮\",\n    \"france\": \"🇫🇷\",\n    \"french_guiana\": \"🇬🇫\",\n    \"french_polynesia\": \"🇵🇫\",\n    \"french_southern_territories\": \"🇹🇫\",\n    \"gabon\": \"🇬🇦\",\n    \"gambia\": \"🇬🇲\",\n    \"gemini\": \"♊\",\n    \"georgia\": \"🇬🇪\",\n    \"germany\": \"🇩🇪\",\n    \"ghana\": \"🇬🇭\",\n    \"gibraltar\": \"🇬🇮\",\n    \"greece\": \"🇬🇷\",\n    \"greenland\": \"🇬🇱\",\n    \"grenada\": \"🇬🇩\",\n    \"guadeloupe\": \"🇬🇵\",\n    \"guam\": \"🇬🇺\",\n    \"guatemala\": \"🇬🇹\",\n    \"guernsey\": \"🇬🇬\",\n    \"guinea\": \"🇬🇳\",\n    \"guinea-bissau\": \"🇬🇼\",\n    \"guyana\": \"🇬🇾\",\n    \"haiti\": \"🇭🇹\",\n    \"heard_&_mcdonald_islands\": \"🇭🇲\",\n    \"honduras\": \"🇭🇳\",\n    \"hong_kong_sar_china\": \"🇭🇰\",\n    \"hungary\": \"🇭🇺\",\n    \"id_button\": \"🆔\",\n    \"iceland\": \"🇮🇸\",\n    \"india\": \"🇮🇳\",\n    \"indonesia\": \"🇮🇩\",\n    \"iran\": \"🇮🇷\",\n    \"iraq\": \"🇮🇶\",\n    \"ireland\": \"🇮🇪\",\n    \"isle_of_man\": \"🇮🇲\",\n    \"israel\": \"🇮🇱\",\n    \"italy\": \"🇮🇹\",\n    \"jamaica\": \"🇯🇲\",\n    \"japan\": \"🗾\",\n    \"japanese_acceptable_button\": \"🉑\",\n    \"japanese_application_button\": \"🈸\",\n    \"japanese_bargain_button\": \"🉐\",\n    \"japanese_castle\": \"🏯\",\n    \"japanese_congratulations_button\": \"㊗\",\n    \"japanese_discount_button\": \"🈹\",\n    \"japanese_dolls\": \"🎎\",\n    \"japanese_free_of_charge_button\": \"🈚\",\n    \"japanese_here_button\": \"🈁\",\n    \"japanese_monthly_amount_button\": \"🈷\",\n    \"japanese_no_vacancy_button\": \"🈵\",\n    \"japanese_not_free_of_charge_button\": \"🈶\",\n    \"japanese_open_for_business_button\": \"🈺\",\n    \"japanese_passing_grade_button\": \"🈴\",\n    \"japanese_post_office\": \"🏣\",\n    \"japanese_prohibited_button\": \"🈲\",\n    \"japanese_reserved_button\": \"🈯\",\n    \"japanese_secret_button\": \"㊙\",\n    \"japanese_service_charge_button\": \"🈂\",\n    \"japanese_symbol_for_beginner\": \"🔰\",\n    \"japanese_vacancy_button\": \"🈳\",\n    \"jersey\": \"🇯🇪\",\n    \"jordan\": \"🇯🇴\",\n    \"kazakhstan\": \"🇰🇿\",\n    \"kenya\": \"🇰🇪\",\n    \"kiribati\": \"🇰🇮\",\n    \"kosovo\": \"🇽🇰\",\n    \"kuwait\": \"🇰🇼\",\n    \"kyrgyzstan\": \"🇰🇬\",\n    \"laos\": \"🇱🇦\",\n    \"latvia\": \"🇱🇻\",\n    \"lebanon\": \"🇱🇧\",\n    \"leo\": \"♌\",\n    \"lesotho\": \"🇱🇸\",\n    \"liberia\": \"🇱🇷\",\n    \"libra\": \"♎\",\n    \"libya\": \"🇱🇾\",\n    \"liechtenstein\": \"🇱🇮\",\n    \"lithuania\": \"🇱🇹\",\n    \"luxembourg\": \"🇱🇺\",\n    \"macau_sar_china\": \"🇲🇴\",\n    \"macedonia\": \"🇲🇰\",\n    \"madagascar\": \"🇲🇬\",\n    \"malawi\": \"🇲🇼\",\n    \"malaysia\": \"🇲🇾\",\n    \"maldives\": \"🇲🇻\",\n    \"mali\": \"🇲🇱\",\n    \"malta\": \"🇲🇹\",\n    \"marshall_islands\": \"🇲🇭\",\n    \"martinique\": \"🇲🇶\",\n    \"mauritania\": \"🇲🇷\",\n    \"mauritius\": \"🇲🇺\",\n    \"mayotte\": \"🇾🇹\",\n    \"mexico\": \"🇲🇽\",\n    \"micronesia\": \"🇫🇲\",\n    \"moldova\": \"🇲🇩\",\n    \"monaco\": \"🇲🇨\",\n    \"mongolia\": \"🇲🇳\",\n    \"montenegro\": \"🇲🇪\",\n    \"montserrat\": \"🇲🇸\",\n    \"morocco\": \"🇲🇦\",\n    \"mozambique\": \"🇲🇿\",\n    \"mrs._claus\": \"🤶\",\n    \"mrs._claus_dark_skin_tone\": \"🤶🏿\",\n    \"mrs._claus_light_skin_tone\": \"🤶🏻\",\n    \"mrs._claus_medium-dark_skin_tone\": \"🤶🏾\",\n    \"mrs._claus_medium-light_skin_tone\": \"🤶🏼\",\n    \"mrs._claus_medium_skin_tone\": \"🤶🏽\",\n    \"myanmar_(burma)\": \"🇲🇲\",\n    \"new_button\": \"🆕\",\n    \"ng_button\": \"🆖\",\n    \"namibia\": \"🇳🇦\",\n    \"nauru\": \"🇳🇷\",\n    \"nepal\": \"🇳🇵\",\n    \"netherlands\": \"🇳🇱\",\n    \"new_caledonia\": \"🇳🇨\",\n    \"new_zealand\": \"🇳🇿\",\n    \"nicaragua\": \"🇳🇮\",\n    \"niger\": \"🇳🇪\",\n    \"nigeria\": \"🇳🇬\",\n    \"niue\": \"🇳🇺\",\n    \"norfolk_island\": \"🇳🇫\",\n    \"north_korea\": \"🇰🇵\",\n    \"northern_mariana_islands\": \"🇲🇵\",\n    \"norway\": \"🇳🇴\",\n    \"ok_button\": \"🆗\",\n    \"ok_hand\": \"👌\",\n    \"ok_hand_dark_skin_tone\": \"👌🏿\",\n    \"ok_hand_light_skin_tone\": \"👌🏻\",\n    \"ok_hand_medium-dark_skin_tone\": \"👌🏾\",\n    \"ok_hand_medium-light_skin_tone\": \"👌🏼\",\n    \"ok_hand_medium_skin_tone\": \"👌🏽\",\n    \"on!_arrow\": \"🔛\",\n    \"o_button_(blood_type)\": \"🅾\",\n    \"oman\": \"🇴🇲\",\n    \"ophiuchus\": \"⛎\",\n    \"p_button\": \"🅿\",\n    \"pakistan\": \"🇵🇰\",\n    \"palau\": \"🇵🇼\",\n    \"palestinian_territories\": \"🇵🇸\",\n    \"panama\": \"🇵🇦\",\n    \"papua_new_guinea\": \"🇵🇬\",\n    \"paraguay\": \"🇵🇾\",\n    \"peru\": \"🇵🇪\",\n    \"philippines\": \"🇵🇭\",\n    \"pisces\": \"♓\",\n    \"pitcairn_islands\": \"🇵🇳\",\n    \"poland\": \"🇵🇱\",\n    \"portugal\": \"🇵🇹\",\n    \"puerto_rico\": \"🇵🇷\",\n    \"qatar\": \"🇶🇦\",\n    \"romania\": \"🇷🇴\",\n    \"russia\": \"🇷🇺\",\n    \"rwanda\": \"🇷🇼\",\n    \"réunion\": \"🇷🇪\",\n    \"soon_arrow\": \"🔜\",\n    \"sos_button\": \"🆘\",\n    \"sagittarius\": \"♐\",\n    \"samoa\": \"🇼🇸\",\n    \"san_marino\": \"🇸🇲\",\n    \"santa_claus\": \"🎅\",\n    \"santa_claus_dark_skin_tone\": \"🎅🏿\",\n    \"santa_claus_light_skin_tone\": \"🎅🏻\",\n    \"santa_claus_medium-dark_skin_tone\": \"🎅🏾\",\n    \"santa_claus_medium-light_skin_tone\": \"🎅🏼\",\n    \"santa_claus_medium_skin_tone\": \"🎅🏽\",\n    \"saudi_arabia\": \"🇸🇦\",\n    \"scorpio\": \"♏\",\n    \"scotland\": \"🏴\\U000e0067\\U000e0062\\U000e0073\\U000e0063\\U000e0074\\U000e007f\",\n    \"senegal\": \"🇸🇳\",\n    \"serbia\": \"🇷🇸\",\n    \"seychelles\": \"🇸🇨\",\n    \"sierra_leone\": \"🇸🇱\",\n    \"singapore\": \"🇸🇬\",\n    \"sint_maarten\": \"🇸🇽\",\n    \"slovakia\": \"🇸🇰\",\n    \"slovenia\": \"🇸🇮\",\n    \"solomon_islands\": \"🇸🇧\",\n    \"somalia\": \"🇸🇴\",\n    \"south_africa\": \"🇿🇦\",\n    \"south_georgia_&_south_sandwich_islands\": \"🇬🇸\",\n    \"south_korea\": \"🇰🇷\",\n    \"south_sudan\": \"🇸🇸\",\n    \"spain\": \"🇪🇸\",\n    \"sri_lanka\": \"🇱🇰\",\n    \"st._barthélemy\": \"🇧🇱\",\n    \"st._helena\": \"🇸🇭\",\n    \"st._kitts_&_nevis\": \"🇰🇳\",\n    \"st._lucia\": \"🇱🇨\",\n    \"st._martin\": \"🇲🇫\",\n    \"st._pierre_&_miquelon\": \"🇵🇲\",\n    \"st._vincent_&_grenadines\": \"🇻🇨\",\n    \"statue_of_liberty\": \"🗽\",\n    \"sudan\": \"🇸🇩\",\n    \"suriname\": \"🇸🇷\",\n    \"svalbard_&_jan_mayen\": \"🇸🇯\",\n    \"swaziland\": \"🇸🇿\",\n    \"sweden\": \"🇸🇪\",\n    \"switzerland\": \"🇨🇭\",\n    \"syria\": \"🇸🇾\",\n    \"são_tomé_&_príncipe\": \"🇸🇹\",\n    \"t-rex\": \"🦖\",\n    \"top_arrow\": \"🔝\",\n    \"taiwan\": \"🇹🇼\",\n    \"tajikistan\": \"🇹🇯\",\n    \"tanzania\": \"🇹🇿\",\n    \"taurus\": \"♉\",\n    \"thailand\": \"🇹🇭\",\n    \"timor-leste\": \"🇹🇱\",\n    \"togo\": \"🇹🇬\",\n    \"tokelau\": \"🇹🇰\",\n    \"tokyo_tower\": \"🗼\",\n    \"tonga\": \"🇹🇴\",\n    \"trinidad_&_tobago\": \"🇹🇹\",\n    \"tristan_da_cunha\": \"🇹🇦\",\n    \"tunisia\": \"🇹🇳\",\n    \"turkey\": \"🦃\",\n    \"turkmenistan\": \"🇹🇲\",\n    \"turks_&_caicos_islands\": \"🇹🇨\",\n    \"tuvalu\": \"🇹🇻\",\n    \"u.s._outlying_islands\": \"🇺🇲\",\n    \"u.s._virgin_islands\": \"🇻🇮\",\n    \"up!_button\": \"🆙\",\n    \"uganda\": \"🇺🇬\",\n    \"ukraine\": \"🇺🇦\",\n    \"united_arab_emirates\": \"🇦🇪\",\n    \"united_kingdom\": \"🇬🇧\",\n    \"united_nations\": \"🇺🇳\",\n    \"united_states\": \"🇺🇸\",\n    \"uruguay\": \"🇺🇾\",\n    \"uzbekistan\": \"🇺🇿\",\n    \"vs_button\": \"🆚\",\n    \"vanuatu\": \"🇻🇺\",\n    \"vatican_city\": \"🇻🇦\",\n    \"venezuela\": \"🇻🇪\",\n    \"vietnam\": \"🇻🇳\",\n    \"virgo\": \"♍\",\n    \"wales\": \"🏴\\U000e0067\\U000e0062\\U000e0077\\U000e006c\\U000e0073\\U000e007f\",\n    \"wallis_&_futuna\": \"🇼🇫\",\n    \"western_sahara\": \"🇪🇭\",\n    \"yemen\": \"🇾🇪\",\n    \"zambia\": \"🇿🇲\",\n    \"zimbabwe\": \"🇿🇼\",\n    \"abacus\": \"🧮\",\n    \"adhesive_bandage\": \"🩹\",\n    \"admission_tickets\": \"🎟\",\n    \"adult\": \"🧑\",\n    \"adult_dark_skin_tone\": \"🧑🏿\",\n    \"adult_light_skin_tone\": \"🧑🏻\",\n    \"adult_medium-dark_skin_tone\": \"🧑🏾\",\n    \"adult_medium-light_skin_tone\": \"🧑🏼\",\n    \"adult_medium_skin_tone\": \"🧑🏽\",\n    \"aerial_tramway\": \"🚡\",\n    \"airplane\": \"✈\",\n    \"airplane_arrival\": \"🛬\",\n    \"airplane_departure\": \"🛫\",\n    \"alarm_clock\": \"⏰\",\n    \"alembic\": \"⚗\",\n    \"alien\": \"👽\",\n    \"alien_monster\": \"👾\",\n    \"ambulance\": \"🚑\",\n    \"american_football\": \"🏈\",\n    \"amphora\": \"🏺\",\n    \"anchor\": \"⚓\",\n    \"anger_symbol\": \"💢\",\n    \"angry_face\": \"😠\",\n    \"angry_face_with_horns\": \"👿\",\n    \"anguished_face\": \"😧\",\n    \"ant\": \"🐜\",\n    \"antenna_bars\": \"📶\",\n    \"anxious_face_with_sweat\": \"😰\",\n    \"articulated_lorry\": \"🚛\",\n    \"artist_palette\": \"🎨\",\n    \"astonished_face\": \"😲\",\n    \"atom_symbol\": \"⚛\",\n    \"auto_rickshaw\": \"🛺\",\n    \"automobile\": \"🚗\",\n    \"avocado\": \"🥑\",\n    \"axe\": \"🪓\",\n    \"baby\": \"👶\",\n    \"baby_angel\": \"👼\",\n    \"baby_angel_dark_skin_tone\": \"👼🏿\",\n    \"baby_angel_light_skin_tone\": \"👼🏻\",\n    \"baby_angel_medium-dark_skin_tone\": \"👼🏾\",\n    \"baby_angel_medium-light_skin_tone\": \"👼🏼\",\n    \"baby_angel_medium_skin_tone\": \"👼🏽\",\n    \"baby_bottle\": \"🍼\",\n    \"baby_chick\": \"🐤\",\n    \"baby_dark_skin_tone\": \"👶🏿\",\n    \"baby_light_skin_tone\": \"👶🏻\",\n    \"baby_medium-dark_skin_tone\": \"👶🏾\",\n    \"baby_medium-light_skin_tone\": \"👶🏼\",\n    \"baby_medium_skin_tone\": \"👶🏽\",\n    \"baby_symbol\": \"🚼\",\n    \"backhand_index_pointing_down\": \"👇\",\n    \"backhand_index_pointing_down_dark_skin_tone\": \"👇🏿\",\n    \"backhand_index_pointing_down_light_skin_tone\": \"👇🏻\",\n    \"backhand_index_pointing_down_medium-dark_skin_tone\": \"👇🏾\",\n    \"backhand_index_pointing_down_medium-light_skin_tone\": \"👇🏼\",\n    \"backhand_index_pointing_down_medium_skin_tone\": \"👇🏽\",\n    \"backhand_index_pointing_left\": \"👈\",\n    \"backhand_index_pointing_left_dark_skin_tone\": \"👈🏿\",\n    \"backhand_index_pointing_left_light_skin_tone\": \"👈🏻\",\n    \"backhand_index_pointing_left_medium-dark_skin_tone\": \"👈🏾\",\n    \"backhand_index_pointing_left_medium-light_skin_tone\": \"👈🏼\",\n    \"backhand_index_pointing_left_medium_skin_tone\": \"👈🏽\",\n    \"backhand_index_pointing_right\": \"👉\",\n    \"backhand_index_pointing_right_dark_skin_tone\": \"👉🏿\",\n    \"backhand_index_pointing_right_light_skin_tone\": \"👉🏻\",\n    \"backhand_index_pointing_right_medium-dark_skin_tone\": \"👉🏾\",\n    \"backhand_index_pointing_right_medium-light_skin_tone\": \"👉🏼\",\n    \"backhand_index_pointing_right_medium_skin_tone\": \"👉🏽\",\n    \"backhand_index_pointing_up\": \"👆\",\n    \"backhand_index_pointing_up_dark_skin_tone\": \"👆🏿\",\n    \"backhand_index_pointing_up_light_skin_tone\": \"👆🏻\",\n    \"backhand_index_pointing_up_medium-dark_skin_tone\": \"👆🏾\",\n    \"backhand_index_pointing_up_medium-light_skin_tone\": \"👆🏼\",\n    \"backhand_index_pointing_up_medium_skin_tone\": \"👆🏽\",\n    \"bacon\": \"🥓\",\n    \"badger\": \"🦡\",\n    \"badminton\": \"🏸\",\n    \"bagel\": \"🥯\",\n    \"baggage_claim\": \"🛄\",\n    \"baguette_bread\": \"🥖\",\n    \"balance_scale\": \"⚖\",\n    \"bald\": \"🦲\",\n    \"bald_man\": \"👨\\u200d🦲\",\n    \"bald_woman\": \"👩\\u200d🦲\",\n    \"ballet_shoes\": \"🩰\",\n    \"balloon\": \"🎈\",\n    \"ballot_box_with_ballot\": \"🗳\",\n    \"ballot_box_with_check\": \"☑\",\n    \"banana\": \"🍌\",\n    \"banjo\": \"🪕\",\n    \"bank\": \"🏦\",\n    \"bar_chart\": \"📊\",\n    \"barber_pole\": \"💈\",\n    \"baseball\": \"⚾\",\n    \"basket\": \"🧺\",\n    \"basketball\": \"🏀\",\n    \"bat\": \"🦇\",\n    \"bathtub\": \"🛁\",\n    \"battery\": \"🔋\",\n    \"beach_with_umbrella\": \"🏖\",\n    \"beaming_face_with_smiling_eyes\": \"😁\",\n    \"bear_face\": \"🐻\",\n    \"bearded_person\": \"🧔\",\n    \"bearded_person_dark_skin_tone\": \"🧔🏿\",\n    \"bearded_person_light_skin_tone\": \"🧔🏻\",\n    \"bearded_person_medium-dark_skin_tone\": \"🧔🏾\",\n    \"bearded_person_medium-light_skin_tone\": \"🧔🏼\",\n    \"bearded_person_medium_skin_tone\": \"🧔🏽\",\n    \"beating_heart\": \"💓\",\n    \"bed\": \"🛏\",\n    \"beer_mug\": \"🍺\",\n    \"bell\": \"🔔\",\n    \"bell_with_slash\": \"🔕\",\n    \"bellhop_bell\": \"🛎\",\n    \"bento_box\": \"🍱\",\n    \"beverage_box\": \"🧃\",\n    \"bicycle\": \"🚲\",\n    \"bikini\": \"👙\",\n    \"billed_cap\": \"🧢\",\n    \"biohazard\": \"☣\",\n    \"bird\": \"🐦\",\n    \"birthday_cake\": \"🎂\",\n    \"black_circle\": \"⚫\",\n    \"black_flag\": \"🏴\",\n    \"black_heart\": \"🖤\",\n    \"black_large_square\": \"⬛\",\n    \"black_medium-small_square\": \"◾\",\n    \"black_medium_square\": \"◼\",\n    \"black_nib\": \"✒\",\n    \"black_small_square\": \"▪\",\n    \"black_square_button\": \"🔲\",\n    \"blond-haired_man\": \"👱\\u200d♂️\",\n    \"blond-haired_man_dark_skin_tone\": \"👱🏿\\u200d♂️\",\n    \"blond-haired_man_light_skin_tone\": \"👱🏻\\u200d♂️\",\n    \"blond-haired_man_medium-dark_skin_tone\": \"👱🏾\\u200d♂️\",\n    \"blond-haired_man_medium-light_skin_tone\": \"👱🏼\\u200d♂️\",\n    \"blond-haired_man_medium_skin_tone\": \"👱🏽\\u200d♂️\",\n    \"blond-haired_person\": \"👱\",\n    \"blond-haired_person_dark_skin_tone\": \"👱🏿\",\n    \"blond-haired_person_light_skin_tone\": \"👱🏻\",\n    \"blond-haired_person_medium-dark_skin_tone\": \"👱🏾\",\n    \"blond-haired_person_medium-light_skin_tone\": \"👱🏼\",\n    \"blond-haired_person_medium_skin_tone\": \"👱🏽\",\n    \"blond-haired_woman\": \"👱\\u200d♀️\",\n    \"blond-haired_woman_dark_skin_tone\": \"👱🏿\\u200d♀️\",\n    \"blond-haired_woman_light_skin_tone\": \"👱🏻\\u200d♀️\",\n    \"blond-haired_woman_medium-dark_skin_tone\": \"👱🏾\\u200d♀️\",\n    \"blond-haired_woman_medium-light_skin_tone\": \"👱🏼\\u200d♀️\",\n    \"blond-haired_woman_medium_skin_tone\": \"👱🏽\\u200d♀️\",\n    \"blossom\": \"🌼\",\n    \"blowfish\": \"🐡\",\n    \"blue_book\": \"📘\",\n    \"blue_circle\": \"🔵\",\n    \"blue_heart\": \"💙\",\n    \"blue_square\": \"🟦\",\n    \"boar\": \"🐗\",\n    \"bomb\": \"💣\",\n    \"bone\": \"🦴\",\n    \"bookmark\": \"🔖\",\n    \"bookmark_tabs\": \"📑\",\n    \"books\": \"📚\",\n    \"bottle_with_popping_cork\": \"🍾\",\n    \"bouquet\": \"💐\",\n    \"bow_and_arrow\": \"🏹\",\n    \"bowl_with_spoon\": \"🥣\",\n    \"bowling\": \"🎳\",\n    \"boxing_glove\": \"🥊\",\n    \"boy\": \"👦\",\n    \"boy_dark_skin_tone\": \"👦🏿\",\n    \"boy_light_skin_tone\": \"👦🏻\",\n    \"boy_medium-dark_skin_tone\": \"👦🏾\",\n    \"boy_medium-light_skin_tone\": \"👦🏼\",\n    \"boy_medium_skin_tone\": \"👦🏽\",\n    \"brain\": \"🧠\",\n    \"bread\": \"🍞\",\n    \"breast-feeding\": \"🤱\",\n    \"breast-feeding_dark_skin_tone\": \"🤱🏿\",\n    \"breast-feeding_light_skin_tone\": \"🤱🏻\",\n    \"breast-feeding_medium-dark_skin_tone\": \"🤱🏾\",\n    \"breast-feeding_medium-light_skin_tone\": \"🤱🏼\",\n    \"breast-feeding_medium_skin_tone\": \"🤱🏽\",\n    \"brick\": \"🧱\",\n    \"bride_with_veil\": \"👰\",\n    \"bride_with_veil_dark_skin_tone\": \"👰🏿\",\n    \"bride_with_veil_light_skin_tone\": \"👰🏻\",\n    \"bride_with_veil_medium-dark_skin_tone\": \"👰🏾\",\n    \"bride_with_veil_medium-light_skin_tone\": \"👰🏼\",\n    \"bride_with_veil_medium_skin_tone\": \"👰🏽\",\n    \"bridge_at_night\": \"🌉\",\n    \"briefcase\": \"💼\",\n    \"briefs\": \"🩲\",\n    \"bright_button\": \"🔆\",\n    \"broccoli\": \"🥦\",\n    \"broken_heart\": \"💔\",\n    \"broom\": \"🧹\",\n    \"brown_circle\": \"🟤\",\n    \"brown_heart\": \"🤎\",\n    \"brown_square\": \"🟫\",\n    \"bug\": \"🐛\",\n    \"building_construction\": \"🏗\",\n    \"bullet_train\": \"🚅\",\n    \"burrito\": \"🌯\",\n    \"bus\": \"🚌\",\n    \"bus_stop\": \"🚏\",\n    \"bust_in_silhouette\": \"👤\",\n    \"busts_in_silhouette\": \"👥\",\n    \"butter\": \"🧈\",\n    \"butterfly\": \"🦋\",\n    \"cactus\": \"🌵\",\n    \"calendar\": \"📆\",\n    \"call_me_hand\": \"🤙\",\n    \"call_me_hand_dark_skin_tone\": \"🤙🏿\",\n    \"call_me_hand_light_skin_tone\": \"🤙🏻\",\n    \"call_me_hand_medium-dark_skin_tone\": \"🤙🏾\",\n    \"call_me_hand_medium-light_skin_tone\": \"🤙🏼\",\n    \"call_me_hand_medium_skin_tone\": \"🤙🏽\",\n    \"camel\": \"🐫\",\n    \"camera\": \"📷\",\n    \"camera_with_flash\": \"📸\",\n    \"camping\": \"🏕\",\n    \"candle\": \"🕯\",\n    \"candy\": \"🍬\",\n    \"canned_food\": \"🥫\",\n    \"canoe\": \"🛶\",\n    \"card_file_box\": \"🗃\",\n    \"card_index\": \"📇\",\n    \"card_index_dividers\": \"🗂\",\n    \"carousel_horse\": \"🎠\",\n    \"carp_streamer\": \"🎏\",\n    \"carrot\": \"🥕\",\n    \"castle\": \"🏰\",\n    \"cat\": \"🐱\",\n    \"cat_face\": \"🐱\",\n    \"cat_face_with_tears_of_joy\": \"😹\",\n    \"cat_face_with_wry_smile\": \"😼\",\n    \"chains\": \"⛓\",\n    \"chair\": \"🪑\",\n    \"chart_decreasing\": \"📉\",\n    \"chart_increasing\": \"📈\",\n    \"chart_increasing_with_yen\": \"💹\",\n    \"cheese_wedge\": \"🧀\",\n    \"chequered_flag\": \"🏁\",\n    \"cherries\": \"🍒\",\n    \"cherry_blossom\": \"🌸\",\n    \"chess_pawn\": \"♟\",\n    \"chestnut\": \"🌰\",\n    \"chicken\": \"🐔\",\n    \"child\": \"🧒\",\n    \"child_dark_skin_tone\": \"🧒🏿\",\n    \"child_light_skin_tone\": \"🧒🏻\",\n    \"child_medium-dark_skin_tone\": \"🧒🏾\",\n    \"child_medium-light_skin_tone\": \"🧒🏼\",\n    \"child_medium_skin_tone\": \"🧒🏽\",\n    \"children_crossing\": \"🚸\",\n    \"chipmunk\": \"🐿\",\n    \"chocolate_bar\": \"🍫\",\n    \"chopsticks\": \"🥢\",\n    \"church\": \"⛪\",\n    \"cigarette\": \"🚬\",\n    \"cinema\": \"🎦\",\n    \"circled_m\": \"Ⓜ\",\n    \"circus_tent\": \"🎪\",\n    \"cityscape\": \"🏙\",\n    \"cityscape_at_dusk\": \"🌆\",\n    \"clamp\": \"🗜\",\n    \"clapper_board\": \"🎬\",\n    \"clapping_hands\": \"👏\",\n    \"clapping_hands_dark_skin_tone\": \"👏🏿\",\n    \"clapping_hands_light_skin_tone\": \"👏🏻\",\n    \"clapping_hands_medium-dark_skin_tone\": \"👏🏾\",\n    \"clapping_hands_medium-light_skin_tone\": \"👏🏼\",\n    \"clapping_hands_medium_skin_tone\": \"👏🏽\",\n    \"classical_building\": \"🏛\",\n    \"clinking_beer_mugs\": \"🍻\",\n    \"clinking_glasses\": \"🥂\",\n    \"clipboard\": \"📋\",\n    \"clockwise_vertical_arrows\": \"🔃\",\n    \"closed_book\": \"📕\",\n    \"closed_mailbox_with_lowered_flag\": \"📪\",\n    \"closed_mailbox_with_raised_flag\": \"📫\",\n    \"closed_umbrella\": \"🌂\",\n    \"cloud\": \"☁\",\n    \"cloud_with_lightning\": \"🌩\",\n    \"cloud_with_lightning_and_rain\": \"⛈\",\n    \"cloud_with_rain\": \"🌧\",\n    \"cloud_with_snow\": \"🌨\",\n    \"clown_face\": \"🤡\",\n    \"club_suit\": \"♣\",\n    \"clutch_bag\": \"👝\",\n    \"coat\": \"🧥\",\n    \"cocktail_glass\": \"🍸\",\n    \"coconut\": \"🥥\",\n    \"coffin\": \"⚰\",\n    \"cold_face\": \"🥶\",\n    \"collision\": \"💥\",\n    \"comet\": \"☄\",\n    \"compass\": \"🧭\",\n    \"computer_disk\": \"💽\",\n    \"computer_mouse\": \"🖱\",\n    \"confetti_ball\": \"🎊\",\n    \"confounded_face\": \"😖\",\n    \"confused_face\": \"😕\",\n    \"construction\": \"🚧\",\n    \"construction_worker\": \"👷\",\n    \"construction_worker_dark_skin_tone\": \"👷🏿\",\n    \"construction_worker_light_skin_tone\": \"👷🏻\",\n    \"construction_worker_medium-dark_skin_tone\": \"👷🏾\",\n    \"construction_worker_medium-light_skin_tone\": \"👷🏼\",\n    \"construction_worker_medium_skin_tone\": \"👷🏽\",\n    \"control_knobs\": \"🎛\",\n    \"convenience_store\": \"🏪\",\n    \"cooked_rice\": \"🍚\",\n    \"cookie\": \"🍪\",\n    \"cooking\": \"🍳\",\n    \"copyright\": \"©\",\n    \"couch_and_lamp\": \"🛋\",\n    \"counterclockwise_arrows_button\": \"🔄\",\n    \"couple_with_heart\": \"💑\",\n    \"couple_with_heart_man_man\": \"👨\\u200d❤️\\u200d👨\",\n    \"couple_with_heart_woman_man\": \"👩\\u200d❤️\\u200d👨\",\n    \"couple_with_heart_woman_woman\": \"👩\\u200d❤️\\u200d👩\",\n    \"cow\": \"🐮\",\n    \"cow_face\": \"🐮\",\n    \"cowboy_hat_face\": \"🤠\",\n    \"crab\": \"🦀\",\n    \"crayon\": \"🖍\",\n    \"credit_card\": \"💳\",\n    \"crescent_moon\": \"🌙\",\n    \"cricket\": \"🦗\",\n    \"cricket_game\": \"🏏\",\n    \"crocodile\": \"🐊\",\n    \"croissant\": \"🥐\",\n    \"cross_mark\": \"❌\",\n    \"cross_mark_button\": \"❎\",\n    \"crossed_fingers\": \"🤞\",\n    \"crossed_fingers_dark_skin_tone\": \"🤞🏿\",\n    \"crossed_fingers_light_skin_tone\": \"🤞🏻\",\n    \"crossed_fingers_medium-dark_skin_tone\": \"🤞🏾\",\n    \"crossed_fingers_medium-light_skin_tone\": \"🤞🏼\",\n    \"crossed_fingers_medium_skin_tone\": \"🤞🏽\",\n    \"crossed_flags\": \"🎌\",\n    \"crossed_swords\": \"⚔\",\n    \"crown\": \"👑\",\n    \"crying_cat_face\": \"😿\",\n    \"crying_face\": \"😢\",\n    \"crystal_ball\": \"🔮\",\n    \"cucumber\": \"🥒\",\n    \"cupcake\": \"🧁\",\n    \"cup_with_straw\": \"🥤\",\n    \"curling_stone\": \"🥌\",\n    \"curly_hair\": \"🦱\",\n    \"curly-haired_man\": \"👨\\u200d🦱\",\n    \"curly-haired_woman\": \"👩\\u200d🦱\",\n    \"curly_loop\": \"➰\",\n    \"currency_exchange\": \"💱\",\n    \"curry_rice\": \"🍛\",\n    \"custard\": \"🍮\",\n    \"customs\": \"🛃\",\n    \"cut_of_meat\": \"🥩\",\n    \"cyclone\": \"🌀\",\n    \"dagger\": \"🗡\",\n    \"dango\": \"🍡\",\n    \"dashing_away\": \"💨\",\n    \"deaf_person\": \"🧏\",\n    \"deciduous_tree\": \"🌳\",\n    \"deer\": \"🦌\",\n    \"delivery_truck\": \"🚚\",\n    \"department_store\": \"🏬\",\n    \"derelict_house\": \"🏚\",\n    \"desert\": \"🏜\",\n    \"desert_island\": \"🏝\",\n    \"desktop_computer\": \"🖥\",\n    \"detective\": \"🕵\",\n    \"detective_dark_skin_tone\": \"🕵🏿\",\n    \"detective_light_skin_tone\": \"🕵🏻\",\n    \"detective_medium-dark_skin_tone\": \"🕵🏾\",\n    \"detective_medium-light_skin_tone\": \"🕵🏼\",\n    \"detective_medium_skin_tone\": \"🕵🏽\",\n    \"diamond_suit\": \"♦\",\n    \"diamond_with_a_dot\": \"💠\",\n    \"dim_button\": \"🔅\",\n    \"direct_hit\": \"🎯\",\n    \"disappointed_face\": \"😞\",\n    \"diving_mask\": \"🤿\",\n    \"diya_lamp\": \"🪔\",\n    \"dizzy\": \"💫\",\n    \"dizzy_face\": \"😵\",\n    \"dna\": \"🧬\",\n    \"dog\": \"🐶\",\n    \"dog_face\": \"🐶\",\n    \"dollar_banknote\": \"💵\",\n    \"dolphin\": \"🐬\",\n    \"door\": \"🚪\",\n    \"dotted_six-pointed_star\": \"🔯\",\n    \"double_curly_loop\": \"➿\",\n    \"double_exclamation_mark\": \"‼\",\n    \"doughnut\": \"🍩\",\n    \"dove\": \"🕊\",\n    \"down-left_arrow\": \"↙\",\n    \"down-right_arrow\": \"↘\",\n    \"down_arrow\": \"⬇\",\n    \"downcast_face_with_sweat\": \"😓\",\n    \"downwards_button\": \"🔽\",\n    \"dragon\": \"🐉\",\n    \"dragon_face\": \"🐲\",\n    \"dress\": \"👗\",\n    \"drooling_face\": \"🤤\",\n    \"drop_of_blood\": \"🩸\",\n    \"droplet\": \"💧\",\n    \"drum\": \"🥁\",\n    \"duck\": \"🦆\",\n    \"dumpling\": \"🥟\",\n    \"dvd\": \"📀\",\n    \"e-mail\": \"📧\",\n    \"eagle\": \"🦅\",\n    \"ear\": \"👂\",\n    \"ear_dark_skin_tone\": \"👂🏿\",\n    \"ear_light_skin_tone\": \"👂🏻\",\n    \"ear_medium-dark_skin_tone\": \"👂🏾\",\n    \"ear_medium-light_skin_tone\": \"👂🏼\",\n    \"ear_medium_skin_tone\": \"👂🏽\",\n    \"ear_of_corn\": \"🌽\",\n    \"ear_with_hearing_aid\": \"🦻\",\n    \"egg\": \"🍳\",\n    \"eggplant\": \"🍆\",\n    \"eight-pointed_star\": \"✴\",\n    \"eight-spoked_asterisk\": \"✳\",\n    \"eight-thirty\": \"🕣\",\n    \"eight_o’clock\": \"🕗\",\n    \"eject_button\": \"⏏\",\n    \"electric_plug\": \"🔌\",\n    \"elephant\": \"🐘\",\n    \"eleven-thirty\": \"🕦\",\n    \"eleven_o’clock\": \"🕚\",\n    \"elf\": \"🧝\",\n    \"elf_dark_skin_tone\": \"🧝🏿\",\n    \"elf_light_skin_tone\": \"🧝🏻\",\n    \"elf_medium-dark_skin_tone\": \"🧝🏾\",\n    \"elf_medium-light_skin_tone\": \"🧝🏼\",\n    \"elf_medium_skin_tone\": \"🧝🏽\",\n    \"envelope\": \"✉\",\n    \"envelope_with_arrow\": \"📩\",\n    \"euro_banknote\": \"💶\",\n    \"evergreen_tree\": \"🌲\",\n    \"ewe\": \"🐑\",\n    \"exclamation_mark\": \"❗\",\n    \"exclamation_question_mark\": \"⁉\",\n    \"exploding_head\": \"🤯\",\n    \"expressionless_face\": \"😑\",\n    \"eye\": \"👁\",\n    \"eye_in_speech_bubble\": \"👁️\\u200d🗨️\",\n    \"eyes\": \"👀\",\n    \"face_blowing_a_kiss\": \"😘\",\n    \"face_savoring_food\": \"😋\",\n    \"face_screaming_in_fear\": \"😱\",\n    \"face_vomiting\": \"🤮\",\n    \"face_with_hand_over_mouth\": \"🤭\",\n    \"face_with_head-bandage\": \"🤕\",\n    \"face_with_medical_mask\": \"😷\",\n    \"face_with_monocle\": \"🧐\",\n    \"face_with_open_mouth\": \"😮\",\n    \"face_with_raised_eyebrow\": \"🤨\",\n    \"face_with_rolling_eyes\": \"🙄\",\n    \"face_with_steam_from_nose\": \"😤\",\n    \"face_with_symbols_on_mouth\": \"🤬\",\n    \"face_with_tears_of_joy\": \"😂\",\n    \"face_with_thermometer\": \"🤒\",\n    \"face_with_tongue\": \"😛\",\n    \"face_without_mouth\": \"😶\",\n    \"factory\": \"🏭\",\n    \"fairy\": \"🧚\",\n    \"fairy_dark_skin_tone\": \"🧚🏿\",\n    \"fairy_light_skin_tone\": \"🧚🏻\",\n    \"fairy_medium-dark_skin_tone\": \"🧚🏾\",\n    \"fairy_medium-light_skin_tone\": \"🧚🏼\",\n    \"fairy_medium_skin_tone\": \"🧚🏽\",\n    \"falafel\": \"🧆\",\n    \"fallen_leaf\": \"🍂\",\n    \"family\": \"👪\",\n    \"family_man_boy\": \"👨\\u200d👦\",\n    \"family_man_boy_boy\": \"👨\\u200d👦\\u200d👦\",\n    \"family_man_girl\": \"👨\\u200d👧\",\n    \"family_man_girl_boy\": \"👨\\u200d👧\\u200d👦\",\n    \"family_man_girl_girl\": \"👨\\u200d👧\\u200d👧\",\n    \"family_man_man_boy\": \"👨\\u200d👨\\u200d👦\",\n    \"family_man_man_boy_boy\": \"👨\\u200d👨\\u200d👦\\u200d👦\",\n    \"family_man_man_girl\": \"👨\\u200d👨\\u200d👧\",\n    \"family_man_man_girl_boy\": \"👨\\u200d👨\\u200d👧\\u200d👦\",\n    \"family_man_man_girl_girl\": \"👨\\u200d👨\\u200d👧\\u200d👧\",\n    \"family_man_woman_boy\": \"👨\\u200d👩\\u200d👦\",\n    \"family_man_woman_boy_boy\": \"👨\\u200d👩\\u200d👦\\u200d👦\",\n    \"family_man_woman_girl\": \"👨\\u200d👩\\u200d👧\",\n    \"family_man_woman_girl_boy\": \"👨\\u200d👩\\u200d👧\\u200d👦\",\n    \"family_man_woman_girl_girl\": \"👨\\u200d👩\\u200d👧\\u200d👧\",\n    \"family_woman_boy\": \"👩\\u200d👦\",\n    \"family_woman_boy_boy\": \"👩\\u200d👦\\u200d👦\",\n    \"family_woman_girl\": \"👩\\u200d👧\",\n    \"family_woman_girl_boy\": \"👩\\u200d👧\\u200d👦\",\n    \"family_woman_girl_girl\": \"👩\\u200d👧\\u200d👧\",\n    \"family_woman_woman_boy\": \"👩\\u200d👩\\u200d👦\",\n    \"family_woman_woman_boy_boy\": \"👩\\u200d👩\\u200d👦\\u200d👦\",\n    \"family_woman_woman_girl\": \"👩\\u200d👩\\u200d👧\",\n    \"family_woman_woman_girl_boy\": \"👩\\u200d👩\\u200d👧\\u200d👦\",\n    \"family_woman_woman_girl_girl\": \"👩\\u200d👩\\u200d👧\\u200d👧\",\n    \"fast-forward_button\": \"⏩\",\n    \"fast_down_button\": \"⏬\",\n    \"fast_reverse_button\": \"⏪\",\n    \"fast_up_button\": \"⏫\",\n    \"fax_machine\": \"📠\",\n    \"fearful_face\": \"😨\",\n    \"female_sign\": \"♀\",\n    \"ferris_wheel\": \"🎡\",\n    \"ferry\": \"⛴\",\n    \"field_hockey\": \"🏑\",\n    \"file_cabinet\": \"🗄\",\n    \"file_folder\": \"📁\",\n    \"film_frames\": \"🎞\",\n    \"film_projector\": \"📽\",\n    \"fire\": \"🔥\",\n    \"fire_extinguisher\": \"🧯\",\n    \"firecracker\": \"🧨\",\n    \"fire_engine\": \"🚒\",\n    \"fireworks\": \"🎆\",\n    \"first_quarter_moon\": \"🌓\",\n    \"first_quarter_moon_face\": \"🌛\",\n    \"fish\": \"🐟\",\n    \"fish_cake_with_swirl\": \"🍥\",\n    \"fishing_pole\": \"🎣\",\n    \"five-thirty\": \"🕠\",\n    \"five_o’clock\": \"🕔\",\n    \"flag_in_hole\": \"⛳\",\n    \"flamingo\": \"🦩\",\n    \"flashlight\": \"🔦\",\n    \"flat_shoe\": \"🥿\",\n    \"fleur-de-lis\": \"⚜\",\n    \"flexed_biceps\": \"💪\",\n    \"flexed_biceps_dark_skin_tone\": \"💪🏿\",\n    \"flexed_biceps_light_skin_tone\": \"💪🏻\",\n    \"flexed_biceps_medium-dark_skin_tone\": \"💪🏾\",\n    \"flexed_biceps_medium-light_skin_tone\": \"💪🏼\",\n    \"flexed_biceps_medium_skin_tone\": \"💪🏽\",\n    \"floppy_disk\": \"💾\",\n    \"flower_playing_cards\": \"🎴\",\n    \"flushed_face\": \"😳\",\n    \"flying_disc\": \"🥏\",\n    \"flying_saucer\": \"🛸\",\n    \"fog\": \"🌫\",\n    \"foggy\": \"🌁\",\n    \"folded_hands\": \"🙏\",\n    \"folded_hands_dark_skin_tone\": \"🙏🏿\",\n    \"folded_hands_light_skin_tone\": \"🙏🏻\",\n    \"folded_hands_medium-dark_skin_tone\": \"🙏🏾\",\n    \"folded_hands_medium-light_skin_tone\": \"🙏🏼\",\n    \"folded_hands_medium_skin_tone\": \"🙏🏽\",\n    \"foot\": \"🦶\",\n    \"footprints\": \"👣\",\n    \"fork_and_knife\": \"🍴\",\n    \"fork_and_knife_with_plate\": \"🍽\",\n    \"fortune_cookie\": \"🥠\",\n    \"fountain\": \"⛲\",\n    \"fountain_pen\": \"🖋\",\n    \"four-thirty\": \"🕟\",\n    \"four_leaf_clover\": \"🍀\",\n    \"four_o’clock\": \"🕓\",\n    \"fox_face\": \"🦊\",\n    \"framed_picture\": \"🖼\",\n    \"french_fries\": \"🍟\",\n    \"fried_shrimp\": \"🍤\",\n    \"frog_face\": \"🐸\",\n    \"front-facing_baby_chick\": \"🐥\",\n    \"frowning_face\": \"☹\",\n    \"frowning_face_with_open_mouth\": \"😦\",\n    \"fuel_pump\": \"⛽\",\n    \"full_moon\": \"🌕\",\n    \"full_moon_face\": \"🌝\",\n    \"funeral_urn\": \"⚱\",\n    \"game_die\": \"🎲\",\n    \"garlic\": \"🧄\",\n    \"gear\": \"⚙\",\n    \"gem_stone\": \"💎\",\n    \"genie\": \"🧞\",\n    \"ghost\": \"👻\",\n    \"giraffe\": \"🦒\",\n    \"girl\": \"👧\",\n    \"girl_dark_skin_tone\": \"👧🏿\",\n    \"girl_light_skin_tone\": \"👧🏻\",\n    \"girl_medium-dark_skin_tone\": \"👧🏾\",\n    \"girl_medium-light_skin_tone\": \"👧🏼\",\n    \"girl_medium_skin_tone\": \"👧🏽\",\n    \"glass_of_milk\": \"🥛\",\n    \"glasses\": \"👓\",\n    \"globe_showing_americas\": \"🌎\",\n    \"globe_showing_asia-australia\": \"🌏\",\n    \"globe_showing_europe-africa\": \"🌍\",\n    \"globe_with_meridians\": \"🌐\",\n    \"gloves\": \"🧤\",\n    \"glowing_star\": \"🌟\",\n    \"goal_net\": \"🥅\",\n    \"goat\": \"🐐\",\n    \"goblin\": \"👺\",\n    \"goggles\": \"🥽\",\n    \"gorilla\": \"🦍\",\n    \"graduation_cap\": \"🎓\",\n    \"grapes\": \"🍇\",\n    \"green_apple\": \"🍏\",\n    \"green_book\": \"📗\",\n    \"green_circle\": \"🟢\",\n    \"green_heart\": \"💚\",\n    \"green_salad\": \"🥗\",\n    \"green_square\": \"🟩\",\n    \"grimacing_face\": \"😬\",\n    \"grinning_cat_face\": \"😺\",\n    \"grinning_cat_face_with_smiling_eyes\": \"😸\",\n    \"grinning_face\": \"😀\",\n    \"grinning_face_with_big_eyes\": \"😃\",\n    \"grinning_face_with_smiling_eyes\": \"😄\",\n    \"grinning_face_with_sweat\": \"😅\",\n    \"grinning_squinting_face\": \"😆\",\n    \"growing_heart\": \"💗\",\n    \"guard\": \"💂\",\n    \"guard_dark_skin_tone\": \"💂🏿\",\n    \"guard_light_skin_tone\": \"💂🏻\",\n    \"guard_medium-dark_skin_tone\": \"💂🏾\",\n    \"guard_medium-light_skin_tone\": \"💂🏼\",\n    \"guard_medium_skin_tone\": \"💂🏽\",\n    \"guide_dog\": \"🦮\",\n    \"guitar\": \"🎸\",\n    \"hamburger\": \"🍔\",\n    \"hammer\": \"🔨\",\n    \"hammer_and_pick\": \"⚒\",\n    \"hammer_and_wrench\": \"🛠\",\n    \"hamster_face\": \"🐹\",\n    \"hand_with_fingers_splayed\": \"🖐\",\n    \"hand_with_fingers_splayed_dark_skin_tone\": \"🖐🏿\",\n    \"hand_with_fingers_splayed_light_skin_tone\": \"🖐🏻\",\n    \"hand_with_fingers_splayed_medium-dark_skin_tone\": \"🖐🏾\",\n    \"hand_with_fingers_splayed_medium-light_skin_tone\": \"🖐🏼\",\n    \"hand_with_fingers_splayed_medium_skin_tone\": \"🖐🏽\",\n    \"handbag\": \"👜\",\n    \"handshake\": \"🤝\",\n    \"hatching_chick\": \"🐣\",\n    \"headphone\": \"🎧\",\n    \"hear-no-evil_monkey\": \"🙉\",\n    \"heart_decoration\": \"💟\",\n    \"heart_suit\": \"♥\",\n    \"heart_with_arrow\": \"💘\",\n    \"heart_with_ribbon\": \"💝\",\n    \"heavy_check_mark\": \"✔\",\n    \"heavy_division_sign\": \"➗\",\n    \"heavy_dollar_sign\": \"💲\",\n    \"heavy_heart_exclamation\": \"❣\",\n    \"heavy_large_circle\": \"⭕\",\n    \"heavy_minus_sign\": \"➖\",\n    \"heavy_multiplication_x\": \"✖\",\n    \"heavy_plus_sign\": \"➕\",\n    \"hedgehog\": \"🦔\",\n    \"helicopter\": \"🚁\",\n    \"herb\": \"🌿\",\n    \"hibiscus\": \"🌺\",\n    \"high-heeled_shoe\": \"👠\",\n    \"high-speed_train\": \"🚄\",\n    \"high_voltage\": \"⚡\",\n    \"hiking_boot\": \"🥾\",\n    \"hindu_temple\": \"🛕\",\n    \"hippopotamus\": \"🦛\",\n    \"hole\": \"🕳\",\n    \"honey_pot\": \"🍯\",\n    \"honeybee\": \"🐝\",\n    \"horizontal_traffic_light\": \"🚥\",\n    \"horse\": \"🐴\",\n    \"horse_face\": \"🐴\",\n    \"horse_racing\": \"🏇\",\n    \"horse_racing_dark_skin_tone\": \"🏇🏿\",\n    \"horse_racing_light_skin_tone\": \"🏇🏻\",\n    \"horse_racing_medium-dark_skin_tone\": \"🏇🏾\",\n    \"horse_racing_medium-light_skin_tone\": \"🏇🏼\",\n    \"horse_racing_medium_skin_tone\": \"🏇🏽\",\n    \"hospital\": \"🏥\",\n    \"hot_beverage\": \"☕\",\n    \"hot_dog\": \"🌭\",\n    \"hot_face\": \"🥵\",\n    \"hot_pepper\": \"🌶\",\n    \"hot_springs\": \"♨\",\n    \"hotel\": \"🏨\",\n    \"hourglass_done\": \"⌛\",\n    \"hourglass_not_done\": \"⏳\",\n    \"house\": \"🏠\",\n    \"house_with_garden\": \"🏡\",\n    \"houses\": \"🏘\",\n    \"hugging_face\": \"🤗\",\n    \"hundred_points\": \"💯\",\n    \"hushed_face\": \"😯\",\n    \"ice\": \"🧊\",\n    \"ice_cream\": \"🍨\",\n    \"ice_hockey\": \"🏒\",\n    \"ice_skate\": \"⛸\",\n    \"inbox_tray\": \"📥\",\n    \"incoming_envelope\": \"📨\",\n    \"index_pointing_up\": \"☝\",\n    \"index_pointing_up_dark_skin_tone\": \"☝🏿\",\n    \"index_pointing_up_light_skin_tone\": \"☝🏻\",\n    \"index_pointing_up_medium-dark_skin_tone\": \"☝🏾\",\n    \"index_pointing_up_medium-light_skin_tone\": \"☝🏼\",\n    \"index_pointing_up_medium_skin_tone\": \"☝🏽\",\n    \"infinity\": \"♾\",\n    \"information\": \"ℹ\",\n    \"input_latin_letters\": \"🔤\",\n    \"input_latin_lowercase\": \"🔡\",\n    \"input_latin_uppercase\": \"🔠\",\n    \"input_numbers\": \"🔢\",\n    \"input_symbols\": \"🔣\",\n    \"jack-o-lantern\": \"🎃\",\n    \"jeans\": \"👖\",\n    \"jigsaw\": \"🧩\",\n    \"joker\": \"🃏\",\n    \"joystick\": \"🕹\",\n    \"kaaba\": \"🕋\",\n    \"kangaroo\": \"🦘\",\n    \"key\": \"🔑\",\n    \"keyboard\": \"⌨\",\n    \"keycap_#\": \"#️⃣\",\n    \"keycap_*\": \"*️⃣\",\n    \"keycap_0\": \"0️⃣\",\n    \"keycap_1\": \"1️⃣\",\n    \"keycap_10\": \"🔟\",\n    \"keycap_2\": \"2️⃣\",\n    \"keycap_3\": \"3️⃣\",\n    \"keycap_4\": \"4️⃣\",\n    \"keycap_5\": \"5️⃣\",\n    \"keycap_6\": \"6️⃣\",\n    \"keycap_7\": \"7️⃣\",\n    \"keycap_8\": \"8️⃣\",\n    \"keycap_9\": \"9️⃣\",\n    \"kick_scooter\": \"🛴\",\n    \"kimono\": \"👘\",\n    \"kiss\": \"💋\",\n    \"kiss_man_man\": \"👨\\u200d❤️\\u200d💋\\u200d👨\",\n    \"kiss_mark\": \"💋\",\n    \"kiss_woman_man\": \"👩\\u200d❤️\\u200d💋\\u200d👨\",\n    \"kiss_woman_woman\": \"👩\\u200d❤️\\u200d💋\\u200d👩\",\n    \"kissing_cat_face\": \"😽\",\n    \"kissing_face\": \"😗\",\n    \"kissing_face_with_closed_eyes\": \"😚\",\n    \"kissing_face_with_smiling_eyes\": \"😙\",\n    \"kitchen_knife\": \"🔪\",\n    \"kite\": \"🪁\",\n    \"kiwi_fruit\": \"🥝\",\n    \"koala\": \"🐨\",\n    \"lab_coat\": \"🥼\",\n    \"label\": \"🏷\",\n    \"lacrosse\": \"🥍\",\n    \"lady_beetle\": \"🐞\",\n    \"laptop_computer\": \"💻\",\n    \"large_blue_diamond\": \"🔷\",\n    \"large_orange_diamond\": \"🔶\",\n    \"last_quarter_moon\": \"🌗\",\n    \"last_quarter_moon_face\": \"🌜\",\n    \"last_track_button\": \"⏮\",\n    \"latin_cross\": \"✝\",\n    \"leaf_fluttering_in_wind\": \"🍃\",\n    \"leafy_green\": \"🥬\",\n    \"ledger\": \"📒\",\n    \"left-facing_fist\": \"🤛\",\n    \"left-facing_fist_dark_skin_tone\": \"🤛🏿\",\n    \"left-facing_fist_light_skin_tone\": \"🤛🏻\",\n    \"left-facing_fist_medium-dark_skin_tone\": \"🤛🏾\",\n    \"left-facing_fist_medium-light_skin_tone\": \"🤛🏼\",\n    \"left-facing_fist_medium_skin_tone\": \"🤛🏽\",\n    \"left-right_arrow\": \"↔\",\n    \"left_arrow\": \"⬅\",\n    \"left_arrow_curving_right\": \"↪\",\n    \"left_luggage\": \"🛅\",\n    \"left_speech_bubble\": \"🗨\",\n    \"leg\": \"🦵\",\n    \"lemon\": \"🍋\",\n    \"leopard\": \"🐆\",\n    \"level_slider\": \"🎚\",\n    \"light_bulb\": \"💡\",\n    \"light_rail\": \"🚈\",\n    \"link\": \"🔗\",\n    \"linked_paperclips\": \"🖇\",\n    \"lion_face\": \"🦁\",\n    \"lipstick\": \"💄\",\n    \"litter_in_bin_sign\": \"🚮\",\n    \"lizard\": \"🦎\",\n    \"llama\": \"🦙\",\n    \"lobster\": \"🦞\",\n    \"locked\": \"🔒\",\n    \"locked_with_key\": \"🔐\",\n    \"locked_with_pen\": \"🔏\",\n    \"locomotive\": \"🚂\",\n    \"lollipop\": \"🍭\",\n    \"lotion_bottle\": \"🧴\",\n    \"loudly_crying_face\": \"😭\",\n    \"loudspeaker\": \"📢\",\n    \"love-you_gesture\": \"🤟\",\n    \"love-you_gesture_dark_skin_tone\": \"🤟🏿\",\n    \"love-you_gesture_light_skin_tone\": \"🤟🏻\",\n    \"love-you_gesture_medium-dark_skin_tone\": \"🤟🏾\",\n    \"love-you_gesture_medium-light_skin_tone\": \"🤟🏼\",\n    \"love-you_gesture_medium_skin_tone\": \"🤟🏽\",\n    \"love_hotel\": \"🏩\",\n    \"love_letter\": \"💌\",\n    \"luggage\": \"🧳\",\n    \"lying_face\": \"🤥\",\n    \"mage\": \"🧙\",\n    \"mage_dark_skin_tone\": \"🧙🏿\",\n    \"mage_light_skin_tone\": \"🧙🏻\",\n    \"mage_medium-dark_skin_tone\": \"🧙🏾\",\n    \"mage_medium-light_skin_tone\": \"🧙🏼\",\n    \"mage_medium_skin_tone\": \"🧙🏽\",\n    \"magnet\": \"🧲\",\n    \"magnifying_glass_tilted_left\": \"🔍\",\n    \"magnifying_glass_tilted_right\": \"🔎\",\n    \"mahjong_red_dragon\": \"🀄\",\n    \"male_sign\": \"♂\",\n    \"man\": \"👨\",\n    \"man_and_woman_holding_hands\": \"👫\",\n    \"man_artist\": \"👨\\u200d🎨\",\n    \"man_artist_dark_skin_tone\": \"👨🏿\\u200d🎨\",\n    \"man_artist_light_skin_tone\": \"👨🏻\\u200d🎨\",\n    \"man_artist_medium-dark_skin_tone\": \"👨🏾\\u200d🎨\",\n    \"man_artist_medium-light_skin_tone\": \"👨🏼\\u200d🎨\",\n    \"man_artist_medium_skin_tone\": \"👨🏽\\u200d🎨\",\n    \"man_astronaut\": \"👨\\u200d🚀\",\n    \"man_astronaut_dark_skin_tone\": \"👨🏿\\u200d🚀\",\n    \"man_astronaut_light_skin_tone\": \"👨🏻\\u200d🚀\",\n    \"man_astronaut_medium-dark_skin_tone\": \"👨🏾\\u200d🚀\",\n    \"man_astronaut_medium-light_skin_tone\": \"👨🏼\\u200d🚀\",\n    \"man_astronaut_medium_skin_tone\": \"👨🏽\\u200d🚀\",\n    \"man_biking\": \"🚴\\u200d♂️\",\n    \"man_biking_dark_skin_tone\": \"🚴🏿\\u200d♂️\",\n    \"man_biking_light_skin_tone\": \"🚴🏻\\u200d♂️\",\n    \"man_biking_medium-dark_skin_tone\": \"🚴🏾\\u200d♂️\",\n    \"man_biking_medium-light_skin_tone\": \"🚴🏼\\u200d♂️\",\n    \"man_biking_medium_skin_tone\": \"🚴🏽\\u200d♂️\",\n    \"man_bouncing_ball\": \"⛹️\\u200d♂️\",\n    \"man_bouncing_ball_dark_skin_tone\": \"⛹🏿\\u200d♂️\",\n    \"man_bouncing_ball_light_skin_tone\": \"⛹🏻\\u200d♂️\",\n    \"man_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\\u200d♂️\",\n    \"man_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\\u200d♂️\",\n    \"man_bouncing_ball_medium_skin_tone\": \"⛹🏽\\u200d♂️\",\n    \"man_bowing\": \"🙇\\u200d♂️\",\n    \"man_bowing_dark_skin_tone\": \"🙇🏿\\u200d♂️\",\n    \"man_bowing_light_skin_tone\": \"🙇🏻\\u200d♂️\",\n    \"man_bowing_medium-dark_skin_tone\": \"🙇🏾\\u200d♂️\",\n    \"man_bowing_medium-light_skin_tone\": \"🙇🏼\\u200d♂️\",\n    \"man_bowing_medium_skin_tone\": \"🙇🏽\\u200d♂️\",\n    \"man_cartwheeling\": \"🤸\\u200d♂️\",\n    \"man_cartwheeling_dark_skin_tone\": \"🤸🏿\\u200d♂️\",\n    \"man_cartwheeling_light_skin_tone\": \"🤸🏻\\u200d♂️\",\n    \"man_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\\u200d♂️\",\n    \"man_cartwheeling_medium-light_skin_tone\": \"🤸🏼\\u200d♂️\",\n    \"man_cartwheeling_medium_skin_tone\": \"🤸🏽\\u200d♂️\",\n    \"man_climbing\": \"🧗\\u200d♂️\",\n    \"man_climbing_dark_skin_tone\": \"🧗🏿\\u200d♂️\",\n    \"man_climbing_light_skin_tone\": \"🧗🏻\\u200d♂️\",\n    \"man_climbing_medium-dark_skin_tone\": \"🧗🏾\\u200d♂️\",\n    \"man_climbing_medium-light_skin_tone\": \"🧗🏼\\u200d♂️\",\n    \"man_climbing_medium_skin_tone\": \"🧗🏽\\u200d♂️\",\n    \"man_construction_worker\": \"👷\\u200d♂️\",\n    \"man_construction_worker_dark_skin_tone\": \"👷🏿\\u200d♂️\",\n    \"man_construction_worker_light_skin_tone\": \"👷🏻\\u200d♂️\",\n    \"man_construction_worker_medium-dark_skin_tone\": \"👷🏾\\u200d♂️\",\n    \"man_construction_worker_medium-light_skin_tone\": \"👷🏼\\u200d♂️\",\n    \"man_construction_worker_medium_skin_tone\": \"👷🏽\\u200d♂️\",\n    \"man_cook\": \"👨\\u200d🍳\",\n    \"man_cook_dark_skin_tone\": \"👨🏿\\u200d🍳\",\n    \"man_cook_light_skin_tone\": \"👨🏻\\u200d🍳\",\n    \"man_cook_medium-dark_skin_tone\": \"👨🏾\\u200d🍳\",\n    \"man_cook_medium-light_skin_tone\": \"👨🏼\\u200d🍳\",\n    \"man_cook_medium_skin_tone\": \"👨🏽\\u200d🍳\",\n    \"man_dancing\": \"🕺\",\n    \"man_dancing_dark_skin_tone\": \"🕺🏿\",\n    \"man_dancing_light_skin_tone\": \"🕺🏻\",\n    \"man_dancing_medium-dark_skin_tone\": \"🕺🏾\",\n    \"man_dancing_medium-light_skin_tone\": \"🕺🏼\",\n    \"man_dancing_medium_skin_tone\": \"🕺🏽\",\n    \"man_dark_skin_tone\": \"👨🏿\",\n    \"man_detective\": \"🕵️\\u200d♂️\",\n    \"man_detective_dark_skin_tone\": \"🕵🏿\\u200d♂️\",\n    \"man_detective_light_skin_tone\": \"🕵🏻\\u200d♂️\",\n    \"man_detective_medium-dark_skin_tone\": \"🕵🏾\\u200d♂️\",\n    \"man_detective_medium-light_skin_tone\": \"🕵🏼\\u200d♂️\",\n    \"man_detective_medium_skin_tone\": \"🕵🏽\\u200d♂️\",\n    \"man_elf\": \"🧝\\u200d♂️\",\n    \"man_elf_dark_skin_tone\": \"🧝🏿\\u200d♂️\",\n    \"man_elf_light_skin_tone\": \"🧝🏻\\u200d♂️\",\n    \"man_elf_medium-dark_skin_tone\": \"🧝🏾\\u200d♂️\",\n    \"man_elf_medium-light_skin_tone\": \"🧝🏼\\u200d♂️\",\n    \"man_elf_medium_skin_tone\": \"🧝🏽\\u200d♂️\",\n    \"man_facepalming\": \"🤦\\u200d♂️\",\n    \"man_facepalming_dark_skin_tone\": \"🤦🏿\\u200d♂️\",\n    \"man_facepalming_light_skin_tone\": \"🤦🏻\\u200d♂️\",\n    \"man_facepalming_medium-dark_skin_tone\": \"🤦🏾\\u200d♂️\",\n    \"man_facepalming_medium-light_skin_tone\": \"🤦🏼\\u200d♂️\",\n    \"man_facepalming_medium_skin_tone\": \"🤦🏽\\u200d♂️\",\n    \"man_factory_worker\": \"👨\\u200d🏭\",\n    \"man_factory_worker_dark_skin_tone\": \"👨🏿\\u200d🏭\",\n    \"man_factory_worker_light_skin_tone\": \"👨🏻\\u200d🏭\",\n    \"man_factory_worker_medium-dark_skin_tone\": \"👨🏾\\u200d🏭\",\n    \"man_factory_worker_medium-light_skin_tone\": \"👨🏼\\u200d🏭\",\n    \"man_factory_worker_medium_skin_tone\": \"👨🏽\\u200d🏭\",\n    \"man_fairy\": \"🧚\\u200d♂️\",\n    \"man_fairy_dark_skin_tone\": \"🧚🏿\\u200d♂️\",\n    \"man_fairy_light_skin_tone\": \"🧚🏻\\u200d♂️\",\n    \"man_fairy_medium-dark_skin_tone\": \"🧚🏾\\u200d♂️\",\n    \"man_fairy_medium-light_skin_tone\": \"🧚🏼\\u200d♂️\",\n    \"man_fairy_medium_skin_tone\": \"🧚🏽\\u200d♂️\",\n    \"man_farmer\": \"👨\\u200d🌾\",\n    \"man_farmer_dark_skin_tone\": \"👨🏿\\u200d🌾\",\n    \"man_farmer_light_skin_tone\": \"👨🏻\\u200d🌾\",\n    \"man_farmer_medium-dark_skin_tone\": \"👨🏾\\u200d🌾\",\n    \"man_farmer_medium-light_skin_tone\": \"👨🏼\\u200d🌾\",\n    \"man_farmer_medium_skin_tone\": \"👨🏽\\u200d🌾\",\n    \"man_firefighter\": \"👨\\u200d🚒\",\n    \"man_firefighter_dark_skin_tone\": \"👨🏿\\u200d🚒\",\n    \"man_firefighter_light_skin_tone\": \"👨🏻\\u200d🚒\",\n    \"man_firefighter_medium-dark_skin_tone\": \"👨🏾\\u200d🚒\",\n    \"man_firefighter_medium-light_skin_tone\": \"👨🏼\\u200d🚒\",\n    \"man_firefighter_medium_skin_tone\": \"👨🏽\\u200d🚒\",\n    \"man_frowning\": \"🙍\\u200d♂️\",\n    \"man_frowning_dark_skin_tone\": \"🙍🏿\\u200d♂️\",\n    \"man_frowning_light_skin_tone\": \"🙍🏻\\u200d♂️\",\n    \"man_frowning_medium-dark_skin_tone\": \"🙍🏾\\u200d♂️\",\n    \"man_frowning_medium-light_skin_tone\": \"🙍🏼\\u200d♂️\",\n    \"man_frowning_medium_skin_tone\": \"🙍🏽\\u200d♂️\",\n    \"man_genie\": \"🧞\\u200d♂️\",\n    \"man_gesturing_no\": \"🙅\\u200d♂️\",\n    \"man_gesturing_no_dark_skin_tone\": \"🙅🏿\\u200d♂️\",\n    \"man_gesturing_no_light_skin_tone\": \"🙅🏻\\u200d♂️\",\n    \"man_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\\u200d♂️\",\n    \"man_gesturing_no_medium-light_skin_tone\": \"🙅🏼\\u200d♂️\",\n    \"man_gesturing_no_medium_skin_tone\": \"🙅🏽\\u200d♂️\",\n    \"man_gesturing_ok\": \"🙆\\u200d♂️\",\n    \"man_gesturing_ok_dark_skin_tone\": \"🙆🏿\\u200d♂️\",\n    \"man_gesturing_ok_light_skin_tone\": \"🙆🏻\\u200d♂️\",\n    \"man_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\\u200d♂️\",\n    \"man_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\\u200d♂️\",\n    \"man_gesturing_ok_medium_skin_tone\": \"🙆🏽\\u200d♂️\",\n    \"man_getting_haircut\": \"💇\\u200d♂️\",\n    \"man_getting_haircut_dark_skin_tone\": \"💇🏿\\u200d♂️\",\n    \"man_getting_haircut_light_skin_tone\": \"💇🏻\\u200d♂️\",\n    \"man_getting_haircut_medium-dark_skin_tone\": \"💇🏾\\u200d♂️\",\n    \"man_getting_haircut_medium-light_skin_tone\": \"💇🏼\\u200d♂️\",\n    \"man_getting_haircut_medium_skin_tone\": \"💇🏽\\u200d♂️\",\n    \"man_getting_massage\": \"💆\\u200d♂️\",\n    \"man_getting_massage_dark_skin_tone\": \"💆🏿\\u200d♂️\",\n    \"man_getting_massage_light_skin_tone\": \"💆🏻\\u200d♂️\",\n    \"man_getting_massage_medium-dark_skin_tone\": \"💆🏾\\u200d♂️\",\n    \"man_getting_massage_medium-light_skin_tone\": \"💆🏼\\u200d♂️\",\n    \"man_getting_massage_medium_skin_tone\": \"💆🏽\\u200d♂️\",\n    \"man_golfing\": \"🏌️\\u200d♂️\",\n    \"man_golfing_dark_skin_tone\": \"🏌🏿\\u200d♂️\",\n    \"man_golfing_light_skin_tone\": \"🏌🏻\\u200d♂️\",\n    \"man_golfing_medium-dark_skin_tone\": \"🏌🏾\\u200d♂️\",\n    \"man_golfing_medium-light_skin_tone\": \"🏌🏼\\u200d♂️\",\n    \"man_golfing_medium_skin_tone\": \"🏌🏽\\u200d♂️\",\n    \"man_guard\": \"💂\\u200d♂️\",\n    \"man_guard_dark_skin_tone\": \"💂🏿\\u200d♂️\",\n    \"man_guard_light_skin_tone\": \"💂🏻\\u200d♂️\",\n    \"man_guard_medium-dark_skin_tone\": \"💂🏾\\u200d♂️\",\n    \"man_guard_medium-light_skin_tone\": \"💂🏼\\u200d♂️\",\n    \"man_guard_medium_skin_tone\": \"💂🏽\\u200d♂️\",\n    \"man_health_worker\": \"👨\\u200d⚕️\",\n    \"man_health_worker_dark_skin_tone\": \"👨🏿\\u200d⚕️\",\n    \"man_health_worker_light_skin_tone\": \"👨🏻\\u200d⚕️\",\n    \"man_health_worker_medium-dark_skin_tone\": \"👨🏾\\u200d⚕️\",\n    \"man_health_worker_medium-light_skin_tone\": \"👨🏼\\u200d⚕️\",\n    \"man_health_worker_medium_skin_tone\": \"👨🏽\\u200d⚕️\",\n    \"man_in_lotus_position\": \"🧘\\u200d♂️\",\n    \"man_in_lotus_position_dark_skin_tone\": \"🧘🏿\\u200d♂️\",\n    \"man_in_lotus_position_light_skin_tone\": \"🧘🏻\\u200d♂️\",\n    \"man_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\\u200d♂️\",\n    \"man_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\\u200d♂️\",\n    \"man_in_lotus_position_medium_skin_tone\": \"🧘🏽\\u200d♂️\",\n    \"man_in_manual_wheelchair\": \"👨\\u200d🦽\",\n    \"man_in_motorized_wheelchair\": \"👨\\u200d🦼\",\n    \"man_in_steamy_room\": \"🧖\\u200d♂️\",\n    \"man_in_steamy_room_dark_skin_tone\": \"🧖🏿\\u200d♂️\",\n    \"man_in_steamy_room_light_skin_tone\": \"🧖🏻\\u200d♂️\",\n    \"man_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\\u200d♂️\",\n    \"man_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\\u200d♂️\",\n    \"man_in_steamy_room_medium_skin_tone\": \"🧖🏽\\u200d♂️\",\n    \"man_in_suit_levitating\": \"🕴\",\n    \"man_in_suit_levitating_dark_skin_tone\": \"🕴🏿\",\n    \"man_in_suit_levitating_light_skin_tone\": \"🕴🏻\",\n    \"man_in_suit_levitating_medium-dark_skin_tone\": \"🕴🏾\",\n    \"man_in_suit_levitating_medium-light_skin_tone\": \"🕴🏼\",\n    \"man_in_suit_levitating_medium_skin_tone\": \"🕴🏽\",\n    \"man_in_tuxedo\": \"🤵\",\n    \"man_in_tuxedo_dark_skin_tone\": \"🤵🏿\",\n    \"man_in_tuxedo_light_skin_tone\": \"🤵🏻\",\n    \"man_in_tuxedo_medium-dark_skin_tone\": \"🤵🏾\",\n    \"man_in_tuxedo_medium-light_skin_tone\": \"🤵🏼\",\n    \"man_in_tuxedo_medium_skin_tone\": \"🤵🏽\",\n    \"man_judge\": \"👨\\u200d⚖️\",\n    \"man_judge_dark_skin_tone\": \"👨🏿\\u200d⚖️\",\n    \"man_judge_light_skin_tone\": \"👨🏻\\u200d⚖️\",\n    \"man_judge_medium-dark_skin_tone\": \"👨🏾\\u200d⚖️\",\n    \"man_judge_medium-light_skin_tone\": \"👨🏼\\u200d⚖️\",\n    \"man_judge_medium_skin_tone\": \"👨🏽\\u200d⚖️\",\n    \"man_juggling\": \"🤹\\u200d♂️\",\n    \"man_juggling_dark_skin_tone\": \"🤹🏿\\u200d♂️\",\n    \"man_juggling_light_skin_tone\": \"🤹🏻\\u200d♂️\",\n    \"man_juggling_medium-dark_skin_tone\": \"🤹🏾\\u200d♂️\",\n    \"man_juggling_medium-light_skin_tone\": \"🤹🏼\\u200d♂️\",\n    \"man_juggling_medium_skin_tone\": \"🤹🏽\\u200d♂️\",\n    \"man_lifting_weights\": \"🏋️\\u200d♂️\",\n    \"man_lifting_weights_dark_skin_tone\": \"🏋🏿\\u200d♂️\",\n    \"man_lifting_weights_light_skin_tone\": \"🏋🏻\\u200d♂️\",\n    \"man_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\\u200d♂️\",\n    \"man_lifting_weights_medium-light_skin_tone\": \"🏋🏼\\u200d♂️\",\n    \"man_lifting_weights_medium_skin_tone\": \"🏋🏽\\u200d♂️\",\n    \"man_light_skin_tone\": \"👨🏻\",\n    \"man_mage\": \"🧙\\u200d♂️\",\n    \"man_mage_dark_skin_tone\": \"🧙🏿\\u200d♂️\",\n    \"man_mage_light_skin_tone\": \"🧙🏻\\u200d♂️\",\n    \"man_mage_medium-dark_skin_tone\": \"🧙🏾\\u200d♂️\",\n    \"man_mage_medium-light_skin_tone\": \"🧙🏼\\u200d♂️\",\n    \"man_mage_medium_skin_tone\": \"🧙🏽\\u200d♂️\",\n    \"man_mechanic\": \"👨\\u200d🔧\",\n    \"man_mechanic_dark_skin_tone\": \"👨🏿\\u200d🔧\",\n    \"man_mechanic_light_skin_tone\": \"👨🏻\\u200d🔧\",\n    \"man_mechanic_medium-dark_skin_tone\": \"👨🏾\\u200d🔧\",\n    \"man_mechanic_medium-light_skin_tone\": \"👨🏼\\u200d🔧\",\n    \"man_mechanic_medium_skin_tone\": \"👨🏽\\u200d🔧\",\n    \"man_medium-dark_skin_tone\": \"👨🏾\",\n    \"man_medium-light_skin_tone\": \"👨🏼\",\n    \"man_medium_skin_tone\": \"👨🏽\",\n    \"man_mountain_biking\": \"🚵\\u200d♂️\",\n    \"man_mountain_biking_dark_skin_tone\": \"🚵🏿\\u200d♂️\",\n    \"man_mountain_biking_light_skin_tone\": \"🚵🏻\\u200d♂️\",\n    \"man_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\\u200d♂️\",\n    \"man_mountain_biking_medium-light_skin_tone\": \"🚵🏼\\u200d♂️\",\n    \"man_mountain_biking_medium_skin_tone\": \"🚵🏽\\u200d♂️\",\n    \"man_office_worker\": \"👨\\u200d💼\",\n    \"man_office_worker_dark_skin_tone\": \"👨🏿\\u200d💼\",\n    \"man_office_worker_light_skin_tone\": \"👨🏻\\u200d💼\",\n    \"man_office_worker_medium-dark_skin_tone\": \"👨🏾\\u200d💼\",\n    \"man_office_worker_medium-light_skin_tone\": \"👨🏼\\u200d💼\",\n    \"man_office_worker_medium_skin_tone\": \"👨🏽\\u200d💼\",\n    \"man_pilot\": \"👨\\u200d✈️\",\n    \"man_pilot_dark_skin_tone\": \"👨🏿\\u200d✈️\",\n    \"man_pilot_light_skin_tone\": \"👨🏻\\u200d✈️\",\n    \"man_pilot_medium-dark_skin_tone\": \"👨🏾\\u200d✈️\",\n    \"man_pilot_medium-light_skin_tone\": \"👨🏼\\u200d✈️\",\n    \"man_pilot_medium_skin_tone\": \"👨🏽\\u200d✈️\",\n    \"man_playing_handball\": \"🤾\\u200d♂️\",\n    \"man_playing_handball_dark_skin_tone\": \"🤾🏿\\u200d♂️\",\n    \"man_playing_handball_light_skin_tone\": \"🤾🏻\\u200d♂️\",\n    \"man_playing_handball_medium-dark_skin_tone\": \"🤾🏾\\u200d♂️\",\n    \"man_playing_handball_medium-light_skin_tone\": \"🤾🏼\\u200d♂️\",\n    \"man_playing_handball_medium_skin_tone\": \"🤾🏽\\u200d♂️\",\n    \"man_playing_water_polo\": \"🤽\\u200d♂️\",\n    \"man_playing_water_polo_dark_skin_tone\": \"🤽🏿\\u200d♂️\",\n    \"man_playing_water_polo_light_skin_tone\": \"🤽🏻\\u200d♂️\",\n    \"man_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\\u200d♂️\",\n    \"man_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\\u200d♂️\",\n    \"man_playing_water_polo_medium_skin_tone\": \"🤽🏽\\u200d♂️\",\n    \"man_police_officer\": \"👮\\u200d♂️\",\n    \"man_police_officer_dark_skin_tone\": \"👮🏿\\u200d♂️\",\n    \"man_police_officer_light_skin_tone\": \"👮🏻\\u200d♂️\",\n    \"man_police_officer_medium-dark_skin_tone\": \"👮🏾\\u200d♂️\",\n    \"man_police_officer_medium-light_skin_tone\": \"👮🏼\\u200d♂️\",\n    \"man_police_officer_medium_skin_tone\": \"👮🏽\\u200d♂️\",\n    \"man_pouting\": \"🙎\\u200d♂️\",\n    \"man_pouting_dark_skin_tone\": \"🙎🏿\\u200d♂️\",\n    \"man_pouting_light_skin_tone\": \"🙎🏻\\u200d♂️\",\n    \"man_pouting_medium-dark_skin_tone\": \"🙎🏾\\u200d♂️\",\n    \"man_pouting_medium-light_skin_tone\": \"🙎🏼\\u200d♂️\",\n    \"man_pouting_medium_skin_tone\": \"🙎🏽\\u200d♂️\",\n    \"man_raising_hand\": \"🙋\\u200d♂️\",\n    \"man_raising_hand_dark_skin_tone\": \"🙋🏿\\u200d♂️\",\n    \"man_raising_hand_light_skin_tone\": \"🙋🏻\\u200d♂️\",\n    \"man_raising_hand_medium-dark_skin_tone\": \"🙋🏾\\u200d♂️\",\n    \"man_raising_hand_medium-light_skin_tone\": \"🙋🏼\\u200d♂️\",\n    \"man_raising_hand_medium_skin_tone\": \"🙋🏽\\u200d♂️\",\n    \"man_rowing_boat\": \"🚣\\u200d♂️\",\n    \"man_rowing_boat_dark_skin_tone\": \"🚣🏿\\u200d♂️\",\n    \"man_rowing_boat_light_skin_tone\": \"🚣🏻\\u200d♂️\",\n    \"man_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\\u200d♂️\",\n    \"man_rowing_boat_medium-light_skin_tone\": \"🚣🏼\\u200d♂️\",\n    \"man_rowing_boat_medium_skin_tone\": \"🚣🏽\\u200d♂️\",\n    \"man_running\": \"🏃\\u200d♂️\",\n    \"man_running_dark_skin_tone\": \"🏃🏿\\u200d♂️\",\n    \"man_running_light_skin_tone\": \"🏃🏻\\u200d♂️\",\n    \"man_running_medium-dark_skin_tone\": \"🏃🏾\\u200d♂️\",\n    \"man_running_medium-light_skin_tone\": \"🏃🏼\\u200d♂️\",\n    \"man_running_medium_skin_tone\": \"🏃🏽\\u200d♂️\",\n    \"man_scientist\": \"👨\\u200d🔬\",\n    \"man_scientist_dark_skin_tone\": \"👨🏿\\u200d🔬\",\n    \"man_scientist_light_skin_tone\": \"👨🏻\\u200d🔬\",\n    \"man_scientist_medium-dark_skin_tone\": \"👨🏾\\u200d🔬\",\n    \"man_scientist_medium-light_skin_tone\": \"👨🏼\\u200d🔬\",\n    \"man_scientist_medium_skin_tone\": \"👨🏽\\u200d🔬\",\n    \"man_shrugging\": \"🤷\\u200d♂️\",\n    \"man_shrugging_dark_skin_tone\": \"🤷🏿\\u200d♂️\",\n    \"man_shrugging_light_skin_tone\": \"🤷🏻\\u200d♂️\",\n    \"man_shrugging_medium-dark_skin_tone\": \"🤷🏾\\u200d♂️\",\n    \"man_shrugging_medium-light_skin_tone\": \"🤷🏼\\u200d♂️\",\n    \"man_shrugging_medium_skin_tone\": \"🤷🏽\\u200d♂️\",\n    \"man_singer\": \"👨\\u200d🎤\",\n    \"man_singer_dark_skin_tone\": \"👨🏿\\u200d🎤\",\n    \"man_singer_light_skin_tone\": \"👨🏻\\u200d🎤\",\n    \"man_singer_medium-dark_skin_tone\": \"👨🏾\\u200d🎤\",\n    \"man_singer_medium-light_skin_tone\": \"👨🏼\\u200d🎤\",\n    \"man_singer_medium_skin_tone\": \"👨🏽\\u200d🎤\",\n    \"man_student\": \"👨\\u200d🎓\",\n    \"man_student_dark_skin_tone\": \"👨🏿\\u200d🎓\",\n    \"man_student_light_skin_tone\": \"👨🏻\\u200d🎓\",\n    \"man_student_medium-dark_skin_tone\": \"👨🏾\\u200d🎓\",\n    \"man_student_medium-light_skin_tone\": \"👨🏼\\u200d🎓\",\n    \"man_student_medium_skin_tone\": \"👨🏽\\u200d🎓\",\n    \"man_surfing\": \"🏄\\u200d♂️\",\n    \"man_surfing_dark_skin_tone\": \"🏄🏿\\u200d♂️\",\n    \"man_surfing_light_skin_tone\": \"🏄🏻\\u200d♂️\",\n    \"man_surfing_medium-dark_skin_tone\": \"🏄🏾\\u200d♂️\",\n    \"man_surfing_medium-light_skin_tone\": \"🏄🏼\\u200d♂️\",\n    \"man_surfing_medium_skin_tone\": \"🏄🏽\\u200d♂️\",\n    \"man_swimming\": \"🏊\\u200d♂️\",\n    \"man_swimming_dark_skin_tone\": \"🏊🏿\\u200d♂️\",\n    \"man_swimming_light_skin_tone\": \"🏊🏻\\u200d♂️\",\n    \"man_swimming_medium-dark_skin_tone\": \"🏊🏾\\u200d♂️\",\n    \"man_swimming_medium-light_skin_tone\": \"🏊🏼\\u200d♂️\",\n    \"man_swimming_medium_skin_tone\": \"🏊🏽\\u200d♂️\",\n    \"man_teacher\": \"👨\\u200d🏫\",\n    \"man_teacher_dark_skin_tone\": \"👨🏿\\u200d🏫\",\n    \"man_teacher_light_skin_tone\": \"👨🏻\\u200d🏫\",\n    \"man_teacher_medium-dark_skin_tone\": \"👨🏾\\u200d🏫\",\n    \"man_teacher_medium-light_skin_tone\": \"👨🏼\\u200d🏫\",\n    \"man_teacher_medium_skin_tone\": \"👨🏽\\u200d🏫\",\n    \"man_technologist\": \"👨\\u200d💻\",\n    \"man_technologist_dark_skin_tone\": \"👨🏿\\u200d💻\",\n    \"man_technologist_light_skin_tone\": \"👨🏻\\u200d💻\",\n    \"man_technologist_medium-dark_skin_tone\": \"👨🏾\\u200d💻\",\n    \"man_technologist_medium-light_skin_tone\": \"👨🏼\\u200d💻\",\n    \"man_technologist_medium_skin_tone\": \"👨🏽\\u200d💻\",\n    \"man_tipping_hand\": \"💁\\u200d♂️\",\n    \"man_tipping_hand_dark_skin_tone\": \"💁🏿\\u200d♂️\",\n    \"man_tipping_hand_light_skin_tone\": \"💁🏻\\u200d♂️\",\n    \"man_tipping_hand_medium-dark_skin_tone\": \"💁🏾\\u200d♂️\",\n    \"man_tipping_hand_medium-light_skin_tone\": \"💁🏼\\u200d♂️\",\n    \"man_tipping_hand_medium_skin_tone\": \"💁🏽\\u200d♂️\",\n    \"man_vampire\": \"🧛\\u200d♂️\",\n    \"man_vampire_dark_skin_tone\": \"🧛🏿\\u200d♂️\",\n    \"man_vampire_light_skin_tone\": \"🧛🏻\\u200d♂️\",\n    \"man_vampire_medium-dark_skin_tone\": \"🧛🏾\\u200d♂️\",\n    \"man_vampire_medium-light_skin_tone\": \"🧛🏼\\u200d♂️\",\n    \"man_vampire_medium_skin_tone\": \"🧛🏽\\u200d♂️\",\n    \"man_walking\": \"🚶\\u200d♂️\",\n    \"man_walking_dark_skin_tone\": \"🚶🏿\\u200d♂️\",\n    \"man_walking_light_skin_tone\": \"🚶🏻\\u200d♂️\",\n    \"man_walking_medium-dark_skin_tone\": \"🚶🏾\\u200d♂️\",\n    \"man_walking_medium-light_skin_tone\": \"🚶🏼\\u200d♂️\",\n    \"man_walking_medium_skin_tone\": \"🚶🏽\\u200d♂️\",\n    \"man_wearing_turban\": \"👳\\u200d♂️\",\n    \"man_wearing_turban_dark_skin_tone\": \"👳🏿\\u200d♂️\",\n    \"man_wearing_turban_light_skin_tone\": \"👳🏻\\u200d♂️\",\n    \"man_wearing_turban_medium-dark_skin_tone\": \"👳🏾\\u200d♂️\",\n    \"man_wearing_turban_medium-light_skin_tone\": \"👳🏼\\u200d♂️\",\n    \"man_wearing_turban_medium_skin_tone\": \"👳🏽\\u200d♂️\",\n    \"man_with_probing_cane\": \"👨\\u200d🦯\",\n    \"man_with_chinese_cap\": \"👲\",\n    \"man_with_chinese_cap_dark_skin_tone\": \"👲🏿\",\n    \"man_with_chinese_cap_light_skin_tone\": \"👲🏻\",\n    \"man_with_chinese_cap_medium-dark_skin_tone\": \"👲🏾\",\n    \"man_with_chinese_cap_medium-light_skin_tone\": \"👲🏼\",\n    \"man_with_chinese_cap_medium_skin_tone\": \"👲🏽\",\n    \"man_zombie\": \"🧟\\u200d♂️\",\n    \"mango\": \"🥭\",\n    \"mantelpiece_clock\": \"🕰\",\n    \"manual_wheelchair\": \"🦽\",\n    \"man’s_shoe\": \"👞\",\n    \"map_of_japan\": \"🗾\",\n    \"maple_leaf\": \"🍁\",\n    \"martial_arts_uniform\": \"🥋\",\n    \"mate\": \"🧉\",\n    \"meat_on_bone\": \"🍖\",\n    \"mechanical_arm\": \"🦾\",\n    \"mechanical_leg\": \"🦿\",\n    \"medical_symbol\": \"⚕\",\n    \"megaphone\": \"📣\",\n    \"melon\": \"🍈\",\n    \"memo\": \"📝\",\n    \"men_with_bunny_ears\": \"👯\\u200d♂️\",\n    \"men_wrestling\": \"🤼\\u200d♂️\",\n    \"menorah\": \"🕎\",\n    \"men’s_room\": \"🚹\",\n    \"mermaid\": \"🧜\\u200d♀️\",\n    \"mermaid_dark_skin_tone\": \"🧜🏿\\u200d♀️\",\n    \"mermaid_light_skin_tone\": \"🧜🏻\\u200d♀️\",\n    \"mermaid_medium-dark_skin_tone\": \"🧜🏾\\u200d♀️\",\n    \"mermaid_medium-light_skin_tone\": \"🧜🏼\\u200d♀️\",\n    \"mermaid_medium_skin_tone\": \"🧜🏽\\u200d♀️\",\n    \"merman\": \"🧜\\u200d♂️\",\n    \"merman_dark_skin_tone\": \"🧜🏿\\u200d♂️\",\n    \"merman_light_skin_tone\": \"🧜🏻\\u200d♂️\",\n    \"merman_medium-dark_skin_tone\": \"🧜🏾\\u200d♂️\",\n    \"merman_medium-light_skin_tone\": \"🧜🏼\\u200d♂️\",\n    \"merman_medium_skin_tone\": \"🧜🏽\\u200d♂️\",\n    \"merperson\": \"🧜\",\n    \"merperson_dark_skin_tone\": \"🧜🏿\",\n    \"merperson_light_skin_tone\": \"🧜🏻\",\n    \"merperson_medium-dark_skin_tone\": \"🧜🏾\",\n    \"merperson_medium-light_skin_tone\": \"🧜🏼\",\n    \"merperson_medium_skin_tone\": \"🧜🏽\",\n    \"metro\": \"🚇\",\n    \"microbe\": \"🦠\",\n    \"microphone\": \"🎤\",\n    \"microscope\": \"🔬\",\n    \"middle_finger\": \"🖕\",\n    \"middle_finger_dark_skin_tone\": \"🖕🏿\",\n    \"middle_finger_light_skin_tone\": \"🖕🏻\",\n    \"middle_finger_medium-dark_skin_tone\": \"🖕🏾\",\n    \"middle_finger_medium-light_skin_tone\": \"🖕🏼\",\n    \"middle_finger_medium_skin_tone\": \"🖕🏽\",\n    \"military_medal\": \"🎖\",\n    \"milky_way\": \"🌌\",\n    \"minibus\": \"🚐\",\n    \"moai\": \"🗿\",\n    \"mobile_phone\": \"📱\",\n    \"mobile_phone_off\": \"📴\",\n    \"mobile_phone_with_arrow\": \"📲\",\n    \"money-mouth_face\": \"🤑\",\n    \"money_bag\": \"💰\",\n    \"money_with_wings\": \"💸\",\n    \"monkey\": \"🐒\",\n    \"monkey_face\": \"🐵\",\n    \"monorail\": \"🚝\",\n    \"moon_cake\": \"🥮\",\n    \"moon_viewing_ceremony\": \"🎑\",\n    \"mosque\": \"🕌\",\n    \"mosquito\": \"🦟\",\n    \"motor_boat\": \"🛥\",\n    \"motor_scooter\": \"🛵\",\n    \"motorcycle\": \"🏍\",\n    \"motorized_wheelchair\": \"🦼\",\n    \"motorway\": \"🛣\",\n    \"mount_fuji\": \"🗻\",\n    \"mountain\": \"⛰\",\n    \"mountain_cableway\": \"🚠\",\n    \"mountain_railway\": \"🚞\",\n    \"mouse\": \"🐭\",\n    \"mouse_face\": \"🐭\",\n    \"mouth\": \"👄\",\n    \"movie_camera\": \"🎥\",\n    \"mushroom\": \"🍄\",\n    \"musical_keyboard\": \"🎹\",\n    \"musical_note\": \"🎵\",\n    \"musical_notes\": \"🎶\",\n    \"musical_score\": \"🎼\",\n    \"muted_speaker\": \"🔇\",\n    \"nail_polish\": \"💅\",\n    \"nail_polish_dark_skin_tone\": \"💅🏿\",\n    \"nail_polish_light_skin_tone\": \"💅🏻\",\n    \"nail_polish_medium-dark_skin_tone\": \"💅🏾\",\n    \"nail_polish_medium-light_skin_tone\": \"💅🏼\",\n    \"nail_polish_medium_skin_tone\": \"💅🏽\",\n    \"name_badge\": \"📛\",\n    \"national_park\": \"🏞\",\n    \"nauseated_face\": \"🤢\",\n    \"nazar_amulet\": \"🧿\",\n    \"necktie\": \"👔\",\n    \"nerd_face\": \"🤓\",\n    \"neutral_face\": \"😐\",\n    \"new_moon\": \"🌑\",\n    \"new_moon_face\": \"🌚\",\n    \"newspaper\": \"📰\",\n    \"next_track_button\": \"⏭\",\n    \"night_with_stars\": \"🌃\",\n    \"nine-thirty\": \"🕤\",\n    \"nine_o’clock\": \"🕘\",\n    \"no_bicycles\": \"🚳\",\n    \"no_entry\": \"⛔\",\n    \"no_littering\": \"🚯\",\n    \"no_mobile_phones\": \"📵\",\n    \"no_one_under_eighteen\": \"🔞\",\n    \"no_pedestrians\": \"🚷\",\n    \"no_smoking\": \"🚭\",\n    \"non-potable_water\": \"🚱\",\n    \"nose\": \"👃\",\n    \"nose_dark_skin_tone\": \"👃🏿\",\n    \"nose_light_skin_tone\": \"👃🏻\",\n    \"nose_medium-dark_skin_tone\": \"👃🏾\",\n    \"nose_medium-light_skin_tone\": \"👃🏼\",\n    \"nose_medium_skin_tone\": \"👃🏽\",\n    \"notebook\": \"📓\",\n    \"notebook_with_decorative_cover\": \"📔\",\n    \"nut_and_bolt\": \"🔩\",\n    \"octopus\": \"🐙\",\n    \"oden\": \"🍢\",\n    \"office_building\": \"🏢\",\n    \"ogre\": \"👹\",\n    \"oil_drum\": \"🛢\",\n    \"old_key\": \"🗝\",\n    \"old_man\": \"👴\",\n    \"old_man_dark_skin_tone\": \"👴🏿\",\n    \"old_man_light_skin_tone\": \"👴🏻\",\n    \"old_man_medium-dark_skin_tone\": \"👴🏾\",\n    \"old_man_medium-light_skin_tone\": \"👴🏼\",\n    \"old_man_medium_skin_tone\": \"👴🏽\",\n    \"old_woman\": \"👵\",\n    \"old_woman_dark_skin_tone\": \"👵🏿\",\n    \"old_woman_light_skin_tone\": \"👵🏻\",\n    \"old_woman_medium-dark_skin_tone\": \"👵🏾\",\n    \"old_woman_medium-light_skin_tone\": \"👵🏼\",\n    \"old_woman_medium_skin_tone\": \"👵🏽\",\n    \"older_adult\": \"🧓\",\n    \"older_adult_dark_skin_tone\": \"🧓🏿\",\n    \"older_adult_light_skin_tone\": \"🧓🏻\",\n    \"older_adult_medium-dark_skin_tone\": \"🧓🏾\",\n    \"older_adult_medium-light_skin_tone\": \"🧓🏼\",\n    \"older_adult_medium_skin_tone\": \"🧓🏽\",\n    \"om\": \"🕉\",\n    \"oncoming_automobile\": \"🚘\",\n    \"oncoming_bus\": \"🚍\",\n    \"oncoming_fist\": \"👊\",\n    \"oncoming_fist_dark_skin_tone\": \"👊🏿\",\n    \"oncoming_fist_light_skin_tone\": \"👊🏻\",\n    \"oncoming_fist_medium-dark_skin_tone\": \"👊🏾\",\n    \"oncoming_fist_medium-light_skin_tone\": \"👊🏼\",\n    \"oncoming_fist_medium_skin_tone\": \"👊🏽\",\n    \"oncoming_police_car\": \"🚔\",\n    \"oncoming_taxi\": \"🚖\",\n    \"one-piece_swimsuit\": \"🩱\",\n    \"one-thirty\": \"🕜\",\n    \"one_o’clock\": \"🕐\",\n    \"onion\": \"🧅\",\n    \"open_book\": \"📖\",\n    \"open_file_folder\": \"📂\",\n    \"open_hands\": \"👐\",\n    \"open_hands_dark_skin_tone\": \"👐🏿\",\n    \"open_hands_light_skin_tone\": \"👐🏻\",\n    \"open_hands_medium-dark_skin_tone\": \"👐🏾\",\n    \"open_hands_medium-light_skin_tone\": \"👐🏼\",\n    \"open_hands_medium_skin_tone\": \"👐🏽\",\n    \"open_mailbox_with_lowered_flag\": \"📭\",\n    \"open_mailbox_with_raised_flag\": \"📬\",\n    \"optical_disk\": \"💿\",\n    \"orange_book\": \"📙\",\n    \"orange_circle\": \"🟠\",\n    \"orange_heart\": \"🧡\",\n    \"orange_square\": \"🟧\",\n    \"orangutan\": \"🦧\",\n    \"orthodox_cross\": \"☦\",\n    \"otter\": \"🦦\",\n    \"outbox_tray\": \"📤\",\n    \"owl\": \"🦉\",\n    \"ox\": \"🐂\",\n    \"oyster\": \"🦪\",\n    \"package\": \"📦\",\n    \"page_facing_up\": \"📄\",\n    \"page_with_curl\": \"📃\",\n    \"pager\": \"📟\",\n    \"paintbrush\": \"🖌\",\n    \"palm_tree\": \"🌴\",\n    \"palms_up_together\": \"🤲\",\n    \"palms_up_together_dark_skin_tone\": \"🤲🏿\",\n    \"palms_up_together_light_skin_tone\": \"🤲🏻\",\n    \"palms_up_together_medium-dark_skin_tone\": \"🤲🏾\",\n    \"palms_up_together_medium-light_skin_tone\": \"🤲🏼\",\n    \"palms_up_together_medium_skin_tone\": \"🤲🏽\",\n    \"pancakes\": \"🥞\",\n    \"panda_face\": \"🐼\",\n    \"paperclip\": \"📎\",\n    \"parrot\": \"🦜\",\n    \"part_alternation_mark\": \"〽\",\n    \"party_popper\": \"🎉\",\n    \"partying_face\": \"🥳\",\n    \"passenger_ship\": \"🛳\",\n    \"passport_control\": \"🛂\",\n    \"pause_button\": \"⏸\",\n    \"paw_prints\": \"🐾\",\n    \"peace_symbol\": \"☮\",\n    \"peach\": \"🍑\",\n    \"peacock\": \"🦚\",\n    \"peanuts\": \"🥜\",\n    \"pear\": \"🍐\",\n    \"pen\": \"🖊\",\n    \"pencil\": \"📝\",\n    \"penguin\": \"🐧\",\n    \"pensive_face\": \"😔\",\n    \"people_holding_hands\": \"🧑\\u200d🤝\\u200d🧑\",\n    \"people_with_bunny_ears\": \"👯\",\n    \"people_wrestling\": \"🤼\",\n    \"performing_arts\": \"🎭\",\n    \"persevering_face\": \"😣\",\n    \"person_biking\": \"🚴\",\n    \"person_biking_dark_skin_tone\": \"🚴🏿\",\n    \"person_biking_light_skin_tone\": \"🚴🏻\",\n    \"person_biking_medium-dark_skin_tone\": \"🚴🏾\",\n    \"person_biking_medium-light_skin_tone\": \"🚴🏼\",\n    \"person_biking_medium_skin_tone\": \"🚴🏽\",\n    \"person_bouncing_ball\": \"⛹\",\n    \"person_bouncing_ball_dark_skin_tone\": \"⛹🏿\",\n    \"person_bouncing_ball_light_skin_tone\": \"⛹🏻\",\n    \"person_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\",\n    \"person_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\",\n    \"person_bouncing_ball_medium_skin_tone\": \"⛹🏽\",\n    \"person_bowing\": \"🙇\",\n    \"person_bowing_dark_skin_tone\": \"🙇🏿\",\n    \"person_bowing_light_skin_tone\": \"🙇🏻\",\n    \"person_bowing_medium-dark_skin_tone\": \"🙇🏾\",\n    \"person_bowing_medium-light_skin_tone\": \"🙇🏼\",\n    \"person_bowing_medium_skin_tone\": \"🙇🏽\",\n    \"person_cartwheeling\": \"🤸\",\n    \"person_cartwheeling_dark_skin_tone\": \"🤸🏿\",\n    \"person_cartwheeling_light_skin_tone\": \"🤸🏻\",\n    \"person_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\",\n    \"person_cartwheeling_medium-light_skin_tone\": \"🤸🏼\",\n    \"person_cartwheeling_medium_skin_tone\": \"🤸🏽\",\n    \"person_climbing\": \"🧗\",\n    \"person_climbing_dark_skin_tone\": \"🧗🏿\",\n    \"person_climbing_light_skin_tone\": \"🧗🏻\",\n    \"person_climbing_medium-dark_skin_tone\": \"🧗🏾\",\n    \"person_climbing_medium-light_skin_tone\": \"🧗🏼\",\n    \"person_climbing_medium_skin_tone\": \"🧗🏽\",\n    \"person_facepalming\": \"🤦\",\n    \"person_facepalming_dark_skin_tone\": \"🤦🏿\",\n    \"person_facepalming_light_skin_tone\": \"🤦🏻\",\n    \"person_facepalming_medium-dark_skin_tone\": \"🤦🏾\",\n    \"person_facepalming_medium-light_skin_tone\": \"🤦🏼\",\n    \"person_facepalming_medium_skin_tone\": \"🤦🏽\",\n    \"person_fencing\": \"🤺\",\n    \"person_frowning\": \"🙍\",\n    \"person_frowning_dark_skin_tone\": \"🙍🏿\",\n    \"person_frowning_light_skin_tone\": \"🙍🏻\",\n    \"person_frowning_medium-dark_skin_tone\": \"🙍🏾\",\n    \"person_frowning_medium-light_skin_tone\": \"🙍🏼\",\n    \"person_frowning_medium_skin_tone\": \"🙍🏽\",\n    \"person_gesturing_no\": \"🙅\",\n    \"person_gesturing_no_dark_skin_tone\": \"🙅🏿\",\n    \"person_gesturing_no_light_skin_tone\": \"🙅🏻\",\n    \"person_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\",\n    \"person_gesturing_no_medium-light_skin_tone\": \"🙅🏼\",\n    \"person_gesturing_no_medium_skin_tone\": \"🙅🏽\",\n    \"person_gesturing_ok\": \"🙆\",\n    \"person_gesturing_ok_dark_skin_tone\": \"🙆🏿\",\n    \"person_gesturing_ok_light_skin_tone\": \"🙆🏻\",\n    \"person_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\",\n    \"person_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\",\n    \"person_gesturing_ok_medium_skin_tone\": \"🙆🏽\",\n    \"person_getting_haircut\": \"💇\",\n    \"person_getting_haircut_dark_skin_tone\": \"💇🏿\",\n    \"person_getting_haircut_light_skin_tone\": \"💇🏻\",\n    \"person_getting_haircut_medium-dark_skin_tone\": \"💇🏾\",\n    \"person_getting_haircut_medium-light_skin_tone\": \"💇🏼\",\n    \"person_getting_haircut_medium_skin_tone\": \"💇🏽\",\n    \"person_getting_massage\": \"💆\",\n    \"person_getting_massage_dark_skin_tone\": \"💆🏿\",\n    \"person_getting_massage_light_skin_tone\": \"💆🏻\",\n    \"person_getting_massage_medium-dark_skin_tone\": \"💆🏾\",\n    \"person_getting_massage_medium-light_skin_tone\": \"💆🏼\",\n    \"person_getting_massage_medium_skin_tone\": \"💆🏽\",\n    \"person_golfing\": \"🏌\",\n    \"person_golfing_dark_skin_tone\": \"🏌🏿\",\n    \"person_golfing_light_skin_tone\": \"🏌🏻\",\n    \"person_golfing_medium-dark_skin_tone\": \"🏌🏾\",\n    \"person_golfing_medium-light_skin_tone\": \"🏌🏼\",\n    \"person_golfing_medium_skin_tone\": \"🏌🏽\",\n    \"person_in_bed\": \"🛌\",\n    \"person_in_bed_dark_skin_tone\": \"🛌🏿\",\n    \"person_in_bed_light_skin_tone\": \"🛌🏻\",\n    \"person_in_bed_medium-dark_skin_tone\": \"🛌🏾\",\n    \"person_in_bed_medium-light_skin_tone\": \"🛌🏼\",\n    \"person_in_bed_medium_skin_tone\": \"🛌🏽\",\n    \"person_in_lotus_position\": \"🧘\",\n    \"person_in_lotus_position_dark_skin_tone\": \"🧘🏿\",\n    \"person_in_lotus_position_light_skin_tone\": \"🧘🏻\",\n    \"person_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\",\n    \"person_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\",\n    \"person_in_lotus_position_medium_skin_tone\": \"🧘🏽\",\n    \"person_in_steamy_room\": \"🧖\",\n    \"person_in_steamy_room_dark_skin_tone\": \"🧖🏿\",\n    \"person_in_steamy_room_light_skin_tone\": \"🧖🏻\",\n    \"person_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\",\n    \"person_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\",\n    \"person_in_steamy_room_medium_skin_tone\": \"🧖🏽\",\n    \"person_juggling\": \"🤹\",\n    \"person_juggling_dark_skin_tone\": \"🤹🏿\",\n    \"person_juggling_light_skin_tone\": \"🤹🏻\",\n    \"person_juggling_medium-dark_skin_tone\": \"🤹🏾\",\n    \"person_juggling_medium-light_skin_tone\": \"🤹🏼\",\n    \"person_juggling_medium_skin_tone\": \"🤹🏽\",\n    \"person_kneeling\": \"🧎\",\n    \"person_lifting_weights\": \"🏋\",\n    \"person_lifting_weights_dark_skin_tone\": \"🏋🏿\",\n    \"person_lifting_weights_light_skin_tone\": \"🏋🏻\",\n    \"person_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\",\n    \"person_lifting_weights_medium-light_skin_tone\": \"🏋🏼\",\n    \"person_lifting_weights_medium_skin_tone\": \"🏋🏽\",\n    \"person_mountain_biking\": \"🚵\",\n    \"person_mountain_biking_dark_skin_tone\": \"🚵🏿\",\n    \"person_mountain_biking_light_skin_tone\": \"🚵🏻\",\n    \"person_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\",\n    \"person_mountain_biking_medium-light_skin_tone\": \"🚵🏼\",\n    \"person_mountain_biking_medium_skin_tone\": \"🚵🏽\",\n    \"person_playing_handball\": \"🤾\",\n    \"person_playing_handball_dark_skin_tone\": \"🤾🏿\",\n    \"person_playing_handball_light_skin_tone\": \"🤾🏻\",\n    \"person_playing_handball_medium-dark_skin_tone\": \"🤾🏾\",\n    \"person_playing_handball_medium-light_skin_tone\": \"🤾🏼\",\n    \"person_playing_handball_medium_skin_tone\": \"🤾🏽\",\n    \"person_playing_water_polo\": \"🤽\",\n    \"person_playing_water_polo_dark_skin_tone\": \"🤽🏿\",\n    \"person_playing_water_polo_light_skin_tone\": \"🤽🏻\",\n    \"person_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\",\n    \"person_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\",\n    \"person_playing_water_polo_medium_skin_tone\": \"🤽🏽\",\n    \"person_pouting\": \"🙎\",\n    \"person_pouting_dark_skin_tone\": \"🙎🏿\",\n    \"person_pouting_light_skin_tone\": \"🙎🏻\",\n    \"person_pouting_medium-dark_skin_tone\": \"🙎🏾\",\n    \"person_pouting_medium-light_skin_tone\": \"🙎🏼\",\n    \"person_pouting_medium_skin_tone\": \"🙎🏽\",\n    \"person_raising_hand\": \"🙋\",\n    \"person_raising_hand_dark_skin_tone\": \"🙋🏿\",\n    \"person_raising_hand_light_skin_tone\": \"🙋🏻\",\n    \"person_raising_hand_medium-dark_skin_tone\": \"🙋🏾\",\n    \"person_raising_hand_medium-light_skin_tone\": \"🙋🏼\",\n    \"person_raising_hand_medium_skin_tone\": \"🙋🏽\",\n    \"person_rowing_boat\": \"🚣\",\n    \"person_rowing_boat_dark_skin_tone\": \"🚣🏿\",\n    \"person_rowing_boat_light_skin_tone\": \"🚣🏻\",\n    \"person_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\",\n    \"person_rowing_boat_medium-light_skin_tone\": \"🚣🏼\",\n    \"person_rowing_boat_medium_skin_tone\": \"🚣🏽\",\n    \"person_running\": \"🏃\",\n    \"person_running_dark_skin_tone\": \"🏃🏿\",\n    \"person_running_light_skin_tone\": \"🏃🏻\",\n    \"person_running_medium-dark_skin_tone\": \"🏃🏾\",\n    \"person_running_medium-light_skin_tone\": \"🏃🏼\",\n    \"person_running_medium_skin_tone\": \"🏃🏽\",\n    \"person_shrugging\": \"🤷\",\n    \"person_shrugging_dark_skin_tone\": \"🤷🏿\",\n    \"person_shrugging_light_skin_tone\": \"🤷🏻\",\n    \"person_shrugging_medium-dark_skin_tone\": \"🤷🏾\",\n    \"person_shrugging_medium-light_skin_tone\": \"🤷🏼\",\n    \"person_shrugging_medium_skin_tone\": \"🤷🏽\",\n    \"person_standing\": \"🧍\",\n    \"person_surfing\": \"🏄\",\n    \"person_surfing_dark_skin_tone\": \"🏄🏿\",\n    \"person_surfing_light_skin_tone\": \"🏄🏻\",\n    \"person_surfing_medium-dark_skin_tone\": \"🏄🏾\",\n    \"person_surfing_medium-light_skin_tone\": \"🏄🏼\",\n    \"person_surfing_medium_skin_tone\": \"🏄🏽\",\n    \"person_swimming\": \"🏊\",\n    \"person_swimming_dark_skin_tone\": \"🏊🏿\",\n    \"person_swimming_light_skin_tone\": \"🏊🏻\",\n    \"person_swimming_medium-dark_skin_tone\": \"🏊🏾\",\n    \"person_swimming_medium-light_skin_tone\": \"🏊🏼\",\n    \"person_swimming_medium_skin_tone\": \"🏊🏽\",\n    \"person_taking_bath\": \"🛀\",\n    \"person_taking_bath_dark_skin_tone\": \"🛀🏿\",\n    \"person_taking_bath_light_skin_tone\": \"🛀🏻\",\n    \"person_taking_bath_medium-dark_skin_tone\": \"🛀🏾\",\n    \"person_taking_bath_medium-light_skin_tone\": \"🛀🏼\",\n    \"person_taking_bath_medium_skin_tone\": \"🛀🏽\",\n    \"person_tipping_hand\": \"💁\",\n    \"person_tipping_hand_dark_skin_tone\": \"💁🏿\",\n    \"person_tipping_hand_light_skin_tone\": \"💁🏻\",\n    \"person_tipping_hand_medium-dark_skin_tone\": \"💁🏾\",\n    \"person_tipping_hand_medium-light_skin_tone\": \"💁🏼\",\n    \"person_tipping_hand_medium_skin_tone\": \"💁🏽\",\n    \"person_walking\": \"🚶\",\n    \"person_walking_dark_skin_tone\": \"🚶🏿\",\n    \"person_walking_light_skin_tone\": \"🚶🏻\",\n    \"person_walking_medium-dark_skin_tone\": \"🚶🏾\",\n    \"person_walking_medium-light_skin_tone\": \"🚶🏼\",\n    \"person_walking_medium_skin_tone\": \"🚶🏽\",\n    \"person_wearing_turban\": \"👳\",\n    \"person_wearing_turban_dark_skin_tone\": \"👳🏿\",\n    \"person_wearing_turban_light_skin_tone\": \"👳🏻\",\n    \"person_wearing_turban_medium-dark_skin_tone\": \"👳🏾\",\n    \"person_wearing_turban_medium-light_skin_tone\": \"👳🏼\",\n    \"person_wearing_turban_medium_skin_tone\": \"👳🏽\",\n    \"petri_dish\": \"🧫\",\n    \"pick\": \"⛏\",\n    \"pie\": \"🥧\",\n    \"pig\": \"🐷\",\n    \"pig_face\": \"🐷\",\n    \"pig_nose\": \"🐽\",\n    \"pile_of_poo\": \"💩\",\n    \"pill\": \"💊\",\n    \"pinching_hand\": \"🤏\",\n    \"pine_decoration\": \"🎍\",\n    \"pineapple\": \"🍍\",\n    \"ping_pong\": \"🏓\",\n    \"pirate_flag\": \"🏴\\u200d☠️\",\n    \"pistol\": \"🔫\",\n    \"pizza\": \"🍕\",\n    \"place_of_worship\": \"🛐\",\n    \"play_button\": \"▶\",\n    \"play_or_pause_button\": \"⏯\",\n    \"pleading_face\": \"🥺\",\n    \"police_car\": \"🚓\",\n    \"police_car_light\": \"🚨\",\n    \"police_officer\": \"👮\",\n    \"police_officer_dark_skin_tone\": \"👮🏿\",\n    \"police_officer_light_skin_tone\": \"👮🏻\",\n    \"police_officer_medium-dark_skin_tone\": \"👮🏾\",\n    \"police_officer_medium-light_skin_tone\": \"👮🏼\",\n    \"police_officer_medium_skin_tone\": \"👮🏽\",\n    \"poodle\": \"🐩\",\n    \"pool_8_ball\": \"🎱\",\n    \"popcorn\": \"🍿\",\n    \"post_office\": \"🏣\",\n    \"postal_horn\": \"📯\",\n    \"postbox\": \"📮\",\n    \"pot_of_food\": \"🍲\",\n    \"potable_water\": \"🚰\",\n    \"potato\": \"🥔\",\n    \"poultry_leg\": \"🍗\",\n    \"pound_banknote\": \"💷\",\n    \"pouting_cat_face\": \"😾\",\n    \"pouting_face\": \"😡\",\n    \"prayer_beads\": \"📿\",\n    \"pregnant_woman\": \"🤰\",\n    \"pregnant_woman_dark_skin_tone\": \"🤰🏿\",\n    \"pregnant_woman_light_skin_tone\": \"🤰🏻\",\n    \"pregnant_woman_medium-dark_skin_tone\": \"🤰🏾\",\n    \"pregnant_woman_medium-light_skin_tone\": \"🤰🏼\",\n    \"pregnant_woman_medium_skin_tone\": \"🤰🏽\",\n    \"pretzel\": \"🥨\",\n    \"probing_cane\": \"🦯\",\n    \"prince\": \"🤴\",\n    \"prince_dark_skin_tone\": \"🤴🏿\",\n    \"prince_light_skin_tone\": \"🤴🏻\",\n    \"prince_medium-dark_skin_tone\": \"🤴🏾\",\n    \"prince_medium-light_skin_tone\": \"🤴🏼\",\n    \"prince_medium_skin_tone\": \"🤴🏽\",\n    \"princess\": \"👸\",\n    \"princess_dark_skin_tone\": \"👸🏿\",\n    \"princess_light_skin_tone\": \"👸🏻\",\n    \"princess_medium-dark_skin_tone\": \"👸🏾\",\n    \"princess_medium-light_skin_tone\": \"👸🏼\",\n    \"princess_medium_skin_tone\": \"👸🏽\",\n    \"printer\": \"🖨\",\n    \"prohibited\": \"🚫\",\n    \"purple_circle\": \"🟣\",\n    \"purple_heart\": \"💜\",\n    \"purple_square\": \"🟪\",\n    \"purse\": \"👛\",\n    \"pushpin\": \"📌\",\n    \"question_mark\": \"❓\",\n    \"rabbit\": \"🐰\",\n    \"rabbit_face\": \"🐰\",\n    \"raccoon\": \"🦝\",\n    \"racing_car\": \"🏎\",\n    \"radio\": \"📻\",\n    \"radio_button\": \"🔘\",\n    \"radioactive\": \"☢\",\n    \"railway_car\": \"🚃\",\n    \"railway_track\": \"🛤\",\n    \"rainbow\": \"🌈\",\n    \"rainbow_flag\": \"🏳️\\u200d🌈\",\n    \"raised_back_of_hand\": \"🤚\",\n    \"raised_back_of_hand_dark_skin_tone\": \"🤚🏿\",\n    \"raised_back_of_hand_light_skin_tone\": \"🤚🏻\",\n    \"raised_back_of_hand_medium-dark_skin_tone\": \"🤚🏾\",\n    \"raised_back_of_hand_medium-light_skin_tone\": \"🤚🏼\",\n    \"raised_back_of_hand_medium_skin_tone\": \"🤚🏽\",\n    \"raised_fist\": \"✊\",\n    \"raised_fist_dark_skin_tone\": \"✊🏿\",\n    \"raised_fist_light_skin_tone\": \"✊🏻\",\n    \"raised_fist_medium-dark_skin_tone\": \"✊🏾\",\n    \"raised_fist_medium-light_skin_tone\": \"✊🏼\",\n    \"raised_fist_medium_skin_tone\": \"✊🏽\",\n    \"raised_hand\": \"✋\",\n    \"raised_hand_dark_skin_tone\": \"✋🏿\",\n    \"raised_hand_light_skin_tone\": \"✋🏻\",\n    \"raised_hand_medium-dark_skin_tone\": \"✋🏾\",\n    \"raised_hand_medium-light_skin_tone\": \"✋🏼\",\n    \"raised_hand_medium_skin_tone\": \"✋🏽\",\n    \"raising_hands\": \"🙌\",\n    \"raising_hands_dark_skin_tone\": \"🙌🏿\",\n    \"raising_hands_light_skin_tone\": \"🙌🏻\",\n    \"raising_hands_medium-dark_skin_tone\": \"🙌🏾\",\n    \"raising_hands_medium-light_skin_tone\": \"🙌🏼\",\n    \"raising_hands_medium_skin_tone\": \"🙌🏽\",\n    \"ram\": \"🐏\",\n    \"rat\": \"🐀\",\n    \"razor\": \"🪒\",\n    \"ringed_planet\": \"🪐\",\n    \"receipt\": \"🧾\",\n    \"record_button\": \"⏺\",\n    \"recycling_symbol\": \"♻\",\n    \"red_apple\": \"🍎\",\n    \"red_circle\": \"🔴\",\n    \"red_envelope\": \"🧧\",\n    \"red_hair\": \"🦰\",\n    \"red-haired_man\": \"👨\\u200d🦰\",\n    \"red-haired_woman\": \"👩\\u200d🦰\",\n    \"red_heart\": \"❤\",\n    \"red_paper_lantern\": \"🏮\",\n    \"red_square\": \"🟥\",\n    \"red_triangle_pointed_down\": \"🔻\",\n    \"red_triangle_pointed_up\": \"🔺\",\n    \"registered\": \"®\",\n    \"relieved_face\": \"😌\",\n    \"reminder_ribbon\": \"🎗\",\n    \"repeat_button\": \"🔁\",\n    \"repeat_single_button\": \"🔂\",\n    \"rescue_worker’s_helmet\": \"⛑\",\n    \"restroom\": \"🚻\",\n    \"reverse_button\": \"◀\",\n    \"revolving_hearts\": \"💞\",\n    \"rhinoceros\": \"🦏\",\n    \"ribbon\": \"🎀\",\n    \"rice_ball\": \"🍙\",\n    \"rice_cracker\": \"🍘\",\n    \"right-facing_fist\": \"🤜\",\n    \"right-facing_fist_dark_skin_tone\": \"🤜🏿\",\n    \"right-facing_fist_light_skin_tone\": \"🤜🏻\",\n    \"right-facing_fist_medium-dark_skin_tone\": \"🤜🏾\",\n    \"right-facing_fist_medium-light_skin_tone\": \"🤜🏼\",\n    \"right-facing_fist_medium_skin_tone\": \"🤜🏽\",\n    \"right_anger_bubble\": \"🗯\",\n    \"right_arrow\": \"➡\",\n    \"right_arrow_curving_down\": \"⤵\",\n    \"right_arrow_curving_left\": \"↩\",\n    \"right_arrow_curving_up\": \"⤴\",\n    \"ring\": \"💍\",\n    \"roasted_sweet_potato\": \"🍠\",\n    \"robot_face\": \"🤖\",\n    \"rocket\": \"🚀\",\n    \"roll_of_paper\": \"🧻\",\n    \"rolled-up_newspaper\": \"🗞\",\n    \"roller_coaster\": \"🎢\",\n    \"rolling_on_the_floor_laughing\": \"🤣\",\n    \"rooster\": \"🐓\",\n    \"rose\": \"🌹\",\n    \"rosette\": \"🏵\",\n    \"round_pushpin\": \"📍\",\n    \"rugby_football\": \"🏉\",\n    \"running_shirt\": \"🎽\",\n    \"running_shoe\": \"👟\",\n    \"sad_but_relieved_face\": \"😥\",\n    \"safety_pin\": \"🧷\",\n    \"safety_vest\": \"🦺\",\n    \"salt\": \"🧂\",\n    \"sailboat\": \"⛵\",\n    \"sake\": \"🍶\",\n    \"sandwich\": \"🥪\",\n    \"sari\": \"🥻\",\n    \"satellite\": \"📡\",\n    \"satellite_antenna\": \"📡\",\n    \"sauropod\": \"🦕\",\n    \"saxophone\": \"🎷\",\n    \"scarf\": \"🧣\",\n    \"school\": \"🏫\",\n    \"school_backpack\": \"🎒\",\n    \"scissors\": \"✂\",\n    \"scorpion\": \"🦂\",\n    \"scroll\": \"📜\",\n    \"seat\": \"💺\",\n    \"see-no-evil_monkey\": \"🙈\",\n    \"seedling\": \"🌱\",\n    \"selfie\": \"🤳\",\n    \"selfie_dark_skin_tone\": \"🤳🏿\",\n    \"selfie_light_skin_tone\": \"🤳🏻\",\n    \"selfie_medium-dark_skin_tone\": \"🤳🏾\",\n    \"selfie_medium-light_skin_tone\": \"🤳🏼\",\n    \"selfie_medium_skin_tone\": \"🤳🏽\",\n    \"service_dog\": \"🐕\\u200d🦺\",\n    \"seven-thirty\": \"🕢\",\n    \"seven_o’clock\": \"🕖\",\n    \"shallow_pan_of_food\": \"🥘\",\n    \"shamrock\": \"☘\",\n    \"shark\": \"🦈\",\n    \"shaved_ice\": \"🍧\",\n    \"sheaf_of_rice\": \"🌾\",\n    \"shield\": \"🛡\",\n    \"shinto_shrine\": \"⛩\",\n    \"ship\": \"🚢\",\n    \"shooting_star\": \"🌠\",\n    \"shopping_bags\": \"🛍\",\n    \"shopping_cart\": \"🛒\",\n    \"shortcake\": \"🍰\",\n    \"shorts\": \"🩳\",\n    \"shower\": \"🚿\",\n    \"shrimp\": \"🦐\",\n    \"shuffle_tracks_button\": \"🔀\",\n    \"shushing_face\": \"🤫\",\n    \"sign_of_the_horns\": \"🤘\",\n    \"sign_of_the_horns_dark_skin_tone\": \"🤘🏿\",\n    \"sign_of_the_horns_light_skin_tone\": \"🤘🏻\",\n    \"sign_of_the_horns_medium-dark_skin_tone\": \"🤘🏾\",\n    \"sign_of_the_horns_medium-light_skin_tone\": \"🤘🏼\",\n    \"sign_of_the_horns_medium_skin_tone\": \"🤘🏽\",\n    \"six-thirty\": \"🕡\",\n    \"six_o’clock\": \"🕕\",\n    \"skateboard\": \"🛹\",\n    \"skier\": \"⛷\",\n    \"skis\": \"🎿\",\n    \"skull\": \"💀\",\n    \"skull_and_crossbones\": \"☠\",\n    \"skunk\": \"🦨\",\n    \"sled\": \"🛷\",\n    \"sleeping_face\": \"😴\",\n    \"sleepy_face\": \"😪\",\n    \"slightly_frowning_face\": \"🙁\",\n    \"slightly_smiling_face\": \"🙂\",\n    \"slot_machine\": \"🎰\",\n    \"sloth\": \"🦥\",\n    \"small_airplane\": \"🛩\",\n    \"small_blue_diamond\": \"🔹\",\n    \"small_orange_diamond\": \"🔸\",\n    \"smiling_cat_face_with_heart-eyes\": \"😻\",\n    \"smiling_face\": \"☺\",\n    \"smiling_face_with_halo\": \"😇\",\n    \"smiling_face_with_3_hearts\": \"🥰\",\n    \"smiling_face_with_heart-eyes\": \"😍\",\n    \"smiling_face_with_horns\": \"😈\",\n    \"smiling_face_with_smiling_eyes\": \"😊\",\n    \"smiling_face_with_sunglasses\": \"😎\",\n    \"smirking_face\": \"😏\",\n    \"snail\": \"🐌\",\n    \"snake\": \"🐍\",\n    \"sneezing_face\": \"🤧\",\n    \"snow-capped_mountain\": \"🏔\",\n    \"snowboarder\": \"🏂\",\n    \"snowboarder_dark_skin_tone\": \"🏂🏿\",\n    \"snowboarder_light_skin_tone\": \"🏂🏻\",\n    \"snowboarder_medium-dark_skin_tone\": \"🏂🏾\",\n    \"snowboarder_medium-light_skin_tone\": \"🏂🏼\",\n    \"snowboarder_medium_skin_tone\": \"🏂🏽\",\n    \"snowflake\": \"❄\",\n    \"snowman\": \"☃\",\n    \"snowman_without_snow\": \"⛄\",\n    \"soap\": \"🧼\",\n    \"soccer_ball\": \"⚽\",\n    \"socks\": \"🧦\",\n    \"softball\": \"🥎\",\n    \"soft_ice_cream\": \"🍦\",\n    \"spade_suit\": \"♠\",\n    \"spaghetti\": \"🍝\",\n    \"sparkle\": \"❇\",\n    \"sparkler\": \"🎇\",\n    \"sparkles\": \"✨\",\n    \"sparkling_heart\": \"💖\",\n    \"speak-no-evil_monkey\": \"🙊\",\n    \"speaker_high_volume\": \"🔊\",\n    \"speaker_low_volume\": \"🔈\",\n    \"speaker_medium_volume\": \"🔉\",\n    \"speaking_head\": \"🗣\",\n    \"speech_balloon\": \"💬\",\n    \"speedboat\": \"🚤\",\n    \"spider\": \"🕷\",\n    \"spider_web\": \"🕸\",\n    \"spiral_calendar\": \"🗓\",\n    \"spiral_notepad\": \"🗒\",\n    \"spiral_shell\": \"🐚\",\n    \"spoon\": \"🥄\",\n    \"sponge\": \"🧽\",\n    \"sport_utility_vehicle\": \"🚙\",\n    \"sports_medal\": \"🏅\",\n    \"spouting_whale\": \"🐳\",\n    \"squid\": \"🦑\",\n    \"squinting_face_with_tongue\": \"😝\",\n    \"stadium\": \"🏟\",\n    \"star-struck\": \"🤩\",\n    \"star_and_crescent\": \"☪\",\n    \"star_of_david\": \"✡\",\n    \"station\": \"🚉\",\n    \"steaming_bowl\": \"🍜\",\n    \"stethoscope\": \"🩺\",\n    \"stop_button\": \"⏹\",\n    \"stop_sign\": \"🛑\",\n    \"stopwatch\": \"⏱\",\n    \"straight_ruler\": \"📏\",\n    \"strawberry\": \"🍓\",\n    \"studio_microphone\": \"🎙\",\n    \"stuffed_flatbread\": \"🥙\",\n    \"sun\": \"☀\",\n    \"sun_behind_cloud\": \"⛅\",\n    \"sun_behind_large_cloud\": \"🌥\",\n    \"sun_behind_rain_cloud\": \"🌦\",\n    \"sun_behind_small_cloud\": \"🌤\",\n    \"sun_with_face\": \"🌞\",\n    \"sunflower\": \"🌻\",\n    \"sunglasses\": \"😎\",\n    \"sunrise\": \"🌅\",\n    \"sunrise_over_mountains\": \"🌄\",\n    \"sunset\": \"🌇\",\n    \"superhero\": \"🦸\",\n    \"supervillain\": \"🦹\",\n    \"sushi\": \"🍣\",\n    \"suspension_railway\": \"🚟\",\n    \"swan\": \"🦢\",\n    \"sweat_droplets\": \"💦\",\n    \"synagogue\": \"🕍\",\n    \"syringe\": \"💉\",\n    \"t-shirt\": \"👕\",\n    \"taco\": \"🌮\",\n    \"takeout_box\": \"🥡\",\n    \"tanabata_tree\": \"🎋\",\n    \"tangerine\": \"🍊\",\n    \"taxi\": \"🚕\",\n    \"teacup_without_handle\": \"🍵\",\n    \"tear-off_calendar\": \"📆\",\n    \"teddy_bear\": \"🧸\",\n    \"telephone\": \"☎\",\n    \"telephone_receiver\": \"📞\",\n    \"telescope\": \"🔭\",\n    \"television\": \"📺\",\n    \"ten-thirty\": \"🕥\",\n    \"ten_o’clock\": \"🕙\",\n    \"tennis\": \"🎾\",\n    \"tent\": \"⛺\",\n    \"test_tube\": \"🧪\",\n    \"thermometer\": \"🌡\",\n    \"thinking_face\": \"🤔\",\n    \"thought_balloon\": \"💭\",\n    \"thread\": \"🧵\",\n    \"three-thirty\": \"🕞\",\n    \"three_o’clock\": \"🕒\",\n    \"thumbs_down\": \"👎\",\n    \"thumbs_down_dark_skin_tone\": \"👎🏿\",\n    \"thumbs_down_light_skin_tone\": \"👎🏻\",\n    \"thumbs_down_medium-dark_skin_tone\": \"👎🏾\",\n    \"thumbs_down_medium-light_skin_tone\": \"👎🏼\",\n    \"thumbs_down_medium_skin_tone\": \"👎🏽\",\n    \"thumbs_up\": \"👍\",\n    \"thumbs_up_dark_skin_tone\": \"👍🏿\",\n    \"thumbs_up_light_skin_tone\": \"👍🏻\",\n    \"thumbs_up_medium-dark_skin_tone\": \"👍🏾\",\n    \"thumbs_up_medium-light_skin_tone\": \"👍🏼\",\n    \"thumbs_up_medium_skin_tone\": \"👍🏽\",\n    \"ticket\": \"🎫\",\n    \"tiger\": \"🐯\",\n    \"tiger_face\": \"🐯\",\n    \"timer_clock\": \"⏲\",\n    \"tired_face\": \"😫\",\n    \"toolbox\": \"🧰\",\n    \"toilet\": \"🚽\",\n    \"tomato\": \"🍅\",\n    \"tongue\": \"👅\",\n    \"tooth\": \"🦷\",\n    \"top_hat\": \"🎩\",\n    \"tornado\": \"🌪\",\n    \"trackball\": \"🖲\",\n    \"tractor\": \"🚜\",\n    \"trade_mark\": \"™\",\n    \"train\": \"🚋\",\n    \"tram\": \"🚊\",\n    \"tram_car\": \"🚋\",\n    \"triangular_flag\": \"🚩\",\n    \"triangular_ruler\": \"📐\",\n    \"trident_emblem\": \"🔱\",\n    \"trolleybus\": \"🚎\",\n    \"trophy\": \"🏆\",\n    \"tropical_drink\": \"🍹\",\n    \"tropical_fish\": \"🐠\",\n    \"trumpet\": \"🎺\",\n    \"tulip\": \"🌷\",\n    \"tumbler_glass\": \"🥃\",\n    \"turtle\": \"🐢\",\n    \"twelve-thirty\": \"🕧\",\n    \"twelve_o’clock\": \"🕛\",\n    \"two-hump_camel\": \"🐫\",\n    \"two-thirty\": \"🕝\",\n    \"two_hearts\": \"💕\",\n    \"two_men_holding_hands\": \"👬\",\n    \"two_o’clock\": \"🕑\",\n    \"two_women_holding_hands\": \"👭\",\n    \"umbrella\": \"☂\",\n    \"umbrella_on_ground\": \"⛱\",\n    \"umbrella_with_rain_drops\": \"☔\",\n    \"unamused_face\": \"😒\",\n    \"unicorn_face\": \"🦄\",\n    \"unlocked\": \"🔓\",\n    \"up-down_arrow\": \"↕\",\n    \"up-left_arrow\": \"↖\",\n    \"up-right_arrow\": \"↗\",\n    \"up_arrow\": \"⬆\",\n    \"upside-down_face\": \"🙃\",\n    \"upwards_button\": \"🔼\",\n    \"vampire\": \"🧛\",\n    \"vampire_dark_skin_tone\": \"🧛🏿\",\n    \"vampire_light_skin_tone\": \"🧛🏻\",\n    \"vampire_medium-dark_skin_tone\": \"🧛🏾\",\n    \"vampire_medium-light_skin_tone\": \"🧛🏼\",\n    \"vampire_medium_skin_tone\": \"🧛🏽\",\n    \"vertical_traffic_light\": \"🚦\",\n    \"vibration_mode\": \"📳\",\n    \"victory_hand\": \"✌\",\n    \"victory_hand_dark_skin_tone\": \"✌🏿\",\n    \"victory_hand_light_skin_tone\": \"✌🏻\",\n    \"victory_hand_medium-dark_skin_tone\": \"✌🏾\",\n    \"victory_hand_medium-light_skin_tone\": \"✌🏼\",\n    \"victory_hand_medium_skin_tone\": \"✌🏽\",\n    \"video_camera\": \"📹\",\n    \"video_game\": \"🎮\",\n    \"videocassette\": \"📼\",\n    \"violin\": \"🎻\",\n    \"volcano\": \"🌋\",\n    \"volleyball\": \"🏐\",\n    \"vulcan_salute\": \"🖖\",\n    \"vulcan_salute_dark_skin_tone\": \"🖖🏿\",\n    \"vulcan_salute_light_skin_tone\": \"🖖🏻\",\n    \"vulcan_salute_medium-dark_skin_tone\": \"🖖🏾\",\n    \"vulcan_salute_medium-light_skin_tone\": \"🖖🏼\",\n    \"vulcan_salute_medium_skin_tone\": \"🖖🏽\",\n    \"waffle\": \"🧇\",\n    \"waning_crescent_moon\": \"🌘\",\n    \"waning_gibbous_moon\": \"🌖\",\n    \"warning\": \"⚠\",\n    \"wastebasket\": \"🗑\",\n    \"watch\": \"⌚\",\n    \"water_buffalo\": \"🐃\",\n    \"water_closet\": \"🚾\",\n    \"water_wave\": \"🌊\",\n    \"watermelon\": \"🍉\",\n    \"waving_hand\": \"👋\",\n    \"waving_hand_dark_skin_tone\": \"👋🏿\",\n    \"waving_hand_light_skin_tone\": \"👋🏻\",\n    \"waving_hand_medium-dark_skin_tone\": \"👋🏾\",\n    \"waving_hand_medium-light_skin_tone\": \"👋🏼\",\n    \"waving_hand_medium_skin_tone\": \"👋🏽\",\n    \"wavy_dash\": \"〰\",\n    \"waxing_crescent_moon\": \"🌒\",\n    \"waxing_gibbous_moon\": \"🌔\",\n    \"weary_cat_face\": \"🙀\",\n    \"weary_face\": \"😩\",\n    \"wedding\": \"💒\",\n    \"whale\": \"🐳\",\n    \"wheel_of_dharma\": \"☸\",\n    \"wheelchair_symbol\": \"♿\",\n    \"white_circle\": \"⚪\",\n    \"white_exclamation_mark\": \"❕\",\n    \"white_flag\": \"🏳\",\n    \"white_flower\": \"💮\",\n    \"white_hair\": \"🦳\",\n    \"white-haired_man\": \"👨\\u200d🦳\",\n    \"white-haired_woman\": \"👩\\u200d🦳\",\n    \"white_heart\": \"🤍\",\n    \"white_heavy_check_mark\": \"✅\",\n    \"white_large_square\": \"⬜\",\n    \"white_medium-small_square\": \"◽\",\n    \"white_medium_square\": \"◻\",\n    \"white_medium_star\": \"⭐\",\n    \"white_question_mark\": \"❔\",\n    \"white_small_square\": \"▫\",\n    \"white_square_button\": \"🔳\",\n    \"wilted_flower\": \"🥀\",\n    \"wind_chime\": \"🎐\",\n    \"wind_face\": \"🌬\",\n    \"wine_glass\": \"🍷\",\n    \"winking_face\": \"😉\",\n    \"winking_face_with_tongue\": \"😜\",\n    \"wolf_face\": \"🐺\",\n    \"woman\": \"👩\",\n    \"woman_artist\": \"👩\\u200d🎨\",\n    \"woman_artist_dark_skin_tone\": \"👩🏿\\u200d🎨\",\n    \"woman_artist_light_skin_tone\": \"👩🏻\\u200d🎨\",\n    \"woman_artist_medium-dark_skin_tone\": \"👩🏾\\u200d🎨\",\n    \"woman_artist_medium-light_skin_tone\": \"👩🏼\\u200d🎨\",\n    \"woman_artist_medium_skin_tone\": \"👩🏽\\u200d🎨\",\n    \"woman_astronaut\": \"👩\\u200d🚀\",\n    \"woman_astronaut_dark_skin_tone\": \"👩🏿\\u200d🚀\",\n    \"woman_astronaut_light_skin_tone\": \"👩🏻\\u200d🚀\",\n    \"woman_astronaut_medium-dark_skin_tone\": \"👩🏾\\u200d🚀\",\n    \"woman_astronaut_medium-light_skin_tone\": \"👩🏼\\u200d🚀\",\n    \"woman_astronaut_medium_skin_tone\": \"👩🏽\\u200d🚀\",\n    \"woman_biking\": \"🚴\\u200d♀️\",\n    \"woman_biking_dark_skin_tone\": \"🚴🏿\\u200d♀️\",\n    \"woman_biking_light_skin_tone\": \"🚴🏻\\u200d♀️\",\n    \"woman_biking_medium-dark_skin_tone\": \"🚴🏾\\u200d♀️\",\n    \"woman_biking_medium-light_skin_tone\": \"🚴🏼\\u200d♀️\",\n    \"woman_biking_medium_skin_tone\": \"🚴🏽\\u200d♀️\",\n    \"woman_bouncing_ball\": \"⛹️\\u200d♀️\",\n    \"woman_bouncing_ball_dark_skin_tone\": \"⛹🏿\\u200d♀️\",\n    \"woman_bouncing_ball_light_skin_tone\": \"⛹🏻\\u200d♀️\",\n    \"woman_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\\u200d♀️\",\n    \"woman_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\\u200d♀️\",\n    \"woman_bouncing_ball_medium_skin_tone\": \"⛹🏽\\u200d♀️\",\n    \"woman_bowing\": \"🙇\\u200d♀️\",\n    \"woman_bowing_dark_skin_tone\": \"🙇🏿\\u200d♀️\",\n    \"woman_bowing_light_skin_tone\": \"🙇🏻\\u200d♀️\",\n    \"woman_bowing_medium-dark_skin_tone\": \"🙇🏾\\u200d♀️\",\n    \"woman_bowing_medium-light_skin_tone\": \"🙇🏼\\u200d♀️\",\n    \"woman_bowing_medium_skin_tone\": \"🙇🏽\\u200d♀️\",\n    \"woman_cartwheeling\": \"🤸\\u200d♀️\",\n    \"woman_cartwheeling_dark_skin_tone\": \"🤸🏿\\u200d♀️\",\n    \"woman_cartwheeling_light_skin_tone\": \"🤸🏻\\u200d♀️\",\n    \"woman_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\\u200d♀️\",\n    \"woman_cartwheeling_medium-light_skin_tone\": \"🤸🏼\\u200d♀️\",\n    \"woman_cartwheeling_medium_skin_tone\": \"🤸🏽\\u200d♀️\",\n    \"woman_climbing\": \"🧗\\u200d♀️\",\n    \"woman_climbing_dark_skin_tone\": \"🧗🏿\\u200d♀️\",\n    \"woman_climbing_light_skin_tone\": \"🧗🏻\\u200d♀️\",\n    \"woman_climbing_medium-dark_skin_tone\": \"🧗🏾\\u200d♀️\",\n    \"woman_climbing_medium-light_skin_tone\": \"🧗🏼\\u200d♀️\",\n    \"woman_climbing_medium_skin_tone\": \"🧗🏽\\u200d♀️\",\n    \"woman_construction_worker\": \"👷\\u200d♀️\",\n    \"woman_construction_worker_dark_skin_tone\": \"👷🏿\\u200d♀️\",\n    \"woman_construction_worker_light_skin_tone\": \"👷🏻\\u200d♀️\",\n    \"woman_construction_worker_medium-dark_skin_tone\": \"👷🏾\\u200d♀️\",\n    \"woman_construction_worker_medium-light_skin_tone\": \"👷🏼\\u200d♀️\",\n    \"woman_construction_worker_medium_skin_tone\": \"👷🏽\\u200d♀️\",\n    \"woman_cook\": \"👩\\u200d🍳\",\n    \"woman_cook_dark_skin_tone\": \"👩🏿\\u200d🍳\",\n    \"woman_cook_light_skin_tone\": \"👩🏻\\u200d🍳\",\n    \"woman_cook_medium-dark_skin_tone\": \"👩🏾\\u200d🍳\",\n    \"woman_cook_medium-light_skin_tone\": \"👩🏼\\u200d🍳\",\n    \"woman_cook_medium_skin_tone\": \"👩🏽\\u200d🍳\",\n    \"woman_dancing\": \"💃\",\n    \"woman_dancing_dark_skin_tone\": \"💃🏿\",\n    \"woman_dancing_light_skin_tone\": \"💃🏻\",\n    \"woman_dancing_medium-dark_skin_tone\": \"💃🏾\",\n    \"woman_dancing_medium-light_skin_tone\": \"💃🏼\",\n    \"woman_dancing_medium_skin_tone\": \"💃🏽\",\n    \"woman_dark_skin_tone\": \"👩🏿\",\n    \"woman_detective\": \"🕵️\\u200d♀️\",\n    \"woman_detective_dark_skin_tone\": \"🕵🏿\\u200d♀️\",\n    \"woman_detective_light_skin_tone\": \"🕵🏻\\u200d♀️\",\n    \"woman_detective_medium-dark_skin_tone\": \"🕵🏾\\u200d♀️\",\n    \"woman_detective_medium-light_skin_tone\": \"🕵🏼\\u200d♀️\",\n    \"woman_detective_medium_skin_tone\": \"🕵🏽\\u200d♀️\",\n    \"woman_elf\": \"🧝\\u200d♀️\",\n    \"woman_elf_dark_skin_tone\": \"🧝🏿\\u200d♀️\",\n    \"woman_elf_light_skin_tone\": \"🧝🏻\\u200d♀️\",\n    \"woman_elf_medium-dark_skin_tone\": \"🧝🏾\\u200d♀️\",\n    \"woman_elf_medium-light_skin_tone\": \"🧝🏼\\u200d♀️\",\n    \"woman_elf_medium_skin_tone\": \"🧝🏽\\u200d♀️\",\n    \"woman_facepalming\": \"🤦\\u200d♀️\",\n    \"woman_facepalming_dark_skin_tone\": \"🤦🏿\\u200d♀️\",\n    \"woman_facepalming_light_skin_tone\": \"🤦🏻\\u200d♀️\",\n    \"woman_facepalming_medium-dark_skin_tone\": \"🤦🏾\\u200d♀️\",\n    \"woman_facepalming_medium-light_skin_tone\": \"🤦🏼\\u200d♀️\",\n    \"woman_facepalming_medium_skin_tone\": \"🤦🏽\\u200d♀️\",\n    \"woman_factory_worker\": \"👩\\u200d🏭\",\n    \"woman_factory_worker_dark_skin_tone\": \"👩🏿\\u200d🏭\",\n    \"woman_factory_worker_light_skin_tone\": \"👩🏻\\u200d🏭\",\n    \"woman_factory_worker_medium-dark_skin_tone\": \"👩🏾\\u200d🏭\",\n    \"woman_factory_worker_medium-light_skin_tone\": \"👩🏼\\u200d🏭\",\n    \"woman_factory_worker_medium_skin_tone\": \"👩🏽\\u200d🏭\",\n    \"woman_fairy\": \"🧚\\u200d♀️\",\n    \"woman_fairy_dark_skin_tone\": \"🧚🏿\\u200d♀️\",\n    \"woman_fairy_light_skin_tone\": \"🧚🏻\\u200d♀️\",\n    \"woman_fairy_medium-dark_skin_tone\": \"🧚🏾\\u200d♀️\",\n    \"woman_fairy_medium-light_skin_tone\": \"🧚🏼\\u200d♀️\",\n    \"woman_fairy_medium_skin_tone\": \"🧚🏽\\u200d♀️\",\n    \"woman_farmer\": \"👩\\u200d🌾\",\n    \"woman_farmer_dark_skin_tone\": \"👩🏿\\u200d🌾\",\n    \"woman_farmer_light_skin_tone\": \"👩🏻\\u200d🌾\",\n    \"woman_farmer_medium-dark_skin_tone\": \"👩🏾\\u200d🌾\",\n    \"woman_farmer_medium-light_skin_tone\": \"👩🏼\\u200d🌾\",\n    \"woman_farmer_medium_skin_tone\": \"👩🏽\\u200d🌾\",\n    \"woman_firefighter\": \"👩\\u200d🚒\",\n    \"woman_firefighter_dark_skin_tone\": \"👩🏿\\u200d🚒\",\n    \"woman_firefighter_light_skin_tone\": \"👩🏻\\u200d🚒\",\n    \"woman_firefighter_medium-dark_skin_tone\": \"👩🏾\\u200d🚒\",\n    \"woman_firefighter_medium-light_skin_tone\": \"👩🏼\\u200d🚒\",\n    \"woman_firefighter_medium_skin_tone\": \"👩🏽\\u200d🚒\",\n    \"woman_frowning\": \"🙍\\u200d♀️\",\n    \"woman_frowning_dark_skin_tone\": \"🙍🏿\\u200d♀️\",\n    \"woman_frowning_light_skin_tone\": \"🙍🏻\\u200d♀️\",\n    \"woman_frowning_medium-dark_skin_tone\": \"🙍🏾\\u200d♀️\",\n    \"woman_frowning_medium-light_skin_tone\": \"🙍🏼\\u200d♀️\",\n    \"woman_frowning_medium_skin_tone\": \"🙍🏽\\u200d♀️\",\n    \"woman_genie\": \"🧞\\u200d♀️\",\n    \"woman_gesturing_no\": \"🙅\\u200d♀️\",\n    \"woman_gesturing_no_dark_skin_tone\": \"🙅🏿\\u200d♀️\",\n    \"woman_gesturing_no_light_skin_tone\": \"🙅🏻\\u200d♀️\",\n    \"woman_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\\u200d♀️\",\n    \"woman_gesturing_no_medium-light_skin_tone\": \"🙅🏼\\u200d♀️\",\n    \"woman_gesturing_no_medium_skin_tone\": \"🙅🏽\\u200d♀️\",\n    \"woman_gesturing_ok\": \"🙆\\u200d♀️\",\n    \"woman_gesturing_ok_dark_skin_tone\": \"🙆🏿\\u200d♀️\",\n    \"woman_gesturing_ok_light_skin_tone\": \"🙆🏻\\u200d♀️\",\n    \"woman_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\\u200d♀️\",\n    \"woman_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\\u200d♀️\",\n    \"woman_gesturing_ok_medium_skin_tone\": \"🙆🏽\\u200d♀️\",\n    \"woman_getting_haircut\": \"💇\\u200d♀️\",\n    \"woman_getting_haircut_dark_skin_tone\": \"💇🏿\\u200d♀️\",\n    \"woman_getting_haircut_light_skin_tone\": \"💇🏻\\u200d♀️\",\n    \"woman_getting_haircut_medium-dark_skin_tone\": \"💇🏾\\u200d♀️\",\n    \"woman_getting_haircut_medium-light_skin_tone\": \"💇🏼\\u200d♀️\",\n    \"woman_getting_haircut_medium_skin_tone\": \"💇🏽\\u200d♀️\",\n    \"woman_getting_massage\": \"💆\\u200d♀️\",\n    \"woman_getting_massage_dark_skin_tone\": \"💆🏿\\u200d♀️\",\n    \"woman_getting_massage_light_skin_tone\": \"💆🏻\\u200d♀️\",\n    \"woman_getting_massage_medium-dark_skin_tone\": \"💆🏾\\u200d♀️\",\n    \"woman_getting_massage_medium-light_skin_tone\": \"💆🏼\\u200d♀️\",\n    \"woman_getting_massage_medium_skin_tone\": \"💆🏽\\u200d♀️\",\n    \"woman_golfing\": \"🏌️\\u200d♀️\",\n    \"woman_golfing_dark_skin_tone\": \"🏌🏿\\u200d♀️\",\n    \"woman_golfing_light_skin_tone\": \"🏌🏻\\u200d♀️\",\n    \"woman_golfing_medium-dark_skin_tone\": \"🏌🏾\\u200d♀️\",\n    \"woman_golfing_medium-light_skin_tone\": \"🏌🏼\\u200d♀️\",\n    \"woman_golfing_medium_skin_tone\": \"🏌🏽\\u200d♀️\",\n    \"woman_guard\": \"💂\\u200d♀️\",\n    \"woman_guard_dark_skin_tone\": \"💂🏿\\u200d♀️\",\n    \"woman_guard_light_skin_tone\": \"💂🏻\\u200d♀️\",\n    \"woman_guard_medium-dark_skin_tone\": \"💂🏾\\u200d♀️\",\n    \"woman_guard_medium-light_skin_tone\": \"💂🏼\\u200d♀️\",\n    \"woman_guard_medium_skin_tone\": \"💂🏽\\u200d♀️\",\n    \"woman_health_worker\": \"👩\\u200d⚕️\",\n    \"woman_health_worker_dark_skin_tone\": \"👩🏿\\u200d⚕️\",\n    \"woman_health_worker_light_skin_tone\": \"👩🏻\\u200d⚕️\",\n    \"woman_health_worker_medium-dark_skin_tone\": \"👩🏾\\u200d⚕️\",\n    \"woman_health_worker_medium-light_skin_tone\": \"👩🏼\\u200d⚕️\",\n    \"woman_health_worker_medium_skin_tone\": \"👩🏽\\u200d⚕️\",\n    \"woman_in_lotus_position\": \"🧘\\u200d♀️\",\n    \"woman_in_lotus_position_dark_skin_tone\": \"🧘🏿\\u200d♀️\",\n    \"woman_in_lotus_position_light_skin_tone\": \"🧘🏻\\u200d♀️\",\n    \"woman_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\\u200d♀️\",\n    \"woman_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\\u200d♀️\",\n    \"woman_in_lotus_position_medium_skin_tone\": \"🧘🏽\\u200d♀️\",\n    \"woman_in_manual_wheelchair\": \"👩\\u200d🦽\",\n    \"woman_in_motorized_wheelchair\": \"👩\\u200d🦼\",\n    \"woman_in_steamy_room\": \"🧖\\u200d♀️\",\n    \"woman_in_steamy_room_dark_skin_tone\": \"🧖🏿\\u200d♀️\",\n    \"woman_in_steamy_room_light_skin_tone\": \"🧖🏻\\u200d♀️\",\n    \"woman_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\\u200d♀️\",\n    \"woman_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\\u200d♀️\",\n    \"woman_in_steamy_room_medium_skin_tone\": \"🧖🏽\\u200d♀️\",\n    \"woman_judge\": \"👩\\u200d⚖️\",\n    \"woman_judge_dark_skin_tone\": \"👩🏿\\u200d⚖️\",\n    \"woman_judge_light_skin_tone\": \"👩🏻\\u200d⚖️\",\n    \"woman_judge_medium-dark_skin_tone\": \"👩🏾\\u200d⚖️\",\n    \"woman_judge_medium-light_skin_tone\": \"👩🏼\\u200d⚖️\",\n    \"woman_judge_medium_skin_tone\": \"👩🏽\\u200d⚖️\",\n    \"woman_juggling\": \"🤹\\u200d♀️\",\n    \"woman_juggling_dark_skin_tone\": \"🤹🏿\\u200d♀️\",\n    \"woman_juggling_light_skin_tone\": \"🤹🏻\\u200d♀️\",\n    \"woman_juggling_medium-dark_skin_tone\": \"🤹🏾\\u200d♀️\",\n    \"woman_juggling_medium-light_skin_tone\": \"🤹🏼\\u200d♀️\",\n    \"woman_juggling_medium_skin_tone\": \"🤹🏽\\u200d♀️\",\n    \"woman_lifting_weights\": \"🏋️\\u200d♀️\",\n    \"woman_lifting_weights_dark_skin_tone\": \"🏋🏿\\u200d♀️\",\n    \"woman_lifting_weights_light_skin_tone\": \"🏋🏻\\u200d♀️\",\n    \"woman_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\\u200d♀️\",\n    \"woman_lifting_weights_medium-light_skin_tone\": \"🏋🏼\\u200d♀️\",\n    \"woman_lifting_weights_medium_skin_tone\": \"🏋🏽\\u200d♀️\",\n    \"woman_light_skin_tone\": \"👩🏻\",\n    \"woman_mage\": \"🧙\\u200d♀️\",\n    \"woman_mage_dark_skin_tone\": \"🧙🏿\\u200d♀️\",\n    \"woman_mage_light_skin_tone\": \"🧙🏻\\u200d♀️\",\n    \"woman_mage_medium-dark_skin_tone\": \"🧙🏾\\u200d♀️\",\n    \"woman_mage_medium-light_skin_tone\": \"🧙🏼\\u200d♀️\",\n    \"woman_mage_medium_skin_tone\": \"🧙🏽\\u200d♀️\",\n    \"woman_mechanic\": \"👩\\u200d🔧\",\n    \"woman_mechanic_dark_skin_tone\": \"👩🏿\\u200d🔧\",\n    \"woman_mechanic_light_skin_tone\": \"👩🏻\\u200d🔧\",\n    \"woman_mechanic_medium-dark_skin_tone\": \"👩🏾\\u200d🔧\",\n    \"woman_mechanic_medium-light_skin_tone\": \"👩🏼\\u200d🔧\",\n    \"woman_mechanic_medium_skin_tone\": \"👩🏽\\u200d🔧\",\n    \"woman_medium-dark_skin_tone\": \"👩🏾\",\n    \"woman_medium-light_skin_tone\": \"👩🏼\",\n    \"woman_medium_skin_tone\": \"👩🏽\",\n    \"woman_mountain_biking\": \"🚵\\u200d♀️\",\n    \"woman_mountain_biking_dark_skin_tone\": \"🚵🏿\\u200d♀️\",\n    \"woman_mountain_biking_light_skin_tone\": \"🚵🏻\\u200d♀️\",\n    \"woman_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\\u200d♀️\",\n    \"woman_mountain_biking_medium-light_skin_tone\": \"🚵🏼\\u200d♀️\",\n    \"woman_mountain_biking_medium_skin_tone\": \"🚵🏽\\u200d♀️\",\n    \"woman_office_worker\": \"👩\\u200d💼\",\n    \"woman_office_worker_dark_skin_tone\": \"👩🏿\\u200d💼\",\n    \"woman_office_worker_light_skin_tone\": \"👩🏻\\u200d💼\",\n    \"woman_office_worker_medium-dark_skin_tone\": \"👩🏾\\u200d💼\",\n    \"woman_office_worker_medium-light_skin_tone\": \"👩🏼\\u200d💼\",\n    \"woman_office_worker_medium_skin_tone\": \"👩🏽\\u200d💼\",\n    \"woman_pilot\": \"👩\\u200d✈️\",\n    \"woman_pilot_dark_skin_tone\": \"👩🏿\\u200d✈️\",\n    \"woman_pilot_light_skin_tone\": \"👩🏻\\u200d✈️\",\n    \"woman_pilot_medium-dark_skin_tone\": \"👩🏾\\u200d✈️\",\n    \"woman_pilot_medium-light_skin_tone\": \"👩🏼\\u200d✈️\",\n    \"woman_pilot_medium_skin_tone\": \"👩🏽\\u200d✈️\",\n    \"woman_playing_handball\": \"🤾\\u200d♀️\",\n    \"woman_playing_handball_dark_skin_tone\": \"🤾🏿\\u200d♀️\",\n    \"woman_playing_handball_light_skin_tone\": \"🤾🏻\\u200d♀️\",\n    \"woman_playing_handball_medium-dark_skin_tone\": \"🤾🏾\\u200d♀️\",\n    \"woman_playing_handball_medium-light_skin_tone\": \"🤾🏼\\u200d♀️\",\n    \"woman_playing_handball_medium_skin_tone\": \"🤾🏽\\u200d♀️\",\n    \"woman_playing_water_polo\": \"🤽\\u200d♀️\",\n    \"woman_playing_water_polo_dark_skin_tone\": \"🤽🏿\\u200d♀️\",\n    \"woman_playing_water_polo_light_skin_tone\": \"🤽🏻\\u200d♀️\",\n    \"woman_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\\u200d♀️\",\n    \"woman_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\\u200d♀️\",\n    \"woman_playing_water_polo_medium_skin_tone\": \"🤽🏽\\u200d♀️\",\n    \"woman_police_officer\": \"👮\\u200d♀️\",\n    \"woman_police_officer_dark_skin_tone\": \"👮🏿\\u200d♀️\",\n    \"woman_police_officer_light_skin_tone\": \"👮🏻\\u200d♀️\",\n    \"woman_police_officer_medium-dark_skin_tone\": \"👮🏾\\u200d♀️\",\n    \"woman_police_officer_medium-light_skin_tone\": \"👮🏼\\u200d♀️\",\n    \"woman_police_officer_medium_skin_tone\": \"👮🏽\\u200d♀️\",\n    \"woman_pouting\": \"🙎\\u200d♀️\",\n    \"woman_pouting_dark_skin_tone\": \"🙎🏿\\u200d♀️\",\n    \"woman_pouting_light_skin_tone\": \"🙎🏻\\u200d♀️\",\n    \"woman_pouting_medium-dark_skin_tone\": \"🙎🏾\\u200d♀️\",\n    \"woman_pouting_medium-light_skin_tone\": \"🙎🏼\\u200d♀️\",\n    \"woman_pouting_medium_skin_tone\": \"🙎🏽\\u200d♀️\",\n    \"woman_raising_hand\": \"🙋\\u200d♀️\",\n    \"woman_raising_hand_dark_skin_tone\": \"🙋🏿\\u200d♀️\",\n    \"woman_raising_hand_light_skin_tone\": \"🙋🏻\\u200d♀️\",\n    \"woman_raising_hand_medium-dark_skin_tone\": \"🙋🏾\\u200d♀️\",\n    \"woman_raising_hand_medium-light_skin_tone\": \"🙋🏼\\u200d♀️\",\n    \"woman_raising_hand_medium_skin_tone\": \"🙋🏽\\u200d♀️\",\n    \"woman_rowing_boat\": \"🚣\\u200d♀️\",\n    \"woman_rowing_boat_dark_skin_tone\": \"🚣🏿\\u200d♀️\",\n    \"woman_rowing_boat_light_skin_tone\": \"🚣🏻\\u200d♀️\",\n    \"woman_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\\u200d♀️\",\n    \"woman_rowing_boat_medium-light_skin_tone\": \"🚣🏼\\u200d♀️\",\n    \"woman_rowing_boat_medium_skin_tone\": \"🚣🏽\\u200d♀️\",\n    \"woman_running\": \"🏃\\u200d♀️\",\n    \"woman_running_dark_skin_tone\": \"🏃🏿\\u200d♀️\",\n    \"woman_running_light_skin_tone\": \"🏃🏻\\u200d♀️\",\n    \"woman_running_medium-dark_skin_tone\": \"🏃🏾\\u200d♀️\",\n    \"woman_running_medium-light_skin_tone\": \"🏃🏼\\u200d♀️\",\n    \"woman_running_medium_skin_tone\": \"🏃🏽\\u200d♀️\",\n    \"woman_scientist\": \"👩\\u200d🔬\",\n    \"woman_scientist_dark_skin_tone\": \"👩🏿\\u200d🔬\",\n    \"woman_scientist_light_skin_tone\": \"👩🏻\\u200d🔬\",\n    \"woman_scientist_medium-dark_skin_tone\": \"👩🏾\\u200d🔬\",\n    \"woman_scientist_medium-light_skin_tone\": \"👩🏼\\u200d🔬\",\n    \"woman_scientist_medium_skin_tone\": \"👩🏽\\u200d🔬\",\n    \"woman_shrugging\": \"🤷\\u200d♀️\",\n    \"woman_shrugging_dark_skin_tone\": \"🤷🏿\\u200d♀️\",\n    \"woman_shrugging_light_skin_tone\": \"🤷🏻\\u200d♀️\",\n    \"woman_shrugging_medium-dark_skin_tone\": \"🤷🏾\\u200d♀️\",\n    \"woman_shrugging_medium-light_skin_tone\": \"🤷🏼\\u200d♀️\",\n    \"woman_shrugging_medium_skin_tone\": \"🤷🏽\\u200d♀️\",\n    \"woman_singer\": \"👩\\u200d🎤\",\n    \"woman_singer_dark_skin_tone\": \"👩🏿\\u200d🎤\",\n    \"woman_singer_light_skin_tone\": \"👩🏻\\u200d🎤\",\n    \"woman_singer_medium-dark_skin_tone\": \"👩🏾\\u200d🎤\",\n    \"woman_singer_medium-light_skin_tone\": \"👩🏼\\u200d🎤\",\n    \"woman_singer_medium_skin_tone\": \"👩🏽\\u200d🎤\",\n    \"woman_student\": \"👩\\u200d🎓\",\n    \"woman_student_dark_skin_tone\": \"👩🏿\\u200d🎓\",\n    \"woman_student_light_skin_tone\": \"👩🏻\\u200d🎓\",\n    \"woman_student_medium-dark_skin_tone\": \"👩🏾\\u200d🎓\",\n    \"woman_student_medium-light_skin_tone\": \"👩🏼\\u200d🎓\",\n    \"woman_student_medium_skin_tone\": \"👩🏽\\u200d🎓\",\n    \"woman_surfing\": \"🏄\\u200d♀️\",\n    \"woman_surfing_dark_skin_tone\": \"🏄🏿\\u200d♀️\",\n    \"woman_surfing_light_skin_tone\": \"🏄🏻\\u200d♀️\",\n    \"woman_surfing_medium-dark_skin_tone\": \"🏄🏾\\u200d♀️\",\n    \"woman_surfing_medium-light_skin_tone\": \"🏄🏼\\u200d♀️\",\n    \"woman_surfing_medium_skin_tone\": \"🏄🏽\\u200d♀️\",\n    \"woman_swimming\": \"🏊\\u200d♀️\",\n    \"woman_swimming_dark_skin_tone\": \"🏊🏿\\u200d♀️\",\n    \"woman_swimming_light_skin_tone\": \"🏊🏻\\u200d♀️\",\n    \"woman_swimming_medium-dark_skin_tone\": \"🏊🏾\\u200d♀️\",\n    \"woman_swimming_medium-light_skin_tone\": \"🏊🏼\\u200d♀️\",\n    \"woman_swimming_medium_skin_tone\": \"🏊🏽\\u200d♀️\",\n    \"woman_teacher\": \"👩\\u200d🏫\",\n    \"woman_teacher_dark_skin_tone\": \"👩🏿\\u200d🏫\",\n    \"woman_teacher_light_skin_tone\": \"👩🏻\\u200d🏫\",\n    \"woman_teacher_medium-dark_skin_tone\": \"👩🏾\\u200d🏫\",\n    \"woman_teacher_medium-light_skin_tone\": \"👩🏼\\u200d🏫\",\n    \"woman_teacher_medium_skin_tone\": \"👩🏽\\u200d🏫\",\n    \"woman_technologist\": \"👩\\u200d💻\",\n    \"woman_technologist_dark_skin_tone\": \"👩🏿\\u200d💻\",\n    \"woman_technologist_light_skin_tone\": \"👩🏻\\u200d💻\",\n    \"woman_technologist_medium-dark_skin_tone\": \"👩🏾\\u200d💻\",\n    \"woman_technologist_medium-light_skin_tone\": \"👩🏼\\u200d💻\",\n    \"woman_technologist_medium_skin_tone\": \"👩🏽\\u200d💻\",\n    \"woman_tipping_hand\": \"💁\\u200d♀️\",\n    \"woman_tipping_hand_dark_skin_tone\": \"💁🏿\\u200d♀️\",\n    \"woman_tipping_hand_light_skin_tone\": \"💁🏻\\u200d♀️\",\n    \"woman_tipping_hand_medium-dark_skin_tone\": \"💁🏾\\u200d♀️\",\n    \"woman_tipping_hand_medium-light_skin_tone\": \"💁🏼\\u200d♀️\",\n    \"woman_tipping_hand_medium_skin_tone\": \"💁🏽\\u200d♀️\",\n    \"woman_vampire\": \"🧛\\u200d♀️\",\n    \"woman_vampire_dark_skin_tone\": \"🧛🏿\\u200d♀️\",\n    \"woman_vampire_light_skin_tone\": \"🧛🏻\\u200d♀️\",\n    \"woman_vampire_medium-dark_skin_tone\": \"🧛🏾\\u200d♀️\",\n    \"woman_vampire_medium-light_skin_tone\": \"🧛🏼\\u200d♀️\",\n    \"woman_vampire_medium_skin_tone\": \"🧛🏽\\u200d♀️\",\n    \"woman_walking\": \"🚶\\u200d♀️\",\n    \"woman_walking_dark_skin_tone\": \"🚶🏿\\u200d♀️\",\n    \"woman_walking_light_skin_tone\": \"🚶🏻\\u200d♀️\",\n    \"woman_walking_medium-dark_skin_tone\": \"🚶🏾\\u200d♀️\",\n    \"woman_walking_medium-light_skin_tone\": \"🚶🏼\\u200d♀️\",\n    \"woman_walking_medium_skin_tone\": \"🚶🏽\\u200d♀️\",\n    \"woman_wearing_turban\": \"👳\\u200d♀️\",\n    \"woman_wearing_turban_dark_skin_tone\": \"👳🏿\\u200d♀️\",\n    \"woman_wearing_turban_light_skin_tone\": \"👳🏻\\u200d♀️\",\n    \"woman_wearing_turban_medium-dark_skin_tone\": \"👳🏾\\u200d♀️\",\n    \"woman_wearing_turban_medium-light_skin_tone\": \"👳🏼\\u200d♀️\",\n    \"woman_wearing_turban_medium_skin_tone\": \"👳🏽\\u200d♀️\",\n    \"woman_with_headscarf\": \"🧕\",\n    \"woman_with_headscarf_dark_skin_tone\": \"🧕🏿\",\n    \"woman_with_headscarf_light_skin_tone\": \"🧕🏻\",\n    \"woman_with_headscarf_medium-dark_skin_tone\": \"🧕🏾\",\n    \"woman_with_headscarf_medium-light_skin_tone\": \"🧕🏼\",\n    \"woman_with_headscarf_medium_skin_tone\": \"🧕🏽\",\n    \"woman_with_probing_cane\": \"👩\\u200d🦯\",\n    \"woman_zombie\": \"🧟\\u200d♀️\",\n    \"woman’s_boot\": \"👢\",\n    \"woman’s_clothes\": \"👚\",\n    \"woman’s_hat\": \"👒\",\n    \"woman’s_sandal\": \"👡\",\n    \"women_with_bunny_ears\": \"👯\\u200d♀️\",\n    \"women_wrestling\": \"🤼\\u200d♀️\",\n    \"women’s_room\": \"🚺\",\n    \"woozy_face\": \"🥴\",\n    \"world_map\": \"🗺\",\n    \"worried_face\": \"😟\",\n    \"wrapped_gift\": \"🎁\",\n    \"wrench\": \"🔧\",\n    \"writing_hand\": \"✍\",\n    \"writing_hand_dark_skin_tone\": \"✍🏿\",\n    \"writing_hand_light_skin_tone\": \"✍🏻\",\n    \"writing_hand_medium-dark_skin_tone\": \"✍🏾\",\n    \"writing_hand_medium-light_skin_tone\": \"✍🏼\",\n    \"writing_hand_medium_skin_tone\": \"✍🏽\",\n    \"yarn\": \"🧶\",\n    \"yawning_face\": \"🥱\",\n    \"yellow_circle\": \"🟡\",\n    \"yellow_heart\": \"💛\",\n    \"yellow_square\": \"🟨\",\n    \"yen_banknote\": \"💴\",\n    \"yo-yo\": \"🪀\",\n    \"yin_yang\": \"☯\",\n    \"zany_face\": \"🤪\",\n    \"zebra\": \"🦓\",\n    \"zipper-mouth_face\": \"🤐\",\n    \"zombie\": \"🧟\",\n    \"zzz\": \"💤\",\n    \"åland_islands\": \"🇦🇽\",\n    \"keycap_asterisk\": \"*⃣\",\n    \"keycap_digit_eight\": \"8⃣\",\n    \"keycap_digit_five\": \"5⃣\",\n    \"keycap_digit_four\": \"4⃣\",\n    \"keycap_digit_nine\": \"9⃣\",\n    \"keycap_digit_one\": \"1⃣\",\n    \"keycap_digit_seven\": \"7⃣\",\n    \"keycap_digit_six\": \"6⃣\",\n    \"keycap_digit_three\": \"3⃣\",\n    \"keycap_digit_two\": \"2⃣\",\n    \"keycap_digit_zero\": \"0⃣\",\n    \"keycap_number_sign\": \"#⃣\",\n    \"light_skin_tone\": \"🏻\",\n    \"medium_light_skin_tone\": \"🏼\",\n    \"medium_skin_tone\": \"🏽\",\n    \"medium_dark_skin_tone\": \"🏾\",\n    \"dark_skin_tone\": \"🏿\",\n    \"regional_indicator_symbol_letter_a\": \"🇦\",\n    \"regional_indicator_symbol_letter_b\": \"🇧\",\n    \"regional_indicator_symbol_letter_c\": \"🇨\",\n    \"regional_indicator_symbol_letter_d\": \"🇩\",\n    \"regional_indicator_symbol_letter_e\": \"🇪\",\n    \"regional_indicator_symbol_letter_f\": \"🇫\",\n    \"regional_indicator_symbol_letter_g\": \"🇬\",\n    \"regional_indicator_symbol_letter_h\": \"🇭\",\n    \"regional_indicator_symbol_letter_i\": \"🇮\",\n    \"regional_indicator_symbol_letter_j\": \"🇯\",\n    \"regional_indicator_symbol_letter_k\": \"🇰\",\n    \"regional_indicator_symbol_letter_l\": \"🇱\",\n    \"regional_indicator_symbol_letter_m\": \"🇲\",\n    \"regional_indicator_symbol_letter_n\": \"🇳\",\n    \"regional_indicator_symbol_letter_o\": \"🇴\",\n    \"regional_indicator_symbol_letter_p\": \"🇵\",\n    \"regional_indicator_symbol_letter_q\": \"🇶\",\n    \"regional_indicator_symbol_letter_r\": \"🇷\",\n    \"regional_indicator_symbol_letter_s\": \"🇸\",\n    \"regional_indicator_symbol_letter_t\": \"🇹\",\n    \"regional_indicator_symbol_letter_u\": \"🇺\",\n    \"regional_indicator_symbol_letter_v\": \"🇻\",\n    \"regional_indicator_symbol_letter_w\": \"🇼\",\n    \"regional_indicator_symbol_letter_x\": \"🇽\",\n    \"regional_indicator_symbol_letter_y\": \"🇾\",\n    \"regional_indicator_symbol_letter_z\": \"🇿\",\n    \"airplane_arriving\": \"🛬\",\n    \"space_invader\": \"👾\",\n    \"football\": \"🏈\",\n    \"anger\": \"💢\",\n    \"angry\": \"😠\",\n    \"anguished\": \"😧\",\n    \"signal_strength\": \"📶\",\n    \"arrows_counterclockwise\": \"🔄\",\n    \"arrow_heading_down\": \"⤵\",\n    \"arrow_heading_up\": \"⤴\",\n    \"art\": \"🎨\",\n    \"astonished\": \"😲\",\n    \"athletic_shoe\": \"👟\",\n    \"atm\": \"🏧\",\n    \"car\": \"🚗\",\n    \"red_car\": \"🚗\",\n    \"angel\": \"👼\",\n    \"back\": \"🔙\",\n    \"badminton_racquet_and_shuttlecock\": \"🏸\",\n    \"dollar\": \"💵\",\n    \"euro\": \"💶\",\n    \"pound\": \"💷\",\n    \"yen\": \"💴\",\n    \"barber\": \"💈\",\n    \"bath\": \"🛀\",\n    \"bear\": \"🐻\",\n    \"heartbeat\": \"💓\",\n    \"beer\": \"🍺\",\n    \"no_bell\": \"🔕\",\n    \"bento\": \"🍱\",\n    \"bike\": \"🚲\",\n    \"bicyclist\": \"🚴\",\n    \"8ball\": \"🎱\",\n    \"biohazard_sign\": \"☣\",\n    \"birthday\": \"🎂\",\n    \"black_circle_for_record\": \"⏺\",\n    \"clubs\": \"♣\",\n    \"diamonds\": \"♦\",\n    \"arrow_double_down\": \"⏬\",\n    \"hearts\": \"♥\",\n    \"rewind\": \"⏪\",\n    \"black_left__pointing_double_triangle_with_vertical_bar\": \"⏮\",\n    \"arrow_backward\": \"◀\",\n    \"black_medium_small_square\": \"◾\",\n    \"question\": \"❓\",\n    \"fast_forward\": \"⏩\",\n    \"black_right__pointing_double_triangle_with_vertical_bar\": \"⏭\",\n    \"arrow_forward\": \"▶\",\n    \"black_right__pointing_triangle_with_double_vertical_bar\": \"⏯\",\n    \"arrow_right\": \"➡\",\n    \"spades\": \"♠\",\n    \"black_square_for_stop\": \"⏹\",\n    \"sunny\": \"☀\",\n    \"phone\": \"☎\",\n    \"recycle\": \"♻\",\n    \"arrow_double_up\": \"⏫\",\n    \"busstop\": \"🚏\",\n    \"date\": \"📅\",\n    \"flags\": \"🎏\",\n    \"cat2\": \"🐈\",\n    \"joy_cat\": \"😹\",\n    \"smirk_cat\": \"😼\",\n    \"chart_with_downwards_trend\": \"📉\",\n    \"chart_with_upwards_trend\": \"📈\",\n    \"chart\": \"💹\",\n    \"mega\": \"📣\",\n    \"checkered_flag\": \"🏁\",\n    \"accept\": \"🉑\",\n    \"ideograph_advantage\": \"🉐\",\n    \"congratulations\": \"㊗\",\n    \"secret\": \"㊙\",\n    \"m\": \"Ⓜ\",\n    \"city_sunset\": \"🌆\",\n    \"clapper\": \"🎬\",\n    \"clap\": \"👏\",\n    \"beers\": \"🍻\",\n    \"clock830\": \"🕣\",\n    \"clock8\": \"🕗\",\n    \"clock1130\": \"🕦\",\n    \"clock11\": \"🕚\",\n    \"clock530\": \"🕠\",\n    \"clock5\": \"🕔\",\n    \"clock430\": \"🕟\",\n    \"clock4\": \"🕓\",\n    \"clock930\": \"🕤\",\n    \"clock9\": \"🕘\",\n    \"clock130\": \"🕜\",\n    \"clock1\": \"🕐\",\n    \"clock730\": \"🕢\",\n    \"clock7\": \"🕖\",\n    \"clock630\": \"🕡\",\n    \"clock6\": \"🕕\",\n    \"clock1030\": \"🕥\",\n    \"clock10\": \"🕙\",\n    \"clock330\": \"🕞\",\n    \"clock3\": \"🕒\",\n    \"clock1230\": \"🕧\",\n    \"clock12\": \"🕛\",\n    \"clock230\": \"🕝\",\n    \"clock2\": \"🕑\",\n    \"arrows_clockwise\": \"🔃\",\n    \"repeat\": \"🔁\",\n    \"repeat_one\": \"🔂\",\n    \"closed_lock_with_key\": \"🔐\",\n    \"mailbox_closed\": \"📪\",\n    \"mailbox\": \"📫\",\n    \"cloud_with_tornado\": \"🌪\",\n    \"cocktail\": \"🍸\",\n    \"boom\": \"💥\",\n    \"compression\": \"🗜\",\n    \"confounded\": \"😖\",\n    \"confused\": \"😕\",\n    \"rice\": \"🍚\",\n    \"cow2\": \"🐄\",\n    \"cricket_bat_and_ball\": \"🏏\",\n    \"x\": \"❌\",\n    \"cry\": \"😢\",\n    \"curry\": \"🍛\",\n    \"dagger_knife\": \"🗡\",\n    \"dancer\": \"💃\",\n    \"dark_sunglasses\": \"🕶\",\n    \"dash\": \"💨\",\n    \"truck\": \"🚚\",\n    \"derelict_house_building\": \"🏚\",\n    \"diamond_shape_with_a_dot_inside\": \"💠\",\n    \"dart\": \"🎯\",\n    \"disappointed_relieved\": \"😥\",\n    \"disappointed\": \"😞\",\n    \"do_not_litter\": \"🚯\",\n    \"dog2\": \"🐕\",\n    \"flipper\": \"🐬\",\n    \"loop\": \"➿\",\n    \"bangbang\": \"‼\",\n    \"double_vertical_bar\": \"⏸\",\n    \"dove_of_peace\": \"🕊\",\n    \"small_red_triangle_down\": \"🔻\",\n    \"arrow_down_small\": \"🔽\",\n    \"arrow_down\": \"⬇\",\n    \"dromedary_camel\": \"🐪\",\n    \"e__mail\": \"📧\",\n    \"corn\": \"🌽\",\n    \"ear_of_rice\": \"🌾\",\n    \"earth_americas\": \"🌎\",\n    \"earth_asia\": \"🌏\",\n    \"earth_africa\": \"🌍\",\n    \"eight_pointed_black_star\": \"✴\",\n    \"eight_spoked_asterisk\": \"✳\",\n    \"eject_symbol\": \"⏏\",\n    \"bulb\": \"💡\",\n    \"emoji_modifier_fitzpatrick_type__1__2\": \"🏻\",\n    \"emoji_modifier_fitzpatrick_type__3\": \"🏼\",\n    \"emoji_modifier_fitzpatrick_type__4\": \"🏽\",\n    \"emoji_modifier_fitzpatrick_type__5\": \"🏾\",\n    \"emoji_modifier_fitzpatrick_type__6\": \"🏿\",\n    \"end\": \"🔚\",\n    \"email\": \"✉\",\n    \"european_castle\": \"🏰\",\n    \"european_post_office\": \"🏤\",\n    \"interrobang\": \"⁉\",\n    \"expressionless\": \"😑\",\n    \"eyeglasses\": \"👓\",\n    \"massage\": \"💆\",\n    \"yum\": \"😋\",\n    \"scream\": \"😱\",\n    \"kissing_heart\": \"😘\",\n    \"sweat\": \"😓\",\n    \"face_with_head__bandage\": \"🤕\",\n    \"triumph\": \"😤\",\n    \"mask\": \"😷\",\n    \"no_good\": \"🙅\",\n    \"ok_woman\": \"🙆\",\n    \"open_mouth\": \"😮\",\n    \"cold_sweat\": \"😰\",\n    \"stuck_out_tongue\": \"😛\",\n    \"stuck_out_tongue_closed_eyes\": \"😝\",\n    \"stuck_out_tongue_winking_eye\": \"😜\",\n    \"joy\": \"😂\",\n    \"no_mouth\": \"😶\",\n    \"santa\": \"🎅\",\n    \"fax\": \"📠\",\n    \"fearful\": \"😨\",\n    \"field_hockey_stick_and_ball\": \"🏑\",\n    \"first_quarter_moon_with_face\": \"🌛\",\n    \"fish_cake\": \"🍥\",\n    \"fishing_pole_and_fish\": \"🎣\",\n    \"facepunch\": \"👊\",\n    \"punch\": \"👊\",\n    \"flag_for_afghanistan\": \"🇦🇫\",\n    \"flag_for_albania\": \"🇦🇱\",\n    \"flag_for_algeria\": \"🇩🇿\",\n    \"flag_for_american_samoa\": \"🇦🇸\",\n    \"flag_for_andorra\": \"🇦🇩\",\n    \"flag_for_angola\": \"🇦🇴\",\n    \"flag_for_anguilla\": \"🇦🇮\",\n    \"flag_for_antarctica\": \"🇦🇶\",\n    \"flag_for_antigua_&_barbuda\": \"🇦🇬\",\n    \"flag_for_argentina\": \"🇦🇷\",\n    \"flag_for_armenia\": \"🇦🇲\",\n    \"flag_for_aruba\": \"🇦🇼\",\n    \"flag_for_ascension_island\": \"🇦🇨\",\n    \"flag_for_australia\": \"🇦🇺\",\n    \"flag_for_austria\": \"🇦🇹\",\n    \"flag_for_azerbaijan\": \"🇦🇿\",\n    \"flag_for_bahamas\": \"🇧🇸\",\n    \"flag_for_bahrain\": \"🇧🇭\",\n    \"flag_for_bangladesh\": \"🇧🇩\",\n    \"flag_for_barbados\": \"🇧🇧\",\n    \"flag_for_belarus\": \"🇧🇾\",\n    \"flag_for_belgium\": \"🇧🇪\",\n    \"flag_for_belize\": \"🇧🇿\",\n    \"flag_for_benin\": \"🇧🇯\",\n    \"flag_for_bermuda\": \"🇧🇲\",\n    \"flag_for_bhutan\": \"🇧🇹\",\n    \"flag_for_bolivia\": \"🇧🇴\",\n    \"flag_for_bosnia_&_herzegovina\": \"🇧🇦\",\n    \"flag_for_botswana\": \"🇧🇼\",\n    \"flag_for_bouvet_island\": \"🇧🇻\",\n    \"flag_for_brazil\": \"🇧🇷\",\n    \"flag_for_british_indian_ocean_territory\": \"🇮🇴\",\n    \"flag_for_british_virgin_islands\": \"🇻🇬\",\n    \"flag_for_brunei\": \"🇧🇳\",\n    \"flag_for_bulgaria\": \"🇧🇬\",\n    \"flag_for_burkina_faso\": \"🇧🇫\",\n    \"flag_for_burundi\": \"🇧🇮\",\n    \"flag_for_cambodia\": \"🇰🇭\",\n    \"flag_for_cameroon\": \"🇨🇲\",\n    \"flag_for_canada\": \"🇨🇦\",\n    \"flag_for_canary_islands\": \"🇮🇨\",\n    \"flag_for_cape_verde\": \"🇨🇻\",\n    \"flag_for_caribbean_netherlands\": \"🇧🇶\",\n    \"flag_for_cayman_islands\": \"🇰🇾\",\n    \"flag_for_central_african_republic\": \"🇨🇫\",\n    \"flag_for_ceuta_&_melilla\": \"🇪🇦\",\n    \"flag_for_chad\": \"🇹🇩\",\n    \"flag_for_chile\": \"🇨🇱\",\n    \"flag_for_china\": \"🇨🇳\",\n    \"flag_for_christmas_island\": \"🇨🇽\",\n    \"flag_for_clipperton_island\": \"🇨🇵\",\n    \"flag_for_cocos__islands\": \"🇨🇨\",\n    \"flag_for_colombia\": \"🇨🇴\",\n    \"flag_for_comoros\": \"🇰🇲\",\n    \"flag_for_congo____brazzaville\": \"🇨🇬\",\n    \"flag_for_congo____kinshasa\": \"🇨🇩\",\n    \"flag_for_cook_islands\": \"🇨🇰\",\n    \"flag_for_costa_rica\": \"🇨🇷\",\n    \"flag_for_croatia\": \"🇭🇷\",\n    \"flag_for_cuba\": \"🇨🇺\",\n    \"flag_for_curaçao\": \"🇨🇼\",\n    \"flag_for_cyprus\": \"🇨🇾\",\n    \"flag_for_czech_republic\": \"🇨🇿\",\n    \"flag_for_côte_d’ivoire\": \"🇨🇮\",\n    \"flag_for_denmark\": \"🇩🇰\",\n    \"flag_for_diego_garcia\": \"🇩🇬\",\n    \"flag_for_djibouti\": \"🇩🇯\",\n    \"flag_for_dominica\": \"🇩🇲\",\n    \"flag_for_dominican_republic\": \"🇩🇴\",\n    \"flag_for_ecuador\": \"🇪🇨\",\n    \"flag_for_egypt\": \"🇪🇬\",\n    \"flag_for_el_salvador\": \"🇸🇻\",\n    \"flag_for_equatorial_guinea\": \"🇬🇶\",\n    \"flag_for_eritrea\": \"🇪🇷\",\n    \"flag_for_estonia\": \"🇪🇪\",\n    \"flag_for_ethiopia\": \"🇪🇹\",\n    \"flag_for_european_union\": \"🇪🇺\",\n    \"flag_for_falkland_islands\": \"🇫🇰\",\n    \"flag_for_faroe_islands\": \"🇫🇴\",\n    \"flag_for_fiji\": \"🇫🇯\",\n    \"flag_for_finland\": \"🇫🇮\",\n    \"flag_for_france\": \"🇫🇷\",\n    \"flag_for_french_guiana\": \"🇬🇫\",\n    \"flag_for_french_polynesia\": \"🇵🇫\",\n    \"flag_for_french_southern_territories\": \"🇹🇫\",\n    \"flag_for_gabon\": \"🇬🇦\",\n    \"flag_for_gambia\": \"🇬🇲\",\n    \"flag_for_georgia\": \"🇬🇪\",\n    \"flag_for_germany\": \"🇩🇪\",\n    \"flag_for_ghana\": \"🇬🇭\",\n    \"flag_for_gibraltar\": \"🇬🇮\",\n    \"flag_for_greece\": \"🇬🇷\",\n    \"flag_for_greenland\": \"🇬🇱\",\n    \"flag_for_grenada\": \"🇬🇩\",\n    \"flag_for_guadeloupe\": \"🇬🇵\",\n    \"flag_for_guam\": \"🇬🇺\",\n    \"flag_for_guatemala\": \"🇬🇹\",\n    \"flag_for_guernsey\": \"🇬🇬\",\n    \"flag_for_guinea\": \"🇬🇳\",\n    \"flag_for_guinea__bissau\": \"🇬🇼\",\n    \"flag_for_guyana\": \"🇬🇾\",\n    \"flag_for_haiti\": \"🇭🇹\",\n    \"flag_for_heard_&_mcdonald_islands\": \"🇭🇲\",\n    \"flag_for_honduras\": \"🇭🇳\",\n    \"flag_for_hong_kong\": \"🇭🇰\",\n    \"flag_for_hungary\": \"🇭🇺\",\n    \"flag_for_iceland\": \"🇮🇸\",\n    \"flag_for_india\": \"🇮🇳\",\n    \"flag_for_indonesia\": \"🇮🇩\",\n    \"flag_for_iran\": \"🇮🇷\",\n    \"flag_for_iraq\": \"🇮🇶\",\n    \"flag_for_ireland\": \"🇮🇪\",\n    \"flag_for_isle_of_man\": \"🇮🇲\",\n    \"flag_for_israel\": \"🇮🇱\",\n    \"flag_for_italy\": \"🇮🇹\",\n    \"flag_for_jamaica\": \"🇯🇲\",\n    \"flag_for_japan\": \"🇯🇵\",\n    \"flag_for_jersey\": \"🇯🇪\",\n    \"flag_for_jordan\": \"🇯🇴\",\n    \"flag_for_kazakhstan\": \"🇰🇿\",\n    \"flag_for_kenya\": \"🇰🇪\",\n    \"flag_for_kiribati\": \"🇰🇮\",\n    \"flag_for_kosovo\": \"🇽🇰\",\n    \"flag_for_kuwait\": \"🇰🇼\",\n    \"flag_for_kyrgyzstan\": \"🇰🇬\",\n    \"flag_for_laos\": \"🇱🇦\",\n    \"flag_for_latvia\": \"🇱🇻\",\n    \"flag_for_lebanon\": \"🇱🇧\",\n    \"flag_for_lesotho\": \"🇱🇸\",\n    \"flag_for_liberia\": \"🇱🇷\",\n    \"flag_for_libya\": \"🇱🇾\",\n    \"flag_for_liechtenstein\": \"🇱🇮\",\n    \"flag_for_lithuania\": \"🇱🇹\",\n    \"flag_for_luxembourg\": \"🇱🇺\",\n    \"flag_for_macau\": \"🇲🇴\",\n    \"flag_for_macedonia\": \"🇲🇰\",\n    \"flag_for_madagascar\": \"🇲🇬\",\n    \"flag_for_malawi\": \"🇲🇼\",\n    \"flag_for_malaysia\": \"🇲🇾\",\n    \"flag_for_maldives\": \"🇲🇻\",\n    \"flag_for_mali\": \"🇲🇱\",\n    \"flag_for_malta\": \"🇲🇹\",\n    \"flag_for_marshall_islands\": \"🇲🇭\",\n    \"flag_for_martinique\": \"🇲🇶\",\n    \"flag_for_mauritania\": \"🇲🇷\",\n    \"flag_for_mauritius\": \"🇲🇺\",\n    \"flag_for_mayotte\": \"🇾🇹\",\n    \"flag_for_mexico\": \"🇲🇽\",\n    \"flag_for_micronesia\": \"🇫🇲\",\n    \"flag_for_moldova\": \"🇲🇩\",\n    \"flag_for_monaco\": \"🇲🇨\",\n    \"flag_for_mongolia\": \"🇲🇳\",\n    \"flag_for_montenegro\": \"🇲🇪\",\n    \"flag_for_montserrat\": \"🇲🇸\",\n    \"flag_for_morocco\": \"🇲🇦\",\n    \"flag_for_mozambique\": \"🇲🇿\",\n    \"flag_for_myanmar\": \"🇲🇲\",\n    \"flag_for_namibia\": \"🇳🇦\",\n    \"flag_for_nauru\": \"🇳🇷\",\n    \"flag_for_nepal\": \"🇳🇵\",\n    \"flag_for_netherlands\": \"🇳🇱\",\n    \"flag_for_new_caledonia\": \"🇳🇨\",\n    \"flag_for_new_zealand\": \"🇳🇿\",\n    \"flag_for_nicaragua\": \"🇳🇮\",\n    \"flag_for_niger\": \"🇳🇪\",\n    \"flag_for_nigeria\": \"🇳🇬\",\n    \"flag_for_niue\": \"🇳🇺\",\n    \"flag_for_norfolk_island\": \"🇳🇫\",\n    \"flag_for_north_korea\": \"🇰🇵\",\n    \"flag_for_northern_mariana_islands\": \"🇲🇵\",\n    \"flag_for_norway\": \"🇳🇴\",\n    \"flag_for_oman\": \"🇴🇲\",\n    \"flag_for_pakistan\": \"🇵🇰\",\n    \"flag_for_palau\": \"🇵🇼\",\n    \"flag_for_palestinian_territories\": \"🇵🇸\",\n    \"flag_for_panama\": \"🇵🇦\",\n    \"flag_for_papua_new_guinea\": \"🇵🇬\",\n    \"flag_for_paraguay\": \"🇵🇾\",\n    \"flag_for_peru\": \"🇵🇪\",\n    \"flag_for_philippines\": \"🇵🇭\",\n    \"flag_for_pitcairn_islands\": \"🇵🇳\",\n    \"flag_for_poland\": \"🇵🇱\",\n    \"flag_for_portugal\": \"🇵🇹\",\n    \"flag_for_puerto_rico\": \"🇵🇷\",\n    \"flag_for_qatar\": \"🇶🇦\",\n    \"flag_for_romania\": \"🇷🇴\",\n    \"flag_for_russia\": \"🇷🇺\",\n    \"flag_for_rwanda\": \"🇷🇼\",\n    \"flag_for_réunion\": \"🇷🇪\",\n    \"flag_for_samoa\": \"🇼🇸\",\n    \"flag_for_san_marino\": \"🇸🇲\",\n    \"flag_for_saudi_arabia\": \"🇸🇦\",\n    \"flag_for_senegal\": \"🇸🇳\",\n    \"flag_for_serbia\": \"🇷🇸\",\n    \"flag_for_seychelles\": \"🇸🇨\",\n    \"flag_for_sierra_leone\": \"🇸🇱\",\n    \"flag_for_singapore\": \"🇸🇬\",\n    \"flag_for_sint_maarten\": \"🇸🇽\",\n    \"flag_for_slovakia\": \"🇸🇰\",\n    \"flag_for_slovenia\": \"🇸🇮\",\n    \"flag_for_solomon_islands\": \"🇸🇧\",\n    \"flag_for_somalia\": \"🇸🇴\",\n    \"flag_for_south_africa\": \"🇿🇦\",\n    \"flag_for_south_georgia_&_south_sandwich_islands\": \"🇬🇸\",\n    \"flag_for_south_korea\": \"🇰🇷\",\n    \"flag_for_south_sudan\": \"🇸🇸\",\n    \"flag_for_spain\": \"🇪🇸\",\n    \"flag_for_sri_lanka\": \"🇱🇰\",\n    \"flag_for_st._barthélemy\": \"🇧🇱\",\n    \"flag_for_st._helena\": \"🇸🇭\",\n    \"flag_for_st._kitts_&_nevis\": \"🇰🇳\",\n    \"flag_for_st._lucia\": \"🇱🇨\",\n    \"flag_for_st._martin\": \"🇲🇫\",\n    \"flag_for_st._pierre_&_miquelon\": \"🇵🇲\",\n    \"flag_for_st._vincent_&_grenadines\": \"🇻🇨\",\n    \"flag_for_sudan\": \"🇸🇩\",\n    \"flag_for_suriname\": \"🇸🇷\",\n    \"flag_for_svalbard_&_jan_mayen\": \"🇸🇯\",\n    \"flag_for_swaziland\": \"🇸🇿\",\n    \"flag_for_sweden\": \"🇸🇪\",\n    \"flag_for_switzerland\": \"🇨🇭\",\n    \"flag_for_syria\": \"🇸🇾\",\n    \"flag_for_são_tomé_&_príncipe\": \"🇸🇹\",\n    \"flag_for_taiwan\": \"🇹🇼\",\n    \"flag_for_tajikistan\": \"🇹🇯\",\n    \"flag_for_tanzania\": \"🇹🇿\",\n    \"flag_for_thailand\": \"🇹🇭\",\n    \"flag_for_timor__leste\": \"🇹🇱\",\n    \"flag_for_togo\": \"🇹🇬\",\n    \"flag_for_tokelau\": \"🇹🇰\",\n    \"flag_for_tonga\": \"🇹🇴\",\n    \"flag_for_trinidad_&_tobago\": \"🇹🇹\",\n    \"flag_for_tristan_da_cunha\": \"🇹🇦\",\n    \"flag_for_tunisia\": \"🇹🇳\",\n    \"flag_for_turkey\": \"🇹🇷\",\n    \"flag_for_turkmenistan\": \"🇹🇲\",\n    \"flag_for_turks_&_caicos_islands\": \"🇹🇨\",\n    \"flag_for_tuvalu\": \"🇹🇻\",\n    \"flag_for_u.s._outlying_islands\": \"🇺🇲\",\n    \"flag_for_u.s._virgin_islands\": \"🇻🇮\",\n    \"flag_for_uganda\": \"🇺🇬\",\n    \"flag_for_ukraine\": \"🇺🇦\",\n    \"flag_for_united_arab_emirates\": \"🇦🇪\",\n    \"flag_for_united_kingdom\": \"🇬🇧\",\n    \"flag_for_united_states\": \"🇺🇸\",\n    \"flag_for_uruguay\": \"🇺🇾\",\n    \"flag_for_uzbekistan\": \"🇺🇿\",\n    \"flag_for_vanuatu\": \"🇻🇺\",\n    \"flag_for_vatican_city\": \"🇻🇦\",\n    \"flag_for_venezuela\": \"🇻🇪\",\n    \"flag_for_vietnam\": \"🇻🇳\",\n    \"flag_for_wallis_&_futuna\": \"🇼🇫\",\n    \"flag_for_western_sahara\": \"🇪🇭\",\n    \"flag_for_yemen\": \"🇾🇪\",\n    \"flag_for_zambia\": \"🇿🇲\",\n    \"flag_for_zimbabwe\": \"🇿🇼\",\n    \"flag_for_åland_islands\": \"🇦🇽\",\n    \"golf\": \"⛳\",\n    \"fleur__de__lis\": \"⚜\",\n    \"muscle\": \"💪\",\n    \"flushed\": \"😳\",\n    \"frame_with_picture\": \"🖼\",\n    \"fries\": \"🍟\",\n    \"frog\": \"🐸\",\n    \"hatched_chick\": \"🐥\",\n    \"frowning\": \"😦\",\n    \"fuelpump\": \"⛽\",\n    \"full_moon_with_face\": \"🌝\",\n    \"gem\": \"💎\",\n    \"star2\": \"🌟\",\n    \"golfer\": \"🏌\",\n    \"mortar_board\": \"🎓\",\n    \"grimacing\": \"😬\",\n    \"smile_cat\": \"😸\",\n    \"grinning\": \"😀\",\n    \"grin\": \"😁\",\n    \"heartpulse\": \"💗\",\n    \"guardsman\": \"💂\",\n    \"haircut\": \"💇\",\n    \"hamster\": \"🐹\",\n    \"raising_hand\": \"🙋\",\n    \"headphones\": \"🎧\",\n    \"hear_no_evil\": \"🙉\",\n    \"cupid\": \"💘\",\n    \"gift_heart\": \"💝\",\n    \"heart\": \"❤\",\n    \"exclamation\": \"❗\",\n    \"heavy_exclamation_mark\": \"❗\",\n    \"heavy_heart_exclamation_mark_ornament\": \"❣\",\n    \"o\": \"⭕\",\n    \"helm_symbol\": \"⎈\",\n    \"helmet_with_white_cross\": \"⛑\",\n    \"high_heel\": \"👠\",\n    \"bullettrain_side\": \"🚄\",\n    \"bullettrain_front\": \"🚅\",\n    \"high_brightness\": \"🔆\",\n    \"zap\": \"⚡\",\n    \"hocho\": \"🔪\",\n    \"knife\": \"🔪\",\n    \"bee\": \"🐝\",\n    \"traffic_light\": \"🚥\",\n    \"racehorse\": \"🐎\",\n    \"coffee\": \"☕\",\n    \"hotsprings\": \"♨\",\n    \"hourglass\": \"⌛\",\n    \"hourglass_flowing_sand\": \"⏳\",\n    \"house_buildings\": \"🏘\",\n    \"100\": \"💯\",\n    \"hushed\": \"😯\",\n    \"ice_hockey_stick_and_puck\": \"🏒\",\n    \"imp\": \"👿\",\n    \"information_desk_person\": \"💁\",\n    \"information_source\": \"ℹ\",\n    \"capital_abcd\": \"🔠\",\n    \"abc\": \"🔤\",\n    \"abcd\": \"🔡\",\n    \"1234\": \"🔢\",\n    \"symbols\": \"🔣\",\n    \"izakaya_lantern\": \"🏮\",\n    \"lantern\": \"🏮\",\n    \"jack_o_lantern\": \"🎃\",\n    \"dolls\": \"🎎\",\n    \"japanese_goblin\": \"👺\",\n    \"japanese_ogre\": \"👹\",\n    \"beginner\": \"🔰\",\n    \"zero\": \"0️⃣\",\n    \"one\": \"1️⃣\",\n    \"ten\": \"🔟\",\n    \"two\": \"2️⃣\",\n    \"three\": \"3️⃣\",\n    \"four\": \"4️⃣\",\n    \"five\": \"5️⃣\",\n    \"six\": \"6️⃣\",\n    \"seven\": \"7️⃣\",\n    \"eight\": \"8️⃣\",\n    \"nine\": \"9️⃣\",\n    \"couplekiss\": \"💏\",\n    \"kissing_cat\": \"😽\",\n    \"kissing\": \"😗\",\n    \"kissing_closed_eyes\": \"😚\",\n    \"kissing_smiling_eyes\": \"😙\",\n    \"beetle\": \"🐞\",\n    \"large_blue_circle\": \"🔵\",\n    \"last_quarter_moon_with_face\": \"🌜\",\n    \"leaves\": \"🍃\",\n    \"mag\": \"🔍\",\n    \"left_right_arrow\": \"↔\",\n    \"leftwards_arrow_with_hook\": \"↩\",\n    \"arrow_left\": \"⬅\",\n    \"lock\": \"🔒\",\n    \"lock_with_ink_pen\": \"🔏\",\n    \"sob\": \"😭\",\n    \"low_brightness\": \"🔅\",\n    \"lower_left_ballpoint_pen\": \"🖊\",\n    \"lower_left_crayon\": \"🖍\",\n    \"lower_left_fountain_pen\": \"🖋\",\n    \"lower_left_paintbrush\": \"🖌\",\n    \"mahjong\": \"🀄\",\n    \"couple\": \"👫\",\n    \"man_in_business_suit_levitating\": \"🕴\",\n    \"man_with_gua_pi_mao\": \"👲\",\n    \"man_with_turban\": \"👳\",\n    \"mans_shoe\": \"👞\",\n    \"shoe\": \"👞\",\n    \"menorah_with_nine_branches\": \"🕎\",\n    \"mens\": \"🚹\",\n    \"minidisc\": \"💽\",\n    \"iphone\": \"📱\",\n    \"calling\": \"📲\",\n    \"money__mouth_face\": \"🤑\",\n    \"moneybag\": \"💰\",\n    \"rice_scene\": \"🎑\",\n    \"mountain_bicyclist\": \"🚵\",\n    \"mouse2\": \"🐁\",\n    \"lips\": \"👄\",\n    \"moyai\": \"🗿\",\n    \"notes\": \"🎶\",\n    \"nail_care\": \"💅\",\n    \"ab\": \"🆎\",\n    \"negative_squared_cross_mark\": \"❎\",\n    \"a\": \"🅰\",\n    \"b\": \"🅱\",\n    \"o2\": \"🅾\",\n    \"parking\": \"🅿\",\n    \"new_moon_with_face\": \"🌚\",\n    \"no_entry_sign\": \"🚫\",\n    \"underage\": \"🔞\",\n    \"non__potable_water\": \"🚱\",\n    \"arrow_upper_right\": \"↗\",\n    \"arrow_upper_left\": \"↖\",\n    \"office\": \"🏢\",\n    \"older_man\": \"👴\",\n    \"older_woman\": \"👵\",\n    \"om_symbol\": \"🕉\",\n    \"on\": \"🔛\",\n    \"book\": \"📖\",\n    \"unlock\": \"🔓\",\n    \"mailbox_with_no_mail\": \"📭\",\n    \"mailbox_with_mail\": \"📬\",\n    \"cd\": \"💿\",\n    \"tada\": \"🎉\",\n    \"feet\": \"🐾\",\n    \"walking\": \"🚶\",\n    \"pencil2\": \"✏\",\n    \"pensive\": \"😔\",\n    \"persevere\": \"😣\",\n    \"bow\": \"🙇\",\n    \"raised_hands\": \"🙌\",\n    \"person_with_ball\": \"⛹\",\n    \"person_with_blond_hair\": \"👱\",\n    \"pray\": \"🙏\",\n    \"person_with_pouting_face\": \"🙎\",\n    \"computer\": \"💻\",\n    \"pig2\": \"🐖\",\n    \"hankey\": \"💩\",\n    \"poop\": \"💩\",\n    \"shit\": \"💩\",\n    \"bamboo\": \"🎍\",\n    \"gun\": \"🔫\",\n    \"black_joker\": \"🃏\",\n    \"rotating_light\": \"🚨\",\n    \"cop\": \"👮\",\n    \"stew\": \"🍲\",\n    \"pouch\": \"👝\",\n    \"pouting_cat\": \"😾\",\n    \"rage\": \"😡\",\n    \"put_litter_in_its_place\": \"🚮\",\n    \"rabbit2\": \"🐇\",\n    \"racing_motorcycle\": \"🏍\",\n    \"radioactive_sign\": \"☢\",\n    \"fist\": \"✊\",\n    \"hand\": \"✋\",\n    \"raised_hand_with_fingers_splayed\": \"🖐\",\n    \"raised_hand_with_part_between_middle_and_ring_fingers\": \"🖖\",\n    \"blue_car\": \"🚙\",\n    \"apple\": \"🍎\",\n    \"relieved\": \"😌\",\n    \"reversed_hand_with_middle_finger_extended\": \"🖕\",\n    \"mag_right\": \"🔎\",\n    \"arrow_right_hook\": \"↪\",\n    \"sweet_potato\": \"🍠\",\n    \"robot\": \"🤖\",\n    \"rolled__up_newspaper\": \"🗞\",\n    \"rowboat\": \"🚣\",\n    \"runner\": \"🏃\",\n    \"running\": \"🏃\",\n    \"running_shirt_with_sash\": \"🎽\",\n    \"boat\": \"⛵\",\n    \"scales\": \"⚖\",\n    \"school_satchel\": \"🎒\",\n    \"scorpius\": \"♏\",\n    \"see_no_evil\": \"🙈\",\n    \"sheep\": \"🐑\",\n    \"stars\": \"🌠\",\n    \"cake\": \"🍰\",\n    \"six_pointed_star\": \"🔯\",\n    \"ski\": \"🎿\",\n    \"sleeping_accommodation\": \"🛌\",\n    \"sleeping\": \"😴\",\n    \"sleepy\": \"😪\",\n    \"sleuth_or_spy\": \"🕵\",\n    \"heart_eyes_cat\": \"😻\",\n    \"smiley_cat\": \"😺\",\n    \"innocent\": \"😇\",\n    \"heart_eyes\": \"😍\",\n    \"smiling_imp\": \"😈\",\n    \"smiley\": \"😃\",\n    \"sweat_smile\": \"😅\",\n    \"smile\": \"😄\",\n    \"laughing\": \"😆\",\n    \"satisfied\": \"😆\",\n    \"blush\": \"😊\",\n    \"smirk\": \"😏\",\n    \"smoking\": \"🚬\",\n    \"snow_capped_mountain\": \"🏔\",\n    \"soccer\": \"⚽\",\n    \"icecream\": \"🍦\",\n    \"soon\": \"🔜\",\n    \"arrow_lower_right\": \"↘\",\n    \"arrow_lower_left\": \"↙\",\n    \"speak_no_evil\": \"🙊\",\n    \"speaker\": \"🔈\",\n    \"mute\": \"🔇\",\n    \"sound\": \"🔉\",\n    \"loud_sound\": \"🔊\",\n    \"speaking_head_in_silhouette\": \"🗣\",\n    \"spiral_calendar_pad\": \"🗓\",\n    \"spiral_note_pad\": \"🗒\",\n    \"shell\": \"🐚\",\n    \"sweat_drops\": \"💦\",\n    \"u5272\": \"🈹\",\n    \"u5408\": \"🈴\",\n    \"u55b6\": \"🈺\",\n    \"u6307\": \"🈯\",\n    \"u6708\": \"🈷\",\n    \"u6709\": \"🈶\",\n    \"u6e80\": \"🈵\",\n    \"u7121\": \"🈚\",\n    \"u7533\": \"🈸\",\n    \"u7981\": \"🈲\",\n    \"u7a7a\": \"🈳\",\n    \"cl\": \"🆑\",\n    \"cool\": \"🆒\",\n    \"free\": \"🆓\",\n    \"id\": \"🆔\",\n    \"koko\": \"🈁\",\n    \"sa\": \"🈂\",\n    \"new\": \"🆕\",\n    \"ng\": \"🆖\",\n    \"ok\": \"🆗\",\n    \"sos\": \"🆘\",\n    \"up\": \"🆙\",\n    \"vs\": \"🆚\",\n    \"steam_locomotive\": \"🚂\",\n    \"ramen\": \"🍜\",\n    \"partly_sunny\": \"⛅\",\n    \"city_sunrise\": \"🌇\",\n    \"surfer\": \"🏄\",\n    \"swimmer\": \"🏊\",\n    \"shirt\": \"👕\",\n    \"tshirt\": \"👕\",\n    \"table_tennis_paddle_and_ball\": \"🏓\",\n    \"tea\": \"🍵\",\n    \"tv\": \"📺\",\n    \"three_button_mouse\": \"🖱\",\n    \"+1\": \"👍\",\n    \"thumbsup\": \"👍\",\n    \"__1\": \"👎\",\n    \"-1\": \"👎\",\n    \"thumbsdown\": \"👎\",\n    \"thunder_cloud_and_rain\": \"⛈\",\n    \"tiger2\": \"🐅\",\n    \"tophat\": \"🎩\",\n    \"top\": \"🔝\",\n    \"tm\": \"™\",\n    \"train2\": \"🚆\",\n    \"triangular_flag_on_post\": \"🚩\",\n    \"trident\": \"🔱\",\n    \"twisted_rightwards_arrows\": \"🔀\",\n    \"unamused\": \"😒\",\n    \"small_red_triangle\": \"🔺\",\n    \"arrow_up_small\": \"🔼\",\n    \"arrow_up_down\": \"↕\",\n    \"upside__down_face\": \"🙃\",\n    \"arrow_up\": \"⬆\",\n    \"v\": \"✌\",\n    \"vhs\": \"📼\",\n    \"wc\": \"🚾\",\n    \"ocean\": \"🌊\",\n    \"waving_black_flag\": \"🏴\",\n    \"wave\": \"👋\",\n    \"waving_white_flag\": \"🏳\",\n    \"moon\": \"🌔\",\n    \"scream_cat\": \"🙀\",\n    \"weary\": \"😩\",\n    \"weight_lifter\": \"🏋\",\n    \"whale2\": \"🐋\",\n    \"wheelchair\": \"♿\",\n    \"point_down\": \"👇\",\n    \"grey_exclamation\": \"❕\",\n    \"white_frowning_face\": \"☹\",\n    \"white_check_mark\": \"✅\",\n    \"point_left\": \"👈\",\n    \"white_medium_small_square\": \"◽\",\n    \"star\": \"⭐\",\n    \"grey_question\": \"❔\",\n    \"point_right\": \"👉\",\n    \"relaxed\": \"☺\",\n    \"white_sun_behind_cloud\": \"🌥\",\n    \"white_sun_behind_cloud_with_rain\": \"🌦\",\n    \"white_sun_with_small_cloud\": \"🌤\",\n    \"point_up_2\": \"👆\",\n    \"point_up\": \"☝\",\n    \"wind_blowing_face\": \"🌬\",\n    \"wink\": \"😉\",\n    \"wolf\": \"🐺\",\n    \"dancers\": \"👯\",\n    \"boot\": \"👢\",\n    \"womans_clothes\": \"👚\",\n    \"womans_hat\": \"👒\",\n    \"sandal\": \"👡\",\n    \"womens\": \"🚺\",\n    \"worried\": \"😟\",\n    \"gift\": \"🎁\",\n    \"zipper__mouth_face\": \"🤐\",\n    \"regional_indicator_a\": \"🇦\",\n    \"regional_indicator_b\": \"🇧\",\n    \"regional_indicator_c\": \"🇨\",\n    \"regional_indicator_d\": \"🇩\",\n    \"regional_indicator_e\": \"🇪\",\n    \"regional_indicator_f\": \"🇫\",\n    \"regional_indicator_g\": \"🇬\",\n    \"regional_indicator_h\": \"🇭\",\n    \"regional_indicator_i\": \"🇮\",\n    \"regional_indicator_j\": \"🇯\",\n    \"regional_indicator_k\": \"🇰\",\n    \"regional_indicator_l\": \"🇱\",\n    \"regional_indicator_m\": \"🇲\",\n    \"regional_indicator_n\": \"🇳\",\n    \"regional_indicator_o\": \"🇴\",\n    \"regional_indicator_p\": \"🇵\",\n    \"regional_indicator_q\": \"🇶\",\n    \"regional_indicator_r\": \"🇷\",\n    \"regional_indicator_s\": \"🇸\",\n    \"regional_indicator_t\": \"🇹\",\n    \"regional_indicator_u\": \"🇺\",\n    \"regional_indicator_v\": \"🇻\",\n    \"regional_indicator_w\": \"🇼\",\n    \"regional_indicator_x\": \"🇽\",\n    \"regional_indicator_y\": \"🇾\",\n    \"regional_indicator_z\": \"🇿\",\n}\n"
  },
  {
    "path": "src/pip/_vendor/rich/_emoji_replace.py",
    "content": "from typing import Callable, Match, Optional\nimport re\n\nfrom ._emoji_codes import EMOJI\n\n\n_ReStringMatch = Match[str]  # regex match object\n_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub\n_EmojiSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re\n\n\ndef _emoji_replace(\n    text: str,\n    default_variant: Optional[str] = None,\n    _emoji_sub: _EmojiSubMethod = re.compile(r\"(:(\\S*?)(?:(?:\\-)(emoji|text))?:)\").sub,\n) -> str:\n    \"\"\"Replace emoji code in text.\"\"\"\n    get_emoji = EMOJI.__getitem__\n    variants = {\"text\": \"\\uFE0E\", \"emoji\": \"\\uFE0F\"}\n    get_variant = variants.get\n    default_variant_code = variants.get(default_variant, \"\") if default_variant else \"\"\n\n    def do_replace(match: Match[str]) -> str:\n        emoji_code, emoji_name, variant = match.groups()\n        try:\n            return get_emoji(emoji_name.lower()) + get_variant(\n                variant, default_variant_code\n            )\n        except KeyError:\n            return emoji_code\n\n    return _emoji_sub(do_replace, text)\n"
  },
  {
    "path": "src/pip/_vendor/rich/_export_format.py",
    "content": "CONSOLE_HTML_FORMAT = \"\"\"\\\n<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<style>\n{stylesheet}\nbody {{\n    color: {foreground};\n    background-color: {background};\n}}\n</style>\n</head>\n<body>\n    <pre style=\"font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><code style=\"font-family:inherit\">{code}</code></pre>\n</body>\n</html>\n\"\"\"\n\nCONSOLE_SVG_FORMAT = \"\"\"\\\n<svg class=\"rich-terminal\" viewBox=\"0 0 {width} {height}\" xmlns=\"http://www.w3.org/2000/svg\">\n    <!-- Generated with Rich https://www.textualize.io -->\n    <style>\n\n    @font-face {{\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Regular\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff\") format(\"woff\");\n        font-style: normal;\n        font-weight: 400;\n    }}\n    @font-face {{\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Bold\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff\") format(\"woff\");\n        font-style: bold;\n        font-weight: 700;\n    }}\n\n    .{unique_id}-matrix {{\n        font-family: Fira Code, monospace;\n        font-size: {char_height}px;\n        line-height: {line_height}px;\n        font-variant-east-asian: full-width;\n    }}\n\n    .{unique_id}-title {{\n        font-size: 18px;\n        font-weight: bold;\n        font-family: arial;\n    }}\n\n    {styles}\n    </style>\n\n    <defs>\n    <clipPath id=\"{unique_id}-clip-terminal\">\n      <rect x=\"0\" y=\"0\" width=\"{terminal_width}\" height=\"{terminal_height}\" />\n    </clipPath>\n    {lines}\n    </defs>\n\n    {chrome}\n    <g transform=\"translate({terminal_x}, {terminal_y})\" clip-path=\"url(#{unique_id}-clip-terminal)\">\n    {backgrounds}\n    <g class=\"{unique_id}-matrix\">\n    {matrix}\n    </g>\n    </g>\n</svg>\n\"\"\"\n\n_SVG_FONT_FAMILY = \"Rich Fira Code\"\n_SVG_CLASSES_PREFIX = \"rich-svg\"\n"
  },
  {
    "path": "src/pip/_vendor/rich/_extension.py",
    "content": "from typing import Any\n\n\ndef load_ipython_extension(ip: Any) -> None:  # pragma: no cover\n    # prevent circular import\n    from pip._vendor.rich.pretty import install\n    from pip._vendor.rich.traceback import install as tr_install\n\n    install()\n    tr_install()\n"
  },
  {
    "path": "src/pip/_vendor/rich/_fileno.py",
    "content": "from __future__ import annotations\n\nfrom typing import IO, Callable\n\n\ndef get_fileno(file_like: IO[str]) -> int | None:\n    \"\"\"Get fileno() from a file, accounting for poorly implemented file-like objects.\n\n    Args:\n        file_like (IO): A file-like object.\n\n    Returns:\n        int | None: The result of fileno if available, or None if operation failed.\n    \"\"\"\n    fileno: Callable[[], int] | None = getattr(file_like, \"fileno\", None)\n    if fileno is not None:\n        try:\n            return fileno()\n        except Exception:\n            # `fileno` is documented as potentially raising a OSError\n            # Alas, from the issues, there are so many poorly implemented file-like objects,\n            # that `fileno()` can raise just about anything.\n            return None\n    return None\n"
  },
  {
    "path": "src/pip/_vendor/rich/_inspect.py",
    "content": "import inspect\nfrom inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature\nfrom typing import Any, Collection, Iterable, Optional, Tuple, Type, Union\n\nfrom .console import Group, RenderableType\nfrom .control import escape_control_codes\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\n\ndef _first_paragraph(doc: str) -> str:\n    \"\"\"Get the first paragraph from a docstring.\"\"\"\n    paragraph, _, _ = doc.partition(\"\\n\\n\")\n    return paragraph\n\n\nclass Inspect(JupyterMixin):\n    \"\"\"A renderable to inspect any Python Object.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value of object. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        obj: Any,\n        *,\n        title: Optional[TextType] = None,\n        help: bool = False,\n        methods: bool = False,\n        docs: bool = True,\n        private: bool = False,\n        dunder: bool = False,\n        sort: bool = True,\n        all: bool = True,\n        value: bool = True,\n    ) -> None:\n        self.highlighter = ReprHighlighter()\n        self.obj = obj\n        self.title = title or self._make_title(obj)\n        if all:\n            methods = private = dunder = True\n        self.help = help\n        self.methods = methods\n        self.docs = docs or help\n        self.private = private or dunder\n        self.dunder = dunder\n        self.sort = sort\n        self.value = value\n\n    def _make_title(self, obj: Any) -> Text:\n        \"\"\"Make a default title.\"\"\"\n        title_str = (\n            str(obj)\n            if (isclass(obj) or callable(obj) or ismodule(obj))\n            else str(type(obj))\n        )\n        title_text = self.highlighter(title_str)\n        return title_text\n\n    def __rich__(self) -> Panel:\n        return Panel.fit(\n            Group(*self._render()),\n            title=self.title,\n            border_style=\"scope.border\",\n            padding=(0, 1),\n        )\n\n    def _get_signature(self, name: str, obj: Any) -> Optional[Text]:\n        \"\"\"Get a signature for a callable.\"\"\"\n        try:\n            _signature = str(signature(obj)) + \":\"\n        except ValueError:\n            _signature = \"(...)\"\n        except TypeError:\n            return None\n\n        source_filename: Optional[str] = None\n        try:\n            source_filename = getfile(obj)\n        except (OSError, TypeError):\n            # OSError is raised if obj has no source file, e.g. when defined in REPL.\n            pass\n\n        callable_name = Text(name, style=\"inspect.callable\")\n        if source_filename:\n            callable_name.stylize(f\"link file://{source_filename}\")\n        signature_text = self.highlighter(_signature)\n\n        qualname = name or getattr(obj, \"__qualname__\", name)\n\n        # If obj is a module, there may be classes (which are callable) to display\n        if inspect.isclass(obj):\n            prefix = \"class\"\n        elif inspect.iscoroutinefunction(obj):\n            prefix = \"async def\"\n        else:\n            prefix = \"def\"\n\n        qual_signature = Text.assemble(\n            (f\"{prefix} \", f\"inspect.{prefix.replace(' ', '_')}\"),\n            (qualname, \"inspect.callable\"),\n            signature_text,\n        )\n\n        return qual_signature\n\n    def _render(self) -> Iterable[RenderableType]:\n        \"\"\"Render object.\"\"\"\n\n        def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n            key, (_error, value) = item\n            return (callable(value), key.strip(\"_\").lower())\n\n        def safe_getattr(attr_name: str) -> Tuple[Any, Any]:\n            \"\"\"Get attribute or any exception.\"\"\"\n            try:\n                return (None, getattr(obj, attr_name))\n            except Exception as error:\n                return (error, None)\n\n        obj = self.obj\n        keys = dir(obj)\n        total_items = len(keys)\n        if not self.dunder:\n            keys = [key for key in keys if not key.startswith(\"__\")]\n        if not self.private:\n            keys = [key for key in keys if not key.startswith(\"_\")]\n        not_shown_count = total_items - len(keys)\n        items = [(key, safe_getattr(key)) for key in keys]\n        if self.sort:\n            items.sort(key=sort_items)\n\n        items_table = Table.grid(padding=(0, 1), expand=False)\n        items_table.add_column(justify=\"right\")\n        add_row = items_table.add_row\n        highlighter = self.highlighter\n\n        if callable(obj):\n            signature = self._get_signature(\"\", obj)\n            if signature is not None:\n                yield signature\n                yield \"\"\n\n        if self.docs:\n            _doc = self._get_formatted_doc(obj)\n            if _doc is not None:\n                doc_text = Text(_doc, style=\"inspect.help\")\n                doc_text = highlighter(doc_text)\n                yield doc_text\n                yield \"\"\n\n        if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):\n            yield Panel(\n                Pretty(obj, indent_guides=True, max_length=10, max_string=60),\n                border_style=\"inspect.value.border\",\n            )\n            yield \"\"\n\n        for key, (error, value) in items:\n            key_text = Text.assemble(\n                (\n                    key,\n                    \"inspect.attr.dunder\" if key.startswith(\"__\") else \"inspect.attr\",\n                ),\n                (\" =\", \"inspect.equals\"),\n            )\n            if error is not None:\n                warning = key_text.copy()\n                warning.stylize(\"inspect.error\")\n                add_row(warning, highlighter(repr(error)))\n                continue\n\n            if callable(value):\n                if not self.methods:\n                    continue\n\n                _signature_text = self._get_signature(key, value)\n                if _signature_text is None:\n                    add_row(key_text, Pretty(value, highlighter=highlighter))\n                else:\n                    if self.docs:\n                        docs = self._get_formatted_doc(value)\n                        if docs is not None:\n                            _signature_text.append(\"\\n\" if \"\\n\" in docs else \" \")\n                            doc = highlighter(docs)\n                            doc.stylize(\"inspect.doc\")\n                            _signature_text.append(doc)\n\n                    add_row(key_text, _signature_text)\n            else:\n                add_row(key_text, Pretty(value, highlighter=highlighter))\n        if items_table.row_count:\n            yield items_table\n        elif not_shown_count:\n            yield Text.from_markup(\n                f\"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] \"\n                f\"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options.\"\n            )\n\n    def _get_formatted_doc(self, object_: Any) -> Optional[str]:\n        \"\"\"\n        Extract the docstring of an object, process it and returns it.\n        The processing consists in cleaning up the docstring's indentation,\n        taking only its 1st paragraph if `self.help` is not True,\n        and escape its control codes.\n\n        Args:\n            object_ (Any): the object to get the docstring from.\n\n        Returns:\n            Optional[str]: the processed docstring, or None if no docstring was found.\n        \"\"\"\n        docs = getdoc(object_)\n        if docs is None:\n            return None\n        docs = cleandoc(docs).strip()\n        if not self.help:\n            docs = _first_paragraph(docs)\n        return escape_control_codes(docs)\n\n\ndef get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]:\n    \"\"\"Returns the MRO of an object's class, or of the object itself if it's a class.\"\"\"\n    if not hasattr(obj, \"__mro__\"):\n        # N.B. we cannot use `if type(obj) is type` here because it doesn't work with\n        # some types of classes, such as the ones that use abc.ABCMeta.\n        obj = type(obj)\n    return getattr(obj, \"__mro__\", ())\n\n\ndef get_object_types_mro_as_strings(obj: object) -> Collection[str]:\n    \"\"\"\n    Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class.\n\n    Examples:\n        `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']`\n    \"\"\"\n    return [\n        f'{getattr(type_, \"__module__\", \"\")}.{getattr(type_, \"__qualname__\", \"\")}'\n        for type_ in get_object_types_mro(obj)\n    ]\n\n\ndef is_object_one_of_types(\n    obj: object, fully_qualified_types_names: Collection[str]\n) -> bool:\n    \"\"\"\n    Returns `True` if the given object's class (or the object itself, if it's a class) has one of the\n    fully qualified names in its MRO.\n    \"\"\"\n    for type_name in get_object_types_mro_as_strings(obj):\n        if type_name in fully_qualified_types_names:\n            return True\n    return False\n"
  },
  {
    "path": "src/pip/_vendor/rich/_log_render.py",
    "content": "from datetime import datetime\nfrom typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable\n\n\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleRenderable, RenderableType\n    from .table import Table\n\nFormatTimeCallable = Callable[[datetime], Text]\n\n\nclass LogRender:\n    def __init__(\n        self,\n        show_time: bool = True,\n        show_level: bool = False,\n        show_path: bool = True,\n        time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n        omit_repeated_times: bool = True,\n        level_width: Optional[int] = 8,\n    ) -> None:\n        self.show_time = show_time\n        self.show_level = show_level\n        self.show_path = show_path\n        self.time_format = time_format\n        self.omit_repeated_times = omit_repeated_times\n        self.level_width = level_width\n        self._last_time: Optional[Text] = None\n\n    def __call__(\n        self,\n        console: \"Console\",\n        renderables: Iterable[\"ConsoleRenderable\"],\n        log_time: Optional[datetime] = None,\n        time_format: Optional[Union[str, FormatTimeCallable]] = None,\n        level: TextType = \"\",\n        path: Optional[str] = None,\n        line_no: Optional[int] = None,\n        link_path: Optional[str] = None,\n    ) -> \"Table\":\n        from .containers import Renderables\n        from .table import Table\n\n        output = Table.grid(padding=(0, 1))\n        output.expand = True\n        if self.show_time:\n            output.add_column(style=\"log.time\")\n        if self.show_level:\n            output.add_column(style=\"log.level\", width=self.level_width)\n        output.add_column(ratio=1, style=\"log.message\", overflow=\"fold\")\n        if self.show_path and path:\n            output.add_column(style=\"log.path\")\n        row: List[\"RenderableType\"] = []\n        if self.show_time:\n            log_time = log_time or console.get_datetime()\n            time_format = time_format or self.time_format\n            if callable(time_format):\n                log_time_display = time_format(log_time)\n            else:\n                log_time_display = Text(log_time.strftime(time_format))\n            if log_time_display == self._last_time and self.omit_repeated_times:\n                row.append(Text(\" \" * len(log_time_display)))\n            else:\n                row.append(log_time_display)\n                self._last_time = log_time_display\n        if self.show_level:\n            row.append(level)\n\n        row.append(Renderables(renderables))\n        if self.show_path and path:\n            path_text = Text()\n            path_text.append(\n                path, style=f\"link file://{link_path}\" if link_path else \"\"\n            )\n            if line_no:\n                path_text.append(\":\")\n                path_text.append(\n                    f\"{line_no}\",\n                    style=f\"link file://{link_path}#{line_no}\" if link_path else \"\",\n                )\n            row.append(path_text)\n\n        output.add_row(*row)\n        return output\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    c = Console()\n    c.print(\"[on blue]Hello\", justify=\"right\")\n    c.log(\"[on blue]hello\", justify=\"right\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/_loop.py",
    "content": "from typing import Iterable, Tuple, TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for first value.\"\"\"\n    iter_values = iter(values)\n    try:\n        value = next(iter_values)\n    except StopIteration:\n        return\n    yield True, value\n    for value in iter_values:\n        yield False, value\n\n\ndef loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value\n\n\ndef loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for first and last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    first = True\n    for value in iter_values:\n        yield first, False, previous_value\n        first = False\n        previous_value = value\n    yield first, True, previous_value\n"
  },
  {
    "path": "src/pip/_vendor/rich/_null_file.py",
    "content": "from types import TracebackType\nfrom typing import IO, Iterable, Iterator, List, Optional, Type\n\n\nclass NullFile(IO[str]):\n    def close(self) -> None:\n        pass\n\n    def isatty(self) -> bool:\n        return False\n\n    def read(self, __n: int = 1) -> str:\n        return \"\"\n\n    def readable(self) -> bool:\n        return False\n\n    def readline(self, __limit: int = 1) -> str:\n        return \"\"\n\n    def readlines(self, __hint: int = 1) -> List[str]:\n        return []\n\n    def seek(self, __offset: int, __whence: int = 1) -> int:\n        return 0\n\n    def seekable(self) -> bool:\n        return False\n\n    def tell(self) -> int:\n        return 0\n\n    def truncate(self, __size: Optional[int] = 1) -> int:\n        return 0\n\n    def writable(self) -> bool:\n        return False\n\n    def writelines(self, __lines: Iterable[str]) -> None:\n        pass\n\n    def __next__(self) -> str:\n        return \"\"\n\n    def __iter__(self) -> Iterator[str]:\n        return iter([\"\"])\n\n    def __enter__(self) -> IO[str]:\n        return self\n\n    def __exit__(\n        self,\n        __t: Optional[Type[BaseException]],\n        __value: Optional[BaseException],\n        __traceback: Optional[TracebackType],\n    ) -> None:\n        pass\n\n    def write(self, text: str) -> int:\n        return 0\n\n    def flush(self) -> None:\n        pass\n\n    def fileno(self) -> int:\n        return -1\n\n\nNULL_FILE = NullFile()\n"
  },
  {
    "path": "src/pip/_vendor/rich/_palettes.py",
    "content": "from .palette import Palette\n\n\n# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column)\nWINDOWS_PALETTE = Palette(\n    [\n        (12, 12, 12),\n        (197, 15, 31),\n        (19, 161, 14),\n        (193, 156, 0),\n        (0, 55, 218),\n        (136, 23, 152),\n        (58, 150, 221),\n        (204, 204, 204),\n        (118, 118, 118),\n        (231, 72, 86),\n        (22, 198, 12),\n        (249, 241, 165),\n        (59, 120, 255),\n        (180, 0, 158),\n        (97, 214, 214),\n        (242, 242, 242),\n    ]\n)\n\n# # The standard ansi colors (including bright variants)\nSTANDARD_PALETTE = Palette(\n    [\n        (0, 0, 0),\n        (170, 0, 0),\n        (0, 170, 0),\n        (170, 85, 0),\n        (0, 0, 170),\n        (170, 0, 170),\n        (0, 170, 170),\n        (170, 170, 170),\n        (85, 85, 85),\n        (255, 85, 85),\n        (85, 255, 85),\n        (255, 255, 85),\n        (85, 85, 255),\n        (255, 85, 255),\n        (85, 255, 255),\n        (255, 255, 255),\n    ]\n)\n\n\n# The 256 color palette\nEIGHT_BIT_PALETTE = Palette(\n    [\n        (0, 0, 0),\n        (128, 0, 0),\n        (0, 128, 0),\n        (128, 128, 0),\n        (0, 0, 128),\n        (128, 0, 128),\n        (0, 128, 128),\n        (192, 192, 192),\n        (128, 128, 128),\n        (255, 0, 0),\n        (0, 255, 0),\n        (255, 255, 0),\n        (0, 0, 255),\n        (255, 0, 255),\n        (0, 255, 255),\n        (255, 255, 255),\n        (0, 0, 0),\n        (0, 0, 95),\n        (0, 0, 135),\n        (0, 0, 175),\n        (0, 0, 215),\n        (0, 0, 255),\n        (0, 95, 0),\n        (0, 95, 95),\n        (0, 95, 135),\n        (0, 95, 175),\n        (0, 95, 215),\n        (0, 95, 255),\n        (0, 135, 0),\n        (0, 135, 95),\n        (0, 135, 135),\n        (0, 135, 175),\n        (0, 135, 215),\n        (0, 135, 255),\n        (0, 175, 0),\n        (0, 175, 95),\n        (0, 175, 135),\n        (0, 175, 175),\n        (0, 175, 215),\n        (0, 175, 255),\n        (0, 215, 0),\n        (0, 215, 95),\n        (0, 215, 135),\n        (0, 215, 175),\n        (0, 215, 215),\n        (0, 215, 255),\n        (0, 255, 0),\n        (0, 255, 95),\n        (0, 255, 135),\n        (0, 255, 175),\n        (0, 255, 215),\n        (0, 255, 255),\n        (95, 0, 0),\n        (95, 0, 95),\n        (95, 0, 135),\n        (95, 0, 175),\n        (95, 0, 215),\n        (95, 0, 255),\n        (95, 95, 0),\n        (95, 95, 95),\n        (95, 95, 135),\n        (95, 95, 175),\n        (95, 95, 215),\n        (95, 95, 255),\n        (95, 135, 0),\n        (95, 135, 95),\n        (95, 135, 135),\n        (95, 135, 175),\n        (95, 135, 215),\n        (95, 135, 255),\n        (95, 175, 0),\n        (95, 175, 95),\n        (95, 175, 135),\n        (95, 175, 175),\n        (95, 175, 215),\n        (95, 175, 255),\n        (95, 215, 0),\n        (95, 215, 95),\n        (95, 215, 135),\n        (95, 215, 175),\n        (95, 215, 215),\n        (95, 215, 255),\n        (95, 255, 0),\n        (95, 255, 95),\n        (95, 255, 135),\n        (95, 255, 175),\n        (95, 255, 215),\n        (95, 255, 255),\n        (135, 0, 0),\n        (135, 0, 95),\n        (135, 0, 135),\n        (135, 0, 175),\n        (135, 0, 215),\n        (135, 0, 255),\n        (135, 95, 0),\n        (135, 95, 95),\n        (135, 95, 135),\n        (135, 95, 175),\n        (135, 95, 215),\n        (135, 95, 255),\n        (135, 135, 0),\n        (135, 135, 95),\n        (135, 135, 135),\n        (135, 135, 175),\n        (135, 135, 215),\n        (135, 135, 255),\n        (135, 175, 0),\n        (135, 175, 95),\n        (135, 175, 135),\n        (135, 175, 175),\n        (135, 175, 215),\n        (135, 175, 255),\n        (135, 215, 0),\n        (135, 215, 95),\n        (135, 215, 135),\n        (135, 215, 175),\n        (135, 215, 215),\n        (135, 215, 255),\n        (135, 255, 0),\n        (135, 255, 95),\n        (135, 255, 135),\n        (135, 255, 175),\n        (135, 255, 215),\n        (135, 255, 255),\n        (175, 0, 0),\n        (175, 0, 95),\n        (175, 0, 135),\n        (175, 0, 175),\n        (175, 0, 215),\n        (175, 0, 255),\n        (175, 95, 0),\n        (175, 95, 95),\n        (175, 95, 135),\n        (175, 95, 175),\n        (175, 95, 215),\n        (175, 95, 255),\n        (175, 135, 0),\n        (175, 135, 95),\n        (175, 135, 135),\n        (175, 135, 175),\n        (175, 135, 215),\n        (175, 135, 255),\n        (175, 175, 0),\n        (175, 175, 95),\n        (175, 175, 135),\n        (175, 175, 175),\n        (175, 175, 215),\n        (175, 175, 255),\n        (175, 215, 0),\n        (175, 215, 95),\n        (175, 215, 135),\n        (175, 215, 175),\n        (175, 215, 215),\n        (175, 215, 255),\n        (175, 255, 0),\n        (175, 255, 95),\n        (175, 255, 135),\n        (175, 255, 175),\n        (175, 255, 215),\n        (175, 255, 255),\n        (215, 0, 0),\n        (215, 0, 95),\n        (215, 0, 135),\n        (215, 0, 175),\n        (215, 0, 215),\n        (215, 0, 255),\n        (215, 95, 0),\n        (215, 95, 95),\n        (215, 95, 135),\n        (215, 95, 175),\n        (215, 95, 215),\n        (215, 95, 255),\n        (215, 135, 0),\n        (215, 135, 95),\n        (215, 135, 135),\n        (215, 135, 175),\n        (215, 135, 215),\n        (215, 135, 255),\n        (215, 175, 0),\n        (215, 175, 95),\n        (215, 175, 135),\n        (215, 175, 175),\n        (215, 175, 215),\n        (215, 175, 255),\n        (215, 215, 0),\n        (215, 215, 95),\n        (215, 215, 135),\n        (215, 215, 175),\n        (215, 215, 215),\n        (215, 215, 255),\n        (215, 255, 0),\n        (215, 255, 95),\n        (215, 255, 135),\n        (215, 255, 175),\n        (215, 255, 215),\n        (215, 255, 255),\n        (255, 0, 0),\n        (255, 0, 95),\n        (255, 0, 135),\n        (255, 0, 175),\n        (255, 0, 215),\n        (255, 0, 255),\n        (255, 95, 0),\n        (255, 95, 95),\n        (255, 95, 135),\n        (255, 95, 175),\n        (255, 95, 215),\n        (255, 95, 255),\n        (255, 135, 0),\n        (255, 135, 95),\n        (255, 135, 135),\n        (255, 135, 175),\n        (255, 135, 215),\n        (255, 135, 255),\n        (255, 175, 0),\n        (255, 175, 95),\n        (255, 175, 135),\n        (255, 175, 175),\n        (255, 175, 215),\n        (255, 175, 255),\n        (255, 215, 0),\n        (255, 215, 95),\n        (255, 215, 135),\n        (255, 215, 175),\n        (255, 215, 215),\n        (255, 215, 255),\n        (255, 255, 0),\n        (255, 255, 95),\n        (255, 255, 135),\n        (255, 255, 175),\n        (255, 255, 215),\n        (255, 255, 255),\n        (8, 8, 8),\n        (18, 18, 18),\n        (28, 28, 28),\n        (38, 38, 38),\n        (48, 48, 48),\n        (58, 58, 58),\n        (68, 68, 68),\n        (78, 78, 78),\n        (88, 88, 88),\n        (98, 98, 98),\n        (108, 108, 108),\n        (118, 118, 118),\n        (128, 128, 128),\n        (138, 138, 138),\n        (148, 148, 148),\n        (158, 158, 158),\n        (168, 168, 168),\n        (178, 178, 178),\n        (188, 188, 188),\n        (198, 198, 198),\n        (208, 208, 208),\n        (218, 218, 218),\n        (228, 228, 228),\n        (238, 238, 238),\n    ]\n)\n"
  },
  {
    "path": "src/pip/_vendor/rich/_pick.py",
    "content": "from typing import Optional\n\n\ndef pick_bool(*values: Optional[bool]) -> bool:\n    \"\"\"Pick the first non-none bool or return the last value.\n\n    Args:\n        *values (bool): Any number of boolean or None values.\n\n    Returns:\n        bool: First non-none boolean.\n    \"\"\"\n    assert values, \"1 or more values required\"\n    for value in values:\n        if value is not None:\n            return value\n    return bool(value)\n"
  },
  {
    "path": "src/pip/_vendor/rich/_ratio.py",
    "content": "from fractions import Fraction\nfrom math import ceil\nfrom typing import cast, List, Optional, Sequence, Protocol\n\n\nclass Edge(Protocol):\n    \"\"\"Any object that defines an edge (such as Layout).\"\"\"\n\n    size: Optional[int] = None\n    ratio: int = 1\n    minimum_size: int = 1\n\n\ndef ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:\n    \"\"\"Divide total space to satisfy size, ratio, and minimum_size, constraints.\n\n    The returned list of integers should add up to total in most cases, unless it is\n    impossible to satisfy all the constraints. For instance, if there are two edges\n    with a minimum size of 20 each and `total` is 30 then the returned list will be\n    greater than total. In practice, this would mean that a Layout object would\n    clip the rows that would overflow the screen height.\n\n    Args:\n        total (int): Total number of characters.\n        edges (List[Edge]): Edges within total space.\n\n    Returns:\n        List[int]: Number of characters for each edge.\n    \"\"\"\n    # Size of edge or None for yet to be determined\n    sizes = [(edge.size or None) for edge in edges]\n\n    _Fraction = Fraction\n\n    # While any edges haven't been calculated\n    while None in sizes:\n        # Get flexible edges and index to map these back on to sizes list\n        flexible_edges = [\n            (index, edge)\n            for index, (size, edge) in enumerate(zip(sizes, edges))\n            if size is None\n        ]\n        # Remaining space in total\n        remaining = total - sum(size or 0 for size in sizes)\n        if remaining <= 0:\n            # No room for flexible edges\n            return [\n                ((edge.minimum_size or 1) if size is None else size)\n                for size, edge in zip(sizes, edges)\n            ]\n        # Calculate number of characters in a ratio portion\n        portion = _Fraction(\n            remaining, sum((edge.ratio or 1) for _, edge in flexible_edges)\n        )\n\n        # If any edges will be less than their minimum, replace size with the minimum\n        for index, edge in flexible_edges:\n            if portion * edge.ratio <= edge.minimum_size:\n                sizes[index] = edge.minimum_size\n                # New fixed size will invalidate calculations, so we need to repeat the process\n                break\n        else:\n            # Distribute flexible space and compensate for rounding error\n            # Since edge sizes can only be integers we need to add the remainder\n            # to the following line\n            remainder = _Fraction(0)\n            for index, edge in flexible_edges:\n                size, remainder = divmod(portion * edge.ratio + remainder, 1)\n                sizes[index] = size\n            break\n    # Sizes now contains integers only\n    return cast(List[int], sizes)\n\n\ndef ratio_reduce(\n    total: int, ratios: List[int], maximums: List[int], values: List[int]\n) -> List[int]:\n    \"\"\"Divide an integer total in to parts based on ratios.\n\n    Args:\n        total (int): The total to divide.\n        ratios (List[int]): A list of integer ratios.\n        maximums (List[int]): List of maximums values for each slot.\n        values (List[int]): List of values\n\n    Returns:\n        List[int]: A list of integers guaranteed to sum to total.\n    \"\"\"\n    ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)]\n    total_ratio = sum(ratios)\n    if not total_ratio:\n        return values[:]\n    total_remaining = total\n    result: List[int] = []\n    append = result.append\n    for ratio, maximum, value in zip(ratios, maximums, values):\n        if ratio and total_ratio > 0:\n            distributed = min(maximum, round(ratio * total_remaining / total_ratio))\n            append(value - distributed)\n            total_remaining -= distributed\n            total_ratio -= ratio\n        else:\n            append(value)\n    return result\n\n\ndef ratio_distribute(\n    total: int, ratios: List[int], minimums: Optional[List[int]] = None\n) -> List[int]:\n    \"\"\"Distribute an integer total in to parts based on ratios.\n\n    Args:\n        total (int): The total to divide.\n        ratios (List[int]): A list of integer ratios.\n        minimums (List[int]): List of minimum values for each slot.\n\n    Returns:\n        List[int]: A list of integers guaranteed to sum to total.\n    \"\"\"\n    if minimums:\n        ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)]\n    total_ratio = sum(ratios)\n    assert total_ratio > 0, \"Sum of ratios must be > 0\"\n\n    total_remaining = total\n    distributed_total: List[int] = []\n    append = distributed_total.append\n    if minimums is None:\n        _minimums = [0] * len(ratios)\n    else:\n        _minimums = minimums\n    for ratio, minimum in zip(ratios, _minimums):\n        if total_ratio > 0:\n            distributed = max(minimum, ceil(ratio * total_remaining / total_ratio))\n        else:\n            distributed = total_remaining\n        append(distributed)\n        total_ratio -= ratio\n        total_remaining -= distributed\n    return distributed_total\n\n\nif __name__ == \"__main__\":\n    from dataclasses import dataclass\n\n    @dataclass\n    class E:\n        size: Optional[int] = None\n        ratio: int = 1\n        minimum_size: int = 1\n\n    resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)])\n    print(sum(resolved))\n"
  },
  {
    "path": "src/pip/_vendor/rich/_spinners.py",
    "content": "\"\"\"\nSpinners are from:\n* cli-spinners:\n    MIT License\n    Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights to\n    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n    the Software, and to permit persons to whom the Software is furnished to do so,\n    subject to the following conditions:\n    The above copyright notice and this permission notice shall be included\n    in all copies or substantial portions of the Software.\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n    PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n    FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n    IN THE SOFTWARE.\n\"\"\"\n\nSPINNERS = {\n    \"dots\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\",\n    },\n    \"dots2\": {\"interval\": 80, \"frames\": \"⣾⣽⣻⢿⡿⣟⣯⣷\"},\n    \"dots3\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓\",\n    },\n    \"dots4\": {\n        \"interval\": 80,\n        \"frames\": \"⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆\",\n    },\n    \"dots5\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋\",\n    },\n    \"dots6\": {\n        \"interval\": 80,\n        \"frames\": \"⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁\",\n    },\n    \"dots7\": {\n        \"interval\": 80,\n        \"frames\": \"⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈\",\n    },\n    \"dots8\": {\n        \"interval\": 80,\n        \"frames\": \"⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈\",\n    },\n    \"dots9\": {\"interval\": 80, \"frames\": \"⢹⢺⢼⣸⣇⡧⡗⡏\"},\n    \"dots10\": {\"interval\": 80, \"frames\": \"⢄⢂⢁⡁⡈⡐⡠\"},\n    \"dots11\": {\"interval\": 100, \"frames\": \"⠁⠂⠄⡀⢀⠠⠐⠈\"},\n    \"dots12\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"⢀⠀\",\n            \"⡀⠀\",\n            \"⠄⠀\",\n            \"⢂⠀\",\n            \"⡂⠀\",\n            \"⠅⠀\",\n            \"⢃⠀\",\n            \"⡃⠀\",\n            \"⠍⠀\",\n            \"⢋⠀\",\n            \"⡋⠀\",\n            \"⠍⠁\",\n            \"⢋⠁\",\n            \"⡋⠁\",\n            \"⠍⠉\",\n            \"⠋⠉\",\n            \"⠋⠉\",\n            \"⠉⠙\",\n            \"⠉⠙\",\n            \"⠉⠩\",\n            \"⠈⢙\",\n            \"⠈⡙\",\n            \"⢈⠩\",\n            \"⡀⢙\",\n            \"⠄⡙\",\n            \"⢂⠩\",\n            \"⡂⢘\",\n            \"⠅⡘\",\n            \"⢃⠨\",\n            \"⡃⢐\",\n            \"⠍⡐\",\n            \"⢋⠠\",\n            \"⡋⢀\",\n            \"⠍⡁\",\n            \"⢋⠁\",\n            \"⡋⠁\",\n            \"⠍⠉\",\n            \"⠋⠉\",\n            \"⠋⠉\",\n            \"⠉⠙\",\n            \"⠉⠙\",\n            \"⠉⠩\",\n            \"⠈⢙\",\n            \"⠈⡙\",\n            \"⠈⠩\",\n            \"⠀⢙\",\n            \"⠀⡙\",\n            \"⠀⠩\",\n            \"⠀⢘\",\n            \"⠀⡘\",\n            \"⠀⠨\",\n            \"⠀⢐\",\n            \"⠀⡐\",\n            \"⠀⠠\",\n            \"⠀⢀\",\n            \"⠀⡀\",\n        ],\n    },\n    \"dots8Bit\": {\n        \"interval\": 80,\n        \"frames\": \"⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙\"\n        \"⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻\"\n        \"⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕\"\n        \"⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷\"\n        \"⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿\",\n    },\n    \"line\": {\"interval\": 130, \"frames\": [\"-\", \"\\\\\", \"|\", \"/\"]},\n    \"line2\": {\"interval\": 100, \"frames\": \"⠂-–—–-\"},\n    \"pipe\": {\"interval\": 100, \"frames\": \"┤┘┴└├┌┬┐\"},\n    \"simpleDots\": {\"interval\": 400, \"frames\": [\".  \", \".. \", \"...\", \"   \"]},\n    \"simpleDotsScrolling\": {\n        \"interval\": 200,\n        \"frames\": [\".  \", \".. \", \"...\", \" ..\", \"  .\", \"   \"],\n    },\n    \"star\": {\"interval\": 70, \"frames\": \"✶✸✹✺✹✷\"},\n    \"star2\": {\"interval\": 80, \"frames\": \"+x*\"},\n    \"flip\": {\n        \"interval\": 70,\n        \"frames\": \"___-``'´-___\",\n    },\n    \"hamburger\": {\"interval\": 100, \"frames\": \"☱☲☴\"},\n    \"growVertical\": {\n        \"interval\": 120,\n        \"frames\": \"▁▃▄▅▆▇▆▅▄▃\",\n    },\n    \"growHorizontal\": {\n        \"interval\": 120,\n        \"frames\": \"▏▎▍▌▋▊▉▊▋▌▍▎\",\n    },\n    \"balloon\": {\"interval\": 140, \"frames\": \" .oO@* \"},\n    \"balloon2\": {\"interval\": 120, \"frames\": \".oO°Oo.\"},\n    \"noise\": {\"interval\": 100, \"frames\": \"▓▒░\"},\n    \"bounce\": {\"interval\": 120, \"frames\": \"⠁⠂⠄⠂\"},\n    \"boxBounce\": {\"interval\": 120, \"frames\": \"▖▘▝▗\"},\n    \"boxBounce2\": {\"interval\": 100, \"frames\": \"▌▀▐▄\"},\n    \"triangle\": {\"interval\": 50, \"frames\": \"◢◣◤◥\"},\n    \"arc\": {\"interval\": 100, \"frames\": \"◜◠◝◞◡◟\"},\n    \"circle\": {\"interval\": 120, \"frames\": \"◡⊙◠\"},\n    \"squareCorners\": {\"interval\": 180, \"frames\": \"◰◳◲◱\"},\n    \"circleQuarters\": {\"interval\": 120, \"frames\": \"◴◷◶◵\"},\n    \"circleHalves\": {\"interval\": 50, \"frames\": \"◐◓◑◒\"},\n    \"squish\": {\"interval\": 100, \"frames\": \"╫╪\"},\n    \"toggle\": {\"interval\": 250, \"frames\": \"⊶⊷\"},\n    \"toggle2\": {\"interval\": 80, \"frames\": \"▫▪\"},\n    \"toggle3\": {\"interval\": 120, \"frames\": \"□■\"},\n    \"toggle4\": {\"interval\": 100, \"frames\": \"■□▪▫\"},\n    \"toggle5\": {\"interval\": 100, \"frames\": \"▮▯\"},\n    \"toggle6\": {\"interval\": 300, \"frames\": \"ဝ၀\"},\n    \"toggle7\": {\"interval\": 80, \"frames\": \"⦾⦿\"},\n    \"toggle8\": {\"interval\": 100, \"frames\": \"◍◌\"},\n    \"toggle9\": {\"interval\": 100, \"frames\": \"◉◎\"},\n    \"toggle10\": {\"interval\": 100, \"frames\": \"㊂㊀㊁\"},\n    \"toggle11\": {\"interval\": 50, \"frames\": \"⧇⧆\"},\n    \"toggle12\": {\"interval\": 120, \"frames\": \"☗☖\"},\n    \"toggle13\": {\"interval\": 80, \"frames\": \"=*-\"},\n    \"arrow\": {\"interval\": 100, \"frames\": \"←↖↑↗→↘↓↙\"},\n    \"arrow2\": {\n        \"interval\": 80,\n        \"frames\": [\"⬆️ \", \"↗️ \", \"➡️ \", \"↘️ \", \"⬇️ \", \"↙️ \", \"⬅️ \", \"↖️ \"],\n    },\n    \"arrow3\": {\n        \"interval\": 120,\n        \"frames\": [\"▹▹▹▹▹\", \"▸▹▹▹▹\", \"▹▸▹▹▹\", \"▹▹▸▹▹\", \"▹▹▹▸▹\", \"▹▹▹▹▸\"],\n    },\n    \"bouncingBar\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"[    ]\",\n            \"[=   ]\",\n            \"[==  ]\",\n            \"[=== ]\",\n            \"[ ===]\",\n            \"[  ==]\",\n            \"[   =]\",\n            \"[    ]\",\n            \"[   =]\",\n            \"[  ==]\",\n            \"[ ===]\",\n            \"[====]\",\n            \"[=== ]\",\n            \"[==  ]\",\n            \"[=   ]\",\n        ],\n    },\n    \"bouncingBall\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"( ●    )\",\n            \"(  ●   )\",\n            \"(   ●  )\",\n            \"(    ● )\",\n            \"(     ●)\",\n            \"(    ● )\",\n            \"(   ●  )\",\n            \"(  ●   )\",\n            \"( ●    )\",\n            \"(●     )\",\n        ],\n    },\n    \"smiley\": {\"interval\": 200, \"frames\": [\"😄 \", \"😝 \"]},\n    \"monkey\": {\"interval\": 300, \"frames\": [\"🙈 \", \"🙈 \", \"🙉 \", \"🙊 \"]},\n    \"hearts\": {\"interval\": 100, \"frames\": [\"💛 \", \"💙 \", \"💜 \", \"💚 \", \"❤️ \"]},\n    \"clock\": {\n        \"interval\": 100,\n        \"frames\": [\n            \"🕛 \",\n            \"🕐 \",\n            \"🕑 \",\n            \"🕒 \",\n            \"🕓 \",\n            \"🕔 \",\n            \"🕕 \",\n            \"🕖 \",\n            \"🕗 \",\n            \"🕘 \",\n            \"🕙 \",\n            \"🕚 \",\n        ],\n    },\n    \"earth\": {\"interval\": 180, \"frames\": [\"🌍 \", \"🌎 \", \"🌏 \"]},\n    \"material\": {\n        \"interval\": 17,\n        \"frames\": [\n            \"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███████▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████████▁▁▁▁▁▁▁▁▁▁\",\n            \"███████████▁▁▁▁▁▁▁▁▁\",\n            \"█████████████▁▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁▁██████████████▁▁▁▁\",\n            \"▁▁▁██████████████▁▁▁\",\n            \"▁▁▁▁█████████████▁▁▁\",\n            \"▁▁▁▁██████████████▁▁\",\n            \"▁▁▁▁██████████████▁▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁▁██████████████\",\n            \"▁▁▁▁▁▁██████████████\",\n            \"▁▁▁▁▁▁▁█████████████\",\n            \"▁▁▁▁▁▁▁█████████████\",\n            \"▁▁▁▁▁▁▁▁████████████\",\n            \"▁▁▁▁▁▁▁▁████████████\",\n            \"▁▁▁▁▁▁▁▁▁███████████\",\n            \"▁▁▁▁▁▁▁▁▁███████████\",\n            \"▁▁▁▁▁▁▁▁▁▁██████████\",\n            \"▁▁▁▁▁▁▁▁▁▁██████████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁████████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███████████▁▁▁▁▁▁▁▁▁\",\n            \"████████████▁▁▁▁▁▁▁▁\",\n            \"████████████▁▁▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁▁▁█████████████▁▁▁▁\",\n            \"▁▁▁▁▁████████████▁▁▁\",\n            \"▁▁▁▁▁████████████▁▁▁\",\n            \"▁▁▁▁▁▁███████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁█████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁█████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁█████████▁▁\",\n            \"▁▁▁▁▁▁▁▁▁█████████▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁█████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n        ],\n    },\n    \"moon\": {\n        \"interval\": 80,\n        \"frames\": [\"🌑 \", \"🌒 \", \"🌓 \", \"🌔 \", \"🌕 \", \"🌖 \", \"🌗 \", \"🌘 \"],\n    },\n    \"runner\": {\"interval\": 140, \"frames\": [\"🚶 \", \"🏃 \"]},\n    \"pong\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"▐⠂       ▌\",\n            \"▐⠈       ▌\",\n            \"▐ ⠂      ▌\",\n            \"▐ ⠠      ▌\",\n            \"▐  ⡀     ▌\",\n            \"▐  ⠠     ▌\",\n            \"▐   ⠂    ▌\",\n            \"▐   ⠈    ▌\",\n            \"▐    ⠂   ▌\",\n            \"▐    ⠠   ▌\",\n            \"▐     ⡀  ▌\",\n            \"▐     ⠠  ▌\",\n            \"▐      ⠂ ▌\",\n            \"▐      ⠈ ▌\",\n            \"▐       ⠂▌\",\n            \"▐       ⠠▌\",\n            \"▐       ⡀▌\",\n            \"▐      ⠠ ▌\",\n            \"▐      ⠂ ▌\",\n            \"▐     ⠈  ▌\",\n            \"▐     ⠂  ▌\",\n            \"▐    ⠠   ▌\",\n            \"▐    ⡀   ▌\",\n            \"▐   ⠠    ▌\",\n            \"▐   ⠂    ▌\",\n            \"▐  ⠈     ▌\",\n            \"▐  ⠂     ▌\",\n            \"▐ ⠠      ▌\",\n            \"▐ ⡀      ▌\",\n            \"▐⠠       ▌\",\n        ],\n    },\n    \"shark\": {\n        \"interval\": 120,\n        \"frames\": [\n            \"▐|\\\\____________▌\",\n            \"▐_|\\\\___________▌\",\n            \"▐__|\\\\__________▌\",\n            \"▐___|\\\\_________▌\",\n            \"▐____|\\\\________▌\",\n            \"▐_____|\\\\_______▌\",\n            \"▐______|\\\\______▌\",\n            \"▐_______|\\\\_____▌\",\n            \"▐________|\\\\____▌\",\n            \"▐_________|\\\\___▌\",\n            \"▐__________|\\\\__▌\",\n            \"▐___________|\\\\_▌\",\n            \"▐____________|\\\\▌\",\n            \"▐____________/|▌\",\n            \"▐___________/|_▌\",\n            \"▐__________/|__▌\",\n            \"▐_________/|___▌\",\n            \"▐________/|____▌\",\n            \"▐_______/|_____▌\",\n            \"▐______/|______▌\",\n            \"▐_____/|_______▌\",\n            \"▐____/|________▌\",\n            \"▐___/|_________▌\",\n            \"▐__/|__________▌\",\n            \"▐_/|___________▌\",\n            \"▐/|____________▌\",\n        ],\n    },\n    \"dqpb\": {\"interval\": 100, \"frames\": \"dqpb\"},\n    \"weather\": {\n        \"interval\": 100,\n        \"frames\": [\n            \"☀️ \",\n            \"☀️ \",\n            \"☀️ \",\n            \"🌤 \",\n            \"⛅️ \",\n            \"🌥 \",\n            \"☁️ \",\n            \"🌧 \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"⛈ \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"☁️ \",\n            \"🌥 \",\n            \"⛅️ \",\n            \"🌤 \",\n            \"☀️ \",\n            \"☀️ \",\n        ],\n    },\n    \"christmas\": {\"interval\": 400, \"frames\": \"🌲🎄\"},\n    \"grenade\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"،   \",\n            \"′   \",\n            \" ´ \",\n            \" ‾ \",\n            \"  ⸌\",\n            \"  ⸊\",\n            \"  |\",\n            \"  ⁎\",\n            \"  ⁕\",\n            \" ෴ \",\n            \"  ⁓\",\n            \"   \",\n            \"   \",\n            \"   \",\n        ],\n    },\n    \"point\": {\"interval\": 125, \"frames\": [\"∙∙∙\", \"●∙∙\", \"∙●∙\", \"∙∙●\", \"∙∙∙\"]},\n    \"layer\": {\"interval\": 150, \"frames\": \"-=≡\"},\n    \"betaWave\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"ρββββββ\",\n            \"βρβββββ\",\n            \"ββρββββ\",\n            \"βββρβββ\",\n            \"ββββρββ\",\n            \"βββββρβ\",\n            \"ββββββρ\",\n        ],\n    },\n    \"aesthetic\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"▰▱▱▱▱▱▱\",\n            \"▰▰▱▱▱▱▱\",\n            \"▰▰▰▱▱▱▱\",\n            \"▰▰▰▰▱▱▱\",\n            \"▰▰▰▰▰▱▱\",\n            \"▰▰▰▰▰▰▱\",\n            \"▰▰▰▰▰▰▰\",\n            \"▰▱▱▱▱▱▱\",\n        ],\n    },\n}\n"
  },
  {
    "path": "src/pip/_vendor/rich/_stack.py",
    "content": "from typing import List, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass Stack(List[T]):\n    \"\"\"A small shim over builtin list.\"\"\"\n\n    @property\n    def top(self) -> T:\n        \"\"\"Get top of stack.\"\"\"\n        return self[-1]\n\n    def push(self, item: T) -> None:\n        \"\"\"Push an item on to the stack (append in stack nomenclature).\"\"\"\n        self.append(item)\n"
  },
  {
    "path": "src/pip/_vendor/rich/_timer.py",
    "content": "\"\"\"\nTimer context manager, only used in debug.\n\n\"\"\"\n\nfrom time import time\n\nimport contextlib\nfrom typing import Generator\n\n\n@contextlib.contextmanager\ndef timer(subject: str = \"time\") -> Generator[None, None, None]:\n    \"\"\"print the elapsed time. (only used in debugging)\"\"\"\n    start = time()\n    yield\n    elapsed = time() - start\n    elapsed_ms = elapsed * 1000\n    print(f\"{subject} elapsed {elapsed_ms:.1f}ms\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/_win32_console.py",
    "content": "\"\"\"Light wrapper around the Win32 Console API - this module should only be imported on Windows\n\nThe API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions\n\"\"\"\n\nimport ctypes\nimport sys\nfrom typing import Any\n\nwindll: Any = None\nif sys.platform == \"win32\":\n    windll = ctypes.LibraryLoader(ctypes.WinDLL)\nelse:\n    raise ImportError(f\"{__name__} can only be imported on Windows\")\n\nimport time\nfrom ctypes import Structure, byref, wintypes\nfrom typing import IO, NamedTuple, Type, cast\n\nfrom pip._vendor.rich.color import ColorSystem\nfrom pip._vendor.rich.style import Style\n\nSTDOUT = -11\nENABLE_VIRTUAL_TERMINAL_PROCESSING = 4\n\nCOORD = wintypes._COORD\n\n\nclass LegacyWindowsError(Exception):\n    pass\n\n\nclass WindowsCoordinates(NamedTuple):\n    \"\"\"Coordinates in the Windows Console API are (y, x), not (x, y).\n    This class is intended to prevent that confusion.\n    Rows and columns are indexed from 0.\n    This class can be used in place of wintypes._COORD in arguments and argtypes.\n    \"\"\"\n\n    row: int\n    col: int\n\n    @classmethod\n    def from_param(cls, value: \"WindowsCoordinates\") -> COORD:\n        \"\"\"Converts a WindowsCoordinates into a wintypes _COORD structure.\n        This classmethod is internally called by ctypes to perform the conversion.\n\n        Args:\n            value (WindowsCoordinates): The input coordinates to convert.\n\n        Returns:\n            wintypes._COORD: The converted coordinates struct.\n        \"\"\"\n        return COORD(value.col, value.row)\n\n\nclass CONSOLE_SCREEN_BUFFER_INFO(Structure):\n    _fields_ = [\n        (\"dwSize\", COORD),\n        (\"dwCursorPosition\", COORD),\n        (\"wAttributes\", wintypes.WORD),\n        (\"srWindow\", wintypes.SMALL_RECT),\n        (\"dwMaximumWindowSize\", COORD),\n    ]\n\n\nclass CONSOLE_CURSOR_INFO(ctypes.Structure):\n    _fields_ = [(\"dwSize\", wintypes.DWORD), (\"bVisible\", wintypes.BOOL)]\n\n\n_GetStdHandle = windll.kernel32.GetStdHandle\n_GetStdHandle.argtypes = [\n    wintypes.DWORD,\n]\n_GetStdHandle.restype = wintypes.HANDLE\n\n\ndef GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE:\n    \"\"\"Retrieves a handle to the specified standard device (standard input, standard output, or standard error).\n\n    Args:\n        handle (int): Integer identifier for the handle. Defaults to -11 (stdout).\n\n    Returns:\n        wintypes.HANDLE: The handle\n    \"\"\"\n    return cast(wintypes.HANDLE, _GetStdHandle(handle))\n\n\n_GetConsoleMode = windll.kernel32.GetConsoleMode\n_GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD]\n_GetConsoleMode.restype = wintypes.BOOL\n\n\ndef GetConsoleMode(std_handle: wintypes.HANDLE) -> int:\n    \"\"\"Retrieves the current input mode of a console's input buffer\n    or the current output mode of a console screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n    Raises:\n        LegacyWindowsError: If any error occurs while calling the Windows console API.\n\n    Returns:\n        int: Value representing the current console mode as documented at\n            https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters\n    \"\"\"\n\n    console_mode = wintypes.DWORD()\n    success = bool(_GetConsoleMode(std_handle, console_mode))\n    if not success:\n        raise LegacyWindowsError(\"Unable to get legacy Windows Console Mode\")\n    return console_mode.value\n\n\n_FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW\n_FillConsoleOutputCharacterW.argtypes = [\n    wintypes.HANDLE,\n    ctypes.c_char,\n    wintypes.DWORD,\n    cast(Type[COORD], WindowsCoordinates),\n    ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputCharacterW.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputCharacter(\n    std_handle: wintypes.HANDLE,\n    char: str,\n    length: int,\n    start: WindowsCoordinates,\n) -> int:\n    \"\"\"Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        char (str): The character to write. Must be a string of length 1.\n        length (int): The number of times to write the character.\n        start (WindowsCoordinates): The coordinates to start writing at.\n\n    Returns:\n        int: The number of characters written.\n    \"\"\"\n    character = ctypes.c_char(char.encode())\n    num_characters = wintypes.DWORD(length)\n    num_written = wintypes.DWORD(0)\n    _FillConsoleOutputCharacterW(\n        std_handle,\n        character,\n        num_characters,\n        start,\n        byref(num_written),\n    )\n    return num_written.value\n\n\n_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute\n_FillConsoleOutputAttribute.argtypes = [\n    wintypes.HANDLE,\n    wintypes.WORD,\n    wintypes.DWORD,\n    cast(Type[COORD], WindowsCoordinates),\n    ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputAttribute.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputAttribute(\n    std_handle: wintypes.HANDLE,\n    attributes: int,\n    length: int,\n    start: WindowsCoordinates,\n) -> int:\n    \"\"\"Sets the character attributes for a specified number of character cells,\n    beginning at the specified coordinates in a screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        attributes (int): Integer value representing the foreground and background colours of the cells.\n        length (int): The number of cells to set the output attribute of.\n        start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set.\n\n    Returns:\n        int: The number of cells whose attributes were actually set.\n    \"\"\"\n    num_cells = wintypes.DWORD(length)\n    style_attrs = wintypes.WORD(attributes)\n    num_written = wintypes.DWORD(0)\n    _FillConsoleOutputAttribute(\n        std_handle, style_attrs, num_cells, start, byref(num_written)\n    )\n    return num_written.value\n\n\n_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute\n_SetConsoleTextAttribute.argtypes = [\n    wintypes.HANDLE,\n    wintypes.WORD,\n]\n_SetConsoleTextAttribute.restype = wintypes.BOOL\n\n\ndef SetConsoleTextAttribute(\n    std_handle: wintypes.HANDLE, attributes: wintypes.WORD\n) -> bool:\n    \"\"\"Set the colour attributes for all text written after this function is called.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        attributes (int): Integer value representing the foreground and background colours.\n\n\n    Returns:\n        bool: True if the attribute was set successfully, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleTextAttribute(std_handle, attributes))\n\n\n_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo\n_GetConsoleScreenBufferInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),\n]\n_GetConsoleScreenBufferInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleScreenBufferInfo(\n    std_handle: wintypes.HANDLE,\n) -> CONSOLE_SCREEN_BUFFER_INFO:\n    \"\"\"Retrieves information about the specified console screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n    Returns:\n        CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about\n            screen size, cursor position, colour attributes, and more.\"\"\"\n    console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO()\n    _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info))\n    return console_screen_buffer_info\n\n\n_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition\n_SetConsoleCursorPosition.argtypes = [\n    wintypes.HANDLE,\n    cast(Type[COORD], WindowsCoordinates),\n]\n_SetConsoleCursorPosition.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorPosition(\n    std_handle: wintypes.HANDLE, coords: WindowsCoordinates\n) -> bool:\n    \"\"\"Set the position of the cursor in the console screen\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        coords (WindowsCoordinates): The coordinates to move the cursor to.\n\n    Returns:\n        bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleCursorPosition(std_handle, coords))\n\n\n_GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo\n_GetConsoleCursorInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_GetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleCursorInfo(\n    std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n    \"\"\"Get the cursor info - used to get cursor visibility and width\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information\n            about the console's cursor.\n\n    Returns:\n          bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo\n_SetConsoleCursorInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_SetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorInfo(\n    std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n    \"\"\"Set the cursor info - used for adjusting cursor visibility and width\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info.\n\n    Returns:\n          bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleTitle = windll.kernel32.SetConsoleTitleW\n_SetConsoleTitle.argtypes = [wintypes.LPCWSTR]\n_SetConsoleTitle.restype = wintypes.BOOL\n\n\ndef SetConsoleTitle(title: str) -> bool:\n    \"\"\"Sets the title of the current console window\n\n    Args:\n        title (str): The new title of the console window.\n\n    Returns:\n        bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleTitle(title))\n\n\nclass LegacyWindowsTerm:\n    \"\"\"This class allows interaction with the legacy Windows Console API. It should only be used in the context\n    of environments where virtual terminal processing is not available. However, if it is used in a Windows environment,\n    the entire API should work.\n\n    Args:\n        file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout.\n    \"\"\"\n\n    BRIGHT_BIT = 8\n\n    # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers\n    ANSI_TO_WINDOWS = [\n        0,  # black                      The Windows colours are defined in wincon.h as follows:\n        4,  # red                         define FOREGROUND_BLUE            0x0001 -- 0000 0001\n        2,  # green                       define FOREGROUND_GREEN           0x0002 -- 0000 0010\n        6,  # yellow                      define FOREGROUND_RED             0x0004 -- 0000 0100\n        1,  # blue                        define FOREGROUND_INTENSITY       0x0008 -- 0000 1000\n        5,  # magenta                     define BACKGROUND_BLUE            0x0010 -- 0001 0000\n        3,  # cyan                        define BACKGROUND_GREEN           0x0020 -- 0010 0000\n        7,  # white                       define BACKGROUND_RED             0x0040 -- 0100 0000\n        8,  # bright black (grey)         define BACKGROUND_INTENSITY       0x0080 -- 1000 0000\n        12,  # bright red\n        10,  # bright green\n        14,  # bright yellow\n        9,  # bright blue\n        13,  # bright magenta\n        11,  # bright cyan\n        15,  # bright white\n    ]\n\n    def __init__(self, file: \"IO[str]\") -> None:\n        handle = GetStdHandle(STDOUT)\n        self._handle = handle\n        default_text = GetConsoleScreenBufferInfo(handle).wAttributes\n        self._default_text = default_text\n\n        self._default_fore = default_text & 7\n        self._default_back = (default_text >> 4) & 7\n        self._default_attrs = self._default_fore | (self._default_back << 4)\n\n        self._file = file\n        self.write = file.write\n        self.flush = file.flush\n\n    @property\n    def cursor_position(self) -> WindowsCoordinates:\n        \"\"\"Returns the current position of the cursor (0-based)\n\n        Returns:\n            WindowsCoordinates: The current cursor position.\n        \"\"\"\n        coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition\n        return WindowsCoordinates(row=coord.Y, col=coord.X)\n\n    @property\n    def screen_size(self) -> WindowsCoordinates:\n        \"\"\"Returns the current size of the console screen buffer, in character columns and rows\n\n        Returns:\n            WindowsCoordinates: The width and height of the screen as WindowsCoordinates.\n        \"\"\"\n        screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize\n        return WindowsCoordinates(row=screen_size.Y, col=screen_size.X)\n\n    def write_text(self, text: str) -> None:\n        \"\"\"Write text directly to the terminal without any modification of styles\n\n        Args:\n            text (str): The text to write to the console\n        \"\"\"\n        self.write(text)\n        self.flush()\n\n    def write_styled(self, text: str, style: Style) -> None:\n        \"\"\"Write styled text to the terminal.\n\n        Args:\n            text (str): The text to write\n            style (Style): The style of the text\n        \"\"\"\n        color = style.color\n        bgcolor = style.bgcolor\n        if style.reverse:\n            color, bgcolor = bgcolor, color\n\n        if color:\n            fore = color.downgrade(ColorSystem.WINDOWS).number\n            fore = fore if fore is not None else 7  # Default to ANSI 7: White\n            if style.bold:\n                fore = fore | self.BRIGHT_BIT\n            if style.dim:\n                fore = fore & ~self.BRIGHT_BIT\n            fore = self.ANSI_TO_WINDOWS[fore]\n        else:\n            fore = self._default_fore\n\n        if bgcolor:\n            back = bgcolor.downgrade(ColorSystem.WINDOWS).number\n            back = back if back is not None else 0  # Default to ANSI 0: Black\n            back = self.ANSI_TO_WINDOWS[back]\n        else:\n            back = self._default_back\n\n        assert fore is not None\n        assert back is not None\n\n        SetConsoleTextAttribute(\n            self._handle, attributes=ctypes.c_ushort(fore | (back << 4))\n        )\n        self.write_text(text)\n        SetConsoleTextAttribute(self._handle, attributes=self._default_text)\n\n    def move_cursor_to(self, new_position: WindowsCoordinates) -> None:\n        \"\"\"Set the position of the cursor\n\n        Args:\n            new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor.\n        \"\"\"\n        if new_position.col < 0 or new_position.row < 0:\n            return\n        SetConsoleCursorPosition(self._handle, coords=new_position)\n\n    def erase_line(self) -> None:\n        \"\"\"Erase all content on the line the cursor is currently located at\"\"\"\n        screen_size = self.screen_size\n        cursor_position = self.cursor_position\n        cells_to_erase = screen_size.col\n        start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0)\n        FillConsoleOutputCharacter(\n            self._handle, \" \", length=cells_to_erase, start=start_coordinates\n        )\n        FillConsoleOutputAttribute(\n            self._handle,\n            self._default_attrs,\n            length=cells_to_erase,\n            start=start_coordinates,\n        )\n\n    def erase_end_of_line(self) -> None:\n        \"\"\"Erase all content from the cursor position to the end of that line\"\"\"\n        cursor_position = self.cursor_position\n        cells_to_erase = self.screen_size.col - cursor_position.col\n        FillConsoleOutputCharacter(\n            self._handle, \" \", length=cells_to_erase, start=cursor_position\n        )\n        FillConsoleOutputAttribute(\n            self._handle,\n            self._default_attrs,\n            length=cells_to_erase,\n            start=cursor_position,\n        )\n\n    def erase_start_of_line(self) -> None:\n        \"\"\"Erase all content from the cursor position to the start of that line\"\"\"\n        row, col = self.cursor_position\n        start = WindowsCoordinates(row, 0)\n        FillConsoleOutputCharacter(self._handle, \" \", length=col, start=start)\n        FillConsoleOutputAttribute(\n            self._handle, self._default_attrs, length=col, start=start\n        )\n\n    def move_cursor_up(self) -> None:\n        \"\"\"Move the cursor up a single cell\"\"\"\n        cursor_position = self.cursor_position\n        SetConsoleCursorPosition(\n            self._handle,\n            coords=WindowsCoordinates(\n                row=cursor_position.row - 1, col=cursor_position.col\n            ),\n        )\n\n    def move_cursor_down(self) -> None:\n        \"\"\"Move the cursor down a single cell\"\"\"\n        cursor_position = self.cursor_position\n        SetConsoleCursorPosition(\n            self._handle,\n            coords=WindowsCoordinates(\n                row=cursor_position.row + 1,\n                col=cursor_position.col,\n            ),\n        )\n\n    def move_cursor_forward(self) -> None:\n        \"\"\"Move the cursor forward a single cell. Wrap to the next line if required.\"\"\"\n        row, col = self.cursor_position\n        if col == self.screen_size.col - 1:\n            row += 1\n            col = 0\n        else:\n            col += 1\n        SetConsoleCursorPosition(\n            self._handle, coords=WindowsCoordinates(row=row, col=col)\n        )\n\n    def move_cursor_to_column(self, column: int) -> None:\n        \"\"\"Move cursor to the column specified by the zero-based column index, staying on the same row\n\n        Args:\n            column (int): The zero-based column index to move the cursor to.\n        \"\"\"\n        row, _ = self.cursor_position\n        SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column))\n\n    def move_cursor_backward(self) -> None:\n        \"\"\"Move the cursor backward a single cell. Wrap to the previous line if required.\"\"\"\n        row, col = self.cursor_position\n        if col == 0:\n            row -= 1\n            col = self.screen_size.col - 1\n        else:\n            col -= 1\n        SetConsoleCursorPosition(\n            self._handle, coords=WindowsCoordinates(row=row, col=col)\n        )\n\n    def hide_cursor(self) -> None:\n        \"\"\"Hide the cursor\"\"\"\n        current_cursor_size = self._get_cursor_size()\n        invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0)\n        SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor)\n\n    def show_cursor(self) -> None:\n        \"\"\"Show the cursor\"\"\"\n        current_cursor_size = self._get_cursor_size()\n        visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1)\n        SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor)\n\n    def set_title(self, title: str) -> None:\n        \"\"\"Set the title of the terminal window\n\n        Args:\n            title (str): The new title of the console window\n        \"\"\"\n        assert len(title) < 255, \"Console title must be less than 255 characters\"\n        SetConsoleTitle(title)\n\n    def _get_cursor_size(self) -> int:\n        \"\"\"Get the percentage of the character cell that is filled by the cursor\"\"\"\n        cursor_info = CONSOLE_CURSOR_INFO()\n        GetConsoleCursorInfo(self._handle, cursor_info=cursor_info)\n        return int(cursor_info.dwSize)\n\n\nif __name__ == \"__main__\":\n    handle = GetStdHandle()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n\n    term = LegacyWindowsTerm(sys.stdout)\n    term.set_title(\"Win32 Console Examples\")\n\n    style = Style(color=\"black\", bgcolor=\"red\")\n\n    heading = Style.parse(\"black on green\")\n\n    # Check colour output\n    console.rule(\"Checking colour output\")\n    console.print(\"[on red]on red!\")\n    console.print(\"[blue]blue!\")\n    console.print(\"[yellow]yellow!\")\n    console.print(\"[bold yellow]bold yellow!\")\n    console.print(\"[bright_yellow]bright_yellow!\")\n    console.print(\"[dim bright_yellow]dim bright_yellow!\")\n    console.print(\"[italic cyan]italic cyan!\")\n    console.print(\"[bold white on blue]bold white on blue!\")\n    console.print(\"[reverse bold white on blue]reverse bold white on blue!\")\n    console.print(\"[bold black on cyan]bold black on cyan!\")\n    console.print(\"[black on green]black on green!\")\n    console.print(\"[blue on green]blue on green!\")\n    console.print(\"[white on black]white on black!\")\n    console.print(\"[black on white]black on white!\")\n    console.print(\"[#1BB152 on #DA812D]#1BB152 on #DA812D!\")\n\n    # Check cursor movement\n    console.rule(\"Checking cursor movement\")\n    console.print()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"went back and wrapped to prev line\")\n    time.sleep(1)\n    term.move_cursor_up()\n    term.write_text(\"we go up\")\n    time.sleep(1)\n    term.move_cursor_down()\n    term.write_text(\"and down\")\n    time.sleep(1)\n    term.move_cursor_up()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"we went up and back 2\")\n    time.sleep(1)\n    term.move_cursor_down()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"we went down and back 2\")\n    time.sleep(1)\n\n    # Check erasing of lines\n    term.hide_cursor()\n    console.print()\n    console.rule(\"Checking line erasing\")\n    console.print(\"\\n...Deleting to the start of the line...\")\n    term.write_text(\"The red arrow shows the cursor location, and direction of erase\")\n    time.sleep(1)\n    term.move_cursor_to_column(16)\n    term.write_styled(\"<\", Style.parse(\"black on red\"))\n    term.move_cursor_backward()\n    time.sleep(1)\n    term.erase_start_of_line()\n    time.sleep(1)\n\n    console.print(\"\\n\\n...And to the end of the line...\")\n    term.write_text(\"The red arrow shows the cursor location, and direction of erase\")\n    time.sleep(1)\n\n    term.move_cursor_to_column(16)\n    term.write_styled(\">\", Style.parse(\"black on red\"))\n    time.sleep(1)\n    term.erase_end_of_line()\n    time.sleep(1)\n\n    console.print(\"\\n\\n...Now the whole line will be erased...\")\n    term.write_styled(\"I'm going to disappear!\", style=Style.parse(\"black on cyan\"))\n    time.sleep(1)\n    term.erase_line()\n\n    term.show_cursor()\n    print(\"\\n\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/_windows.py",
    "content": "import sys\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass WindowsConsoleFeatures:\n    \"\"\"Windows features available.\"\"\"\n\n    vt: bool = False\n    \"\"\"The console supports VT codes.\"\"\"\n    truecolor: bool = False\n    \"\"\"The console supports truecolor.\"\"\"\n\n\ntry:\n    import ctypes\n    from ctypes import LibraryLoader\n\n    if sys.platform == \"win32\":\n        windll = LibraryLoader(ctypes.WinDLL)\n    else:\n        windll = None\n        raise ImportError(\"Not windows\")\n\n    from pip._vendor.rich._win32_console import (\n        ENABLE_VIRTUAL_TERMINAL_PROCESSING,\n        GetConsoleMode,\n        GetStdHandle,\n        LegacyWindowsError,\n    )\n\nexcept (AttributeError, ImportError, ValueError):\n    # Fallback if we can't load the Windows DLL\n    def get_windows_console_features() -> WindowsConsoleFeatures:\n        features = WindowsConsoleFeatures()\n        return features\n\nelse:\n\n    def get_windows_console_features() -> WindowsConsoleFeatures:\n        \"\"\"Get windows console features.\n\n        Returns:\n            WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.\n        \"\"\"\n        handle = GetStdHandle()\n        try:\n            console_mode = GetConsoleMode(handle)\n            success = True\n        except LegacyWindowsError:\n            console_mode = 0\n            success = False\n        vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)\n        truecolor = False\n        if vt:\n            win_version = sys.getwindowsversion()\n            truecolor = win_version.major > 10 or (\n                win_version.major == 10 and win_version.build >= 15063\n            )\n        features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)\n        return features\n\n\nif __name__ == \"__main__\":\n    import platform\n\n    features = get_windows_console_features()\n    from pip._vendor.rich import print\n\n    print(f'platform=\"{platform.system()}\"')\n    print(repr(features))\n"
  },
  {
    "path": "src/pip/_vendor/rich/_windows_renderer.py",
    "content": "from typing import Iterable, Sequence, Tuple, cast\n\nfrom pip._vendor.rich._win32_console import LegacyWindowsTerm, WindowsCoordinates\nfrom pip._vendor.rich.segment import ControlCode, ControlType, Segment\n\n\ndef legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None:\n    \"\"\"Makes appropriate Windows Console API calls based on the segments in the buffer.\n\n    Args:\n        buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls.\n        term (LegacyWindowsTerm): Used to call the Windows Console API.\n    \"\"\"\n    for text, style, control in buffer:\n        if not control:\n            if style:\n                term.write_styled(text, style)\n            else:\n                term.write_text(text)\n        else:\n            control_codes: Sequence[ControlCode] = control\n            for control_code in control_codes:\n                control_type = control_code[0]\n                if control_type == ControlType.CURSOR_MOVE_TO:\n                    _, x, y = cast(Tuple[ControlType, int, int], control_code)\n                    term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1))\n                elif control_type == ControlType.CARRIAGE_RETURN:\n                    term.write_text(\"\\r\")\n                elif control_type == ControlType.HOME:\n                    term.move_cursor_to(WindowsCoordinates(0, 0))\n                elif control_type == ControlType.CURSOR_UP:\n                    term.move_cursor_up()\n                elif control_type == ControlType.CURSOR_DOWN:\n                    term.move_cursor_down()\n                elif control_type == ControlType.CURSOR_FORWARD:\n                    term.move_cursor_forward()\n                elif control_type == ControlType.CURSOR_BACKWARD:\n                    term.move_cursor_backward()\n                elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN:\n                    _, column = cast(Tuple[ControlType, int], control_code)\n                    term.move_cursor_to_column(column - 1)\n                elif control_type == ControlType.HIDE_CURSOR:\n                    term.hide_cursor()\n                elif control_type == ControlType.SHOW_CURSOR:\n                    term.show_cursor()\n                elif control_type == ControlType.ERASE_IN_LINE:\n                    _, mode = cast(Tuple[ControlType, int], control_code)\n                    if mode == 0:\n                        term.erase_end_of_line()\n                    elif mode == 1:\n                        term.erase_start_of_line()\n                    elif mode == 2:\n                        term.erase_line()\n                elif control_type == ControlType.SET_WINDOW_TITLE:\n                    _, title = cast(Tuple[ControlType, str], control_code)\n                    term.set_title(title)\n"
  },
  {
    "path": "src/pip/_vendor/rich/_wrap.py",
    "content": "from __future__ import annotations\n\nimport re\nfrom typing import Iterable\n\nfrom ._loop import loop_last\nfrom .cells import cell_len, chop_cells\n\nre_word = re.compile(r\"\\s*\\S+\\s*\")\n\n\ndef words(text: str) -> Iterable[tuple[int, int, str]]:\n    \"\"\"Yields each word from the text as a tuple\n    containing (start_index, end_index, word). A \"word\" in this context may\n    include the actual word and any whitespace to the right.\n    \"\"\"\n    position = 0\n    word_match = re_word.match(text, position)\n    while word_match is not None:\n        start, end = word_match.span()\n        word = word_match.group(0)\n        yield start, end, word\n        word_match = re_word.match(text, end)\n\n\ndef divide_line(text: str, width: int, fold: bool = True) -> list[int]:\n    \"\"\"Given a string of text, and a width (measured in cells), return a list\n    of cell offsets which the string should be split at in order for it to fit\n    within the given width.\n\n    Args:\n        text: The text to examine.\n        width: The available cell width.\n        fold: If True, words longer than `width` will be folded onto a new line.\n\n    Returns:\n        A list of indices to break the line at.\n    \"\"\"\n    break_positions: list[int] = []  # offsets to insert the breaks at\n    append = break_positions.append\n    cell_offset = 0\n    _cell_len = cell_len\n\n    for start, _end, word in words(text):\n        word_length = _cell_len(word.rstrip())\n        remaining_space = width - cell_offset\n        word_fits_remaining_space = remaining_space >= word_length\n\n        if word_fits_remaining_space:\n            # Simplest case - the word fits within the remaining width for this line.\n            cell_offset += _cell_len(word)\n        else:\n            # Not enough space remaining for this word on the current line.\n            if word_length > width:\n                # The word doesn't fit on any line, so we can't simply\n                # place it on the next line...\n                if fold:\n                    # Fold the word across multiple lines.\n                    folded_word = chop_cells(word, width=width)\n                    for last, line in loop_last(folded_word):\n                        if start:\n                            append(start)\n                        if last:\n                            cell_offset = _cell_len(line)\n                        else:\n                            start += len(line)\n                else:\n                    # Folding isn't allowed, so crop the word.\n                    if start:\n                        append(start)\n                    cell_offset = _cell_len(word)\n            elif cell_offset and start:\n                # The word doesn't fit within the remaining space on the current\n                # line, but it *can* fit on to the next (empty) line.\n                append(start)\n                cell_offset = _cell_len(word)\n\n    return break_positions\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    console = Console(width=10)\n    console.print(\"12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345\")\n    print(chop_cells(\"abcdefghijklmnopqrstuvwxyz\", 10))\n\n    console = Console(width=20)\n    console.rule()\n    console.print(\"TextualはPythonの高速アプリケーション開発フレームワークです\")\n\n    console.rule()\n    console.print(\"アプリケーションは1670万色を使用でき\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/abc.py",
    "content": "from abc import ABC\n\n\nclass RichRenderable(ABC):\n    \"\"\"An abstract base class for Rich renderables.\n\n    Note that there is no need to extend this class, the intended use is to check if an\n    object supports the Rich renderable protocol. For example::\n\n        if isinstance(my_object, RichRenderable):\n            console.print(my_object)\n\n    \"\"\"\n\n    @classmethod\n    def __subclasshook__(cls, other: type) -> bool:\n        \"\"\"Check if this class supports the rich render protocol.\"\"\"\n        return hasattr(other, \"__rich_console__\") or hasattr(other, \"__rich__\")\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.text import Text\n\n    t = Text()\n    print(isinstance(Text, RichRenderable))\n    print(isinstance(t, RichRenderable))\n\n    class Foo:\n        pass\n\n    f = Foo()\n    print(isinstance(f, RichRenderable))\n    print(isinstance(\"\", RichRenderable))\n"
  },
  {
    "path": "src/pip/_vendor/rich/align.py",
    "content": "from itertools import chain\nfrom typing import TYPE_CHECKING, Iterable, Optional, Literal\n\nfrom .constrain import Constrain\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\nAlignMethod = Literal[\"left\", \"center\", \"right\"]\nVerticalAlignMethod = Literal[\"top\", \"middle\", \"bottom\"]\n\n\nclass Align(JupyterMixin):\n    \"\"\"Align a renderable by adding spaces if necessary.\n\n    Args:\n        renderable (RenderableType): A console renderable.\n        align (AlignMethod): One of \"left\", \"center\", or \"right\"\"\n        style (StyleType, optional): An optional style to apply to the background.\n        vertical (Optional[VerticalAlignMethod], optional): Optional vertical align, one of \"top\", \"middle\", or \"bottom\". Defaults to None.\n        pad (bool, optional): Pad the right with spaces. Defaults to True.\n        width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None.\n        height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None.\n\n    Raises:\n        ValueError: if ``align`` is not one of the expected values.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        align: AlignMethod = \"left\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> None:\n        if align not in (\"left\", \"center\", \"right\"):\n            raise ValueError(\n                f'invalid value for align, expected \"left\", \"center\", or \"right\" (not {align!r})'\n            )\n        if vertical is not None and vertical not in (\"top\", \"middle\", \"bottom\"):\n            raise ValueError(\n                f'invalid value for vertical, expected \"top\", \"middle\", or \"bottom\" (not {vertical!r})'\n            )\n        self.renderable = renderable\n        self.align = align\n        self.style = style\n        self.vertical = vertical\n        self.pad = pad\n        self.width = width\n        self.height = height\n\n    def __repr__(self) -> str:\n        return f\"Align({self.renderable!r}, {self.align!r})\"\n\n    @classmethod\n    def left(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the left.\"\"\"\n        return cls(\n            renderable,\n            \"left\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    @classmethod\n    def center(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the center.\"\"\"\n        return cls(\n            renderable,\n            \"center\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    @classmethod\n    def right(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the right.\"\"\"\n        return cls(\n            renderable,\n            \"right\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        align = self.align\n        width = console.measure(self.renderable, options=options).maximum\n        rendered = console.render(\n            Constrain(\n                self.renderable, width if self.width is None else min(width, self.width)\n            ),\n            options.update(height=None),\n        )\n        lines = list(Segment.split_lines(rendered))\n        width, height = Segment.get_shape(lines)\n        lines = Segment.set_shape(lines, width, height)\n        new_line = Segment.line()\n        excess_space = options.max_width - width\n        style = console.get_style(self.style) if self.style is not None else None\n\n        def generate_segments() -> Iterable[Segment]:\n            if excess_space <= 0:\n                # Exact fit\n                for line in lines:\n                    yield from line\n                    yield new_line\n\n            elif align == \"left\":\n                # Pad on the right\n                pad = Segment(\" \" * excess_space, style) if self.pad else None\n                for line in lines:\n                    yield from line\n                    if pad:\n                        yield pad\n                    yield new_line\n\n            elif align == \"center\":\n                # Pad left and right\n                left = excess_space // 2\n                pad = Segment(\" \" * left, style)\n                pad_right = (\n                    Segment(\" \" * (excess_space - left), style) if self.pad else None\n                )\n                for line in lines:\n                    if left:\n                        yield pad\n                    yield from line\n                    if pad_right:\n                        yield pad_right\n                    yield new_line\n\n            elif align == \"right\":\n                # Padding on left\n                pad = Segment(\" \" * excess_space, style)\n                for line in lines:\n                    yield pad\n                    yield from line\n                    yield new_line\n\n        blank_line = (\n            Segment(f\"{' ' * (self.width or options.max_width)}\\n\", style)\n            if self.pad\n            else Segment(\"\\n\")\n        )\n\n        def blank_lines(count: int) -> Iterable[Segment]:\n            if count > 0:\n                for _ in range(count):\n                    yield blank_line\n\n        vertical_height = self.height or options.height\n        iter_segments: Iterable[Segment]\n        if self.vertical and vertical_height is not None:\n            if self.vertical == \"top\":\n                bottom_space = vertical_height - height\n                iter_segments = chain(generate_segments(), blank_lines(bottom_space))\n            elif self.vertical == \"middle\":\n                top_space = (vertical_height - height) // 2\n                bottom_space = vertical_height - top_space - height\n                iter_segments = chain(\n                    blank_lines(top_space),\n                    generate_segments(),\n                    blank_lines(bottom_space),\n                )\n            else:  #  self.vertical == \"bottom\":\n                top_space = vertical_height - height\n                iter_segments = chain(blank_lines(top_space), generate_segments())\n        else:\n            iter_segments = generate_segments()\n        if self.style:\n            style = console.get_style(self.style)\n            iter_segments = Segment.apply_style(iter_segments, style)\n        yield from iter_segments\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n\n\nclass VerticalCenter(JupyterMixin):\n    \"\"\"Vertically aligns a renderable.\n\n    Warn:\n        This class is deprecated and may be removed in a future version. Use Align class with\n        `vertical=\"middle\"`.\n\n    Args:\n        renderable (RenderableType): A renderable object.\n        style (StyleType, optional): An optional style to apply to the background. Defaults to None.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n    ) -> None:\n        self.renderable = renderable\n        self.style = style\n\n    def __repr__(self) -> str:\n        return f\"VerticalCenter({self.renderable!r})\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style) if self.style is not None else None\n        lines = console.render_lines(\n            self.renderable, options.update(height=None), pad=False\n        )\n        width, _height = Segment.get_shape(lines)\n        new_line = Segment.line()\n        height = options.height or options.size.height\n        top_space = (height - len(lines)) // 2\n        bottom_space = height - top_space - len(lines)\n        blank_line = Segment(f\"{' ' * width}\", style)\n\n        def blank_lines(count: int) -> Iterable[Segment]:\n            for _ in range(count):\n                yield blank_line\n                yield new_line\n\n        if top_space > 0:\n            yield from blank_lines(top_space)\n        for line in lines:\n            yield from line\n            yield new_line\n        if bottom_space > 0:\n            yield from blank_lines(bottom_space)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console, Group\n    from pip._vendor.rich.highlighter import ReprHighlighter\n    from pip._vendor.rich.panel import Panel\n\n    highlighter = ReprHighlighter()\n    console = Console()\n\n    panel = Panel(\n        Group(\n            Align.left(highlighter(\"align='left'\")),\n            Align.center(highlighter(\"align='center'\")),\n            Align.right(highlighter(\"align='right'\")),\n        ),\n        width=60,\n        style=\"on dark_blue\",\n        title=\"Align\",\n    )\n\n    console.print(\n        Align.center(panel, vertical=\"middle\", style=\"on red\", height=console.height)\n    )\n"
  },
  {
    "path": "src/pip/_vendor/rich/ansi.py",
    "content": "import re\nimport sys\nfrom contextlib import suppress\nfrom typing import Iterable, NamedTuple, Optional\n\nfrom .color import Color\nfrom .style import Style\nfrom .text import Text\n\nre_ansi = re.compile(\n    r\"\"\"\n(?:\\x1b[0-?])|\n(?:\\x1b\\](.*?)\\x1b\\\\)|\n(?:\\x1b([(@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~]))\n\"\"\",\n    re.VERBOSE,\n)\n\n\nclass _AnsiToken(NamedTuple):\n    \"\"\"Result of ansi tokenized string.\"\"\"\n\n    plain: str = \"\"\n    sgr: Optional[str] = \"\"\n    osc: Optional[str] = \"\"\n\n\ndef _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:\n    \"\"\"Tokenize a string in to plain text and ANSI codes.\n\n    Args:\n        ansi_text (str): A String containing ANSI codes.\n\n    Yields:\n        AnsiToken: A named tuple of (plain, sgr, osc)\n    \"\"\"\n\n    position = 0\n    sgr: Optional[str]\n    osc: Optional[str]\n    for match in re_ansi.finditer(ansi_text):\n        start, end = match.span(0)\n        osc, sgr = match.groups()\n        if start > position:\n            yield _AnsiToken(ansi_text[position:start])\n        if sgr:\n            if sgr == \"(\":\n                position = end + 1\n                continue\n            if sgr.endswith(\"m\"):\n                yield _AnsiToken(\"\", sgr[1:-1], osc)\n        else:\n            yield _AnsiToken(\"\", sgr, osc)\n        position = end\n    if position < len(ansi_text):\n        yield _AnsiToken(ansi_text[position:])\n\n\nSGR_STYLE_MAP = {\n    1: \"bold\",\n    2: \"dim\",\n    3: \"italic\",\n    4: \"underline\",\n    5: \"blink\",\n    6: \"blink2\",\n    7: \"reverse\",\n    8: \"conceal\",\n    9: \"strike\",\n    21: \"underline2\",\n    22: \"not dim not bold\",\n    23: \"not italic\",\n    24: \"not underline\",\n    25: \"not blink\",\n    26: \"not blink2\",\n    27: \"not reverse\",\n    28: \"not conceal\",\n    29: \"not strike\",\n    30: \"color(0)\",\n    31: \"color(1)\",\n    32: \"color(2)\",\n    33: \"color(3)\",\n    34: \"color(4)\",\n    35: \"color(5)\",\n    36: \"color(6)\",\n    37: \"color(7)\",\n    39: \"default\",\n    40: \"on color(0)\",\n    41: \"on color(1)\",\n    42: \"on color(2)\",\n    43: \"on color(3)\",\n    44: \"on color(4)\",\n    45: \"on color(5)\",\n    46: \"on color(6)\",\n    47: \"on color(7)\",\n    49: \"on default\",\n    51: \"frame\",\n    52: \"encircle\",\n    53: \"overline\",\n    54: \"not frame not encircle\",\n    55: \"not overline\",\n    90: \"color(8)\",\n    91: \"color(9)\",\n    92: \"color(10)\",\n    93: \"color(11)\",\n    94: \"color(12)\",\n    95: \"color(13)\",\n    96: \"color(14)\",\n    97: \"color(15)\",\n    100: \"on color(8)\",\n    101: \"on color(9)\",\n    102: \"on color(10)\",\n    103: \"on color(11)\",\n    104: \"on color(12)\",\n    105: \"on color(13)\",\n    106: \"on color(14)\",\n    107: \"on color(15)\",\n}\n\n\nclass AnsiDecoder:\n    \"\"\"Translate ANSI code in to styled Text.\"\"\"\n\n    def __init__(self) -> None:\n        self.style = Style.null()\n\n    def decode(self, terminal_text: str) -> Iterable[Text]:\n        \"\"\"Decode ANSI codes in an iterable of lines.\n\n        Args:\n            lines (Iterable[str]): An iterable of lines of terminal output.\n\n        Yields:\n            Text: Marked up Text.\n        \"\"\"\n        for line in terminal_text.splitlines():\n            yield self.decode_line(line)\n\n    def decode_line(self, line: str) -> Text:\n        \"\"\"Decode a line containing ansi codes.\n\n        Args:\n            line (str): A line of terminal output.\n\n        Returns:\n            Text: A Text instance marked up according to ansi codes.\n        \"\"\"\n        from_ansi = Color.from_ansi\n        from_rgb = Color.from_rgb\n        _Style = Style\n        text = Text()\n        append = text.append\n        line = line.rsplit(\"\\r\", 1)[-1]\n        for plain_text, sgr, osc in _ansi_tokenize(line):\n            if plain_text:\n                append(plain_text, self.style or None)\n            elif osc is not None:\n                if osc.startswith(\"8;\"):\n                    _params, semicolon, link = osc[2:].partition(\";\")\n                    if semicolon:\n                        self.style = self.style.update_link(link or None)\n            elif sgr is not None:\n                # Translate in to semi-colon separated codes\n                # Ignore invalid codes, because we want to be lenient\n                codes = [\n                    min(255, int(_code) if _code else 0)\n                    for _code in sgr.split(\";\")\n                    if _code.isdigit() or _code == \"\"\n                ]\n                iter_codes = iter(codes)\n                for code in iter_codes:\n                    if code == 0:\n                        # reset\n                        self.style = _Style.null()\n                    elif code in SGR_STYLE_MAP:\n                        # styles\n                        self.style += _Style.parse(SGR_STYLE_MAP[code])\n                    elif code == 38:\n                        #  Foreground\n                        with suppress(StopIteration):\n                            color_type = next(iter_codes)\n                            if color_type == 5:\n                                self.style += _Style.from_color(\n                                    from_ansi(next(iter_codes))\n                                )\n                            elif color_type == 2:\n                                self.style += _Style.from_color(\n                                    from_rgb(\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                    )\n                                )\n                    elif code == 48:\n                        # Background\n                        with suppress(StopIteration):\n                            color_type = next(iter_codes)\n                            if color_type == 5:\n                                self.style += _Style.from_color(\n                                    None, from_ansi(next(iter_codes))\n                                )\n                            elif color_type == 2:\n                                self.style += _Style.from_color(\n                                    None,\n                                    from_rgb(\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                    ),\n                                )\n\n        return text\n\n\nif sys.platform != \"win32\" and __name__ == \"__main__\":  # pragma: no cover\n    import io\n    import os\n    import pty\n    import sys\n\n    decoder = AnsiDecoder()\n\n    stdout = io.BytesIO()\n\n    def read(fd: int) -> bytes:\n        data = os.read(fd, 1024)\n        stdout.write(data)\n        return data\n\n    pty.spawn(sys.argv[1:], read)\n\n    from .console import Console\n\n    console = Console(record=True)\n\n    stdout_result = stdout.getvalue().decode(\"utf-8\")\n    print(stdout_result)\n\n    for line in decoder.decode(stdout_result):\n        console.print(line)\n\n    console.save_html(\"stdout.html\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/bar.py",
    "content": "from typing import Optional, Union\n\nfrom .color import Color\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style\n\n# There are left-aligned characters for 1/8 to 7/8, but\n# the right-aligned characters exist only for 1/8 and 4/8.\nBEGIN_BLOCK_ELEMENTS = [\"█\", \"█\", \"█\", \"▐\", \"▐\", \"▐\", \"▕\", \"▕\"]\nEND_BLOCK_ELEMENTS = [\" \", \"▏\", \"▎\", \"▍\", \"▌\", \"▋\", \"▊\", \"▉\"]\nFULL_BLOCK = \"█\"\n\n\nclass Bar(JupyterMixin):\n    \"\"\"Renders a solid block bar.\n\n    Args:\n        size (float): Value for the end of the bar.\n        begin (float): Begin point (between 0 and size, inclusive).\n        end (float): End point (between 0 and size, inclusive).\n        width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.\n        color (Union[Color, str], optional): Color of the bar. Defaults to \"default\".\n        bgcolor (Union[Color, str], optional): Color of bar background. Defaults to \"default\".\n    \"\"\"\n\n    def __init__(\n        self,\n        size: float,\n        begin: float,\n        end: float,\n        *,\n        width: Optional[int] = None,\n        color: Union[Color, str] = \"default\",\n        bgcolor: Union[Color, str] = \"default\",\n    ):\n        self.size = size\n        self.begin = max(begin, 0)\n        self.end = min(end, size)\n        self.width = width\n        self.style = Style(color=color, bgcolor=bgcolor)\n\n    def __repr__(self) -> str:\n        return f\"Bar({self.size}, {self.begin}, {self.end})\"\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = min(\n            self.width if self.width is not None else options.max_width,\n            options.max_width,\n        )\n\n        if self.begin >= self.end:\n            yield Segment(\" \" * width, self.style)\n            yield Segment.line()\n            return\n\n        prefix_complete_eights = int(width * 8 * self.begin / self.size)\n        prefix_bar_count = prefix_complete_eights // 8\n        prefix_eights_count = prefix_complete_eights % 8\n\n        body_complete_eights = int(width * 8 * self.end / self.size)\n        body_bar_count = body_complete_eights // 8\n        body_eights_count = body_complete_eights % 8\n\n        # When start and end fall into the same cell, we ideally should render\n        # a symbol that's \"center-aligned\", but there is no good symbol in Unicode.\n        # In this case, we fall back to right-aligned block symbol for simplicity.\n\n        prefix = \" \" * prefix_bar_count\n        if prefix_eights_count:\n            prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count]\n\n        body = FULL_BLOCK * body_bar_count\n        if body_eights_count:\n            body += END_BLOCK_ELEMENTS[body_eights_count]\n\n        suffix = \" \" * (width - len(body))\n\n        yield Segment(prefix + body[len(prefix) :] + suffix, self.style)\n        yield Segment.line()\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return (\n            Measurement(self.width, self.width)\n            if self.width is not None\n            else Measurement(4, options.max_width)\n        )\n"
  },
  {
    "path": "src/pip/_vendor/rich/box.py",
    "content": "from typing import TYPE_CHECKING, Iterable, List, Literal\n\n\nfrom ._loop import loop_last\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleOptions\n\n\nclass Box:\n    \"\"\"Defines characters to render boxes.\n\n    ┌─┬┐ top\n    │ ││ head\n    ├─┼┤ head_row\n    │ ││ mid\n    ├─┼┤ row\n    ├─┼┤ foot_row\n    │ ││ foot\n    └─┴┘ bottom\n\n    Args:\n        box (str): Characters making up box.\n        ascii (bool, optional): True if this box uses ascii characters only. Default is False.\n    \"\"\"\n\n    def __init__(self, box: str, *, ascii: bool = False) -> None:\n        self._box = box\n        self.ascii = ascii\n        line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines()\n        # top\n        self.top_left, self.top, self.top_divider, self.top_right = iter(line1)\n        # head\n        self.head_left, _, self.head_vertical, self.head_right = iter(line2)\n        # head_row\n        (\n            self.head_row_left,\n            self.head_row_horizontal,\n            self.head_row_cross,\n            self.head_row_right,\n        ) = iter(line3)\n\n        # mid\n        self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4)\n        # row\n        self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5)\n        # foot_row\n        (\n            self.foot_row_left,\n            self.foot_row_horizontal,\n            self.foot_row_cross,\n            self.foot_row_right,\n        ) = iter(line6)\n        # foot\n        self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7)\n        # bottom\n        self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter(\n            line8\n        )\n\n    def __repr__(self) -> str:\n        return \"Box(...)\"\n\n    def __str__(self) -> str:\n        return self._box\n\n    def substitute(self, options: \"ConsoleOptions\", safe: bool = True) -> \"Box\":\n        \"\"\"Substitute this box for another if it won't render due to platform issues.\n\n        Args:\n            options (ConsoleOptions): Console options used in rendering.\n            safe (bool, optional): Substitute this for another Box if there are known problems\n                displaying on the platform (currently only relevant on Windows). Default is True.\n\n        Returns:\n            Box: A different Box or the same Box.\n        \"\"\"\n        box = self\n        if options.legacy_windows and safe:\n            box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)\n        if options.ascii_only and not box.ascii:\n            box = ASCII\n        return box\n\n    def get_plain_headed_box(self) -> \"Box\":\n        \"\"\"If this box uses special characters for the borders of the header, then\n        return the equivalent box that does not.\n\n        Returns:\n            Box: The most similar Box that doesn't use header-specific box characters.\n                If the current Box already satisfies this criterion, then it's returned.\n        \"\"\"\n        return PLAIN_HEADED_SUBSTITUTIONS.get(self, self)\n\n    def get_top(self, widths: Iterable[int]) -> str:\n        \"\"\"Get the top of a simple box.\n\n        Args:\n            widths (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n\n        parts: List[str] = []\n        append = parts.append\n        append(self.top_left)\n        for last, width in loop_last(widths):\n            append(self.top * width)\n            if not last:\n                append(self.top_divider)\n        append(self.top_right)\n        return \"\".join(parts)\n\n    def get_row(\n        self,\n        widths: Iterable[int],\n        level: Literal[\"head\", \"row\", \"foot\", \"mid\"] = \"row\",\n        edge: bool = True,\n    ) -> str:\n        \"\"\"Get the top of a simple box.\n\n        Args:\n            width (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n        if level == \"head\":\n            left = self.head_row_left\n            horizontal = self.head_row_horizontal\n            cross = self.head_row_cross\n            right = self.head_row_right\n        elif level == \"row\":\n            left = self.row_left\n            horizontal = self.row_horizontal\n            cross = self.row_cross\n            right = self.row_right\n        elif level == \"mid\":\n            left = self.mid_left\n            horizontal = \" \"\n            cross = self.mid_vertical\n            right = self.mid_right\n        elif level == \"foot\":\n            left = self.foot_row_left\n            horizontal = self.foot_row_horizontal\n            cross = self.foot_row_cross\n            right = self.foot_row_right\n        else:\n            raise ValueError(\"level must be 'head', 'row' or 'foot'\")\n\n        parts: List[str] = []\n        append = parts.append\n        if edge:\n            append(left)\n        for last, width in loop_last(widths):\n            append(horizontal * width)\n            if not last:\n                append(cross)\n        if edge:\n            append(right)\n        return \"\".join(parts)\n\n    def get_bottom(self, widths: Iterable[int]) -> str:\n        \"\"\"Get the bottom of a simple box.\n\n        Args:\n            widths (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n\n        parts: List[str] = []\n        append = parts.append\n        append(self.bottom_left)\n        for last, width in loop_last(widths):\n            append(self.bottom * width)\n            if not last:\n                append(self.bottom_divider)\n        append(self.bottom_right)\n        return \"\".join(parts)\n\n\n# fmt: off\nASCII: Box = Box(\n    \"+--+\\n\"\n    \"| ||\\n\"\n    \"|-+|\\n\"\n    \"| ||\\n\"\n    \"|-+|\\n\"\n    \"|-+|\\n\"\n    \"| ||\\n\"\n    \"+--+\\n\",\n    ascii=True,\n)\n\nASCII2: Box = Box(\n    \"+-++\\n\"\n    \"| ||\\n\"\n    \"+-++\\n\"\n    \"| ||\\n\"\n    \"+-++\\n\"\n    \"+-++\\n\"\n    \"| ||\\n\"\n    \"+-++\\n\",\n    ascii=True,\n)\n\nASCII_DOUBLE_HEAD: Box = Box(\n    \"+-++\\n\"\n    \"| ||\\n\"\n    \"+=++\\n\"\n    \"| ||\\n\"\n    \"+-++\\n\"\n    \"+-++\\n\"\n    \"| ||\\n\"\n    \"+-++\\n\",\n    ascii=True,\n)\n\nSQUARE: Box = Box(\n    \"┌─┬┐\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"└─┴┘\\n\"\n)\n\nSQUARE_DOUBLE_HEAD: Box = Box(\n    \"┌─┬┐\\n\"\n    \"│ ││\\n\"\n    \"╞═╪╡\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"└─┴┘\\n\"\n)\n\nMINIMAL: Box = Box(\n    \"  ╷ \\n\"\n    \"  │ \\n\"\n    \"╶─┼╴\\n\"\n    \"  │ \\n\"\n    \"╶─┼╴\\n\"\n    \"╶─┼╴\\n\"\n    \"  │ \\n\"\n    \"  ╵ \\n\"\n)\n\n\nMINIMAL_HEAVY_HEAD: Box = Box(\n    \"  ╷ \\n\"\n    \"  │ \\n\"\n    \"╺━┿╸\\n\"\n    \"  │ \\n\"\n    \"╶─┼╴\\n\"\n    \"╶─┼╴\\n\"\n    \"  │ \\n\"\n    \"  ╵ \\n\"\n)\n\nMINIMAL_DOUBLE_HEAD: Box = Box(\n    \"  ╷ \\n\"\n    \"  │ \\n\"\n    \" ═╪ \\n\"\n    \"  │ \\n\"\n    \" ─┼ \\n\"\n    \" ─┼ \\n\"\n    \"  │ \\n\"\n    \"  ╵ \\n\"\n)\n\n\nSIMPLE: Box = Box(\n    \"    \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n    \"    \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n    \"    \\n\"\n    \"    \\n\"\n)\n\nSIMPLE_HEAD: Box = Box(\n    \"    \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n    \"    \\n\"\n    \"    \\n\"\n    \"    \\n\"\n    \"    \\n\"\n    \"    \\n\"\n)\n\n\nSIMPLE_HEAVY: Box = Box(\n    \"    \\n\"\n    \"    \\n\"\n    \" ━━ \\n\"\n    \"    \\n\"\n    \"    \\n\"\n    \" ━━ \\n\"\n    \"    \\n\"\n    \"    \\n\"\n)\n\n\nHORIZONTALS: Box = Box(\n    \" ── \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n    \" ── \\n\"\n    \"    \\n\"\n    \" ── \\n\"\n)\n\nROUNDED: Box = Box(\n    \"╭─┬╮\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"╰─┴╯\\n\"\n)\n\nHEAVY: Box = Box(\n    \"┏━┳┓\\n\"\n    \"┃ ┃┃\\n\"\n    \"┣━╋┫\\n\"\n    \"┃ ┃┃\\n\"\n    \"┣━╋┫\\n\"\n    \"┣━╋┫\\n\"\n    \"┃ ┃┃\\n\"\n    \"┗━┻┛\\n\"\n)\n\nHEAVY_EDGE: Box = Box(\n    \"┏━┯┓\\n\"\n    \"┃ │┃\\n\"\n    \"┠─┼┨\\n\"\n    \"┃ │┃\\n\"\n    \"┠─┼┨\\n\"\n    \"┠─┼┨\\n\"\n    \"┃ │┃\\n\"\n    \"┗━┷┛\\n\"\n)\n\nHEAVY_HEAD: Box = Box(\n    \"┏━┳┓\\n\"\n    \"┃ ┃┃\\n\"\n    \"┡━╇┩\\n\"\n    \"│ ││\\n\"\n    \"├─┼┤\\n\"\n    \"├─┼┤\\n\"\n    \"│ ││\\n\"\n    \"└─┴┘\\n\"\n)\n\nDOUBLE: Box = Box(\n    \"╔═╦╗\\n\"\n    \"║ ║║\\n\"\n    \"╠═╬╣\\n\"\n    \"║ ║║\\n\"\n    \"╠═╬╣\\n\"\n    \"╠═╬╣\\n\"\n    \"║ ║║\\n\"\n    \"╚═╩╝\\n\"\n)\n\nDOUBLE_EDGE: Box = Box(\n    \"╔═╤╗\\n\"\n    \"║ │║\\n\"\n    \"╟─┼╢\\n\"\n    \"║ │║\\n\"\n    \"╟─┼╢\\n\"\n    \"╟─┼╢\\n\"\n    \"║ │║\\n\"\n    \"╚═╧╝\\n\"\n)\n\nMARKDOWN: Box = Box(\n    \"    \\n\"\n    \"| ||\\n\"\n    \"|-||\\n\"\n    \"| ||\\n\"\n    \"|-||\\n\"\n    \"|-||\\n\"\n    \"| ||\\n\"\n    \"    \\n\",\n    ascii=True,\n)\n# fmt: on\n\n# Map Boxes that don't render with raster fonts on to equivalent that do\nLEGACY_WINDOWS_SUBSTITUTIONS = {\n    ROUNDED: SQUARE,\n    MINIMAL_HEAVY_HEAD: MINIMAL,\n    SIMPLE_HEAVY: SIMPLE,\n    HEAVY: SQUARE,\n    HEAVY_EDGE: SQUARE,\n    HEAVY_HEAD: SQUARE,\n}\n\n# Map headed boxes to their headerless equivalents\nPLAIN_HEADED_SUBSTITUTIONS = {\n    HEAVY_HEAD: SQUARE,\n    SQUARE_DOUBLE_HEAD: SQUARE,\n    MINIMAL_DOUBLE_HEAD: MINIMAL,\n    MINIMAL_HEAVY_HEAD: MINIMAL,\n    ASCII_DOUBLE_HEAD: ASCII2,\n}\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.columns import Columns\n    from pip._vendor.rich.panel import Panel\n\n    from . import box as box\n    from .console import Console\n    from .table import Table\n    from .text import Text\n\n    console = Console(record=True)\n\n    BOXES = [\n        \"ASCII\",\n        \"ASCII2\",\n        \"ASCII_DOUBLE_HEAD\",\n        \"SQUARE\",\n        \"SQUARE_DOUBLE_HEAD\",\n        \"MINIMAL\",\n        \"MINIMAL_HEAVY_HEAD\",\n        \"MINIMAL_DOUBLE_HEAD\",\n        \"SIMPLE\",\n        \"SIMPLE_HEAD\",\n        \"SIMPLE_HEAVY\",\n        \"HORIZONTALS\",\n        \"ROUNDED\",\n        \"HEAVY\",\n        \"HEAVY_EDGE\",\n        \"HEAVY_HEAD\",\n        \"DOUBLE\",\n        \"DOUBLE_EDGE\",\n        \"MARKDOWN\",\n    ]\n\n    console.print(Panel(\"[bold green]Box Constants\", style=\"green\"), justify=\"center\")\n    console.print()\n\n    columns = Columns(expand=True, padding=2)\n    for box_name in sorted(BOXES):\n        table = Table(\n            show_footer=True, style=\"dim\", border_style=\"not dim\", expand=True\n        )\n        table.add_column(\"Header 1\", \"Footer 1\")\n        table.add_column(\"Header 2\", \"Footer 2\")\n        table.add_row(\"Cell\", \"Cell\")\n        table.add_row(\"Cell\", \"Cell\")\n        table.box = getattr(box, box_name)\n        table.title = Text(f\"box.{box_name}\", style=\"magenta\")\n        columns.add_renderable(table)\n    console.print(columns)\n\n    # console.save_svg(\"box.svg\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/cells.py",
    "content": "from __future__ import annotations\n\nfrom functools import lru_cache\nfrom typing import Callable\n\nfrom ._cell_widths import CELL_WIDTHS\n\n# Ranges of unicode ordinals that produce a 1-cell wide character\n# This is non-exhaustive, but covers most common Western characters\n_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [\n    (0x20, 0x7E),  # Latin (excluding non-printable)\n    (0xA0, 0xAC),\n    (0xAE, 0x002FF),\n    (0x00370, 0x00482),  # Greek / Cyrillic\n    (0x02500, 0x025FC),  # Box drawing, box elements, geometric shapes\n    (0x02800, 0x028FF),  # Braille\n]\n\n# A set of characters that are a single cell wide\n_SINGLE_CELLS = frozenset(\n    [\n        character\n        for _start, _end in _SINGLE_CELL_UNICODE_RANGES\n        for character in map(chr, range(_start, _end + 1))\n    ]\n)\n\n# When called with a string this will return True if all\n# characters are single-cell, otherwise False\n_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset\n\n\n@lru_cache(4096)\ndef cached_cell_len(text: str) -> int:\n    \"\"\"Get the number of cells required to display text.\n\n    This method always caches, which may use up a lot of memory. It is recommended to use\n    `cell_len` over this method.\n\n    Args:\n        text (str): Text to display.\n\n    Returns:\n        int: Get the number of cells required to display text.\n    \"\"\"\n    if _is_single_cell_widths(text):\n        return len(text)\n    return sum(map(get_character_cell_size, text))\n\n\ndef cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int:\n    \"\"\"Get the number of cells required to display text.\n\n    Args:\n        text (str): Text to display.\n\n    Returns:\n        int: Get the number of cells required to display text.\n    \"\"\"\n    if len(text) < 512:\n        return _cell_len(text)\n    if _is_single_cell_widths(text):\n        return len(text)\n    return sum(map(get_character_cell_size, text))\n\n\n@lru_cache(maxsize=4096)\ndef get_character_cell_size(character: str) -> int:\n    \"\"\"Get the cell size of a character.\n\n    Args:\n        character (str): A single character.\n\n    Returns:\n        int: Number of cells (0, 1 or 2) occupied by that character.\n    \"\"\"\n    codepoint = ord(character)\n    _table = CELL_WIDTHS\n    lower_bound = 0\n    upper_bound = len(_table) - 1\n    index = (lower_bound + upper_bound) // 2\n    while True:\n        start, end, width = _table[index]\n        if codepoint < start:\n            upper_bound = index - 1\n        elif codepoint > end:\n            lower_bound = index + 1\n        else:\n            return 0 if width == -1 else width\n        if upper_bound < lower_bound:\n            break\n        index = (lower_bound + upper_bound) // 2\n    return 1\n\n\ndef set_cell_size(text: str, total: int) -> str:\n    \"\"\"Set the length of a string to fit within given number of cells.\"\"\"\n\n    if _is_single_cell_widths(text):\n        size = len(text)\n        if size < total:\n            return text + \" \" * (total - size)\n        return text[:total]\n\n    if total <= 0:\n        return \"\"\n    cell_size = cell_len(text)\n    if cell_size == total:\n        return text\n    if cell_size < total:\n        return text + \" \" * (total - cell_size)\n\n    start = 0\n    end = len(text)\n\n    # Binary search until we find the right size\n    while True:\n        pos = (start + end) // 2\n        before = text[: pos + 1]\n        before_len = cell_len(before)\n        if before_len == total + 1 and cell_len(before[-1]) == 2:\n            return before[:-1] + \" \"\n        if before_len == total:\n            return before\n        if before_len > total:\n            end = pos\n        else:\n            start = pos\n\n\ndef chop_cells(\n    text: str,\n    width: int,\n) -> list[str]:\n    \"\"\"Split text into lines such that each line fits within the available (cell) width.\n\n    Args:\n        text: The text to fold such that it fits in the given width.\n        width: The width available (number of cells).\n\n    Returns:\n        A list of strings such that each string in the list has cell width\n        less than or equal to the available width.\n    \"\"\"\n    _get_character_cell_size = get_character_cell_size\n    lines: list[list[str]] = [[]]\n\n    append_new_line = lines.append\n    append_to_last_line = lines[-1].append\n\n    total_width = 0\n\n    for character in text:\n        cell_width = _get_character_cell_size(character)\n        char_doesnt_fit = total_width + cell_width > width\n\n        if char_doesnt_fit:\n            append_new_line([character])\n            append_to_last_line = lines[-1].append\n            total_width = cell_width\n        else:\n            append_to_last_line(character)\n            total_width += cell_width\n\n    return [\"\".join(line) for line in lines]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    print(get_character_cell_size(\"😽\"))\n    for line in chop_cells(\"\"\"这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑。\"\"\", 8):\n        print(line)\n    for n in range(80, 1, -1):\n        print(set_cell_size(\"\"\"这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑。\"\"\", n) + \"|\")\n        print(\"x\" * n)\n"
  },
  {
    "path": "src/pip/_vendor/rich/color.py",
    "content": "import re\nimport sys\nfrom colorsys import rgb_to_hls\nfrom enum import IntEnum\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, NamedTuple, Optional, Tuple\n\nfrom ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE\nfrom .color_triplet import ColorTriplet\nfrom .repr import Result, rich_repr\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME\n\nif TYPE_CHECKING:  # pragma: no cover\n    from .terminal_theme import TerminalTheme\n    from .text import Text\n\n\nWINDOWS = sys.platform == \"win32\"\n\n\nclass ColorSystem(IntEnum):\n    \"\"\"One of the 3 color system supported by terminals.\"\"\"\n\n    STANDARD = 1\n    EIGHT_BIT = 2\n    TRUECOLOR = 3\n    WINDOWS = 4\n\n    def __repr__(self) -> str:\n        return f\"ColorSystem.{self.name}\"\n\n    def __str__(self) -> str:\n        return repr(self)\n\n\nclass ColorType(IntEnum):\n    \"\"\"Type of color stored in Color class.\"\"\"\n\n    DEFAULT = 0\n    STANDARD = 1\n    EIGHT_BIT = 2\n    TRUECOLOR = 3\n    WINDOWS = 4\n\n    def __repr__(self) -> str:\n        return f\"ColorType.{self.name}\"\n\n\nANSI_COLOR_NAMES = {\n    \"black\": 0,\n    \"red\": 1,\n    \"green\": 2,\n    \"yellow\": 3,\n    \"blue\": 4,\n    \"magenta\": 5,\n    \"cyan\": 6,\n    \"white\": 7,\n    \"bright_black\": 8,\n    \"bright_red\": 9,\n    \"bright_green\": 10,\n    \"bright_yellow\": 11,\n    \"bright_blue\": 12,\n    \"bright_magenta\": 13,\n    \"bright_cyan\": 14,\n    \"bright_white\": 15,\n    \"grey0\": 16,\n    \"gray0\": 16,\n    \"navy_blue\": 17,\n    \"dark_blue\": 18,\n    \"blue3\": 20,\n    \"blue1\": 21,\n    \"dark_green\": 22,\n    \"deep_sky_blue4\": 25,\n    \"dodger_blue3\": 26,\n    \"dodger_blue2\": 27,\n    \"green4\": 28,\n    \"spring_green4\": 29,\n    \"turquoise4\": 30,\n    \"deep_sky_blue3\": 32,\n    \"dodger_blue1\": 33,\n    \"green3\": 40,\n    \"spring_green3\": 41,\n    \"dark_cyan\": 36,\n    \"light_sea_green\": 37,\n    \"deep_sky_blue2\": 38,\n    \"deep_sky_blue1\": 39,\n    \"spring_green2\": 47,\n    \"cyan3\": 43,\n    \"dark_turquoise\": 44,\n    \"turquoise2\": 45,\n    \"green1\": 46,\n    \"spring_green1\": 48,\n    \"medium_spring_green\": 49,\n    \"cyan2\": 50,\n    \"cyan1\": 51,\n    \"dark_red\": 88,\n    \"deep_pink4\": 125,\n    \"purple4\": 55,\n    \"purple3\": 56,\n    \"blue_violet\": 57,\n    \"orange4\": 94,\n    \"grey37\": 59,\n    \"gray37\": 59,\n    \"medium_purple4\": 60,\n    \"slate_blue3\": 62,\n    \"royal_blue1\": 63,\n    \"chartreuse4\": 64,\n    \"dark_sea_green4\": 71,\n    \"pale_turquoise4\": 66,\n    \"steel_blue\": 67,\n    \"steel_blue3\": 68,\n    \"cornflower_blue\": 69,\n    \"chartreuse3\": 76,\n    \"cadet_blue\": 73,\n    \"sky_blue3\": 74,\n    \"steel_blue1\": 81,\n    \"pale_green3\": 114,\n    \"sea_green3\": 78,\n    \"aquamarine3\": 79,\n    \"medium_turquoise\": 80,\n    \"chartreuse2\": 112,\n    \"sea_green2\": 83,\n    \"sea_green1\": 85,\n    \"aquamarine1\": 122,\n    \"dark_slate_gray2\": 87,\n    \"dark_magenta\": 91,\n    \"dark_violet\": 128,\n    \"purple\": 129,\n    \"light_pink4\": 95,\n    \"plum4\": 96,\n    \"medium_purple3\": 98,\n    \"slate_blue1\": 99,\n    \"yellow4\": 106,\n    \"wheat4\": 101,\n    \"grey53\": 102,\n    \"gray53\": 102,\n    \"light_slate_grey\": 103,\n    \"light_slate_gray\": 103,\n    \"medium_purple\": 104,\n    \"light_slate_blue\": 105,\n    \"dark_olive_green3\": 149,\n    \"dark_sea_green\": 108,\n    \"light_sky_blue3\": 110,\n    \"sky_blue2\": 111,\n    \"dark_sea_green3\": 150,\n    \"dark_slate_gray3\": 116,\n    \"sky_blue1\": 117,\n    \"chartreuse1\": 118,\n    \"light_green\": 120,\n    \"pale_green1\": 156,\n    \"dark_slate_gray1\": 123,\n    \"red3\": 160,\n    \"medium_violet_red\": 126,\n    \"magenta3\": 164,\n    \"dark_orange3\": 166,\n    \"indian_red\": 167,\n    \"hot_pink3\": 168,\n    \"medium_orchid3\": 133,\n    \"medium_orchid\": 134,\n    \"medium_purple2\": 140,\n    \"dark_goldenrod\": 136,\n    \"light_salmon3\": 173,\n    \"rosy_brown\": 138,\n    \"grey63\": 139,\n    \"gray63\": 139,\n    \"medium_purple1\": 141,\n    \"gold3\": 178,\n    \"dark_khaki\": 143,\n    \"navajo_white3\": 144,\n    \"grey69\": 145,\n    \"gray69\": 145,\n    \"light_steel_blue3\": 146,\n    \"light_steel_blue\": 147,\n    \"yellow3\": 184,\n    \"dark_sea_green2\": 157,\n    \"light_cyan3\": 152,\n    \"light_sky_blue1\": 153,\n    \"green_yellow\": 154,\n    \"dark_olive_green2\": 155,\n    \"dark_sea_green1\": 193,\n    \"pale_turquoise1\": 159,\n    \"deep_pink3\": 162,\n    \"magenta2\": 200,\n    \"hot_pink2\": 169,\n    \"orchid\": 170,\n    \"medium_orchid1\": 207,\n    \"orange3\": 172,\n    \"light_pink3\": 174,\n    \"pink3\": 175,\n    \"plum3\": 176,\n    \"violet\": 177,\n    \"light_goldenrod3\": 179,\n    \"tan\": 180,\n    \"misty_rose3\": 181,\n    \"thistle3\": 182,\n    \"plum2\": 183,\n    \"khaki3\": 185,\n    \"light_goldenrod2\": 222,\n    \"light_yellow3\": 187,\n    \"grey84\": 188,\n    \"gray84\": 188,\n    \"light_steel_blue1\": 189,\n    \"yellow2\": 190,\n    \"dark_olive_green1\": 192,\n    \"honeydew2\": 194,\n    \"light_cyan1\": 195,\n    \"red1\": 196,\n    \"deep_pink2\": 197,\n    \"deep_pink1\": 199,\n    \"magenta1\": 201,\n    \"orange_red1\": 202,\n    \"indian_red1\": 204,\n    \"hot_pink\": 206,\n    \"dark_orange\": 208,\n    \"salmon1\": 209,\n    \"light_coral\": 210,\n    \"pale_violet_red1\": 211,\n    \"orchid2\": 212,\n    \"orchid1\": 213,\n    \"orange1\": 214,\n    \"sandy_brown\": 215,\n    \"light_salmon1\": 216,\n    \"light_pink1\": 217,\n    \"pink1\": 218,\n    \"plum1\": 219,\n    \"gold1\": 220,\n    \"navajo_white1\": 223,\n    \"misty_rose1\": 224,\n    \"thistle1\": 225,\n    \"yellow1\": 226,\n    \"light_goldenrod1\": 227,\n    \"khaki1\": 228,\n    \"wheat1\": 229,\n    \"cornsilk1\": 230,\n    \"grey100\": 231,\n    \"gray100\": 231,\n    \"grey3\": 232,\n    \"gray3\": 232,\n    \"grey7\": 233,\n    \"gray7\": 233,\n    \"grey11\": 234,\n    \"gray11\": 234,\n    \"grey15\": 235,\n    \"gray15\": 235,\n    \"grey19\": 236,\n    \"gray19\": 236,\n    \"grey23\": 237,\n    \"gray23\": 237,\n    \"grey27\": 238,\n    \"gray27\": 238,\n    \"grey30\": 239,\n    \"gray30\": 239,\n    \"grey35\": 240,\n    \"gray35\": 240,\n    \"grey39\": 241,\n    \"gray39\": 241,\n    \"grey42\": 242,\n    \"gray42\": 242,\n    \"grey46\": 243,\n    \"gray46\": 243,\n    \"grey50\": 244,\n    \"gray50\": 244,\n    \"grey54\": 245,\n    \"gray54\": 245,\n    \"grey58\": 246,\n    \"gray58\": 246,\n    \"grey62\": 247,\n    \"gray62\": 247,\n    \"grey66\": 248,\n    \"gray66\": 248,\n    \"grey70\": 249,\n    \"gray70\": 249,\n    \"grey74\": 250,\n    \"gray74\": 250,\n    \"grey78\": 251,\n    \"gray78\": 251,\n    \"grey82\": 252,\n    \"gray82\": 252,\n    \"grey85\": 253,\n    \"gray85\": 253,\n    \"grey89\": 254,\n    \"gray89\": 254,\n    \"grey93\": 255,\n    \"gray93\": 255,\n}\n\n\nclass ColorParseError(Exception):\n    \"\"\"The color could not be parsed.\"\"\"\n\n\nRE_COLOR = re.compile(\n    r\"\"\"^\n\\#([0-9a-f]{6})$|\ncolor\\(([0-9]{1,3})\\)$|\nrgb\\(([\\d\\s,]+)\\)$\n\"\"\",\n    re.VERBOSE,\n)\n\n\n@rich_repr\nclass Color(NamedTuple):\n    \"\"\"Terminal color definition.\"\"\"\n\n    name: str\n    \"\"\"The name of the color (typically the input to Color.parse).\"\"\"\n    type: ColorType\n    \"\"\"The type of the color.\"\"\"\n    number: Optional[int] = None\n    \"\"\"The color number, if a standard color, or None.\"\"\"\n    triplet: Optional[ColorTriplet] = None\n    \"\"\"A triplet of color components, if an RGB color.\"\"\"\n\n    def __rich__(self) -> \"Text\":\n        \"\"\"Displays the actual color if Rich printed.\"\"\"\n        from .style import Style\n        from .text import Text\n\n        return Text.assemble(\n            f\"<color {self.name!r} ({self.type.name.lower()})\",\n            (\"⬤\", Style(color=self)),\n            \" >\",\n        )\n\n    def __rich_repr__(self) -> Result:\n        yield self.name\n        yield self.type\n        yield \"number\", self.number, None\n        yield \"triplet\", self.triplet, None\n\n    @property\n    def system(self) -> ColorSystem:\n        \"\"\"Get the native color system for this color.\"\"\"\n        if self.type == ColorType.DEFAULT:\n            return ColorSystem.STANDARD\n        return ColorSystem(int(self.type))\n\n    @property\n    def is_system_defined(self) -> bool:\n        \"\"\"Check if the color is ultimately defined by the system.\"\"\"\n        return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR)\n\n    @property\n    def is_default(self) -> bool:\n        \"\"\"Check if the color is a default color.\"\"\"\n        return self.type == ColorType.DEFAULT\n\n    def get_truecolor(\n        self, theme: Optional[\"TerminalTheme\"] = None, foreground: bool = True\n    ) -> ColorTriplet:\n        \"\"\"Get an equivalent color triplet for this color.\n\n        Args:\n            theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None.\n            foreground (bool, optional): True for a foreground color, or False for background. Defaults to True.\n\n        Returns:\n            ColorTriplet: A color triplet containing RGB components.\n        \"\"\"\n\n        if theme is None:\n            theme = DEFAULT_TERMINAL_THEME\n        if self.type == ColorType.TRUECOLOR:\n            assert self.triplet is not None\n            return self.triplet\n        elif self.type == ColorType.EIGHT_BIT:\n            assert self.number is not None\n            return EIGHT_BIT_PALETTE[self.number]\n        elif self.type == ColorType.STANDARD:\n            assert self.number is not None\n            return theme.ansi_colors[self.number]\n        elif self.type == ColorType.WINDOWS:\n            assert self.number is not None\n            return WINDOWS_PALETTE[self.number]\n        else:  # self.type == ColorType.DEFAULT:\n            assert self.number is None\n            return theme.foreground_color if foreground else theme.background_color\n\n    @classmethod\n    def from_ansi(cls, number: int) -> \"Color\":\n        \"\"\"Create a Color number from it's 8-bit ansi number.\n\n        Args:\n            number (int): A number between 0-255 inclusive.\n\n        Returns:\n            Color: A new Color instance.\n        \"\"\"\n        return cls(\n            name=f\"color({number})\",\n            type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n            number=number,\n        )\n\n    @classmethod\n    def from_triplet(cls, triplet: \"ColorTriplet\") -> \"Color\":\n        \"\"\"Create a truecolor RGB color from a triplet of values.\n\n        Args:\n            triplet (ColorTriplet): A color triplet containing red, green and blue components.\n\n        Returns:\n            Color: A new color object.\n        \"\"\"\n        return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet)\n\n    @classmethod\n    def from_rgb(cls, red: float, green: float, blue: float) -> \"Color\":\n        \"\"\"Create a truecolor from three color components in the range(0->255).\n\n        Args:\n            red (float): Red component in range 0-255.\n            green (float): Green component in range 0-255.\n            blue (float): Blue component in range 0-255.\n\n        Returns:\n            Color: A new color object.\n        \"\"\"\n        return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue)))\n\n    @classmethod\n    def default(cls) -> \"Color\":\n        \"\"\"Get a Color instance representing the default color.\n\n        Returns:\n            Color: Default color.\n        \"\"\"\n        return cls(name=\"default\", type=ColorType.DEFAULT)\n\n    @classmethod\n    @lru_cache(maxsize=1024)\n    def parse(cls, color: str) -> \"Color\":\n        \"\"\"Parse a color definition.\"\"\"\n        original_color = color\n        color = color.lower().strip()\n\n        if color == \"default\":\n            return cls(color, type=ColorType.DEFAULT)\n\n        color_number = ANSI_COLOR_NAMES.get(color)\n        if color_number is not None:\n            return cls(\n                color,\n                type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),\n                number=color_number,\n            )\n\n        color_match = RE_COLOR.match(color)\n        if color_match is None:\n            raise ColorParseError(f\"{original_color!r} is not a valid color\")\n\n        color_24, color_8, color_rgb = color_match.groups()\n        if color_24:\n            triplet = ColorTriplet(\n                int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)\n            )\n            return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n        elif color_8:\n            number = int(color_8)\n            if number > 255:\n                raise ColorParseError(f\"color number must be <= 255 in {color!r}\")\n            return cls(\n                color,\n                type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n                number=number,\n            )\n\n        else:  #  color_rgb:\n            components = color_rgb.split(\",\")\n            if len(components) != 3:\n                raise ColorParseError(\n                    f\"expected three components in {original_color!r}\"\n                )\n            red, green, blue = components\n            triplet = ColorTriplet(int(red), int(green), int(blue))\n            if not all(component <= 255 for component in triplet):\n                raise ColorParseError(\n                    f\"color components must be <= 255 in {original_color!r}\"\n                )\n            return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n    @lru_cache(maxsize=1024)\n    def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]:\n        \"\"\"Get the ANSI escape codes for this color.\"\"\"\n        _type = self.type\n        if _type == ColorType.DEFAULT:\n            return (\"39\" if foreground else \"49\",)\n\n        elif _type == ColorType.WINDOWS:\n            number = self.number\n            assert number is not None\n            fore, back = (30, 40) if number < 8 else (82, 92)\n            return (str(fore + number if foreground else back + number),)\n\n        elif _type == ColorType.STANDARD:\n            number = self.number\n            assert number is not None\n            fore, back = (30, 40) if number < 8 else (82, 92)\n            return (str(fore + number if foreground else back + number),)\n\n        elif _type == ColorType.EIGHT_BIT:\n            assert self.number is not None\n            return (\"38\" if foreground else \"48\", \"5\", str(self.number))\n\n        else:  # self.standard == ColorStandard.TRUECOLOR:\n            assert self.triplet is not None\n            red, green, blue = self.triplet\n            return (\"38\" if foreground else \"48\", \"2\", str(red), str(green), str(blue))\n\n    @lru_cache(maxsize=1024)\n    def downgrade(self, system: ColorSystem) -> \"Color\":\n        \"\"\"Downgrade a color system to a system with fewer colors.\"\"\"\n\n        if self.type in (ColorType.DEFAULT, system):\n            return self\n        # Convert to 8-bit color from truecolor color\n        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:\n            assert self.triplet is not None\n            _h, l, s = rgb_to_hls(*self.triplet.normalized)\n            # If saturation is under 15% assume it is grayscale\n            if s < 0.15:\n                gray = round(l * 25.0)\n                if gray == 0:\n                    color_number = 16\n                elif gray == 25:\n                    color_number = 231\n                else:\n                    color_number = 231 + gray\n                return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n            red, green, blue = self.triplet\n            six_red = red / 95 if red < 95 else 1 + (red - 95) / 40\n            six_green = green / 95 if green < 95 else 1 + (green - 95) / 40\n            six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40\n\n            color_number = (\n                16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue)\n            )\n            return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n        # Convert to standard from truecolor or 8-bit\n        elif system == ColorSystem.STANDARD:\n            if self.system == ColorSystem.TRUECOLOR:\n                assert self.triplet is not None\n                triplet = self.triplet\n            else:  # self.system == ColorSystem.EIGHT_BIT\n                assert self.number is not None\n                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n            color_number = STANDARD_PALETTE.match(triplet)\n            return Color(self.name, ColorType.STANDARD, number=color_number)\n\n        elif system == ColorSystem.WINDOWS:\n            if self.system == ColorSystem.TRUECOLOR:\n                assert self.triplet is not None\n                triplet = self.triplet\n            else:  # self.system == ColorSystem.EIGHT_BIT\n                assert self.number is not None\n                if self.number < 16:\n                    return Color(self.name, ColorType.WINDOWS, number=self.number)\n                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n            color_number = WINDOWS_PALETTE.match(triplet)\n            return Color(self.name, ColorType.WINDOWS, number=color_number)\n\n        return self\n\n\ndef parse_rgb_hex(hex_color: str) -> ColorTriplet:\n    \"\"\"Parse six hex characters in to RGB triplet.\"\"\"\n    assert len(hex_color) == 6, \"must be 6 characters\"\n    color = ColorTriplet(\n        int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)\n    )\n    return color\n\n\ndef blend_rgb(\n    color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5\n) -> ColorTriplet:\n    \"\"\"Blend one RGB color in to another.\"\"\"\n    r1, g1, b1 = color1\n    r2, g2, b2 = color2\n    new_color = ColorTriplet(\n        int(r1 + (r2 - r1) * cross_fade),\n        int(g1 + (g2 - g1) * cross_fade),\n        int(b1 + (b2 - b1) * cross_fade),\n    )\n    return new_color\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n    from .table import Table\n    from .text import Text\n\n    console = Console()\n\n    table = Table(show_footer=False, show_edge=True)\n    table.add_column(\"Color\", width=10, overflow=\"ellipsis\")\n    table.add_column(\"Number\", justify=\"right\", style=\"yellow\")\n    table.add_column(\"Name\", style=\"green\")\n    table.add_column(\"Hex\", style=\"blue\")\n    table.add_column(\"RGB\", style=\"magenta\")\n\n    colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items())\n    for color_number, name in colors:\n        if \"grey\" in name:\n            continue\n        color_cell = Text(\" \" * 10, style=f\"on {name}\")\n        if color_number < 16:\n            table.add_row(color_cell, f\"{color_number}\", Text(f'\"{name}\"'))\n        else:\n            color = EIGHT_BIT_PALETTE[color_number]  # type: ignore[has-type]\n            table.add_row(\n                color_cell, str(color_number), Text(f'\"{name}\"'), color.hex, color.rgb\n            )\n\n    console.print(table)\n"
  },
  {
    "path": "src/pip/_vendor/rich/color_triplet.py",
    "content": "from typing import NamedTuple, Tuple\n\n\nclass ColorTriplet(NamedTuple):\n    \"\"\"The red, green, and blue components of a color.\"\"\"\n\n    red: int\n    \"\"\"Red component in 0 to 255 range.\"\"\"\n    green: int\n    \"\"\"Green component in 0 to 255 range.\"\"\"\n    blue: int\n    \"\"\"Blue component in 0 to 255 range.\"\"\"\n\n    @property\n    def hex(self) -> str:\n        \"\"\"get the color triplet in CSS style.\"\"\"\n        red, green, blue = self\n        return f\"#{red:02x}{green:02x}{blue:02x}\"\n\n    @property\n    def rgb(self) -> str:\n        \"\"\"The color in RGB format.\n\n        Returns:\n            str: An rgb color, e.g. ``\"rgb(100,23,255)\"``.\n        \"\"\"\n        red, green, blue = self\n        return f\"rgb({red},{green},{blue})\"\n\n    @property\n    def normalized(self) -> Tuple[float, float, float]:\n        \"\"\"Convert components into floats between 0 and 1.\n\n        Returns:\n            Tuple[float, float, float]: A tuple of three normalized colour components.\n        \"\"\"\n        red, green, blue = self\n        return red / 255.0, green / 255.0, blue / 255.0\n"
  },
  {
    "path": "src/pip/_vendor/rich/columns.py",
    "content": "from collections import defaultdict\nfrom itertools import chain\nfrom operator import itemgetter\nfrom typing import Dict, Iterable, List, Optional, Tuple\n\nfrom .align import Align, AlignMethod\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .constrain import Constrain\nfrom .measure import Measurement\nfrom .padding import Padding, PaddingDimensions\nfrom .table import Table\nfrom .text import TextType\nfrom .jupyter import JupyterMixin\n\n\nclass Columns(JupyterMixin):\n    \"\"\"Display renderables in neat columns.\n\n    Args:\n        renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).\n        width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.\n        padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1).\n        expand (bool, optional): Expand columns to full width. Defaults to False.\n        equal (bool, optional): Arrange in to equal sized columns. Defaults to False.\n        column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False.\n        right_to_left (bool, optional): Start column from right hand side. Defaults to False.\n        align (str, optional): Align value (\"left\", \"right\", or \"center\") or None for default. Defaults to None.\n        title (TextType, optional): Optional title for Columns.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderables: Optional[Iterable[RenderableType]] = None,\n        padding: PaddingDimensions = (0, 1),\n        *,\n        width: Optional[int] = None,\n        expand: bool = False,\n        equal: bool = False,\n        column_first: bool = False,\n        right_to_left: bool = False,\n        align: Optional[AlignMethod] = None,\n        title: Optional[TextType] = None,\n    ) -> None:\n        self.renderables = list(renderables or [])\n        self.width = width\n        self.padding = padding\n        self.expand = expand\n        self.equal = equal\n        self.column_first = column_first\n        self.right_to_left = right_to_left\n        self.align: Optional[AlignMethod] = align\n        self.title = title\n\n    def add_renderable(self, renderable: RenderableType) -> None:\n        \"\"\"Add a renderable to the columns.\n\n        Args:\n            renderable (RenderableType): Any renderable object.\n        \"\"\"\n        self.renderables.append(renderable)\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        render_str = console.render_str\n        renderables = [\n            render_str(renderable) if isinstance(renderable, str) else renderable\n            for renderable in self.renderables\n        ]\n        if not renderables:\n            return\n        _top, right, _bottom, left = Padding.unpack(self.padding)\n        width_padding = max(left, right)\n        max_width = options.max_width\n        widths: Dict[int, int] = defaultdict(int)\n        column_count = len(renderables)\n\n        get_measurement = Measurement.get\n        renderable_widths = [\n            get_measurement(console, options, renderable).maximum\n            for renderable in renderables\n        ]\n        if self.equal:\n            renderable_widths = [max(renderable_widths)] * len(renderable_widths)\n\n        def iter_renderables(\n            column_count: int,\n        ) -> Iterable[Tuple[int, Optional[RenderableType]]]:\n            item_count = len(renderables)\n            if self.column_first:\n                width_renderables = list(zip(renderable_widths, renderables))\n\n                column_lengths: List[int] = [item_count // column_count] * column_count\n                for col_no in range(item_count % column_count):\n                    column_lengths[col_no] += 1\n\n                row_count = (item_count + column_count - 1) // column_count\n                cells = [[-1] * column_count for _ in range(row_count)]\n                row = col = 0\n                for index in range(item_count):\n                    cells[row][col] = index\n                    column_lengths[col] -= 1\n                    if column_lengths[col]:\n                        row += 1\n                    else:\n                        col += 1\n                        row = 0\n                for index in chain.from_iterable(cells):\n                    if index == -1:\n                        break\n                    yield width_renderables[index]\n            else:\n                yield from zip(renderable_widths, renderables)\n            # Pad odd elements with spaces\n            if item_count % column_count:\n                for _ in range(column_count - (item_count % column_count)):\n                    yield 0, None\n\n        table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False)\n        table.expand = self.expand\n        table.title = self.title\n\n        if self.width is not None:\n            column_count = (max_width) // (self.width + width_padding)\n            for _ in range(column_count):\n                table.add_column(width=self.width)\n        else:\n            while column_count > 1:\n                widths.clear()\n                column_no = 0\n                for renderable_width, _ in iter_renderables(column_count):\n                    widths[column_no] = max(widths[column_no], renderable_width)\n                    total_width = sum(widths.values()) + width_padding * (\n                        len(widths) - 1\n                    )\n                    if total_width > max_width:\n                        column_count = len(widths) - 1\n                        break\n                    else:\n                        column_no = (column_no + 1) % column_count\n                else:\n                    break\n\n        get_renderable = itemgetter(1)\n        _renderables = [\n            get_renderable(_renderable)\n            for _renderable in iter_renderables(column_count)\n        ]\n        if self.equal:\n            _renderables = [\n                None\n                if renderable is None\n                else Constrain(renderable, renderable_widths[0])\n                for renderable in _renderables\n            ]\n        if self.align:\n            align = self.align\n            _Align = Align\n            _renderables = [\n                None if renderable is None else _Align(renderable, align)\n                for renderable in _renderables\n            ]\n\n        right_to_left = self.right_to_left\n        add_row = table.add_row\n        for start in range(0, len(_renderables), column_count):\n            row = _renderables[start : start + column_count]\n            if right_to_left:\n                row = row[::-1]\n            add_row(*row)\n        yield table\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import os\n\n    console = Console()\n\n    files = [f\"{i} {s}\" for i, s in enumerate(sorted(os.listdir()))]\n    columns = Columns(files, padding=(0, 1), expand=False, equal=False)\n    console.print(columns)\n    console.rule()\n    columns.column_first = True\n    console.print(columns)\n    columns.right_to_left = True\n    console.rule()\n    console.print(columns)\n"
  },
  {
    "path": "src/pip/_vendor/rich/console.py",
    "content": "import inspect\nimport os\nimport sys\nimport threading\nimport zlib\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom functools import wraps\nfrom getpass import getpass\nfrom html import escape\nfrom inspect import isclass\nfrom itertools import islice\nfrom math import ceil\nfrom time import monotonic\nfrom types import FrameType, ModuleType, TracebackType\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Literal,\n    Mapping,\n    NamedTuple,\n    Optional,\n    Protocol,\n    TextIO,\n    Tuple,\n    Type,\n    Union,\n    cast,\n    runtime_checkable,\n)\n\nfrom pip._vendor.rich._null_file import NULL_FILE\n\nfrom . import errors, themes\nfrom ._emoji_replace import _emoji_replace\nfrom ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT\nfrom ._fileno import get_fileno\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .align import Align, AlignMethod\nfrom .color import ColorSystem, blend_rgb\nfrom .control import Control\nfrom .emoji import EmojiVariant\nfrom .highlighter import NullHighlighter, ReprHighlighter\nfrom .markup import render as render_markup\nfrom .measure import Measurement, measure_renderables\nfrom .pager import Pager, SystemPager\nfrom .pretty import Pretty, is_expandable\nfrom .protocol import rich_cast\nfrom .region import Region\nfrom .scope import render_scope\nfrom .screen import Screen\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .styled import Styled\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme\nfrom .text import Text, TextType\nfrom .theme import Theme, ThemeStack\n\nif TYPE_CHECKING:\n    from ._windows import WindowsConsoleFeatures\n    from .live import Live\n    from .status import Status\n\nJUPYTER_DEFAULT_COLUMNS = 115\nJUPYTER_DEFAULT_LINES = 100\nWINDOWS = sys.platform == \"win32\"\n\nHighlighterType = Callable[[Union[str, \"Text\"]], \"Text\"]\nJustifyMethod = Literal[\"default\", \"left\", \"center\", \"right\", \"full\"]\nOverflowMethod = Literal[\"fold\", \"crop\", \"ellipsis\", \"ignore\"]\n\n\nclass NoChange:\n    pass\n\n\nNO_CHANGE = NoChange()\n\ntry:\n    _STDIN_FILENO = sys.__stdin__.fileno()  # type: ignore[union-attr]\nexcept Exception:\n    _STDIN_FILENO = 0\ntry:\n    _STDOUT_FILENO = sys.__stdout__.fileno()  # type: ignore[union-attr]\nexcept Exception:\n    _STDOUT_FILENO = 1\ntry:\n    _STDERR_FILENO = sys.__stderr__.fileno()  # type: ignore[union-attr]\nexcept Exception:\n    _STDERR_FILENO = 2\n\n_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)\n_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)\n\n\n_TERM_COLORS = {\n    \"kitty\": ColorSystem.EIGHT_BIT,\n    \"256color\": ColorSystem.EIGHT_BIT,\n    \"16color\": ColorSystem.STANDARD,\n}\n\n\nclass ConsoleDimensions(NamedTuple):\n    \"\"\"Size of the terminal.\"\"\"\n\n    width: int\n    \"\"\"The width of the console in 'cells'.\"\"\"\n    height: int\n    \"\"\"The height of the console in lines.\"\"\"\n\n\n@dataclass\nclass ConsoleOptions:\n    \"\"\"Options for __rich_console__ method.\"\"\"\n\n    size: ConsoleDimensions\n    \"\"\"Size of console.\"\"\"\n    legacy_windows: bool\n    \"\"\"legacy_windows: flag for legacy windows.\"\"\"\n    min_width: int\n    \"\"\"Minimum width of renderable.\"\"\"\n    max_width: int\n    \"\"\"Maximum width of renderable.\"\"\"\n    is_terminal: bool\n    \"\"\"True if the target is a terminal, otherwise False.\"\"\"\n    encoding: str\n    \"\"\"Encoding of terminal.\"\"\"\n    max_height: int\n    \"\"\"Height of container (starts as terminal)\"\"\"\n    justify: Optional[JustifyMethod] = None\n    \"\"\"Justify value override for renderable.\"\"\"\n    overflow: Optional[OverflowMethod] = None\n    \"\"\"Overflow value override for renderable.\"\"\"\n    no_wrap: Optional[bool] = False\n    \"\"\"Disable wrapping for text.\"\"\"\n    highlight: Optional[bool] = None\n    \"\"\"Highlight override for render_str.\"\"\"\n    markup: Optional[bool] = None\n    \"\"\"Enable markup when rendering strings.\"\"\"\n    height: Optional[int] = None\n\n    @property\n    def ascii_only(self) -> bool:\n        \"\"\"Check if renderables should use ascii only.\"\"\"\n        return not self.encoding.startswith(\"utf\")\n\n    def copy(self) -> \"ConsoleOptions\":\n        \"\"\"Return a copy of the options.\n\n        Returns:\n            ConsoleOptions: a copy of self.\n        \"\"\"\n        options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)\n        options.__dict__ = self.__dict__.copy()\n        return options\n\n    def update(\n        self,\n        *,\n        width: Union[int, NoChange] = NO_CHANGE,\n        min_width: Union[int, NoChange] = NO_CHANGE,\n        max_width: Union[int, NoChange] = NO_CHANGE,\n        justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,\n        overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,\n        no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,\n        highlight: Union[Optional[bool], NoChange] = NO_CHANGE,\n        markup: Union[Optional[bool], NoChange] = NO_CHANGE,\n        height: Union[Optional[int], NoChange] = NO_CHANGE,\n    ) -> \"ConsoleOptions\":\n        \"\"\"Update values, return a copy.\"\"\"\n        options = self.copy()\n        if not isinstance(width, NoChange):\n            options.min_width = options.max_width = max(0, width)\n        if not isinstance(min_width, NoChange):\n            options.min_width = min_width\n        if not isinstance(max_width, NoChange):\n            options.max_width = max_width\n        if not isinstance(justify, NoChange):\n            options.justify = justify\n        if not isinstance(overflow, NoChange):\n            options.overflow = overflow\n        if not isinstance(no_wrap, NoChange):\n            options.no_wrap = no_wrap\n        if not isinstance(highlight, NoChange):\n            options.highlight = highlight\n        if not isinstance(markup, NoChange):\n            options.markup = markup\n        if not isinstance(height, NoChange):\n            if height is not None:\n                options.max_height = height\n            options.height = None if height is None else max(0, height)\n        return options\n\n    def update_width(self, width: int) -> \"ConsoleOptions\":\n        \"\"\"Update just the width, return a copy.\n\n        Args:\n            width (int): New width (sets both min_width and max_width)\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.min_width = options.max_width = max(0, width)\n        return options\n\n    def update_height(self, height: int) -> \"ConsoleOptions\":\n        \"\"\"Update the height, and return a copy.\n\n        Args:\n            height (int): New height\n\n        Returns:\n            ~ConsoleOptions: New Console options instance.\n        \"\"\"\n        options = self.copy()\n        options.max_height = options.height = height\n        return options\n\n    def reset_height(self) -> \"ConsoleOptions\":\n        \"\"\"Return a copy of the options with height set to ``None``.\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.height = None\n        return options\n\n    def update_dimensions(self, width: int, height: int) -> \"ConsoleOptions\":\n        \"\"\"Update the width and height, and return a copy.\n\n        Args:\n            width (int): New width (sets both min_width and max_width).\n            height (int): New height.\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.min_width = options.max_width = max(0, width)\n        options.height = options.max_height = height\n        return options\n\n\n@runtime_checkable\nclass RichCast(Protocol):\n    \"\"\"An object that may be 'cast' to a console renderable.\"\"\"\n\n    def __rich__(\n        self,\n    ) -> Union[\"ConsoleRenderable\", \"RichCast\", str]:  # pragma: no cover\n        ...\n\n\n@runtime_checkable\nclass ConsoleRenderable(Protocol):\n    \"\"\"An object that supports the console protocol.\"\"\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":  # pragma: no cover\n        ...\n\n\n# A type that may be rendered by Console.\nRenderableType = Union[ConsoleRenderable, RichCast, str]\n\"\"\"A string or any object that may be rendered by Rich.\"\"\"\n\n# The result of calling a __rich_console__ method.\nRenderResult = Iterable[Union[RenderableType, Segment]]\n\n_null_highlighter = NullHighlighter()\n\n\nclass CaptureError(Exception):\n    \"\"\"An error in the Capture context manager.\"\"\"\n\n\nclass NewLine:\n    \"\"\"A renderable to generate new line(s)\"\"\"\n\n    def __init__(self, count: int = 1) -> None:\n        self.count = count\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Iterable[Segment]:\n        yield Segment(\"\\n\" * self.count)\n\n\nclass ScreenUpdate:\n    \"\"\"Render a list of lines at a given offset.\"\"\"\n\n    def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:\n        self._lines = lines\n        self.x = x\n        self.y = y\n\n    def __rich_console__(\n        self, console: \"Console\", options: ConsoleOptions\n    ) -> RenderResult:\n        x = self.x\n        move_to = Control.move_to\n        for offset, line in enumerate(self._lines, self.y):\n            yield move_to(x, offset)\n            yield from line\n\n\nclass Capture:\n    \"\"\"Context manager to capture the result of printing to the console.\n    See :meth:`~rich.console.Console.capture` for how to use.\n\n    Args:\n        console (Console): A console instance to capture output.\n    \"\"\"\n\n    def __init__(self, console: \"Console\") -> None:\n        self._console = console\n        self._result: Optional[str] = None\n\n    def __enter__(self) -> \"Capture\":\n        self._console.begin_capture()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self._result = self._console.end_capture()\n\n    def get(self) -> str:\n        \"\"\"Get the result of the capture.\"\"\"\n        if self._result is None:\n            raise CaptureError(\n                \"Capture result is not available until context manager exits.\"\n            )\n        return self._result\n\n\nclass ThemeContext:\n    \"\"\"A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.\"\"\"\n\n    def __init__(self, console: \"Console\", theme: Theme, inherit: bool = True) -> None:\n        self.console = console\n        self.theme = theme\n        self.inherit = inherit\n\n    def __enter__(self) -> \"ThemeContext\":\n        self.console.push_theme(self.theme)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.console.pop_theme()\n\n\nclass PagerContext:\n    \"\"\"A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.\"\"\"\n\n    def __init__(\n        self,\n        console: \"Console\",\n        pager: Optional[Pager] = None,\n        styles: bool = False,\n        links: bool = False,\n    ) -> None:\n        self._console = console\n        self.pager = SystemPager() if pager is None else pager\n        self.styles = styles\n        self.links = links\n\n    def __enter__(self) -> \"PagerContext\":\n        self._console._enter_buffer()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        if exc_type is None:\n            with self._console._lock:\n                buffer: List[Segment] = self._console._buffer[:]\n                del self._console._buffer[:]\n                segments: Iterable[Segment] = buffer\n                if not self.styles:\n                    segments = Segment.strip_styles(segments)\n                elif not self.links:\n                    segments = Segment.strip_links(segments)\n                content = self._console._render_buffer(segments)\n            self.pager.show(content)\n        self._console._exit_buffer()\n\n\nclass ScreenContext:\n    \"\"\"A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.\"\"\"\n\n    def __init__(\n        self, console: \"Console\", hide_cursor: bool, style: StyleType = \"\"\n    ) -> None:\n        self.console = console\n        self.hide_cursor = hide_cursor\n        self.screen = Screen(style=style)\n        self._changed = False\n\n    def update(\n        self, *renderables: RenderableType, style: Optional[StyleType] = None\n    ) -> None:\n        \"\"\"Update the screen.\n\n        Args:\n            renderable (RenderableType, optional): Optional renderable to replace current renderable,\n                or None for no change. Defaults to None.\n            style: (Style, optional): Replacement style, or None for no change. Defaults to None.\n        \"\"\"\n        if renderables:\n            self.screen.renderable = (\n                Group(*renderables) if len(renderables) > 1 else renderables[0]\n            )\n        if style is not None:\n            self.screen.style = style\n        self.console.print(self.screen, end=\"\")\n\n    def __enter__(self) -> \"ScreenContext\":\n        self._changed = self.console.set_alt_screen(True)\n        if self._changed and self.hide_cursor:\n            self.console.show_cursor(False)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        if self._changed:\n            self.console.set_alt_screen(False)\n            if self.hide_cursor:\n                self.console.show_cursor(True)\n\n\nclass Group:\n    \"\"\"Takes a group of renderables and returns a renderable object that renders the group.\n\n    Args:\n        renderables (Iterable[RenderableType]): An iterable of renderable objects.\n        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\n    \"\"\"\n\n    def __init__(self, *renderables: \"RenderableType\", fit: bool = True) -> None:\n        self._renderables = renderables\n        self.fit = fit\n        self._render: Optional[List[RenderableType]] = None\n\n    @property\n    def renderables(self) -> List[\"RenderableType\"]:\n        if self._render is None:\n            self._render = list(self._renderables)\n        return self._render\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        if self.fit:\n            return measure_renderables(console, options, self.renderables)\n        else:\n            return Measurement(options.max_width, options.max_width)\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> RenderResult:\n        yield from self.renderables\n\n\ndef group(fit: bool = True) -> Callable[..., Callable[..., Group]]:\n    \"\"\"A decorator that turns an iterable of renderables in to a group.\n\n    Args:\n        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\n    \"\"\"\n\n    def decorator(\n        method: Callable[..., Iterable[RenderableType]],\n    ) -> Callable[..., Group]:\n        \"\"\"Convert a method that returns an iterable of renderables in to a Group.\"\"\"\n\n        @wraps(method)\n        def _replace(*args: Any, **kwargs: Any) -> Group:\n            renderables = method(*args, **kwargs)\n            return Group(*renderables, fit=fit)\n\n        return _replace\n\n    return decorator\n\n\ndef _is_jupyter() -> bool:  # pragma: no cover\n    \"\"\"Check if we're running in a Jupyter notebook.\"\"\"\n    try:\n        get_ipython  # type: ignore[name-defined]\n    except NameError:\n        return False\n    ipython = get_ipython()  # type: ignore[name-defined]\n    shell = ipython.__class__.__name__\n    if (\n        \"google.colab\" in str(ipython.__class__)\n        or os.getenv(\"DATABRICKS_RUNTIME_VERSION\")\n        or shell == \"ZMQInteractiveShell\"\n    ):\n        return True  # Jupyter notebook or qtconsole\n    elif shell == \"TerminalInteractiveShell\":\n        return False  # Terminal running IPython\n    else:\n        return False  # Other type (?)\n\n\nCOLOR_SYSTEMS = {\n    \"standard\": ColorSystem.STANDARD,\n    \"256\": ColorSystem.EIGHT_BIT,\n    \"truecolor\": ColorSystem.TRUECOLOR,\n    \"windows\": ColorSystem.WINDOWS,\n}\n\n_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}\n\n\n@dataclass\nclass ConsoleThreadLocals(threading.local):\n    \"\"\"Thread local values for Console context.\"\"\"\n\n    theme_stack: ThemeStack\n    buffer: List[Segment] = field(default_factory=list)\n    buffer_index: int = 0\n\n\nclass RenderHook(ABC):\n    \"\"\"Provides hooks in to the render process.\"\"\"\n\n    @abstractmethod\n    def process_renderables(\n        self, renderables: List[ConsoleRenderable]\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Called with a list of objects to render.\n\n        This method can return a new list of renderables, or modify and return the same list.\n\n        Args:\n            renderables (List[ConsoleRenderable]): A number of renderable objects.\n\n        Returns:\n            List[ConsoleRenderable]: A replacement list of renderables.\n        \"\"\"\n\n\n_windows_console_features: Optional[\"WindowsConsoleFeatures\"] = None\n\n\ndef get_windows_console_features() -> \"WindowsConsoleFeatures\":  # pragma: no cover\n    global _windows_console_features\n    if _windows_console_features is not None:\n        return _windows_console_features\n    from ._windows import get_windows_console_features\n\n    _windows_console_features = get_windows_console_features()\n    return _windows_console_features\n\n\ndef detect_legacy_windows() -> bool:\n    \"\"\"Detect legacy Windows.\"\"\"\n    return WINDOWS and not get_windows_console_features().vt\n\n\nclass Console:\n    \"\"\"A high level console interface.\n\n    Args:\n        color_system (str, optional): The color system supported by your terminal,\n            either ``\"standard\"``, ``\"256\"`` or ``\"truecolor\"``. Leave as ``\"auto\"`` to autodetect.\n        force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.\n        force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.\n        force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.\n        soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.\n        theme (Theme, optional): An optional style theme object, or ``None`` for default theme.\n        stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.\n        file (IO, optional): A file object where the console should write to. Defaults to stdout.\n        quiet (bool, Optional): Boolean to suppress all output. Defaults to False.\n        width (int, optional): The width of the terminal. Leave as default to auto-detect width.\n        height (int, optional): The height of the terminal. Leave as default to auto-detect height.\n        style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.\n        no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.\n        tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.\n        record (bool, optional): Boolean to enable recording of terminal output,\n            required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False.\n        markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.\n        emoji (bool, optional): Enable emoji code. Defaults to True.\n        emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n        highlight (bool, optional): Enable automatic highlighting. Defaults to True.\n        log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.\n        log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.\n        log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to \"[%X] \".\n        highlighter (HighlighterType, optional): Default highlighter.\n        legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.\n        safe_box (bool, optional): Restrict box options that don't render on legacy Windows.\n        get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),\n            or None for datetime.now.\n        get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.\n    \"\"\"\n\n    _environ: Mapping[str, str] = os.environ\n\n    def __init__(\n        self,\n        *,\n        color_system: Optional[\n            Literal[\"auto\", \"standard\", \"256\", \"truecolor\", \"windows\"]\n        ] = \"auto\",\n        force_terminal: Optional[bool] = None,\n        force_jupyter: Optional[bool] = None,\n        force_interactive: Optional[bool] = None,\n        soft_wrap: bool = False,\n        theme: Optional[Theme] = None,\n        stderr: bool = False,\n        file: Optional[IO[str]] = None,\n        quiet: bool = False,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        style: Optional[StyleType] = None,\n        no_color: Optional[bool] = None,\n        tab_size: int = 8,\n        record: bool = False,\n        markup: bool = True,\n        emoji: bool = True,\n        emoji_variant: Optional[EmojiVariant] = None,\n        highlight: bool = True,\n        log_time: bool = True,\n        log_path: bool = True,\n        log_time_format: Union[str, FormatTimeCallable] = \"[%X]\",\n        highlighter: Optional[\"HighlighterType\"] = ReprHighlighter(),\n        legacy_windows: Optional[bool] = None,\n        safe_box: bool = True,\n        get_datetime: Optional[Callable[[], datetime]] = None,\n        get_time: Optional[Callable[[], float]] = None,\n        _environ: Optional[Mapping[str, str]] = None,\n    ):\n        # Copy of os.environ allows us to replace it for testing\n        if _environ is not None:\n            self._environ = _environ\n\n        self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter\n        if self.is_jupyter:\n            if width is None:\n                jupyter_columns = self._environ.get(\"JUPYTER_COLUMNS\")\n                if jupyter_columns is not None and jupyter_columns.isdigit():\n                    width = int(jupyter_columns)\n                else:\n                    width = JUPYTER_DEFAULT_COLUMNS\n            if height is None:\n                jupyter_lines = self._environ.get(\"JUPYTER_LINES\")\n                if jupyter_lines is not None and jupyter_lines.isdigit():\n                    height = int(jupyter_lines)\n                else:\n                    height = JUPYTER_DEFAULT_LINES\n\n        self.tab_size = tab_size\n        self.record = record\n        self._markup = markup\n        self._emoji = emoji\n        self._emoji_variant: Optional[EmojiVariant] = emoji_variant\n        self._highlight = highlight\n        self.legacy_windows: bool = (\n            (detect_legacy_windows() and not self.is_jupyter)\n            if legacy_windows is None\n            else legacy_windows\n        )\n\n        if width is None:\n            columns = self._environ.get(\"COLUMNS\")\n            if columns is not None and columns.isdigit():\n                width = int(columns) - self.legacy_windows\n        if height is None:\n            lines = self._environ.get(\"LINES\")\n            if lines is not None and lines.isdigit():\n                height = int(lines)\n\n        self.soft_wrap = soft_wrap\n        self._width = width\n        self._height = height\n\n        self._color_system: Optional[ColorSystem]\n\n        self._force_terminal = None\n        if force_terminal is not None:\n            self._force_terminal = force_terminal\n\n        self._file = file\n        self.quiet = quiet\n        self.stderr = stderr\n\n        if color_system is None:\n            self._color_system = None\n        elif color_system == \"auto\":\n            self._color_system = self._detect_color_system()\n        else:\n            self._color_system = COLOR_SYSTEMS[color_system]\n\n        self._lock = threading.RLock()\n        self._log_render = LogRender(\n            show_time=log_time,\n            show_path=log_path,\n            time_format=log_time_format,\n        )\n        self.highlighter: HighlighterType = highlighter or _null_highlighter\n        self.safe_box = safe_box\n        self.get_datetime = get_datetime or datetime.now\n        self.get_time = get_time or monotonic\n        self.style = style\n        self.no_color = (\n            no_color\n            if no_color is not None\n            else self._environ.get(\"NO_COLOR\", \"\") != \"\"\n        )\n        if force_interactive is None:\n            tty_interactive = self._environ.get(\"TTY_INTERACTIVE\", None)\n            if tty_interactive is not None:\n                if tty_interactive == \"0\":\n                    force_interactive = False\n                elif tty_interactive == \"1\":\n                    force_interactive = True\n\n        self.is_interactive = (\n            (self.is_terminal and not self.is_dumb_terminal)\n            if force_interactive is None\n            else force_interactive\n        )\n\n        self._record_buffer_lock = threading.RLock()\n        self._thread_locals = ConsoleThreadLocals(\n            theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)\n        )\n        self._record_buffer: List[Segment] = []\n        self._render_hooks: List[RenderHook] = []\n        self._live_stack: List[Live] = []\n        self._is_alt_screen = False\n\n    def __repr__(self) -> str:\n        return f\"<console width={self.width} {self._color_system!s}>\"\n\n    @property\n    def file(self) -> IO[str]:\n        \"\"\"Get the file object to write to.\"\"\"\n        file = self._file or (sys.stderr if self.stderr else sys.stdout)\n        file = getattr(file, \"rich_proxied_file\", file)\n        if file is None:\n            file = NULL_FILE\n        return file\n\n    @file.setter\n    def file(self, new_file: IO[str]) -> None:\n        \"\"\"Set a new file object.\"\"\"\n        self._file = new_file\n\n    @property\n    def _buffer(self) -> List[Segment]:\n        \"\"\"Get a thread local buffer.\"\"\"\n        return self._thread_locals.buffer\n\n    @property\n    def _buffer_index(self) -> int:\n        \"\"\"Get a thread local buffer.\"\"\"\n        return self._thread_locals.buffer_index\n\n    @_buffer_index.setter\n    def _buffer_index(self, value: int) -> None:\n        self._thread_locals.buffer_index = value\n\n    @property\n    def _theme_stack(self) -> ThemeStack:\n        \"\"\"Get the thread local theme stack.\"\"\"\n        return self._thread_locals.theme_stack\n\n    def _detect_color_system(self) -> Optional[ColorSystem]:\n        \"\"\"Detect color system from env vars.\"\"\"\n        if self.is_jupyter:\n            return ColorSystem.TRUECOLOR\n        if not self.is_terminal or self.is_dumb_terminal:\n            return None\n        if WINDOWS:  # pragma: no cover\n            if self.legacy_windows:  # pragma: no cover\n                return ColorSystem.WINDOWS\n            windows_console_features = get_windows_console_features()\n            return (\n                ColorSystem.TRUECOLOR\n                if windows_console_features.truecolor\n                else ColorSystem.EIGHT_BIT\n            )\n        else:\n            color_term = self._environ.get(\"COLORTERM\", \"\").strip().lower()\n            if color_term in (\"truecolor\", \"24bit\"):\n                return ColorSystem.TRUECOLOR\n            term = self._environ.get(\"TERM\", \"\").strip().lower()\n            _term_name, _hyphen, colors = term.rpartition(\"-\")\n            color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)\n            return color_system\n\n    def _enter_buffer(self) -> None:\n        \"\"\"Enter in to a buffer context, and buffer all output.\"\"\"\n        self._buffer_index += 1\n\n    def _exit_buffer(self) -> None:\n        \"\"\"Leave buffer context, and render content if required.\"\"\"\n        self._buffer_index -= 1\n        self._check_buffer()\n\n    def set_live(self, live: \"Live\") -> bool:\n        \"\"\"Set Live instance. Used by Live context manager (no need to call directly).\n\n        Args:\n            live (Live): Live instance using this Console.\n\n        Returns:\n            Boolean that indicates if the live is the topmost of the stack.\n\n        Raises:\n            errors.LiveError: If this Console has a Live context currently active.\n        \"\"\"\n        with self._lock:\n            self._live_stack.append(live)\n            return len(self._live_stack) == 1\n\n    def clear_live(self) -> None:\n        \"\"\"Clear the Live instance. Used by the Live context manager (no need to call directly).\"\"\"\n        with self._lock:\n            self._live_stack.pop()\n\n    def push_render_hook(self, hook: RenderHook) -> None:\n        \"\"\"Add a new render hook to the stack.\n\n        Args:\n            hook (RenderHook): Render hook instance.\n        \"\"\"\n        with self._lock:\n            self._render_hooks.append(hook)\n\n    def pop_render_hook(self) -> None:\n        \"\"\"Pop the last renderhook from the stack.\"\"\"\n        with self._lock:\n            self._render_hooks.pop()\n\n    def __enter__(self) -> \"Console\":\n        \"\"\"Own context manager to enter buffer context.\"\"\"\n        self._enter_buffer()\n        return self\n\n    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:\n        \"\"\"Exit buffer context.\"\"\"\n        self._exit_buffer()\n\n    def begin_capture(self) -> None:\n        \"\"\"Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.\"\"\"\n        self._enter_buffer()\n\n    def end_capture(self) -> str:\n        \"\"\"End capture mode and return captured string.\n\n        Returns:\n            str: Console output.\n        \"\"\"\n        render_result = self._render_buffer(self._buffer)\n        del self._buffer[:]\n        self._exit_buffer()\n        return render_result\n\n    def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:\n        \"\"\"Push a new theme on to the top of the stack, replacing the styles from the previous theme.\n        Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather\n        than calling this method directly.\n\n        Args:\n            theme (Theme): A theme instance.\n            inherit (bool, optional): Inherit existing styles. Defaults to True.\n        \"\"\"\n        self._theme_stack.push_theme(theme, inherit=inherit)\n\n    def pop_theme(self) -> None:\n        \"\"\"Remove theme from top of stack, restoring previous theme.\"\"\"\n        self._theme_stack.pop_theme()\n\n    def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:\n        \"\"\"Use a different theme for the duration of the context manager.\n\n        Args:\n            theme (Theme): Theme instance to user.\n            inherit (bool, optional): Inherit existing console styles. Defaults to True.\n\n        Returns:\n            ThemeContext: [description]\n        \"\"\"\n        return ThemeContext(self, theme, inherit)\n\n    @property\n    def color_system(self) -> Optional[str]:\n        \"\"\"Get color system string.\n\n        Returns:\n            Optional[str]: \"standard\", \"256\" or \"truecolor\".\n        \"\"\"\n\n        if self._color_system is not None:\n            return _COLOR_SYSTEMS_NAMES[self._color_system]\n        else:\n            return None\n\n    @property\n    def encoding(self) -> str:\n        \"\"\"Get the encoding of the console file, e.g. ``\"utf-8\"``.\n\n        Returns:\n            str: A standard encoding string.\n        \"\"\"\n        return (getattr(self.file, \"encoding\", \"utf-8\") or \"utf-8\").lower()\n\n    @property\n    def is_terminal(self) -> bool:\n        \"\"\"Check if the console is writing to a terminal.\n\n        Returns:\n            bool: True if the console writing to a device capable of\n                understanding escape sequences, otherwise False.\n        \"\"\"\n        # If dev has explicitly set this value, return it\n        if self._force_terminal is not None:\n            return self._force_terminal\n\n        # Fudge for Idle\n        if hasattr(sys.stdin, \"__module__\") and sys.stdin.__module__.startswith(\n            \"idlelib\"\n        ):\n            # Return False for Idle which claims to be a tty but can't handle ansi codes\n            return False\n\n        if self.is_jupyter:\n            # return False for Jupyter, which may have FORCE_COLOR set\n            return False\n\n        environ = self._environ\n\n        tty_compatible = environ.get(\"TTY_COMPATIBLE\", \"\")\n        # 0 indicates device is not tty compatible\n        if tty_compatible == \"0\":\n            return False\n        # 1 indicates device is tty compatible\n        if tty_compatible == \"1\":\n            return True\n\n        # https://force-color.org/\n        force_color = environ.get(\"FORCE_COLOR\")\n        if force_color is not None:\n            return force_color != \"\"\n\n        # Any other value defaults to auto detect\n        isatty: Optional[Callable[[], bool]] = getattr(self.file, \"isatty\", None)\n        try:\n            return False if isatty is None else isatty()\n        except ValueError:\n            # in some situation (at the end of a pytest run for example) isatty() can raise\n            # ValueError: I/O operation on closed file\n            # return False because we aren't in a terminal anymore\n            return False\n\n    @property\n    def is_dumb_terminal(self) -> bool:\n        \"\"\"Detect dumb terminal.\n\n        Returns:\n            bool: True if writing to a dumb terminal, otherwise False.\n\n        \"\"\"\n        _term = self._environ.get(\"TERM\", \"\")\n        is_dumb = _term.lower() in (\"dumb\", \"unknown\")\n        return self.is_terminal and is_dumb\n\n    @property\n    def options(self) -> ConsoleOptions:\n        \"\"\"Get default console options.\"\"\"\n        size = self.size\n        return ConsoleOptions(\n            max_height=size.height,\n            size=size,\n            legacy_windows=self.legacy_windows,\n            min_width=1,\n            max_width=size.width,\n            encoding=self.encoding,\n            is_terminal=self.is_terminal,\n        )\n\n    @property\n    def size(self) -> ConsoleDimensions:\n        \"\"\"Get the size of the console.\n\n        Returns:\n            ConsoleDimensions: A named tuple containing the dimensions.\n        \"\"\"\n\n        if self._width is not None and self._height is not None:\n            return ConsoleDimensions(self._width - self.legacy_windows, self._height)\n\n        if self.is_dumb_terminal:\n            return ConsoleDimensions(80, 25)\n\n        width: Optional[int] = None\n        height: Optional[int] = None\n\n        streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS\n        for file_descriptor in streams:\n            try:\n                width, height = os.get_terminal_size(file_descriptor)\n            except (AttributeError, ValueError, OSError):  # Probably not a terminal\n                pass\n            else:\n                break\n\n        columns = self._environ.get(\"COLUMNS\")\n        if columns is not None and columns.isdigit():\n            width = int(columns)\n        lines = self._environ.get(\"LINES\")\n        if lines is not None and lines.isdigit():\n            height = int(lines)\n\n        # get_terminal_size can report 0, 0 if run from pseudo-terminal\n        width = width or 80\n        height = height or 25\n        return ConsoleDimensions(\n            width - self.legacy_windows if self._width is None else self._width,\n            height if self._height is None else self._height,\n        )\n\n    @size.setter\n    def size(self, new_size: Tuple[int, int]) -> None:\n        \"\"\"Set a new size for the terminal.\n\n        Args:\n            new_size (Tuple[int, int]): New width and height.\n        \"\"\"\n        width, height = new_size\n        self._width = width\n        self._height = height\n\n    @property\n    def width(self) -> int:\n        \"\"\"Get the width of the console.\n\n        Returns:\n            int: The width (in characters) of the console.\n        \"\"\"\n        return self.size.width\n\n    @width.setter\n    def width(self, width: int) -> None:\n        \"\"\"Set width.\n\n        Args:\n            width (int): New width.\n        \"\"\"\n        self._width = width\n\n    @property\n    def height(self) -> int:\n        \"\"\"Get the height of the console.\n\n        Returns:\n            int: The height (in lines) of the console.\n        \"\"\"\n        return self.size.height\n\n    @height.setter\n    def height(self, height: int) -> None:\n        \"\"\"Set height.\n\n        Args:\n            height (int): new height.\n        \"\"\"\n        self._height = height\n\n    def bell(self) -> None:\n        \"\"\"Play a 'bell' sound (if supported by the terminal).\"\"\"\n        self.control(Control.bell())\n\n    def capture(self) -> Capture:\n        \"\"\"A context manager to *capture* the result of print() or log() in a string,\n        rather than writing it to the console.\n\n        Example:\n            >>> from rich.console import Console\n            >>> console = Console()\n            >>> with console.capture() as capture:\n            ...     console.print(\"[bold magenta]Hello World[/]\")\n            >>> print(capture.get())\n\n        Returns:\n            Capture: Context manager with disables writing to the terminal.\n        \"\"\"\n        capture = Capture(self)\n        return capture\n\n    def pager(\n        self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False\n    ) -> PagerContext:\n        \"\"\"A context manager to display anything printed within a \"pager\". The pager application\n        is defined by the system and will typically support at least pressing a key to scroll.\n\n        Args:\n            pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.\n            styles (bool, optional): Show styles in pager. Defaults to False.\n            links (bool, optional): Show links in pager. Defaults to False.\n\n        Example:\n            >>> from rich.console import Console\n            >>> from rich.__main__ import make_test_card\n            >>> console = Console()\n            >>> with console.pager():\n                    console.print(make_test_card())\n\n        Returns:\n            PagerContext: A context manager.\n        \"\"\"\n        return PagerContext(self, pager=pager, styles=styles, links=links)\n\n    def line(self, count: int = 1) -> None:\n        \"\"\"Write new line(s).\n\n        Args:\n            count (int, optional): Number of new lines. Defaults to 1.\n        \"\"\"\n\n        assert count >= 0, \"count must be >= 0\"\n        self.print(NewLine(count))\n\n    def clear(self, home: bool = True) -> None:\n        \"\"\"Clear the screen.\n\n        Args:\n            home (bool, optional): Also move the cursor to 'home' position. Defaults to True.\n        \"\"\"\n        if home:\n            self.control(Control.clear(), Control.home())\n        else:\n            self.control(Control.clear())\n\n    def status(\n        self,\n        status: RenderableType,\n        *,\n        spinner: str = \"dots\",\n        spinner_style: StyleType = \"status.spinner\",\n        speed: float = 1.0,\n        refresh_per_second: float = 12.5,\n    ) -> \"Status\":\n        \"\"\"Display a status and spinner.\n\n        Args:\n            status (RenderableType): A status renderable (str or Text typically).\n            spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to \"dots\".\n            spinner_style (StyleType, optional): Style of spinner. Defaults to \"status.spinner\".\n            speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.\n            refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.\n\n        Returns:\n            Status: A Status object that may be used as a context manager.\n        \"\"\"\n        from .status import Status\n\n        status_renderable = Status(\n            status,\n            console=self,\n            spinner=spinner,\n            spinner_style=spinner_style,\n            speed=speed,\n            refresh_per_second=refresh_per_second,\n        )\n        return status_renderable\n\n    def show_cursor(self, show: bool = True) -> bool:\n        \"\"\"Show or hide the cursor.\n\n        Args:\n            show (bool, optional): Set visibility of the cursor.\n        \"\"\"\n        if self.is_terminal:\n            self.control(Control.show_cursor(show))\n            return True\n        return False\n\n    def set_alt_screen(self, enable: bool = True) -> bool:\n        \"\"\"Enables alternative screen mode.\n\n        Note, if you enable this mode, you should ensure that is disabled before\n        the application exits. See :meth:`~rich.Console.screen` for a context manager\n        that handles this for you.\n\n        Args:\n            enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.\n\n        Returns:\n            bool: True if the control codes were written.\n\n        \"\"\"\n        changed = False\n        if self.is_terminal and not self.legacy_windows:\n            self.control(Control.alt_screen(enable))\n            changed = True\n            self._is_alt_screen = enable\n        return changed\n\n    @property\n    def is_alt_screen(self) -> bool:\n        \"\"\"Check if the alt screen was enabled.\n\n        Returns:\n            bool: True if the alt screen was enabled, otherwise False.\n        \"\"\"\n        return self._is_alt_screen\n\n    def set_window_title(self, title: str) -> bool:\n        \"\"\"Set the title of the console terminal window.\n\n        Warning: There is no means within Rich of \"resetting\" the window title to its\n        previous value, meaning the title you set will persist even after your application\n        exits.\n\n        ``fish`` shell resets the window title before and after each command by default,\n        negating this issue. Windows Terminal and command prompt will also reset the title for you.\n        Most other shells and terminals, however, do not do this.\n\n        Some terminals may require configuration changes before you can set the title.\n        Some terminals may not support setting the title at all.\n\n        Other software (including the terminal itself, the shell, custom prompts, plugins, etc.)\n        may also set the terminal window title. This could result in whatever value you write\n        using this method being overwritten.\n\n        Args:\n            title (str): The new title of the terminal window.\n\n        Returns:\n            bool: True if the control code to change the terminal title was\n                written, otherwise False. Note that a return value of True\n                does not guarantee that the window title has actually changed,\n                since the feature may be unsupported/disabled in some terminals.\n        \"\"\"\n        if self.is_terminal:\n            self.control(Control.title(title))\n            return True\n        return False\n\n    def screen(\n        self, hide_cursor: bool = True, style: Optional[StyleType] = None\n    ) -> \"ScreenContext\":\n        \"\"\"Context manager to enable and disable 'alternative screen' mode.\n\n        Args:\n            hide_cursor (bool, optional): Also hide the cursor. Defaults to False.\n            style (Style, optional): Optional style for screen. Defaults to None.\n\n        Returns:\n            ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.\n        \"\"\"\n        return ScreenContext(self, hide_cursor=hide_cursor, style=style or \"\")\n\n    def measure(\n        self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None\n    ) -> Measurement:\n        \"\"\"Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains\n        information regarding the number of characters required to print the renderable.\n\n        Args:\n            renderable (RenderableType): Any renderable or string.\n            options (Optional[ConsoleOptions], optional): Options to use when measuring, or None\n                to use default options. Defaults to None.\n\n        Returns:\n            Measurement: A measurement of the renderable.\n        \"\"\"\n        measurement = Measurement.get(self, options or self.options, renderable)\n        return measurement\n\n    def render(\n        self, renderable: RenderableType, options: Optional[ConsoleOptions] = None\n    ) -> Iterable[Segment]:\n        \"\"\"Render an object in to an iterable of `Segment` instances.\n\n        This method contains the logic for rendering objects with the console protocol.\n        You are unlikely to need to use it directly, unless you are extending the library.\n\n        Args:\n            renderable (RenderableType): An object supporting the console protocol, or\n                an object that may be converted to a string.\n            options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.\n\n        Returns:\n            Iterable[Segment]: An iterable of segments that may be rendered.\n        \"\"\"\n\n        _options = options or self.options\n        if _options.max_width < 1:\n            # No space to render anything. This prevents potential recursion errors.\n            return\n        render_iterable: RenderResult\n\n        renderable = rich_cast(renderable)\n        if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):\n            render_iterable = renderable.__rich_console__(self, _options)\n        elif isinstance(renderable, str):\n            text_renderable = self.render_str(\n                renderable, highlight=_options.highlight, markup=_options.markup\n            )\n            render_iterable = text_renderable.__rich_console__(self, _options)\n        else:\n            raise errors.NotRenderableError(\n                f\"Unable to render {renderable!r}; \"\n                \"A str, Segment or object with __rich_console__ method is required\"\n            )\n\n        try:\n            iter_render = iter(render_iterable)\n        except TypeError:\n            raise errors.NotRenderableError(\n                f\"object {render_iterable!r} is not renderable\"\n            )\n        _Segment = Segment\n        _options = _options.reset_height()\n        for render_output in iter_render:\n            if isinstance(render_output, _Segment):\n                yield render_output\n            else:\n                yield from self.render(render_output, _options)\n\n    def render_lines(\n        self,\n        renderable: RenderableType,\n        options: Optional[ConsoleOptions] = None,\n        *,\n        style: Optional[Style] = None,\n        pad: bool = True,\n        new_lines: bool = False,\n    ) -> List[List[Segment]]:\n        \"\"\"Render objects in to a list of lines.\n\n        The output of render_lines is useful when further formatting of rendered console text\n        is required, such as the Panel class which draws a border around any renderable object.\n\n        Args:\n            renderable (RenderableType): Any object renderable in the console.\n            options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.\n            style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.\n            pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.\n            new_lines (bool, optional): Include \"\\n\" characters at end of lines.\n\n        Returns:\n            List[List[Segment]]: A list of lines, where a line is a list of Segment objects.\n        \"\"\"\n        with self._lock:\n            render_options = options or self.options\n            _rendered = self.render(renderable, render_options)\n            if style:\n                _rendered = Segment.apply_style(_rendered, style)\n\n            render_height = render_options.height\n            if render_height is not None:\n                render_height = max(0, render_height)\n\n            lines = list(\n                islice(\n                    Segment.split_and_crop_lines(\n                        _rendered,\n                        render_options.max_width,\n                        include_new_lines=new_lines,\n                        pad=pad,\n                        style=style,\n                    ),\n                    None,\n                    render_height,\n                )\n            )\n            if render_options.height is not None:\n                extra_lines = render_options.height - len(lines)\n                if extra_lines > 0:\n                    pad_line = [\n                        (\n                            [\n                                Segment(\" \" * render_options.max_width, style),\n                                Segment(\"\\n\"),\n                            ]\n                            if new_lines\n                            else [Segment(\" \" * render_options.max_width, style)]\n                        )\n                    ]\n                    lines.extend(pad_line * extra_lines)\n\n            return lines\n\n    def render_str(\n        self,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        justify: Optional[JustifyMethod] = None,\n        overflow: Optional[OverflowMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        highlighter: Optional[HighlighterType] = None,\n    ) -> \"Text\":\n        \"\"\"Convert a string to a Text instance. This is called automatically if\n        you print or log a string.\n\n        Args:\n            text (str): Text to render.\n            style (Union[str, Style], optional): Style to apply to rendered text.\n            justify (str, optional): Justify method: \"default\", \"left\", \"center\", \"full\", or \"right\". Defaults to ``None``.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to ``None``.\n            emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.\n            highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.\n            highlighter (HighlighterType, optional): Optional highlighter to apply.\n        Returns:\n            ConsoleRenderable: Renderable object.\n\n        \"\"\"\n        emoji_enabled = emoji or (emoji is None and self._emoji)\n        markup_enabled = markup or (markup is None and self._markup)\n        highlight_enabled = highlight or (highlight is None and self._highlight)\n\n        if markup_enabled:\n            rich_text = render_markup(\n                text,\n                style=style,\n                emoji=emoji_enabled,\n                emoji_variant=self._emoji_variant,\n            )\n            rich_text.justify = justify\n            rich_text.overflow = overflow\n        else:\n            rich_text = Text(\n                (\n                    _emoji_replace(text, default_variant=self._emoji_variant)\n                    if emoji_enabled\n                    else text\n                ),\n                justify=justify,\n                overflow=overflow,\n                style=style,\n            )\n\n        _highlighter = (highlighter or self.highlighter) if highlight_enabled else None\n        if _highlighter is not None:\n            highlight_text = _highlighter(str(rich_text))\n            highlight_text.copy_styles(rich_text)\n            return highlight_text\n\n        return rich_text\n\n    def get_style(\n        self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None\n    ) -> Style:\n        \"\"\"Get a Style instance by its theme name or parse a definition.\n\n        Args:\n            name (str): The name of a style or a style definition.\n\n        Returns:\n            Style: A Style object.\n\n        Raises:\n            MissingStyle: If no style could be parsed from name.\n\n        \"\"\"\n        if isinstance(name, Style):\n            return name\n\n        try:\n            style = self._theme_stack.get(name)\n            if style is None:\n                style = Style.parse(name)\n            return style.copy() if style.link else style\n        except errors.StyleSyntaxError as error:\n            if default is not None:\n                return self.get_style(default)\n            raise errors.MissingStyle(\n                f\"Failed to get style {name!r}; {error}\"\n            ) from None\n\n    def _collect_renderables(\n        self,\n        objects: Iterable[Any],\n        sep: str,\n        end: str,\n        *,\n        justify: Optional[JustifyMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Combine a number of renderables and text into one renderable.\n\n        Args:\n            objects (Iterable[Any]): Anything that Rich can render.\n            sep (str): String to write between print data.\n            end (str): String to write at end of print data.\n            justify (str, optional): One of \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.\n\n        Returns:\n            List[ConsoleRenderable]: A list of things to render.\n        \"\"\"\n        renderables: List[ConsoleRenderable] = []\n        _append = renderables.append\n        text: List[Text] = []\n        append_text = text.append\n\n        append = _append\n        if justify in (\"left\", \"center\", \"right\"):\n\n            def align_append(renderable: RenderableType) -> None:\n                _append(Align(renderable, cast(AlignMethod, justify)))\n\n            append = align_append\n\n        _highlighter: HighlighterType = _null_highlighter\n        if highlight or (highlight is None and self._highlight):\n            _highlighter = self.highlighter\n\n        def check_text() -> None:\n            if text:\n                sep_text = Text(sep, justify=justify, end=end)\n                append(sep_text.join(text))\n                text.clear()\n\n        for renderable in objects:\n            renderable = rich_cast(renderable)\n            if isinstance(renderable, str):\n                append_text(\n                    self.render_str(\n                        renderable,\n                        emoji=emoji,\n                        markup=markup,\n                        highlight=highlight,\n                        highlighter=_highlighter,\n                    )\n                )\n            elif isinstance(renderable, Text):\n                append_text(renderable)\n            elif isinstance(renderable, ConsoleRenderable):\n                check_text()\n                append(renderable)\n            elif is_expandable(renderable):\n                check_text()\n                append(Pretty(renderable, highlighter=_highlighter))\n            else:\n                append_text(_highlighter(str(renderable)))\n\n        check_text()\n\n        if self.style is not None:\n            style = self.get_style(self.style)\n            renderables = [Styled(renderable, style) for renderable in renderables]\n\n        return renderables\n\n    def rule(\n        self,\n        title: TextType = \"\",\n        *,\n        characters: str = \"─\",\n        style: Union[str, Style] = \"rule.line\",\n        align: AlignMethod = \"center\",\n    ) -> None:\n        \"\"\"Draw a line with optional centered title.\n\n        Args:\n            title (str, optional): Text to render over the rule. Defaults to \"\".\n            characters (str, optional): Character(s) to form the line. Defaults to \"─\".\n            style (str, optional): Style of line. Defaults to \"rule.line\".\n            align (str, optional): How to align the title, one of \"left\", \"center\", or \"right\". Defaults to \"center\".\n        \"\"\"\n        from .rule import Rule\n\n        rule = Rule(title=title, characters=characters, style=style, align=align)\n        self.print(rule)\n\n    def control(self, *control: Control) -> None:\n        \"\"\"Insert non-printing control codes.\n\n        Args:\n            control_codes (str): Control codes, such as those that may move the cursor.\n        \"\"\"\n        if not self.is_dumb_terminal:\n            with self:\n                self._buffer.extend(_control.segment for _control in control)\n\n    def out(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        highlight: Optional[bool] = None,\n    ) -> None:\n        \"\"\"Output to the terminal. This is a low-level way of writing to the terminal which unlike\n        :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will\n        optionally apply highlighting and a basic style.\n\n        Args:\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use\n                console default. Defaults to ``None``.\n        \"\"\"\n        raw_output: str = sep.join(str(_object) for _object in objects)\n        self.print(\n            raw_output,\n            style=style,\n            highlight=highlight,\n            emoji=False,\n            markup=False,\n            no_wrap=True,\n            overflow=\"ignore\",\n            crop=False,\n            end=end,\n        )\n\n    def print(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        justify: Optional[JustifyMethod] = None,\n        overflow: Optional[OverflowMethod] = None,\n        no_wrap: Optional[bool] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        crop: bool = True,\n        soft_wrap: Optional[bool] = None,\n        new_line_start: bool = False,\n    ) -> None:\n        \"\"\"Print to the console.\n\n        Args:\n            objects (positional args): Objects to log to the terminal.\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n            no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n            width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\n            crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\n            soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for\n                Console default. Defaults to ``None``.\n            new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.\n        \"\"\"\n        if not objects:\n            objects = (NewLine(),)\n\n        if soft_wrap is None:\n            soft_wrap = self.soft_wrap\n        if soft_wrap:\n            if no_wrap is None:\n                no_wrap = True\n            if overflow is None:\n                overflow = \"ignore\"\n            crop = False\n        render_hooks = self._render_hooks[:]\n        with self:\n            renderables = self._collect_renderables(\n                objects,\n                sep,\n                end,\n                justify=justify,\n                emoji=emoji,\n                markup=markup,\n                highlight=highlight,\n            )\n            for hook in render_hooks:\n                renderables = hook.process_renderables(renderables)\n            render_options = self.options.update(\n                justify=justify,\n                overflow=overflow,\n                width=min(width, self.width) if width is not None else NO_CHANGE,\n                height=height,\n                no_wrap=no_wrap,\n                markup=markup,\n                highlight=highlight,\n            )\n\n            new_segments: List[Segment] = []\n            extend = new_segments.extend\n            render = self.render\n            if style is None:\n                for renderable in renderables:\n                    extend(render(renderable, render_options))\n            else:\n                for renderable in renderables:\n                    extend(\n                        Segment.apply_style(\n                            render(renderable, render_options), self.get_style(style)\n                        )\n                    )\n            if new_line_start:\n                if (\n                    len(\"\".join(segment.text for segment in new_segments).splitlines())\n                    > 1\n                ):\n                    new_segments.insert(0, Segment.line())\n            if crop:\n                buffer_extend = self._buffer.extend\n                for line in Segment.split_and_crop_lines(\n                    new_segments, self.width, pad=False\n                ):\n                    buffer_extend(line)\n            else:\n                self._buffer.extend(new_segments)\n\n    def print_json(\n        self,\n        json: Optional[str] = None,\n        *,\n        data: Any = None,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = False,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> None:\n        \"\"\"Pretty prints JSON. Output will be valid JSON.\n\n        Args:\n            json (Optional[str]): A string containing JSON.\n            data (Any): If json is not supplied, then encode this data.\n            indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.\n            highlight (bool, optional): Enable highlighting of output: Defaults to True.\n            skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n            ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n            check_circular (bool, optional): Check for circular references. Defaults to True.\n            allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n            default (Callable, optional): A callable that converts values that can not be encoded\n                in to something that can be JSON encoded. Defaults to None.\n            sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n        \"\"\"\n        from pip._vendor.rich.json import JSON\n\n        if json is None:\n            json_renderable = JSON.from_data(\n                data,\n                indent=indent,\n                highlight=highlight,\n                skip_keys=skip_keys,\n                ensure_ascii=ensure_ascii,\n                check_circular=check_circular,\n                allow_nan=allow_nan,\n                default=default,\n                sort_keys=sort_keys,\n            )\n        else:\n            if not isinstance(json, str):\n                raise TypeError(\n                    f\"json must be str. Did you mean print_json(data={json!r}) ?\"\n                )\n            json_renderable = JSON(\n                json,\n                indent=indent,\n                highlight=highlight,\n                skip_keys=skip_keys,\n                ensure_ascii=ensure_ascii,\n                check_circular=check_circular,\n                allow_nan=allow_nan,\n                default=default,\n                sort_keys=sort_keys,\n            )\n        self.print(json_renderable, soft_wrap=True)\n\n    def update_screen(\n        self,\n        renderable: RenderableType,\n        *,\n        region: Optional[Region] = None,\n        options: Optional[ConsoleOptions] = None,\n    ) -> None:\n        \"\"\"Update the screen at a given offset.\n\n        Args:\n            renderable (RenderableType): A Rich renderable.\n            region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.\n            x (int, optional): x offset. Defaults to 0.\n            y (int, optional): y offset. Defaults to 0.\n\n        Raises:\n            errors.NoAltScreen: If the Console isn't in alt screen mode.\n\n        \"\"\"\n        if not self.is_alt_screen:\n            raise errors.NoAltScreen(\"Alt screen must be enabled to call update_screen\")\n        render_options = options or self.options\n        if region is None:\n            x = y = 0\n            render_options = render_options.update_dimensions(\n                render_options.max_width, render_options.height or self.height\n            )\n        else:\n            x, y, width, height = region\n            render_options = render_options.update_dimensions(width, height)\n\n        lines = self.render_lines(renderable, options=render_options)\n        self.update_screen_lines(lines, x, y)\n\n    def update_screen_lines(\n        self, lines: List[List[Segment]], x: int = 0, y: int = 0\n    ) -> None:\n        \"\"\"Update lines of the screen at a given offset.\n\n        Args:\n            lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).\n            x (int, optional): x offset (column no). Defaults to 0.\n            y (int, optional): y offset (column no). Defaults to 0.\n\n        Raises:\n            errors.NoAltScreen: If the Console isn't in alt screen mode.\n        \"\"\"\n        if not self.is_alt_screen:\n            raise errors.NoAltScreen(\"Alt screen must be enabled to call update_screen\")\n        screen_update = ScreenUpdate(lines, x, y)\n        segments = self.render(screen_update)\n        self._buffer.extend(segments)\n        self._check_buffer()\n\n    def print_exception(\n        self,\n        *,\n        width: Optional[int] = 100,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ) -> None:\n        \"\"\"Prints a rich render of the last exception and traceback.\n\n        Args:\n            width (Optional[int], optional): Number of characters used to render code. Defaults to 100.\n            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n            theme (str, optional): Override pygments theme used in traceback\n            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n        \"\"\"\n        from .traceback import Traceback\n\n        traceback = Traceback(\n            width=width,\n            extra_lines=extra_lines,\n            theme=theme,\n            word_wrap=word_wrap,\n            show_locals=show_locals,\n            suppress=suppress,\n            max_frames=max_frames,\n        )\n        self.print(traceback)\n\n    @staticmethod\n    def _caller_frame_info(\n        offset: int,\n        currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,\n    ) -> Tuple[str, int, Dict[str, Any]]:\n        \"\"\"Get caller frame information.\n\n        Args:\n            offset (int): the caller offset within the current frame stack.\n            currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to\n                retrieve the current frame. Defaults to ``inspect.currentframe``.\n\n        Returns:\n            Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and\n                the dictionary of local variables associated with the caller frame.\n\n        Raises:\n            RuntimeError: If the stack offset is invalid.\n        \"\"\"\n        # Ignore the frame of this local helper\n        offset += 1\n\n        frame = currentframe()\n        if frame is not None:\n            # Use the faster currentframe where implemented\n            while offset and frame is not None:\n                frame = frame.f_back\n                offset -= 1\n            assert frame is not None\n            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals\n        else:\n            # Fallback to the slower stack\n            frame_info = inspect.stack()[offset]\n            return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals\n\n    def log(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        justify: Optional[JustifyMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        log_locals: bool = False,\n        _stack_offset: int = 1,\n    ) -> None:\n        \"\"\"Log rich content to the terminal.\n\n        Args:\n            objects (positional args): Objects to log to the terminal.\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            justify (str, optional): One of \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.\n            log_locals (bool, optional): Boolean to enable logging of locals where ``log()``\n                was called. Defaults to False.\n            _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.\n        \"\"\"\n        if not objects:\n            objects = (NewLine(),)\n\n        render_hooks = self._render_hooks[:]\n\n        with self:\n            renderables = self._collect_renderables(\n                objects,\n                sep,\n                end,\n                justify=justify,\n                emoji=emoji,\n                markup=markup,\n                highlight=highlight,\n            )\n            if style is not None:\n                renderables = [Styled(renderable, style) for renderable in renderables]\n\n            filename, line_no, locals = self._caller_frame_info(_stack_offset)\n            link_path = None if filename.startswith(\"<\") else os.path.abspath(filename)\n            path = filename.rpartition(os.sep)[-1]\n            if log_locals:\n                locals_map = {\n                    key: value\n                    for key, value in locals.items()\n                    if not key.startswith(\"__\")\n                }\n                renderables.append(render_scope(locals_map, title=\"[i]locals\"))\n\n            renderables = [\n                self._log_render(\n                    self,\n                    renderables,\n                    log_time=self.get_datetime(),\n                    path=path,\n                    line_no=line_no,\n                    link_path=link_path,\n                )\n            ]\n            for hook in render_hooks:\n                renderables = hook.process_renderables(renderables)\n            new_segments: List[Segment] = []\n            extend = new_segments.extend\n            render = self.render\n            render_options = self.options\n            for renderable in renderables:\n                extend(render(renderable, render_options))\n            buffer_extend = self._buffer.extend\n            for line in Segment.split_and_crop_lines(\n                new_segments, self.width, pad=False\n            ):\n                buffer_extend(line)\n\n    def on_broken_pipe(self) -> None:\n        \"\"\"This function is called when a `BrokenPipeError` is raised.\n\n        This can occur when piping Textual output in Linux and macOS.\n        The default implementation is to exit the app, but you could implement\n        this method in a subclass to change the behavior.\n\n        See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details.\n        \"\"\"\n        self.quiet = True\n        devnull = os.open(os.devnull, os.O_WRONLY)\n        os.dup2(devnull, sys.stdout.fileno())\n        raise SystemExit(1)\n\n    def _check_buffer(self) -> None:\n        \"\"\"Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)\n        Rendering is supported on Windows, Unix and Jupyter environments. For\n        legacy Windows consoles, the win32 API is called directly.\n        This method will also record what it renders if recording is enabled via Console.record.\n        \"\"\"\n        if self.quiet:\n            del self._buffer[:]\n            return\n\n        try:\n            self._write_buffer()\n        except BrokenPipeError:\n            self.on_broken_pipe()\n\n    def _write_buffer(self) -> None:\n        \"\"\"Write the buffer to the output file.\"\"\"\n\n        with self._lock:\n            if self.record and not self._buffer_index:\n                with self._record_buffer_lock:\n                    self._record_buffer.extend(self._buffer[:])\n\n            if self._buffer_index == 0:\n                if self.is_jupyter:  # pragma: no cover\n                    from .jupyter import display\n\n                    display(self._buffer, self._render_buffer(self._buffer[:]))\n                    del self._buffer[:]\n                else:\n                    if WINDOWS:\n                        use_legacy_windows_render = False\n                        if self.legacy_windows:\n                            fileno = get_fileno(self.file)\n                            if fileno is not None:\n                                use_legacy_windows_render = (\n                                    fileno in _STD_STREAMS_OUTPUT\n                                )\n\n                        if use_legacy_windows_render:\n                            from pip._vendor.rich._win32_console import LegacyWindowsTerm\n                            from pip._vendor.rich._windows_renderer import legacy_windows_render\n\n                            buffer = self._buffer[:]\n                            if self.no_color and self._color_system:\n                                buffer = list(Segment.remove_color(buffer))\n\n                            legacy_windows_render(buffer, LegacyWindowsTerm(self.file))\n                        else:\n                            # Either a non-std stream on legacy Windows, or modern Windows.\n                            text = self._render_buffer(self._buffer[:])\n                            # https://bugs.python.org/issue37871\n                            # https://github.com/python/cpython/issues/82052\n                            # We need to avoid writing more than 32Kb in a single write, due to the above bug\n                            write = self.file.write\n                            # Worse case scenario, every character is 4 bytes of utf-8\n                            MAX_WRITE = 32 * 1024 // 4\n                            try:\n                                if len(text) <= MAX_WRITE:\n                                    write(text)\n                                else:\n                                    batch: List[str] = []\n                                    batch_append = batch.append\n                                    size = 0\n                                    for line in text.splitlines(True):\n                                        if size + len(line) > MAX_WRITE and batch:\n                                            write(\"\".join(batch))\n                                            batch.clear()\n                                            size = 0\n                                        batch_append(line)\n                                        size += len(line)\n                                    if batch:\n                                        write(\"\".join(batch))\n                                        batch.clear()\n                            except UnicodeEncodeError as error:\n                                error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n                                raise\n                    else:\n                        text = self._render_buffer(self._buffer[:])\n                        try:\n                            self.file.write(text)\n                        except UnicodeEncodeError as error:\n                            error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n                            raise\n\n                    self.file.flush()\n                    del self._buffer[:]\n\n    def _render_buffer(self, buffer: Iterable[Segment]) -> str:\n        \"\"\"Render buffered output, and clear buffer.\"\"\"\n        output: List[str] = []\n        append = output.append\n        color_system = self._color_system\n        legacy_windows = self.legacy_windows\n        not_terminal = not self.is_terminal\n        if self.no_color and color_system:\n            buffer = Segment.remove_color(buffer)\n        for text, style, control in buffer:\n            if style:\n                append(\n                    style.render(\n                        text,\n                        color_system=color_system,\n                        legacy_windows=legacy_windows,\n                    )\n                )\n            elif not (not_terminal and control):\n                append(text)\n\n        rendered = \"\".join(output)\n        return rendered\n\n    def input(\n        self,\n        prompt: TextType = \"\",\n        *,\n        markup: bool = True,\n        emoji: bool = True,\n        password: bool = False,\n        stream: Optional[TextIO] = None,\n    ) -> str:\n        \"\"\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\n\n        It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.\n\n        Args:\n            prompt (Union[str, Text]): Text to render in the prompt.\n            markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\n            emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\n            password: (bool, optional): Hide typed text. Defaults to False.\n            stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\n\n        Returns:\n            str: Text read from stdin.\n        \"\"\"\n        if prompt:\n            self.print(prompt, markup=markup, emoji=emoji, end=\"\")\n        if password:\n            result = getpass(\"\", stream=stream)\n        else:\n            if stream:\n                result = stream.readline()\n            else:\n                result = input()\n        return result\n\n    def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\n        \"\"\"Generate text from console contents (requires record=True argument in constructor).\n\n        Args:\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\n                Defaults to ``False``.\n\n        Returns:\n            str: String containing console contents.\n\n        \"\"\"\n        assert (\n            self.record\n        ), \"To export console contents set record=True in the constructor or instance\"\n\n        with self._record_buffer_lock:\n            if styles:\n                text = \"\".join(\n                    (style.render(text) if style else text)\n                    for text, style, _ in self._record_buffer\n                )\n            else:\n                text = \"\".join(\n                    segment.text\n                    for segment in self._record_buffer\n                    if not segment.control\n                )\n            if clear:\n                del self._record_buffer[:]\n        return text\n\n    def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:\n        \"\"\"Generate text from console and save to a given location (requires record=True argument in constructor).\n\n        Args:\n            path (str): Path to write text files.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.\n                Defaults to ``False``.\n\n        \"\"\"\n        text = self.export_text(clear=clear, styles=styles)\n        with open(path, \"w\", encoding=\"utf-8\") as write_file:\n            write_file.write(text)\n\n    def export_html(\n        self,\n        *,\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: Optional[str] = None,\n        inline_styles: bool = False,\n    ) -> str:\n        \"\"\"Generate HTML from console contents (requires record=True argument in constructor).\n\n        Args:\n            theme (TerminalTheme, optional): TerminalTheme object containing console colors.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            code_format (str, optional): Format string to render HTML. In addition to '{foreground}',\n                '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.\n            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\n                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\n                Defaults to False.\n\n        Returns:\n            str: String containing console contents as HTML.\n        \"\"\"\n        assert (\n            self.record\n        ), \"To export console contents set record=True in the constructor or instance\"\n        fragments: List[str] = []\n        append = fragments.append\n        _theme = theme or DEFAULT_TERMINAL_THEME\n        stylesheet = \"\"\n\n        render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format\n\n        with self._record_buffer_lock:\n            if inline_styles:\n                for text, style, _ in Segment.filter_control(\n                    Segment.simplify(self._record_buffer)\n                ):\n                    text = escape(text)\n                    if style:\n                        rule = style.get_html_style(_theme)\n                        if style.link:\n                            text = f'<a href=\"{style.link}\">{text}</a>'\n                        text = f'<span style=\"{rule}\">{text}</span>' if rule else text\n                    append(text)\n            else:\n                styles: Dict[str, int] = {}\n                for text, style, _ in Segment.filter_control(\n                    Segment.simplify(self._record_buffer)\n                ):\n                    text = escape(text)\n                    if style:\n                        rule = style.get_html_style(_theme)\n                        style_number = styles.setdefault(rule, len(styles) + 1)\n                        if style.link:\n                            text = f'<a class=\"r{style_number}\" href=\"{style.link}\">{text}</a>'\n                        else:\n                            text = f'<span class=\"r{style_number}\">{text}</span>'\n                    append(text)\n                stylesheet_rules: List[str] = []\n                stylesheet_append = stylesheet_rules.append\n                for style_rule, style_number in styles.items():\n                    if style_rule:\n                        stylesheet_append(f\".r{style_number} {{{style_rule}}}\")\n                stylesheet = \"\\n\".join(stylesheet_rules)\n\n            rendered_code = render_code_format.format(\n                code=\"\".join(fragments),\n                stylesheet=stylesheet,\n                foreground=_theme.foreground_color.hex,\n                background=_theme.background_color.hex,\n            )\n            if clear:\n                del self._record_buffer[:]\n        return rendered_code\n\n    def save_html(\n        self,\n        path: str,\n        *,\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_HTML_FORMAT,\n        inline_styles: bool = False,\n    ) -> None:\n        \"\"\"Generate HTML from console contents and write to a file (requires record=True argument in constructor).\n\n        Args:\n            path (str): Path to write html file.\n            theme (TerminalTheme, optional): TerminalTheme object containing console colors.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            code_format (str, optional): Format string to render HTML. In addition to '{foreground}',\n                '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.\n            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\n                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\n                Defaults to False.\n\n        \"\"\"\n        html = self.export_html(\n            theme=theme,\n            clear=clear,\n            code_format=code_format,\n            inline_styles=inline_styles,\n        )\n        with open(path, \"w\", encoding=\"utf-8\") as write_file:\n            write_file.write(html)\n\n    def export_svg(\n        self,\n        *,\n        title: str = \"Rich\",\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_SVG_FORMAT,\n        font_aspect_ratio: float = 0.61,\n        unique_id: Optional[str] = None,\n    ) -> str:\n        \"\"\"\n        Generate an SVG from the console contents (requires record=True in Console constructor).\n\n        Args:\n            title (str, optional): The title of the tab in the output image\n            theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``\n            code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables\n                into the string in order to form the final SVG output. The default template used and the variables\n                injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.\n            font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``\n                string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).\n                If you aren't specifying a different font inside ``code_format``, you probably don't need this.\n            unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node\n                ids). If not set, this defaults to a computed value based on the recorded content.\n        \"\"\"\n\n        from pip._vendor.rich.cells import cell_len\n\n        style_cache: Dict[Style, str] = {}\n\n        def get_svg_style(style: Style) -> str:\n            \"\"\"Convert a Style to CSS rules for SVG.\"\"\"\n            if style in style_cache:\n                return style_cache[style]\n            css_rules = []\n            color = (\n                _theme.foreground_color\n                if (style.color is None or style.color.is_default)\n                else style.color.get_truecolor(_theme)\n            )\n            bgcolor = (\n                _theme.background_color\n                if (style.bgcolor is None or style.bgcolor.is_default)\n                else style.bgcolor.get_truecolor(_theme)\n            )\n            if style.reverse:\n                color, bgcolor = bgcolor, color\n            if style.dim:\n                color = blend_rgb(color, bgcolor, 0.4)\n            css_rules.append(f\"fill: {color.hex}\")\n            if style.bold:\n                css_rules.append(\"font-weight: bold\")\n            if style.italic:\n                css_rules.append(\"font-style: italic;\")\n            if style.underline:\n                css_rules.append(\"text-decoration: underline;\")\n            if style.strike:\n                css_rules.append(\"text-decoration: line-through;\")\n\n            css = \";\".join(css_rules)\n            style_cache[style] = css\n            return css\n\n        _theme = theme or SVG_EXPORT_THEME\n\n        width = self.width\n        char_height = 20\n        char_width = char_height * font_aspect_ratio\n        line_height = char_height * 1.22\n\n        margin_top = 1\n        margin_right = 1\n        margin_bottom = 1\n        margin_left = 1\n\n        padding_top = 40\n        padding_right = 8\n        padding_bottom = 8\n        padding_left = 8\n\n        padding_width = padding_left + padding_right\n        padding_height = padding_top + padding_bottom\n        margin_width = margin_left + margin_right\n        margin_height = margin_top + margin_bottom\n\n        text_backgrounds: List[str] = []\n        text_group: List[str] = []\n        classes: Dict[str, int] = {}\n        style_no = 1\n\n        def escape_text(text: str) -> str:\n            \"\"\"HTML escape text and replace spaces with nbsp.\"\"\"\n            return escape(text).replace(\" \", \"&#160;\")\n\n        def make_tag(\n            name: str, content: Optional[str] = None, **attribs: object\n        ) -> str:\n            \"\"\"Make a tag from name, content, and attributes.\"\"\"\n\n            def stringify(value: object) -> str:\n                if isinstance(value, (float)):\n                    return format(value, \"g\")\n                return str(value)\n\n            tag_attribs = \" \".join(\n                f'{k.lstrip(\"_\").replace(\"_\", \"-\")}=\"{stringify(v)}\"'\n                for k, v in attribs.items()\n            )\n            return (\n                f\"<{name} {tag_attribs}>{content}</{name}>\"\n                if content\n                else f\"<{name} {tag_attribs}/>\"\n            )\n\n        with self._record_buffer_lock:\n            segments = list(Segment.filter_control(self._record_buffer))\n            if clear:\n                self._record_buffer.clear()\n\n        if unique_id is None:\n            unique_id = \"terminal-\" + str(\n                zlib.adler32(\n                    (\"\".join(repr(segment) for segment in segments)).encode(\n                        \"utf-8\",\n                        \"ignore\",\n                    )\n                    + title.encode(\"utf-8\", \"ignore\")\n                )\n            )\n        y = 0\n        for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):\n            x = 0\n            for text, style, _control in line:\n                style = style or Style()\n                rules = get_svg_style(style)\n                if rules not in classes:\n                    classes[rules] = style_no\n                    style_no += 1\n                class_name = f\"r{classes[rules]}\"\n\n                if style.reverse:\n                    has_background = True\n                    background = (\n                        _theme.foreground_color.hex\n                        if style.color is None\n                        else style.color.get_truecolor(_theme).hex\n                    )\n                else:\n                    bgcolor = style.bgcolor\n                    has_background = bgcolor is not None and not bgcolor.is_default\n                    background = (\n                        _theme.background_color.hex\n                        if style.bgcolor is None\n                        else style.bgcolor.get_truecolor(_theme).hex\n                    )\n\n                text_length = cell_len(text)\n                if has_background:\n                    text_backgrounds.append(\n                        make_tag(\n                            \"rect\",\n                            fill=background,\n                            x=x * char_width,\n                            y=y * line_height + 1.5,\n                            width=char_width * text_length,\n                            height=line_height + 0.25,\n                            shape_rendering=\"crispEdges\",\n                        )\n                    )\n\n                if text != \" \" * len(text):\n                    text_group.append(\n                        make_tag(\n                            \"text\",\n                            escape_text(text),\n                            _class=f\"{unique_id}-{class_name}\",\n                            x=x * char_width,\n                            y=y * line_height + char_height,\n                            textLength=char_width * len(text),\n                            clip_path=f\"url(#{unique_id}-line-{y})\",\n                        )\n                    )\n                x += cell_len(text)\n\n        line_offsets = [line_no * line_height + 1.5 for line_no in range(y)]\n        lines = \"\\n\".join(\n            f\"\"\"<clipPath id=\"{unique_id}-line-{line_no}\">\n    {make_tag(\"rect\", x=0, y=offset, width=char_width * width, height=line_height + 0.25)}\n            </clipPath>\"\"\"\n            for line_no, offset in enumerate(line_offsets)\n        )\n\n        styles = \"\\n\".join(\n            f\".{unique_id}-r{rule_no} {{ {css} }}\" for css, rule_no in classes.items()\n        )\n        backgrounds = \"\".join(text_backgrounds)\n        matrix = \"\".join(text_group)\n\n        terminal_width = ceil(width * char_width + padding_width)\n        terminal_height = (y + 1) * line_height + padding_height\n        chrome = make_tag(\n            \"rect\",\n            fill=_theme.background_color.hex,\n            stroke=\"rgba(255,255,255,0.35)\",\n            stroke_width=\"1\",\n            x=margin_left,\n            y=margin_top,\n            width=terminal_width,\n            height=terminal_height,\n            rx=8,\n        )\n\n        title_color = _theme.foreground_color.hex\n        if title:\n            chrome += make_tag(\n                \"text\",\n                escape_text(title),\n                _class=f\"{unique_id}-title\",\n                fill=title_color,\n                text_anchor=\"middle\",\n                x=terminal_width // 2,\n                y=margin_top + char_height + 6,\n            )\n        chrome += f\"\"\"\n            <g transform=\"translate(26,22)\">\n            <circle cx=\"0\" cy=\"0\" r=\"7\" fill=\"#ff5f57\"/>\n            <circle cx=\"22\" cy=\"0\" r=\"7\" fill=\"#febc2e\"/>\n            <circle cx=\"44\" cy=\"0\" r=\"7\" fill=\"#28c840\"/>\n            </g>\n        \"\"\"\n\n        svg = code_format.format(\n            unique_id=unique_id,\n            char_width=char_width,\n            char_height=char_height,\n            line_height=line_height,\n            terminal_width=char_width * width - 1,\n            terminal_height=(y + 1) * line_height - 1,\n            width=terminal_width + margin_width,\n            height=terminal_height + margin_height,\n            terminal_x=margin_left + padding_left,\n            terminal_y=margin_top + padding_top,\n            styles=styles,\n            chrome=chrome,\n            backgrounds=backgrounds,\n            matrix=matrix,\n            lines=lines,\n        )\n        return svg\n\n    def save_svg(\n        self,\n        path: str,\n        *,\n        title: str = \"Rich\",\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_SVG_FORMAT,\n        font_aspect_ratio: float = 0.61,\n        unique_id: Optional[str] = None,\n    ) -> None:\n        \"\"\"Generate an SVG file from the console contents (requires record=True in Console constructor).\n\n        Args:\n            path (str): The path to write the SVG to.\n            title (str, optional): The title of the tab in the output image\n            theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``\n            code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables\n                into the string in order to form the final SVG output. The default template used and the variables\n                injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.\n            font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``\n                string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).\n                If you aren't specifying a different font inside ``code_format``, you probably don't need this.\n            unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node\n                ids). If not set, this defaults to a computed value based on the recorded content.\n        \"\"\"\n        svg = self.export_svg(\n            title=title,\n            theme=theme,\n            clear=clear,\n            code_format=code_format,\n            font_aspect_ratio=font_aspect_ratio,\n            unique_id=unique_id,\n        )\n        with open(path, \"w\", encoding=\"utf-8\") as write_file:\n            write_file.write(svg)\n\n\ndef _svg_hash(svg_main_code: str) -> str:\n    \"\"\"Returns a unique hash for the given SVG main code.\n\n    Args:\n        svg_main_code (str): The content we're going to inject in the SVG envelope.\n\n    Returns:\n        str: a hash of the given content\n    \"\"\"\n    return str(zlib.adler32(svg_main_code.encode()))\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    console = Console(record=True)\n\n    console.log(\n        \"JSONRPC [i]request[/i]\",\n        5,\n        1.3,\n        True,\n        False,\n        None,\n        {\n            \"jsonrpc\": \"2.0\",\n            \"method\": \"subtract\",\n            \"params\": {\"minuend\": 42, \"subtrahend\": 23},\n            \"id\": 3,\n        },\n    )\n\n    console.log(\"Hello, World!\", \"{'a': 1}\", repr(console))\n\n    console.print(\n        {\n            \"name\": None,\n            \"empty\": [],\n            \"quiz\": {\n                \"sport\": {\n                    \"answered\": True,\n                    \"q1\": {\n                        \"question\": \"Which one is correct team name in NBA?\",\n                        \"options\": [\n                            \"New York Bulls\",\n                            \"Los Angeles Kings\",\n                            \"Golden State Warriors\",\n                            \"Huston Rocket\",\n                        ],\n                        \"answer\": \"Huston Rocket\",\n                    },\n                },\n                \"maths\": {\n                    \"answered\": False,\n                    \"q1\": {\n                        \"question\": \"5 + 7 = ?\",\n                        \"options\": [10, 11, 12, 13],\n                        \"answer\": 12,\n                    },\n                    \"q2\": {\n                        \"question\": \"12 - 8 = ?\",\n                        \"options\": [1, 2, 3, 4],\n                        \"answer\": 4,\n                    },\n                },\n            },\n        }\n    )\n"
  },
  {
    "path": "src/pip/_vendor/rich/constrain.py",
    "content": "from typing import Optional, TYPE_CHECKING\n\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\n\nclass Constrain(JupyterMixin):\n    \"\"\"Constrain the width of a renderable to a given number of characters.\n\n    Args:\n        renderable (RenderableType): A renderable object.\n        width (int, optional): The maximum width (in characters) to render. Defaults to 80.\n    \"\"\"\n\n    def __init__(self, renderable: \"RenderableType\", width: Optional[int] = 80) -> None:\n        self.renderable = renderable\n        self.width = width\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.width is None:\n            yield self.renderable\n        else:\n            child_options = options.update_width(min(self.width, options.max_width))\n            yield from console.render(self.renderable, child_options)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        if self.width is not None:\n            options = options.update_width(self.width)\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n"
  },
  {
    "path": "src/pip/_vendor/rich/containers.py",
    "content": "from itertools import zip_longest\nfrom typing import (\n    TYPE_CHECKING,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    TypeVar,\n    Union,\n    overload,\n)\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        JustifyMethod,\n        OverflowMethod,\n        RenderResult,\n        RenderableType,\n    )\n    from .text import Text\n\nfrom .cells import cell_len\nfrom .measure import Measurement\n\nT = TypeVar(\"T\")\n\n\nclass Renderables:\n    \"\"\"A list subclass which renders its contents to the console.\"\"\"\n\n    def __init__(\n        self, renderables: Optional[Iterable[\"RenderableType\"]] = None\n    ) -> None:\n        self._renderables: List[\"RenderableType\"] = (\n            list(renderables) if renderables is not None else []\n        )\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        \"\"\"Console render method to insert line-breaks.\"\"\"\n        yield from self._renderables\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        dimensions = [\n            Measurement.get(console, options, renderable)\n            for renderable in self._renderables\n        ]\n        if not dimensions:\n            return Measurement(1, 1)\n        _min = max(dimension.minimum for dimension in dimensions)\n        _max = max(dimension.maximum for dimension in dimensions)\n        return Measurement(_min, _max)\n\n    def append(self, renderable: \"RenderableType\") -> None:\n        self._renderables.append(renderable)\n\n    def __iter__(self) -> Iterable[\"RenderableType\"]:\n        return iter(self._renderables)\n\n\nclass Lines:\n    \"\"\"A list subclass which can render to the console.\"\"\"\n\n    def __init__(self, lines: Iterable[\"Text\"] = ()) -> None:\n        self._lines: List[\"Text\"] = list(lines)\n\n    def __repr__(self) -> str:\n        return f\"Lines({self._lines!r})\"\n\n    def __iter__(self) -> Iterator[\"Text\"]:\n        return iter(self._lines)\n\n    @overload\n    def __getitem__(self, index: int) -> \"Text\":\n        ...\n\n    @overload\n    def __getitem__(self, index: slice) -> List[\"Text\"]:\n        ...\n\n    def __getitem__(self, index: Union[slice, int]) -> Union[\"Text\", List[\"Text\"]]:\n        return self._lines[index]\n\n    def __setitem__(self, index: int, value: \"Text\") -> \"Lines\":\n        self._lines[index] = value\n        return self\n\n    def __len__(self) -> int:\n        return self._lines.__len__()\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        \"\"\"Console render method to insert line-breaks.\"\"\"\n        yield from self._lines\n\n    def append(self, line: \"Text\") -> None:\n        self._lines.append(line)\n\n    def extend(self, lines: Iterable[\"Text\"]) -> None:\n        self._lines.extend(lines)\n\n    def pop(self, index: int = -1) -> \"Text\":\n        return self._lines.pop(index)\n\n    def justify(\n        self,\n        console: \"Console\",\n        width: int,\n        justify: \"JustifyMethod\" = \"left\",\n        overflow: \"OverflowMethod\" = \"fold\",\n    ) -> None:\n        \"\"\"Justify and overflow text to a given width.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Number of cells available per line.\n            justify (str, optional): Default justify method for text: \"left\", \"center\", \"full\" or \"right\". Defaults to \"left\".\n            overflow (str, optional): Default overflow for text: \"crop\", \"fold\", or \"ellipsis\". Defaults to \"fold\".\n\n        \"\"\"\n        from .text import Text\n\n        if justify == \"left\":\n            for line in self._lines:\n                line.truncate(width, overflow=overflow, pad=True)\n        elif justify == \"center\":\n            for line in self._lines:\n                line.rstrip()\n                line.truncate(width, overflow=overflow)\n                line.pad_left((width - cell_len(line.plain)) // 2)\n                line.pad_right(width - cell_len(line.plain))\n        elif justify == \"right\":\n            for line in self._lines:\n                line.rstrip()\n                line.truncate(width, overflow=overflow)\n                line.pad_left(width - cell_len(line.plain))\n        elif justify == \"full\":\n            for line_index, line in enumerate(self._lines):\n                if line_index == len(self._lines) - 1:\n                    break\n                words = line.split(\" \")\n                words_size = sum(cell_len(word.plain) for word in words)\n                num_spaces = len(words) - 1\n                spaces = [1 for _ in range(num_spaces)]\n                index = 0\n                if spaces:\n                    while words_size + num_spaces < width:\n                        spaces[len(spaces) - index - 1] += 1\n                        num_spaces += 1\n                        index = (index + 1) % len(spaces)\n                tokens: List[Text] = []\n                for index, (word, next_word) in enumerate(\n                    zip_longest(words, words[1:])\n                ):\n                    tokens.append(word)\n                    if index < len(spaces):\n                        style = word.get_style_at_offset(console, -1)\n                        next_style = next_word.get_style_at_offset(console, 0)\n                        space_style = style if style == next_style else line.style\n                        tokens.append(Text(\" \" * spaces[index], style=space_style))\n                self[line_index] = Text(\"\").join(tokens)\n"
  },
  {
    "path": "src/pip/_vendor/rich/control.py",
    "content": "import time\nfrom typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final\n\nfrom .segment import ControlCode, ControlType, Segment\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\nSTRIP_CONTROL_CODES: Final = [\n    7,  # Bell\n    8,  # Backspace\n    11,  # Vertical tab\n    12,  # Form feed\n    13,  # Carriage return\n]\n_CONTROL_STRIP_TRANSLATE: Final = {\n    _codepoint: None for _codepoint in STRIP_CONTROL_CODES\n}\n\nCONTROL_ESCAPE: Final = {\n    7: \"\\\\a\",\n    8: \"\\\\b\",\n    11: \"\\\\v\",\n    12: \"\\\\f\",\n    13: \"\\\\r\",\n}\n\nCONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = {\n    ControlType.BELL: lambda: \"\\x07\",\n    ControlType.CARRIAGE_RETURN: lambda: \"\\r\",\n    ControlType.HOME: lambda: \"\\x1b[H\",\n    ControlType.CLEAR: lambda: \"\\x1b[2J\",\n    ControlType.ENABLE_ALT_SCREEN: lambda: \"\\x1b[?1049h\",\n    ControlType.DISABLE_ALT_SCREEN: lambda: \"\\x1b[?1049l\",\n    ControlType.SHOW_CURSOR: lambda: \"\\x1b[?25h\",\n    ControlType.HIDE_CURSOR: lambda: \"\\x1b[?25l\",\n    ControlType.CURSOR_UP: lambda param: f\"\\x1b[{param}A\",\n    ControlType.CURSOR_DOWN: lambda param: f\"\\x1b[{param}B\",\n    ControlType.CURSOR_FORWARD: lambda param: f\"\\x1b[{param}C\",\n    ControlType.CURSOR_BACKWARD: lambda param: f\"\\x1b[{param}D\",\n    ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f\"\\x1b[{param+1}G\",\n    ControlType.ERASE_IN_LINE: lambda param: f\"\\x1b[{param}K\",\n    ControlType.CURSOR_MOVE_TO: lambda x, y: f\"\\x1b[{y+1};{x+1}H\",\n    ControlType.SET_WINDOW_TITLE: lambda title: f\"\\x1b]0;{title}\\x07\",\n}\n\n\nclass Control:\n    \"\"\"A renderable that inserts a control code (non printable but may move cursor).\n\n    Args:\n        *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a\n            tuple of ControlType and an integer parameter\n    \"\"\"\n\n    __slots__ = [\"segment\"]\n\n    def __init__(self, *codes: Union[ControlType, ControlCode]) -> None:\n        control_codes: List[ControlCode] = [\n            (code,) if isinstance(code, ControlType) else code for code in codes\n        ]\n        _format_map = CONTROL_CODES_FORMAT\n        rendered_codes = \"\".join(\n            _format_map[code](*parameters) for code, *parameters in control_codes\n        )\n        self.segment = Segment(rendered_codes, None, control_codes)\n\n    @classmethod\n    def bell(cls) -> \"Control\":\n        \"\"\"Ring the 'bell'.\"\"\"\n        return cls(ControlType.BELL)\n\n    @classmethod\n    def home(cls) -> \"Control\":\n        \"\"\"Move cursor to 'home' position.\"\"\"\n        return cls(ControlType.HOME)\n\n    @classmethod\n    def move(cls, x: int = 0, y: int = 0) -> \"Control\":\n        \"\"\"Move cursor relative to current position.\n\n        Args:\n            x (int): X offset.\n            y (int): Y offset.\n\n        Returns:\n            ~Control: Control object.\n\n        \"\"\"\n\n        def get_codes() -> Iterable[ControlCode]:\n            control = ControlType\n            if x:\n                yield (\n                    control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD,\n                    abs(x),\n                )\n            if y:\n                yield (\n                    control.CURSOR_DOWN if y > 0 else control.CURSOR_UP,\n                    abs(y),\n                )\n\n        control = cls(*get_codes())\n        return control\n\n    @classmethod\n    def move_to_column(cls, x: int, y: int = 0) -> \"Control\":\n        \"\"\"Move to the given column, optionally add offset to row.\n\n        Returns:\n            x (int): absolute x (column)\n            y (int): optional y offset (row)\n\n        Returns:\n            ~Control: Control object.\n        \"\"\"\n\n        return (\n            cls(\n                (ControlType.CURSOR_MOVE_TO_COLUMN, x),\n                (\n                    ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP,\n                    abs(y),\n                ),\n            )\n            if y\n            else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x))\n        )\n\n    @classmethod\n    def move_to(cls, x: int, y: int) -> \"Control\":\n        \"\"\"Move cursor to absolute position.\n\n        Args:\n            x (int): x offset (column)\n            y (int): y offset (row)\n\n        Returns:\n            ~Control: Control object.\n        \"\"\"\n        return cls((ControlType.CURSOR_MOVE_TO, x, y))\n\n    @classmethod\n    def clear(cls) -> \"Control\":\n        \"\"\"Clear the screen.\"\"\"\n        return cls(ControlType.CLEAR)\n\n    @classmethod\n    def show_cursor(cls, show: bool) -> \"Control\":\n        \"\"\"Show or hide the cursor.\"\"\"\n        return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR)\n\n    @classmethod\n    def alt_screen(cls, enable: bool) -> \"Control\":\n        \"\"\"Enable or disable alt screen.\"\"\"\n        if enable:\n            return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)\n        else:\n            return cls(ControlType.DISABLE_ALT_SCREEN)\n\n    @classmethod\n    def title(cls, title: str) -> \"Control\":\n        \"\"\"Set the terminal window title\n\n        Args:\n            title (str): The new terminal window title\n        \"\"\"\n        return cls((ControlType.SET_WINDOW_TITLE, title))\n\n    def __str__(self) -> str:\n        return self.segment.text\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.segment.text:\n            yield self.segment\n\n\ndef strip_control_codes(\n    text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE\n) -> str:\n    \"\"\"Remove control codes from text.\n\n    Args:\n        text (str): A string possibly contain control codes.\n\n    Returns:\n        str: String with control codes removed.\n    \"\"\"\n    return text.translate(_translate_table)\n\n\ndef escape_control_codes(\n    text: str,\n    _translate_table: Dict[int, str] = CONTROL_ESCAPE,\n) -> str:\n    \"\"\"Replace control codes with their \"escaped\" equivalent in the given text.\n    (e.g. \"\\b\" becomes \"\\\\b\")\n\n    Args:\n        text (str): A string possibly containing control codes.\n\n    Returns:\n        str: String with control codes replaced with their escaped version.\n    \"\"\"\n    return text.translate(_translate_table)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    console.print(\"Look at the title of your terminal window ^\")\n    # console.print(Control((ControlType.SET_WINDOW_TITLE, \"Hello, world!\")))\n    for i in range(10):\n        console.set_window_title(\"🚀 Loading\" + \".\" * i)\n        time.sleep(0.5)\n"
  },
  {
    "path": "src/pip/_vendor/rich/default_styles.py",
    "content": "from typing import Dict\n\nfrom .style import Style\n\nDEFAULT_STYLES: Dict[str, Style] = {\n    \"none\": Style.null(),\n    \"reset\": Style(\n        color=\"default\",\n        bgcolor=\"default\",\n        dim=False,\n        bold=False,\n        italic=False,\n        underline=False,\n        blink=False,\n        blink2=False,\n        reverse=False,\n        conceal=False,\n        strike=False,\n    ),\n    \"dim\": Style(dim=True),\n    \"bright\": Style(dim=False),\n    \"bold\": Style(bold=True),\n    \"strong\": Style(bold=True),\n    \"code\": Style(reverse=True, bold=True),\n    \"italic\": Style(italic=True),\n    \"emphasize\": Style(italic=True),\n    \"underline\": Style(underline=True),\n    \"blink\": Style(blink=True),\n    \"blink2\": Style(blink2=True),\n    \"reverse\": Style(reverse=True),\n    \"strike\": Style(strike=True),\n    \"black\": Style(color=\"black\"),\n    \"red\": Style(color=\"red\"),\n    \"green\": Style(color=\"green\"),\n    \"yellow\": Style(color=\"yellow\"),\n    \"magenta\": Style(color=\"magenta\"),\n    \"cyan\": Style(color=\"cyan\"),\n    \"white\": Style(color=\"white\"),\n    \"inspect.attr\": Style(color=\"yellow\", italic=True),\n    \"inspect.attr.dunder\": Style(color=\"yellow\", italic=True, dim=True),\n    \"inspect.callable\": Style(bold=True, color=\"red\"),\n    \"inspect.async_def\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.def\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.class\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.error\": Style(bold=True, color=\"red\"),\n    \"inspect.equals\": Style(),\n    \"inspect.help\": Style(color=\"cyan\"),\n    \"inspect.doc\": Style(dim=True),\n    \"inspect.value.border\": Style(color=\"green\"),\n    \"live.ellipsis\": Style(bold=True, color=\"red\"),\n    \"layout.tree.row\": Style(dim=False, color=\"red\"),\n    \"layout.tree.column\": Style(dim=False, color=\"blue\"),\n    \"logging.keyword\": Style(bold=True, color=\"yellow\"),\n    \"logging.level.notset\": Style(dim=True),\n    \"logging.level.debug\": Style(color=\"green\"),\n    \"logging.level.info\": Style(color=\"blue\"),\n    \"logging.level.warning\": Style(color=\"yellow\"),\n    \"logging.level.error\": Style(color=\"red\", bold=True),\n    \"logging.level.critical\": Style(color=\"red\", bold=True, reverse=True),\n    \"log.level\": Style.null(),\n    \"log.time\": Style(color=\"cyan\", dim=True),\n    \"log.message\": Style.null(),\n    \"log.path\": Style(dim=True),\n    \"repr.ellipsis\": Style(color=\"yellow\"),\n    \"repr.indent\": Style(color=\"green\", dim=True),\n    \"repr.error\": Style(color=\"red\", bold=True),\n    \"repr.str\": Style(color=\"green\", italic=False, bold=False),\n    \"repr.brace\": Style(bold=True),\n    \"repr.comma\": Style(bold=True),\n    \"repr.ipv4\": Style(bold=True, color=\"bright_green\"),\n    \"repr.ipv6\": Style(bold=True, color=\"bright_green\"),\n    \"repr.eui48\": Style(bold=True, color=\"bright_green\"),\n    \"repr.eui64\": Style(bold=True, color=\"bright_green\"),\n    \"repr.tag_start\": Style(bold=True),\n    \"repr.tag_name\": Style(color=\"bright_magenta\", bold=True),\n    \"repr.tag_contents\": Style(color=\"default\"),\n    \"repr.tag_end\": Style(bold=True),\n    \"repr.attrib_name\": Style(color=\"yellow\", italic=False),\n    \"repr.attrib_equal\": Style(bold=True),\n    \"repr.attrib_value\": Style(color=\"magenta\", italic=False),\n    \"repr.number\": Style(color=\"cyan\", bold=True, italic=False),\n    \"repr.number_complex\": Style(color=\"cyan\", bold=True, italic=False),  # same\n    \"repr.bool_true\": Style(color=\"bright_green\", italic=True),\n    \"repr.bool_false\": Style(color=\"bright_red\", italic=True),\n    \"repr.none\": Style(color=\"magenta\", italic=True),\n    \"repr.url\": Style(underline=True, color=\"bright_blue\", italic=False, bold=False),\n    \"repr.uuid\": Style(color=\"bright_yellow\", bold=False),\n    \"repr.call\": Style(color=\"magenta\", bold=True),\n    \"repr.path\": Style(color=\"magenta\"),\n    \"repr.filename\": Style(color=\"bright_magenta\"),\n    \"rule.line\": Style(color=\"bright_green\"),\n    \"rule.text\": Style.null(),\n    \"json.brace\": Style(bold=True),\n    \"json.bool_true\": Style(color=\"bright_green\", italic=True),\n    \"json.bool_false\": Style(color=\"bright_red\", italic=True),\n    \"json.null\": Style(color=\"magenta\", italic=True),\n    \"json.number\": Style(color=\"cyan\", bold=True, italic=False),\n    \"json.str\": Style(color=\"green\", italic=False, bold=False),\n    \"json.key\": Style(color=\"blue\", bold=True),\n    \"prompt\": Style.null(),\n    \"prompt.choices\": Style(color=\"magenta\", bold=True),\n    \"prompt.default\": Style(color=\"cyan\", bold=True),\n    \"prompt.invalid\": Style(color=\"red\"),\n    \"prompt.invalid.choice\": Style(color=\"red\"),\n    \"pretty\": Style.null(),\n    \"scope.border\": Style(color=\"blue\"),\n    \"scope.key\": Style(color=\"yellow\", italic=True),\n    \"scope.key.special\": Style(color=\"yellow\", italic=True, dim=True),\n    \"scope.equals\": Style(color=\"red\"),\n    \"table.header\": Style(bold=True),\n    \"table.footer\": Style(bold=True),\n    \"table.cell\": Style.null(),\n    \"table.title\": Style(italic=True),\n    \"table.caption\": Style(italic=True, dim=True),\n    \"traceback.error\": Style(color=\"red\", italic=True),\n    \"traceback.border.syntax_error\": Style(color=\"bright_red\"),\n    \"traceback.border\": Style(color=\"red\"),\n    \"traceback.text\": Style.null(),\n    \"traceback.title\": Style(color=\"red\", bold=True),\n    \"traceback.exc_type\": Style(color=\"bright_red\", bold=True),\n    \"traceback.exc_value\": Style.null(),\n    \"traceback.offset\": Style(color=\"bright_red\", bold=True),\n    \"traceback.error_range\": Style(underline=True, bold=True),\n    \"traceback.note\": Style(color=\"green\", bold=True),\n    \"traceback.group.border\": Style(color=\"magenta\"),\n    \"bar.back\": Style(color=\"grey23\"),\n    \"bar.complete\": Style(color=\"rgb(249,38,114)\"),\n    \"bar.finished\": Style(color=\"rgb(114,156,31)\"),\n    \"bar.pulse\": Style(color=\"rgb(249,38,114)\"),\n    \"progress.description\": Style.null(),\n    \"progress.filesize\": Style(color=\"green\"),\n    \"progress.filesize.total\": Style(color=\"green\"),\n    \"progress.download\": Style(color=\"green\"),\n    \"progress.elapsed\": Style(color=\"yellow\"),\n    \"progress.percentage\": Style(color=\"magenta\"),\n    \"progress.remaining\": Style(color=\"cyan\"),\n    \"progress.data.speed\": Style(color=\"red\"),\n    \"progress.spinner\": Style(color=\"green\"),\n    \"status.spinner\": Style(color=\"green\"),\n    \"tree\": Style(),\n    \"tree.line\": Style(),\n    \"markdown.paragraph\": Style(),\n    \"markdown.text\": Style(),\n    \"markdown.em\": Style(italic=True),\n    \"markdown.emph\": Style(italic=True),  # For commonmark backwards compatibility\n    \"markdown.strong\": Style(bold=True),\n    \"markdown.code\": Style(bold=True, color=\"cyan\", bgcolor=\"black\"),\n    \"markdown.code_block\": Style(color=\"cyan\", bgcolor=\"black\"),\n    \"markdown.block_quote\": Style(color=\"magenta\"),\n    \"markdown.list\": Style(color=\"cyan\"),\n    \"markdown.item\": Style(),\n    \"markdown.item.bullet\": Style(color=\"yellow\", bold=True),\n    \"markdown.item.number\": Style(color=\"yellow\", bold=True),\n    \"markdown.hr\": Style(color=\"yellow\"),\n    \"markdown.h1.border\": Style(),\n    \"markdown.h1\": Style(bold=True),\n    \"markdown.h2\": Style(bold=True, underline=True),\n    \"markdown.h3\": Style(bold=True),\n    \"markdown.h4\": Style(bold=True, dim=True),\n    \"markdown.h5\": Style(underline=True),\n    \"markdown.h6\": Style(italic=True),\n    \"markdown.h7\": Style(italic=True, dim=True),\n    \"markdown.link\": Style(color=\"bright_blue\"),\n    \"markdown.link_url\": Style(color=\"blue\", underline=True),\n    \"markdown.s\": Style(strike=True),\n    \"iso8601.date\": Style(color=\"blue\"),\n    \"iso8601.time\": Style(color=\"magenta\"),\n    \"iso8601.timezone\": Style(color=\"yellow\"),\n}\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import argparse\n    import io\n\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.table import Table\n    from pip._vendor.rich.text import Text\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--html\", action=\"store_true\", help=\"Export as HTML table\")\n    args = parser.parse_args()\n    html: bool = args.html\n    console = Console(record=True, width=70, file=io.StringIO()) if html else Console()\n\n    table = Table(\"Name\", \"Styling\")\n\n    for style_name, style in DEFAULT_STYLES.items():\n        table.add_row(Text(style_name, style=style), str(style))\n\n    console.print(table)\n    if html:\n        print(console.export_html(inline_styles=True))\n"
  },
  {
    "path": "src/pip/_vendor/rich/diagnose.py",
    "content": "import os\nimport platform\n\nfrom pip._vendor.rich import inspect\nfrom pip._vendor.rich.console import Console, get_windows_console_features\nfrom pip._vendor.rich.panel import Panel\nfrom pip._vendor.rich.pretty import Pretty\n\n\ndef report() -> None:  # pragma: no cover\n    \"\"\"Print a report to the terminal with debugging information\"\"\"\n    console = Console()\n    inspect(console)\n    features = get_windows_console_features()\n    inspect(features)\n\n    env_names = (\n        \"CLICOLOR\",\n        \"COLORTERM\",\n        \"COLUMNS\",\n        \"JPY_PARENT_PID\",\n        \"JUPYTER_COLUMNS\",\n        \"JUPYTER_LINES\",\n        \"LINES\",\n        \"NO_COLOR\",\n        \"TERM_PROGRAM\",\n        \"TERM\",\n        \"TTY_COMPATIBLE\",\n        \"TTY_INTERACTIVE\",\n        \"VSCODE_VERBOSE_LOGGING\",\n    )\n    env = {name: os.getenv(name) for name in env_names}\n    console.print(Panel.fit((Pretty(env)), title=\"[b]Environment Variables\"))\n\n    console.print(f'platform=\"{platform.system()}\"')\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    report()\n"
  },
  {
    "path": "src/pip/_vendor/rich/emoji.py",
    "content": "import sys\nfrom typing import TYPE_CHECKING, Optional, Union, Literal\n\nfrom .jupyter import JupyterMixin\nfrom .segment import Segment\nfrom .style import Style\nfrom ._emoji_codes import EMOJI\nfrom ._emoji_replace import _emoji_replace\n\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\n\nEmojiVariant = Literal[\"emoji\", \"text\"]\n\n\nclass NoEmoji(Exception):\n    \"\"\"No emoji by that name.\"\"\"\n\n\nclass Emoji(JupyterMixin):\n    __slots__ = [\"name\", \"style\", \"_char\", \"variant\"]\n\n    VARIANTS = {\"text\": \"\\uFE0E\", \"emoji\": \"\\uFE0F\"}\n\n    def __init__(\n        self,\n        name: str,\n        style: Union[str, Style] = \"none\",\n        variant: Optional[EmojiVariant] = None,\n    ) -> None:\n        \"\"\"A single emoji character.\n\n        Args:\n            name (str): Name of emoji.\n            style (Union[str, Style], optional): Optional style. Defaults to None.\n\n        Raises:\n            NoEmoji: If the emoji doesn't exist.\n        \"\"\"\n        self.name = name\n        self.style = style\n        self.variant = variant\n        try:\n            self._char = EMOJI[name]\n        except KeyError:\n            raise NoEmoji(f\"No emoji called {name!r}\")\n        if variant is not None:\n            self._char += self.VARIANTS.get(variant, \"\")\n\n    @classmethod\n    def replace(cls, text: str) -> str:\n        \"\"\"Replace emoji markup with corresponding unicode characters.\n\n        Args:\n            text (str): A string with emojis codes, e.g. \"Hello :smiley:!\"\n\n        Returns:\n            str: A string with emoji codes replaces with actual emoji.\n        \"\"\"\n        return _emoji_replace(text)\n\n    def __repr__(self) -> str:\n        return f\"<emoji {self.name!r}>\"\n\n    def __str__(self) -> str:\n        return self._char\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        yield Segment(self._char, console.get_style(self.style))\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sys\n\n    from pip._vendor.rich.columns import Columns\n    from pip._vendor.rich.console import Console\n\n    console = Console(record=True)\n\n    columns = Columns(\n        (f\":{name}: {name}\" for name in sorted(EMOJI.keys()) if \"\\u200D\" not in name),\n        column_first=True,\n    )\n\n    console.print(columns)\n    if len(sys.argv) > 1:\n        console.save_html(sys.argv[1])\n"
  },
  {
    "path": "src/pip/_vendor/rich/errors.py",
    "content": "class ConsoleError(Exception):\n    \"\"\"An error in console operation.\"\"\"\n\n\nclass StyleError(Exception):\n    \"\"\"An error in styles.\"\"\"\n\n\nclass StyleSyntaxError(ConsoleError):\n    \"\"\"Style was badly formatted.\"\"\"\n\n\nclass MissingStyle(StyleError):\n    \"\"\"No such style.\"\"\"\n\n\nclass StyleStackError(ConsoleError):\n    \"\"\"Style stack is invalid.\"\"\"\n\n\nclass NotRenderableError(ConsoleError):\n    \"\"\"Object is not renderable.\"\"\"\n\n\nclass MarkupError(ConsoleError):\n    \"\"\"Markup was badly formatted.\"\"\"\n\n\nclass LiveError(ConsoleError):\n    \"\"\"Error related to Live display.\"\"\"\n\n\nclass NoAltScreen(ConsoleError):\n    \"\"\"Alt screen mode was required.\"\"\"\n"
  },
  {
    "path": "src/pip/_vendor/rich/file_proxy.py",
    "content": "import io\nfrom typing import IO, TYPE_CHECKING, Any, List\n\nfrom .ansi import AnsiDecoder\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import Console\n\n\nclass FileProxy(io.TextIOBase):\n    \"\"\"Wraps a file (e.g. sys.stdout) and redirects writes to a console.\"\"\"\n\n    def __init__(self, console: \"Console\", file: IO[str]) -> None:\n        self.__console = console\n        self.__file = file\n        self.__buffer: List[str] = []\n        self.__ansi_decoder = AnsiDecoder()\n\n    @property\n    def rich_proxied_file(self) -> IO[str]:\n        \"\"\"Get proxied file.\"\"\"\n        return self.__file\n\n    def __getattr__(self, name: str) -> Any:\n        return getattr(self.__file, name)\n\n    def write(self, text: str) -> int:\n        if not isinstance(text, str):\n            raise TypeError(f\"write() argument must be str, not {type(text).__name__}\")\n        buffer = self.__buffer\n        lines: List[str] = []\n        while text:\n            line, new_line, text = text.partition(\"\\n\")\n            if new_line:\n                lines.append(\"\".join(buffer) + line)\n                buffer.clear()\n            else:\n                buffer.append(line)\n                break\n        if lines:\n            console = self.__console\n            with console:\n                output = Text(\"\\n\").join(\n                    self.__ansi_decoder.decode_line(line) for line in lines\n                )\n                console.print(output)\n        return len(text)\n\n    def flush(self) -> None:\n        output = \"\".join(self.__buffer)\n        if output:\n            self.__console.print(output)\n        del self.__buffer[:]\n\n    def fileno(self) -> int:\n        return self.__file.fileno()\n"
  },
  {
    "path": "src/pip/_vendor/rich/filesize.py",
    "content": "\"\"\"Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2\n\nThe functions declared in this module should cover the different\nuse cases needed to generate a string representation of a file size\nusing several different units. Since there are many standards regarding\nfile size units, three different functions have been implemented.\n\nSee Also:\n    * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_\n\n\"\"\"\n\n__all__ = [\"decimal\"]\n\nfrom typing import Iterable, List, Optional, Tuple\n\n\ndef _to_str(\n    size: int,\n    suffixes: Iterable[str],\n    base: int,\n    *,\n    precision: Optional[int] = 1,\n    separator: Optional[str] = \" \",\n) -> str:\n    if size == 1:\n        return \"1 byte\"\n    elif size < base:\n        return f\"{size:,} bytes\"\n\n    for i, suffix in enumerate(suffixes, 2):  # noqa: B007\n        unit = base**i\n        if size < unit:\n            break\n    return \"{:,.{precision}f}{separator}{}\".format(\n        (base * size / unit),\n        suffix,\n        precision=precision,\n        separator=separator,\n    )\n\n\ndef pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:\n    \"\"\"Pick a suffix and base for the given size.\"\"\"\n    for i, suffix in enumerate(suffixes):\n        unit = base**i\n        if size < unit * base:\n            break\n    return unit, suffix\n\n\ndef decimal(\n    size: int,\n    *,\n    precision: Optional[int] = 1,\n    separator: Optional[str] = \" \",\n) -> str:\n    \"\"\"Convert a filesize in to a string (powers of 1000, SI prefixes).\n\n    In this convention, ``1000 B = 1 kB``.\n\n    This is typically the format used to advertise the storage\n    capacity of USB flash drives and the like (*256 MB* meaning\n    actually a storage capacity of more than *256 000 000 B*),\n    or used by **Mac OS X** since v10.6 to report file sizes.\n\n    Arguments:\n        int (size): A file size.\n        int (precision): The number of decimal places to include (default = 1).\n        str (separator): The string to separate the value from the units (default = \" \").\n\n    Returns:\n        `str`: A string containing a abbreviated file size and units.\n\n    Example:\n        >>> filesize.decimal(30000)\n        '30.0 kB'\n        >>> filesize.decimal(30000, precision=2, separator=\"\")\n        '30.00kB'\n\n    \"\"\"\n    return _to_str(\n        size,\n        (\"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"),\n        1000,\n        precision=precision,\n        separator=separator,\n    )\n"
  },
  {
    "path": "src/pip/_vendor/rich/highlighter.py",
    "content": "import re\nfrom abc import ABC, abstractmethod\nfrom typing import List, Union\n\nfrom .text import Span, Text\n\n\ndef _combine_regex(*regexes: str) -> str:\n    \"\"\"Combine a number of regexes in to a single regex.\n\n    Returns:\n        str: New regex with all regexes ORed together.\n    \"\"\"\n    return \"|\".join(regexes)\n\n\nclass Highlighter(ABC):\n    \"\"\"Abstract base class for highlighters.\"\"\"\n\n    def __call__(self, text: Union[str, Text]) -> Text:\n        \"\"\"Highlight a str or Text instance.\n\n        Args:\n            text (Union[str, ~Text]): Text to highlight.\n\n        Raises:\n            TypeError: If not called with text or str.\n\n        Returns:\n            Text: A test instance with highlighting applied.\n        \"\"\"\n        if isinstance(text, str):\n            highlight_text = Text(text)\n        elif isinstance(text, Text):\n            highlight_text = text.copy()\n        else:\n            raise TypeError(f\"str or Text instance required, not {text!r}\")\n        self.highlight(highlight_text)\n        return highlight_text\n\n    @abstractmethod\n    def highlight(self, text: Text) -> None:\n        \"\"\"Apply highlighting in place to text.\n\n        Args:\n            text (~Text): A text object highlight.\n        \"\"\"\n\n\nclass NullHighlighter(Highlighter):\n    \"\"\"A highlighter object that doesn't highlight.\n\n    May be used to disable highlighting entirely.\n\n    \"\"\"\n\n    def highlight(self, text: Text) -> None:\n        \"\"\"Nothing to do\"\"\"\n\n\nclass RegexHighlighter(Highlighter):\n    \"\"\"Applies highlighting from a list of regular expressions.\"\"\"\n\n    highlights: List[str] = []\n    base_style: str = \"\"\n\n    def highlight(self, text: Text) -> None:\n        \"\"\"Highlight :class:`rich.text.Text` using regular expressions.\n\n        Args:\n            text (~Text): Text to highlighted.\n\n        \"\"\"\n\n        highlight_regex = text.highlight_regex\n        for re_highlight in self.highlights:\n            highlight_regex(re_highlight, style_prefix=self.base_style)\n\n\nclass ReprHighlighter(RegexHighlighter):\n    \"\"\"Highlights the text typically produced from ``__repr__`` methods.\"\"\"\n\n    base_style = \"repr.\"\n    highlights = [\n        r\"(?P<tag_start><)(?P<tag_name>[-\\w.:|]*)(?P<tag_contents>[\\w\\W]*)(?P<tag_end>>)\",\n        r'(?P<attrib_name>[\\w_]{1,50})=(?P<attrib_value>\"?[\\w_]+\"?)?',\n        r\"(?P<brace>[][{}()])\",\n        _combine_regex(\n            r\"(?P<ipv4>[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\",\n            r\"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})\",\n            r\"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\\.){3}[0-9A-Fa-f]{4})\",\n            r\"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})\",\n            r\"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\",\n            r\"(?P<call>[\\w.]*?)\\(\",\n            r\"\\b(?P<bool_true>True)\\b|\\b(?P<bool_false>False)\\b|\\b(?P<none>None)\\b\",\n            r\"(?P<ellipsis>\\.\\.\\.)\",\n            r\"(?P<number_complex>(?<!\\w)(?:\\-?[0-9]+\\.?[0-9]*(?:e[-+]?\\d+?)?)(?:[-+](?:[0-9]+\\.?[0-9]*(?:e[-+]?\\d+)?))?j)\",\n            r\"(?P<number>(?<!\\w)\\-?[0-9]+\\.?[0-9]*(e[-+]?\\d+?)?\\b|0x[0-9a-fA-F]*)\",\n            r\"(?P<path>\\B(/[-\\w._+]+)*\\/)(?P<filename>[-\\w._+]*)?\",\n            r\"(?<![\\\\\\w])(?P<str>b?'''.*?(?<!\\\\)'''|b?'.*?(?<!\\\\)'|b?\\\"\\\"\\\".*?(?<!\\\\)\\\"\\\"\\\"|b?\\\".*?(?<!\\\\)\\\")\",\n            r\"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)\",\n        ),\n    ]\n\n\nclass JSONHighlighter(RegexHighlighter):\n    \"\"\"Highlights JSON\"\"\"\n\n    # Captures the start and end of JSON strings, handling escaped quotes\n    JSON_STR = r\"(?<![\\\\\\w])(?P<str>b?\\\".*?(?<!\\\\)\\\")\"\n    JSON_WHITESPACE = {\" \", \"\\n\", \"\\r\", \"\\t\"}\n\n    base_style = \"json.\"\n    highlights = [\n        _combine_regex(\n            r\"(?P<brace>[\\{\\[\\(\\)\\]\\}])\",\n            r\"\\b(?P<bool_true>true)\\b|\\b(?P<bool_false>false)\\b|\\b(?P<null>null)\\b\",\n            r\"(?P<number>(?<!\\w)\\-?[0-9]+\\.?[0-9]*(e[\\-\\+]?\\d+?)?\\b|0x[0-9a-fA-F]*)\",\n            JSON_STR,\n        ),\n    ]\n\n    def highlight(self, text: Text) -> None:\n        super().highlight(text)\n\n        # Additional work to handle highlighting JSON keys\n        plain = text.plain\n        append = text.spans.append\n        whitespace = self.JSON_WHITESPACE\n        for match in re.finditer(self.JSON_STR, plain):\n            start, end = match.span()\n            cursor = end\n            while cursor < len(plain):\n                char = plain[cursor]\n                cursor += 1\n                if char == \":\":\n                    append(Span(start, end, \"json.key\"))\n                elif char in whitespace:\n                    continue\n                break\n\n\nclass ISO8601Highlighter(RegexHighlighter):\n    \"\"\"Highlights the ISO8601 date time strings.\n    Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html\n    \"\"\"\n\n    base_style = \"iso8601.\"\n    highlights = [\n        #\n        # Dates\n        #\n        # Calendar month (e.g. 2008-08). The hyphen is required\n        r\"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$\",\n        # Calendar date w/o hyphens (e.g. 20080830)\n        r\"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$\",\n        # Ordinal date (e.g. 2008-243). The hyphen is optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$\",\n        #\n        # Weeks\n        #\n        # Week of the year (e.g., 2008-W35). The hyphen is optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$\",\n        # Week date (e.g., 2008-W35-6). The hyphens are optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$\",\n        #\n        # Times\n        #\n        # Hours and minutes (e.g., 17:21). The colon is optional\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$\",\n        # Hours, minutes, and seconds w/o colons (e.g., 172159)\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$\",\n        # Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional\n        r\"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$\",\n        # Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00).\n        # All the colons are optional. The minutes in the time zone designator are also optional\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$\",\n        #\n        # Date and Time\n        #\n        # Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159).\n        # A space is required between the date and the time. The hyphens and colons are optional.\n        # This regex matches dates and times that specify some hyphens or colons but omit others.\n        # This does not follow ISO 8601\n        r\"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$\",\n        #\n        # XML Schema dates and times\n        #\n        # Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00).\n        # Hyphens are required. This is the XML Schema 'date' type\n        r\"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n        # Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00).\n        # There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n        # Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z).\n        # This is the XML Schema 'dateTime' type\n        r\"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n    ]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    console = Console()\n    console.print(\"[bold green]hello world![/bold green]\")\n    console.print(\"'[bold green]hello world![/bold green]'\")\n\n    console.print(\" /foo\")\n    console.print(\"/foo/\")\n    console.print(\"/foo/bar\")\n    console.print(\"foo/bar/baz\")\n\n    console.print(\"/foo/bar/baz?foo=bar+egg&egg=baz\")\n    console.print(\"/foo/bar/baz/\")\n    console.print(\"/foo/bar/baz/egg\")\n    console.print(\"/foo/bar/baz/egg.py\")\n    console.print(\"/foo/bar/baz/egg.py word\")\n    console.print(\" /foo/bar/baz/egg.py word\")\n    console.print(\"foo /foo/bar/baz/egg.py word\")\n    console.print(\"foo /foo/bar/ba._++z/egg+.py word\")\n    console.print(\"https://example.org?foo=bar#header\")\n\n    console.print(1234567.34)\n    console.print(1 / 2)\n    console.print(-1 / 123123123123)\n\n    console.print(\n        \"127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo\"\n    )\n    import json\n\n    console.print_json(json.dumps(obj={\"name\": \"apple\", \"count\": 1}), indent=None)\n"
  },
  {
    "path": "src/pip/_vendor/rich/json.py",
    "content": "from pathlib import Path\nfrom json import loads, dumps\nfrom typing import Any, Callable, Optional, Union\n\nfrom .text import Text\nfrom .highlighter import JSONHighlighter, NullHighlighter\n\n\nclass JSON:\n    \"\"\"A renderable which pretty prints JSON.\n\n    Args:\n        json (str): JSON encoded data.\n        indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.\n        highlight (bool, optional): Enable highlighting. Defaults to True.\n        skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n        ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n        check_circular (bool, optional): Check for circular references. Defaults to True.\n        allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n        default (Callable, optional): A callable that converts values that can not be encoded\n            in to something that can be JSON encoded. Defaults to None.\n        sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        json: str,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = False,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> None:\n        data = loads(json)\n        json = dumps(\n            data,\n            indent=indent,\n            skipkeys=skip_keys,\n            ensure_ascii=ensure_ascii,\n            check_circular=check_circular,\n            allow_nan=allow_nan,\n            default=default,\n            sort_keys=sort_keys,\n        )\n        highlighter = JSONHighlighter() if highlight else NullHighlighter()\n        self.text = highlighter(json)\n        self.text.no_wrap = True\n        self.text.overflow = None\n\n    @classmethod\n    def from_data(\n        cls,\n        data: Any,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = False,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> \"JSON\":\n        \"\"\"Encodes a JSON object from arbitrary data.\n\n        Args:\n            data (Any): An object that may be encoded in to JSON\n            indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.\n            highlight (bool, optional): Enable highlighting. Defaults to True.\n            default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.\n            skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n            ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n            check_circular (bool, optional): Check for circular references. Defaults to True.\n            allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n            default (Callable, optional): A callable that converts values that can not be encoded\n                in to something that can be JSON encoded. Defaults to None.\n            sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n\n        Returns:\n            JSON: New JSON object from the given data.\n        \"\"\"\n        json_instance: \"JSON\" = cls.__new__(cls)\n        json = dumps(\n            data,\n            indent=indent,\n            skipkeys=skip_keys,\n            ensure_ascii=ensure_ascii,\n            check_circular=check_circular,\n            allow_nan=allow_nan,\n            default=default,\n            sort_keys=sort_keys,\n        )\n        highlighter = JSONHighlighter() if highlight else NullHighlighter()\n        json_instance.text = highlighter(json)\n        json_instance.text.no_wrap = True\n        json_instance.text.overflow = None\n        return json_instance\n\n    def __rich__(self) -> Text:\n        return self.text\n\n\nif __name__ == \"__main__\":\n    import argparse\n    import sys\n\n    parser = argparse.ArgumentParser(description=\"Pretty print json\")\n    parser.add_argument(\n        \"path\",\n        metavar=\"PATH\",\n        help=\"path to file, or - for stdin\",\n    )\n    parser.add_argument(\n        \"-i\",\n        \"--indent\",\n        metavar=\"SPACES\",\n        type=int,\n        help=\"Number of spaces in an indent\",\n        default=2,\n    )\n    args = parser.parse_args()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    error_console = Console(stderr=True)\n\n    try:\n        if args.path == \"-\":\n            json_data = sys.stdin.read()\n        else:\n            json_data = Path(args.path).read_text()\n    except Exception as error:\n        error_console.print(f\"Unable to read {args.path!r}; {error}\")\n        sys.exit(-1)\n\n    console.print(JSON(json_data, indent=args.indent), soft_wrap=True)\n"
  },
  {
    "path": "src/pip/_vendor/rich/jupyter.py",
    "content": "from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleRenderable\n\nfrom . import get_console\nfrom .segment import Segment\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleRenderable\n\nJUPYTER_HTML_FORMAT = \"\"\"\\\n<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">{code}</pre>\n\"\"\"\n\n\nclass JupyterRenderable:\n    \"\"\"A shim to write html to Jupyter notebook.\"\"\"\n\n    def __init__(self, html: str, text: str) -> None:\n        self.html = html\n        self.text = text\n\n    def _repr_mimebundle_(\n        self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any\n    ) -> Dict[str, str]:\n        data = {\"text/plain\": self.text, \"text/html\": self.html}\n        if include:\n            data = {k: v for (k, v) in data.items() if k in include}\n        if exclude:\n            data = {k: v for (k, v) in data.items() if k not in exclude}\n        return data\n\n\nclass JupyterMixin:\n    \"\"\"Add to an Rich renderable to make it render in Jupyter notebook.\"\"\"\n\n    __slots__ = ()\n\n    def _repr_mimebundle_(\n        self: \"ConsoleRenderable\",\n        include: Sequence[str],\n        exclude: Sequence[str],\n        **kwargs: Any,\n    ) -> Dict[str, str]:\n        console = get_console()\n        segments = list(console.render(self, console.options))\n        html = _render_segments(segments)\n        text = console._render_buffer(segments)\n        data = {\"text/plain\": text, \"text/html\": html}\n        if include:\n            data = {k: v for (k, v) in data.items() if k in include}\n        if exclude:\n            data = {k: v for (k, v) in data.items() if k not in exclude}\n        return data\n\n\ndef _render_segments(segments: Iterable[Segment]) -> str:\n    def escape(text: str) -> str:\n        \"\"\"Escape html.\"\"\"\n        return text.replace(\"&\", \"&amp;\").replace(\"<\", \"&lt;\").replace(\">\", \"&gt;\")\n\n    fragments: List[str] = []\n    append_fragment = fragments.append\n    theme = DEFAULT_TERMINAL_THEME\n    for text, style, control in Segment.simplify(segments):\n        if control:\n            continue\n        text = escape(text)\n        if style:\n            rule = style.get_html_style(theme)\n            text = f'<span style=\"{rule}\">{text}</span>' if rule else text\n            if style.link:\n                text = f'<a href=\"{style.link}\" target=\"_blank\">{text}</a>'\n        append_fragment(text)\n\n    code = \"\".join(fragments)\n    html = JUPYTER_HTML_FORMAT.format(code=code)\n\n    return html\n\n\ndef display(segments: Iterable[Segment], text: str) -> None:\n    \"\"\"Render segments to Jupyter.\"\"\"\n    html = _render_segments(segments)\n    jupyter_renderable = JupyterRenderable(html, text)\n    try:\n        from IPython.display import display as ipython_display\n\n        ipython_display(jupyter_renderable)\n    except ModuleNotFoundError:\n        # Handle the case where the Console has force_jupyter=True,\n        # but IPython is not installed.\n        pass\n\n\ndef print(*args: Any, **kwargs: Any) -> None:\n    \"\"\"Proxy for Console print.\"\"\"\n    console = get_console()\n    return console.print(*args, **kwargs)\n"
  },
  {
    "path": "src/pip/_vendor/rich/layout.py",
    "content": "from abc import ABC, abstractmethod\nfrom itertools import islice\nfrom operator import itemgetter\nfrom threading import RLock\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom ._ratio import ratio_resolve\nfrom .align import Align\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .highlighter import ReprHighlighter\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .region import Region\nfrom .repr import Result, rich_repr\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.tree import Tree\n\n\nclass LayoutRender(NamedTuple):\n    \"\"\"An individual layout render.\"\"\"\n\n    region: Region\n    render: List[List[Segment]]\n\n\nRegionMap = Dict[\"Layout\", Region]\nRenderMap = Dict[\"Layout\", LayoutRender]\n\n\nclass LayoutError(Exception):\n    \"\"\"Layout related error.\"\"\"\n\n\nclass NoSplitter(LayoutError):\n    \"\"\"Requested splitter does not exist.\"\"\"\n\n\nclass _Placeholder:\n    \"\"\"An internal renderable used as a Layout placeholder.\"\"\"\n\n    highlighter = ReprHighlighter()\n\n    def __init__(self, layout: \"Layout\", style: StyleType = \"\") -> None:\n        self.layout = layout\n        self.style = style\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = options.max_width\n        height = options.height or options.size.height\n        layout = self.layout\n        title = (\n            f\"{layout.name!r} ({width} x {height})\"\n            if layout.name\n            else f\"({width} x {height})\"\n        )\n        yield Panel(\n            Align.center(Pretty(layout), vertical=\"middle\"),\n            style=self.style,\n            title=self.highlighter(title),\n            border_style=\"blue\",\n            height=height,\n        )\n\n\nclass Splitter(ABC):\n    \"\"\"Base class for a splitter.\"\"\"\n\n    name: str = \"\"\n\n    @abstractmethod\n    def get_tree_icon(self) -> str:\n        \"\"\"Get the icon (emoji) used in layout.tree\"\"\"\n\n    @abstractmethod\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        \"\"\"Divide a region amongst several child layouts.\n\n        Args:\n            children (Sequence(Layout)): A number of child layouts.\n            region (Region): A rectangular region to divide.\n        \"\"\"\n\n\nclass RowSplitter(Splitter):\n    \"\"\"Split a layout region in to rows.\"\"\"\n\n    name = \"row\"\n\n    def get_tree_icon(self) -> str:\n        return \"[layout.tree.row]⬌\"\n\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        x, y, width, height = region\n        render_widths = ratio_resolve(width, children)\n        offset = 0\n        _Region = Region\n        for child, child_width in zip(children, render_widths):\n            yield child, _Region(x + offset, y, child_width, height)\n            offset += child_width\n\n\nclass ColumnSplitter(Splitter):\n    \"\"\"Split a layout region in to columns.\"\"\"\n\n    name = \"column\"\n\n    def get_tree_icon(self) -> str:\n        return \"[layout.tree.column]⬍\"\n\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        x, y, width, height = region\n        render_heights = ratio_resolve(height, children)\n        offset = 0\n        _Region = Region\n        for child, child_height in zip(children, render_heights):\n            yield child, _Region(x, y + offset, width, child_height)\n            offset += child_height\n\n\n@rich_repr\nclass Layout:\n    \"\"\"A renderable to divide a fixed height in to rows or columns.\n\n    Args:\n        renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.\n        name (str, optional): Optional identifier for Layout. Defaults to None.\n        size (int, optional): Optional fixed size of layout. Defaults to None.\n        minimum_size (int, optional): Minimum size of layout. Defaults to 1.\n        ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.\n        visible (bool, optional): Visibility of layout. Defaults to True.\n    \"\"\"\n\n    splitters = {\"row\": RowSplitter, \"column\": ColumnSplitter}\n\n    def __init__(\n        self,\n        renderable: Optional[RenderableType] = None,\n        *,\n        name: Optional[str] = None,\n        size: Optional[int] = None,\n        minimum_size: int = 1,\n        ratio: int = 1,\n        visible: bool = True,\n    ) -> None:\n        self._renderable = renderable or _Placeholder(self)\n        self.size = size\n        self.minimum_size = minimum_size\n        self.ratio = ratio\n        self.name = name\n        self.visible = visible\n        self.splitter: Splitter = self.splitters[\"column\"]()\n        self._children: List[Layout] = []\n        self._render_map: RenderMap = {}\n        self._lock = RLock()\n\n    def __rich_repr__(self) -> Result:\n        yield \"name\", self.name, None\n        yield \"size\", self.size, None\n        yield \"minimum_size\", self.minimum_size, 1\n        yield \"ratio\", self.ratio, 1\n\n    @property\n    def renderable(self) -> RenderableType:\n        \"\"\"Layout renderable.\"\"\"\n        return self if self._children else self._renderable\n\n    @property\n    def children(self) -> List[\"Layout\"]:\n        \"\"\"Gets (visible) layout children.\"\"\"\n        return [child for child in self._children if child.visible]\n\n    @property\n    def map(self) -> RenderMap:\n        \"\"\"Get a map of the last render.\"\"\"\n        return self._render_map\n\n    def get(self, name: str) -> Optional[\"Layout\"]:\n        \"\"\"Get a named layout, or None if it doesn't exist.\n\n        Args:\n            name (str): Name of layout.\n\n        Returns:\n            Optional[Layout]: Layout instance or None if no layout was found.\n        \"\"\"\n        if self.name == name:\n            return self\n        else:\n            for child in self._children:\n                named_layout = child.get(name)\n                if named_layout is not None:\n                    return named_layout\n        return None\n\n    def __getitem__(self, name: str) -> \"Layout\":\n        layout = self.get(name)\n        if layout is None:\n            raise KeyError(f\"No layout with name {name!r}\")\n        return layout\n\n    @property\n    def tree(self) -> \"Tree\":\n        \"\"\"Get a tree renderable to show layout structure.\"\"\"\n        from pip._vendor.rich.styled import Styled\n        from pip._vendor.rich.table import Table\n        from pip._vendor.rich.tree import Tree\n\n        def summary(layout: \"Layout\") -> Table:\n            icon = layout.splitter.get_tree_icon()\n\n            table = Table.grid(padding=(0, 1, 0, 0))\n\n            text: RenderableType = (\n                Pretty(layout) if layout.visible else Styled(Pretty(layout), \"dim\")\n            )\n            table.add_row(icon, text)\n            _summary = table\n            return _summary\n\n        layout = self\n        tree = Tree(\n            summary(layout),\n            guide_style=f\"layout.tree.{layout.splitter.name}\",\n            highlight=True,\n        )\n\n        def recurse(tree: \"Tree\", layout: \"Layout\") -> None:\n            for child in layout._children:\n                recurse(\n                    tree.add(\n                        summary(child),\n                        guide_style=f\"layout.tree.{child.splitter.name}\",\n                    ),\n                    child,\n                )\n\n        recurse(tree, self)\n        return tree\n\n    def split(\n        self,\n        *layouts: Union[\"Layout\", RenderableType],\n        splitter: Union[Splitter, str] = \"column\",\n    ) -> None:\n        \"\"\"Split the layout in to multiple sub-layouts.\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n            splitter (Union[Splitter, str]): Splitter instance or name of splitter.\n        \"\"\"\n        _layouts = [\n            layout if isinstance(layout, Layout) else Layout(layout)\n            for layout in layouts\n        ]\n        try:\n            self.splitter = (\n                splitter\n                if isinstance(splitter, Splitter)\n                else self.splitters[splitter]()\n            )\n        except KeyError:\n            raise NoSplitter(f\"No splitter called {splitter!r}\")\n        self._children[:] = _layouts\n\n    def add_split(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Add a new layout(s) to existing split.\n\n        Args:\n            *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.\n\n        \"\"\"\n        _layouts = (\n            layout if isinstance(layout, Layout) else Layout(layout)\n            for layout in layouts\n        )\n        self._children.extend(_layouts)\n\n    def split_row(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Split the layout in to a row (layouts side by side).\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n        \"\"\"\n        self.split(*layouts, splitter=\"row\")\n\n    def split_column(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Split the layout in to a column (layouts stacked on top of each other).\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n        \"\"\"\n        self.split(*layouts, splitter=\"column\")\n\n    def unsplit(self) -> None:\n        \"\"\"Reset splits to initial state.\"\"\"\n        del self._children[:]\n\n    def update(self, renderable: RenderableType) -> None:\n        \"\"\"Update renderable.\n\n        Args:\n            renderable (RenderableType): New renderable object.\n        \"\"\"\n        with self._lock:\n            self._renderable = renderable\n\n    def refresh_screen(self, console: \"Console\", layout_name: str) -> None:\n        \"\"\"Refresh a sub-layout.\n\n        Args:\n            console (Console): Console instance where Layout is to be rendered.\n            layout_name (str): Name of layout.\n        \"\"\"\n        with self._lock:\n            layout = self[layout_name]\n            region, _lines = self._render_map[layout]\n            (x, y, width, height) = region\n            lines = console.render_lines(\n                layout, console.options.update_dimensions(width, height)\n            )\n            self._render_map[layout] = LayoutRender(region, lines)\n            console.update_screen_lines(lines, x, y)\n\n    def _make_region_map(self, width: int, height: int) -> RegionMap:\n        \"\"\"Create a dict that maps layout on to Region.\"\"\"\n        stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]\n        push = stack.append\n        pop = stack.pop\n        layout_regions: List[Tuple[Layout, Region]] = []\n        append_layout_region = layout_regions.append\n        while stack:\n            append_layout_region(pop())\n            layout, region = layout_regions[-1]\n            children = layout.children\n            if children:\n                for child_and_region in layout.splitter.divide(children, region):\n                    push(child_and_region)\n\n        region_map = {\n            layout: region\n            for layout, region in sorted(layout_regions, key=itemgetter(1))\n        }\n        return region_map\n\n    def render(self, console: Console, options: ConsoleOptions) -> RenderMap:\n        \"\"\"Render the sub_layouts.\n\n        Args:\n            console (Console): Console instance.\n            options (ConsoleOptions): Console options.\n\n        Returns:\n            RenderMap: A dict that maps Layout on to a tuple of Region, lines\n        \"\"\"\n        render_width = options.max_width\n        render_height = options.height or console.height\n        region_map = self._make_region_map(render_width, render_height)\n        layout_regions = [\n            (layout, region)\n            for layout, region in region_map.items()\n            if not layout.children\n        ]\n        render_map: Dict[\"Layout\", \"LayoutRender\"] = {}\n        render_lines = console.render_lines\n        update_dimensions = options.update_dimensions\n\n        for layout, region in layout_regions:\n            lines = render_lines(\n                layout.renderable, update_dimensions(region.width, region.height)\n            )\n            render_map[layout] = LayoutRender(region, lines)\n        return render_map\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        with self._lock:\n            width = options.max_width or console.width\n            height = options.height or console.height\n            render_map = self.render(console, options.update_dimensions(width, height))\n            self._render_map = render_map\n            layout_lines: List[List[Segment]] = [[] for _ in range(height)]\n            _islice = islice\n            for region, lines in render_map.values():\n                _x, y, _layout_width, layout_height = region\n                for row, line in zip(\n                    _islice(layout_lines, y, y + layout_height), lines\n                ):\n                    row.extend(line)\n\n            new_line = Segment.line()\n            for layout_row in layout_lines:\n                yield from layout_row\n                yield new_line\n\n\nif __name__ == \"__main__\":\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    layout = Layout()\n\n    layout.split_column(\n        Layout(name=\"header\", size=3),\n        Layout(ratio=1, name=\"main\"),\n        Layout(size=10, name=\"footer\"),\n    )\n\n    layout[\"main\"].split_row(Layout(name=\"side\"), Layout(name=\"body\", ratio=2))\n\n    layout[\"body\"].split_row(Layout(name=\"content\", ratio=2), Layout(name=\"s2\"))\n\n    layout[\"s2\"].split_column(\n        Layout(name=\"top\"), Layout(name=\"middle\"), Layout(name=\"bottom\")\n    )\n\n    layout[\"side\"].split_column(Layout(layout.tree, name=\"left1\"), Layout(name=\"left2\"))\n\n    layout[\"content\"].update(\"foo\")\n\n    console.print(layout)\n"
  },
  {
    "path": "src/pip/_vendor/rich/live.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom threading import Event, RLock, Thread\nfrom types import TracebackType\nfrom typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast\n\nfrom . import get_console\nfrom .console import Console, ConsoleRenderable, Group, RenderableType, RenderHook\nfrom .control import Control\nfrom .file_proxy import FileProxy\nfrom .jupyter import JupyterMixin\nfrom .live_render import LiveRender, VerticalOverflowMethod\nfrom .screen import Screen\nfrom .text import Text\n\nif TYPE_CHECKING:\n    # Can be replaced with `from typing import Self` in Python 3.11+\n    from typing_extensions import Self  # pragma: no cover\n\n\nclass _RefreshThread(Thread):\n    \"\"\"A thread that calls refresh() at regular intervals.\"\"\"\n\n    def __init__(self, live: \"Live\", refresh_per_second: float) -> None:\n        self.live = live\n        self.refresh_per_second = refresh_per_second\n        self.done = Event()\n        super().__init__(daemon=True)\n\n    def stop(self) -> None:\n        self.done.set()\n\n    def run(self) -> None:\n        while not self.done.wait(1 / self.refresh_per_second):\n            with self.live._lock:\n                if not self.done.is_set():\n                    self.live.refresh()\n\n\nclass Live(JupyterMixin, RenderHook):\n    \"\"\"Renders an auto-updating live display of any given renderable.\n\n    Args:\n        renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.\n        console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.\n        screen (bool, optional): Enable alternate screen mode. Defaults to False.\n        auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True\n        refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.\n        transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.\n        redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.\n        redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.\n        vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to \"ellipsis\".\n        get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: Optional[RenderableType] = None,\n        *,\n        console: Optional[Console] = None,\n        screen: bool = False,\n        auto_refresh: bool = True,\n        refresh_per_second: float = 4,\n        transient: bool = False,\n        redirect_stdout: bool = True,\n        redirect_stderr: bool = True,\n        vertical_overflow: VerticalOverflowMethod = \"ellipsis\",\n        get_renderable: Optional[Callable[[], RenderableType]] = None,\n    ) -> None:\n        assert refresh_per_second > 0, \"refresh_per_second must be > 0\"\n        self._renderable = renderable\n        self.console = console if console is not None else get_console()\n        self._screen = screen\n        self._alt_screen = False\n\n        self._redirect_stdout = redirect_stdout\n        self._redirect_stderr = redirect_stderr\n        self._restore_stdout: Optional[IO[str]] = None\n        self._restore_stderr: Optional[IO[str]] = None\n\n        self._lock = RLock()\n        self.ipy_widget: Optional[Any] = None\n        self.auto_refresh = auto_refresh\n        self._started: bool = False\n        self.transient = True if screen else transient\n\n        self._refresh_thread: Optional[_RefreshThread] = None\n        self.refresh_per_second = refresh_per_second\n\n        self.vertical_overflow = vertical_overflow\n        self._get_renderable = get_renderable\n        self._live_render = LiveRender(\n            self.get_renderable(), vertical_overflow=vertical_overflow\n        )\n        self._nested = False\n\n    @property\n    def is_started(self) -> bool:\n        \"\"\"Check if live display has been started.\"\"\"\n        return self._started\n\n    def get_renderable(self) -> RenderableType:\n        renderable = (\n            self._get_renderable()\n            if self._get_renderable is not None\n            else self._renderable\n        )\n        return renderable or \"\"\n\n    def start(self, refresh: bool = False) -> None:\n        \"\"\"Start live rendering display.\n\n        Args:\n            refresh (bool, optional): Also refresh. Defaults to False.\n        \"\"\"\n        with self._lock:\n            if self._started:\n                return\n            self._started = True\n\n            if not self.console.set_live(self):\n                self._nested = True\n                return\n\n            if self._screen:\n                self._alt_screen = self.console.set_alt_screen(True)\n            self.console.show_cursor(False)\n            self._enable_redirect_io()\n            self.console.push_render_hook(self)\n            if refresh:\n                try:\n                    self.refresh()\n                except Exception:\n                    # If refresh fails, we want to stop the redirection of sys.stderr,\n                    # so the error stacktrace is properly displayed in the terminal.\n                    # (or, if the code that calls Rich captures the exception and wants to display something,\n                    # let this be displayed in the terminal).\n                    self.stop()\n                    raise\n            if self.auto_refresh:\n                self._refresh_thread = _RefreshThread(self, self.refresh_per_second)\n                self._refresh_thread.start()\n\n    def stop(self) -> None:\n        \"\"\"Stop live rendering display.\"\"\"\n        with self._lock:\n            if not self._started:\n                return\n            self._started = False\n            self.console.clear_live()\n            if self._nested:\n                if not self.transient:\n                    self.console.print(self.renderable)\n                return\n\n            if self.auto_refresh and self._refresh_thread is not None:\n                self._refresh_thread.stop()\n                self._refresh_thread = None\n            # allow it to fully render on the last even if overflow\n            self.vertical_overflow = \"visible\"\n            with self.console:\n                try:\n                    if not self._alt_screen and not self.console.is_jupyter:\n                        self.refresh()\n                finally:\n                    self._disable_redirect_io()\n                    self.console.pop_render_hook()\n                    if not self._alt_screen and self.console.is_terminal:\n                        self.console.line()\n                    self.console.show_cursor(True)\n                    if self._alt_screen:\n                        self.console.set_alt_screen(False)\n                    if self.transient and not self._alt_screen:\n                        self.console.control(self._live_render.restore_cursor())\n                    if self.ipy_widget is not None and self.transient:\n                        self.ipy_widget.close()  # pragma: no cover\n\n    def __enter__(self) -> Self:\n        self.start(refresh=self._renderable is not None)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n    def _enable_redirect_io(self) -> None:\n        \"\"\"Enable redirecting of stdout / stderr.\"\"\"\n        if self.console.is_terminal or self.console.is_jupyter:\n            if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):\n                self._restore_stdout = sys.stdout\n                sys.stdout = cast(\"TextIO\", FileProxy(self.console, sys.stdout))\n            if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):\n                self._restore_stderr = sys.stderr\n                sys.stderr = cast(\"TextIO\", FileProxy(self.console, sys.stderr))\n\n    def _disable_redirect_io(self) -> None:\n        \"\"\"Disable redirecting of stdout / stderr.\"\"\"\n        if self._restore_stdout:\n            sys.stdout = cast(\"TextIO\", self._restore_stdout)\n            self._restore_stdout = None\n        if self._restore_stderr:\n            sys.stderr = cast(\"TextIO\", self._restore_stderr)\n            self._restore_stderr = None\n\n    @property\n    def renderable(self) -> RenderableType:\n        \"\"\"Get the renderable that is being displayed\n\n        Returns:\n            RenderableType: Displayed renderable.\n        \"\"\"\n        live_stack = self.console._live_stack\n        renderable: RenderableType\n        if live_stack and self is live_stack[0]:\n            # The first Live instance will render everything in the Live stack\n            renderable = Group(*[live.get_renderable() for live in live_stack])\n        else:\n            renderable = self.get_renderable()\n        return Screen(renderable) if self._alt_screen else renderable\n\n    def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:\n        \"\"\"Update the renderable that is being displayed\n\n        Args:\n            renderable (RenderableType): New renderable to use.\n            refresh (bool, optional): Refresh the display. Defaults to False.\n        \"\"\"\n        if isinstance(renderable, str):\n            renderable = self.console.render_str(renderable)\n        with self._lock:\n            self._renderable = renderable\n            if refresh:\n                self.refresh()\n\n    def refresh(self) -> None:\n        \"\"\"Update the display of the Live Render.\"\"\"\n        with self._lock:\n            self._live_render.set_renderable(self.renderable)\n            if self._nested:\n                if self.console._live_stack:\n                    self.console._live_stack[0].refresh()\n                return\n\n            if self.console.is_jupyter:  # pragma: no cover\n                try:\n                    from IPython.display import display\n                    from ipywidgets import Output\n                except ImportError:\n                    import warnings\n\n                    warnings.warn('install \"ipywidgets\" for Jupyter support')\n                else:\n                    if self.ipy_widget is None:\n                        self.ipy_widget = Output()\n                        display(self.ipy_widget)\n\n                    with self.ipy_widget:\n                        self.ipy_widget.clear_output(wait=True)\n                        self.console.print(self._live_render.renderable)\n            elif self.console.is_terminal and not self.console.is_dumb_terminal:\n                with self.console:\n                    self.console.print(Control())\n            elif (\n                not self._started and not self.transient\n            ):  # if it is finished allow files or dumb-terminals to see final result\n                with self.console:\n                    self.console.print(Control())\n\n    def process_renderables(\n        self, renderables: List[ConsoleRenderable]\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Process renderables to restore cursor and display progress.\"\"\"\n        self._live_render.vertical_overflow = self.vertical_overflow\n        if self.console.is_interactive:\n            # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.\n            with self._lock:\n                reset = (\n                    Control.home()\n                    if self._alt_screen\n                    else self._live_render.position_cursor()\n                )\n                renderables = [reset, *renderables, self._live_render]\n        elif (\n            not self._started and not self.transient\n        ):  # if it is finished render the final output for files or dumb_terminals\n            renderables = [*renderables, self._live_render]\n\n        return renderables\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import random\n    import time\n    from itertools import cycle\n    from typing import Dict, List, Tuple\n\n    from .align import Align\n    from .console import Console\n    from .live import Live as Live\n    from .panel import Panel\n    from .rule import Rule\n    from .syntax import Syntax\n    from .table import Table\n\n    console = Console()\n\n    syntax = Syntax(\n        '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value''',\n        \"python\",\n        line_numbers=True,\n    )\n\n    table = Table(\"foo\", \"bar\", \"baz\")\n    table.add_row(\"1\", \"2\", \"3\")\n\n    progress_renderables = [\n        \"You can make the terminal shorter and taller to see the live table hide\"\n        \"Text may be printed while the progress bars are rendering.\",\n        Panel(\"In fact, [i]any[/i] renderable will work\"),\n        \"Such as [magenta]tables[/]...\",\n        table,\n        \"Pretty printed structures...\",\n        {\"type\": \"example\", \"text\": \"Pretty printed\"},\n        \"Syntax...\",\n        syntax,\n        Rule(\"Give it a try!\"),\n    ]\n\n    examples = cycle(progress_renderables)\n\n    exchanges = [\n        \"SGD\",\n        \"MYR\",\n        \"EUR\",\n        \"USD\",\n        \"AUD\",\n        \"JPY\",\n        \"CNH\",\n        \"HKD\",\n        \"CAD\",\n        \"INR\",\n        \"DKK\",\n        \"GBP\",\n        \"RUB\",\n        \"NZD\",\n        \"MXN\",\n        \"IDR\",\n        \"TWD\",\n        \"THB\",\n        \"VND\",\n    ]\n    with Live(console=console) as live_table:\n        exchange_rate_dict: Dict[Tuple[str, str], float] = {}\n\n        for index in range(100):\n            select_exchange = exchanges[index % len(exchanges)]\n\n            for exchange in exchanges:\n                if exchange == select_exchange:\n                    continue\n                time.sleep(0.4)\n                if random.randint(0, 10) < 1:\n                    console.log(next(examples))\n                exchange_rate_dict[(select_exchange, exchange)] = 200 / (\n                    (random.random() * 320) + 1\n                )\n                if len(exchange_rate_dict) > len(exchanges) - 1:\n                    exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])\n                table = Table(title=\"Exchange Rates\")\n\n                table.add_column(\"Source Currency\")\n                table.add_column(\"Destination Currency\")\n                table.add_column(\"Exchange Rate\")\n\n                for (source, dest), exchange_rate in exchange_rate_dict.items():\n                    table.add_row(\n                        source,\n                        dest,\n                        Text(\n                            f\"{exchange_rate:.4f}\",\n                            style=\"red\" if exchange_rate < 1.0 else \"green\",\n                        ),\n                    )\n\n                live_table.update(Align.center(table))\n"
  },
  {
    "path": "src/pip/_vendor/rich/live_render.py",
    "content": "from typing import Optional, Tuple, Literal\n\n\nfrom ._loop import loop_last\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .control import Control\nfrom .segment import ControlType, Segment\nfrom .style import StyleType\nfrom .text import Text\n\nVerticalOverflowMethod = Literal[\"crop\", \"ellipsis\", \"visible\"]\n\n\nclass LiveRender:\n    \"\"\"Creates a renderable that may be updated.\n\n    Args:\n        renderable (RenderableType): Any renderable object.\n        style (StyleType, optional): An optional style to apply to the renderable. Defaults to \"\".\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: RenderableType,\n        style: StyleType = \"\",\n        vertical_overflow: VerticalOverflowMethod = \"ellipsis\",\n    ) -> None:\n        self.renderable = renderable\n        self.style = style\n        self.vertical_overflow = vertical_overflow\n        self._shape: Optional[Tuple[int, int]] = None\n\n    def set_renderable(self, renderable: RenderableType) -> None:\n        \"\"\"Set a new renderable.\n\n        Args:\n            renderable (RenderableType): Any renderable object, including str.\n        \"\"\"\n        self.renderable = renderable\n\n    def position_cursor(self) -> Control:\n        \"\"\"Get control codes to move cursor to beginning of live render.\n\n        Returns:\n            Control: A control instance that may be printed.\n        \"\"\"\n        if self._shape is not None:\n            _, height = self._shape\n            return Control(\n                ControlType.CARRIAGE_RETURN,\n                (ControlType.ERASE_IN_LINE, 2),\n                *(\n                    (\n                        (ControlType.CURSOR_UP, 1),\n                        (ControlType.ERASE_IN_LINE, 2),\n                    )\n                    * (height - 1)\n                )\n            )\n        return Control()\n\n    def restore_cursor(self) -> Control:\n        \"\"\"Get control codes to clear the render and restore the cursor to its previous position.\n\n        Returns:\n            Control: A Control instance that may be printed.\n        \"\"\"\n        if self._shape is not None:\n            _, height = self._shape\n            return Control(\n                ControlType.CARRIAGE_RETURN,\n                *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height\n            )\n        return Control()\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        renderable = self.renderable\n        style = console.get_style(self.style)\n        lines = console.render_lines(renderable, options, style=style, pad=False)\n        shape = Segment.get_shape(lines)\n\n        _, height = shape\n        if height > options.size.height:\n            if self.vertical_overflow == \"crop\":\n                lines = lines[: options.size.height]\n                shape = Segment.get_shape(lines)\n            elif self.vertical_overflow == \"ellipsis\":\n                lines = lines[: (options.size.height - 1)]\n                overflow_text = Text(\n                    \"...\",\n                    overflow=\"crop\",\n                    justify=\"center\",\n                    end=\"\",\n                    style=\"live.ellipsis\",\n                )\n                lines.append(list(console.render(overflow_text)))\n                shape = Segment.get_shape(lines)\n        self._shape = shape\n\n        new_line = Segment.line()\n        for last, line in loop_last(lines):\n            yield from line\n            if not last:\n                yield new_line\n"
  },
  {
    "path": "src/pip/_vendor/rich/logging.py",
    "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom pip._vendor.rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n    \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n    The level is color coded, and the message is syntax highlighted.\n\n    Note:\n        Be careful when enabling console markup in log messages if you have configured logging for libraries not\n        under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n    Args:\n        level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n        console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n            Default will use a global console instance writing to stdout.\n        show_time (bool, optional): Show a column for the time. Defaults to True.\n        omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n        show_level (bool, optional): Show a column for the level. Defaults to True.\n        show_path (bool, optional): Show the path to the original log call. Defaults to True.\n        enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n        highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n        markup (bool, optional): Enable console markup in log messages. Defaults to False.\n        rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.\n        tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.\n        tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88.\n        tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.\n        tracebacks_theme (str, optional): Override pygments theme used in traceback.\n        tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.\n        tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.\n        tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n        tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback.\n        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to 10.\n        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n        log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to \"[%x %X] \".\n        keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.\n    \"\"\"\n\n    KEYWORDS: ClassVar[Optional[List[str]]] = [\n        \"GET\",\n        \"POST\",\n        \"HEAD\",\n        \"PUT\",\n        \"DELETE\",\n        \"OPTIONS\",\n        \"TRACE\",\n        \"PATCH\",\n    ]\n    HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter\n\n    def __init__(\n        self,\n        level: Union[int, str] = logging.NOTSET,\n        console: Optional[Console] = None,\n        *,\n        show_time: bool = True,\n        omit_repeated_times: bool = True,\n        show_level: bool = True,\n        show_path: bool = True,\n        enable_link_path: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        markup: bool = False,\n        rich_tracebacks: bool = False,\n        tracebacks_width: Optional[int] = None,\n        tracebacks_code_width: Optional[int] = 88,\n        tracebacks_extra_lines: int = 3,\n        tracebacks_theme: Optional[str] = None,\n        tracebacks_word_wrap: bool = True,\n        tracebacks_show_locals: bool = False,\n        tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),\n        tracebacks_max_frames: int = 100,\n        locals_max_length: int = 10,\n        locals_max_string: int = 80,\n        log_time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n        keywords: Optional[List[str]] = None,\n    ) -> None:\n        super().__init__(level=level)\n        self.console = console or get_console()\n        self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()\n        self._log_render = LogRender(\n            show_time=show_time,\n            show_level=show_level,\n            show_path=show_path,\n            time_format=log_time_format,\n            omit_repeated_times=omit_repeated_times,\n            level_width=None,\n        )\n        self.enable_link_path = enable_link_path\n        self.markup = markup\n        self.rich_tracebacks = rich_tracebacks\n        self.tracebacks_width = tracebacks_width\n        self.tracebacks_extra_lines = tracebacks_extra_lines\n        self.tracebacks_theme = tracebacks_theme\n        self.tracebacks_word_wrap = tracebacks_word_wrap\n        self.tracebacks_show_locals = tracebacks_show_locals\n        self.tracebacks_suppress = tracebacks_suppress\n        self.tracebacks_max_frames = tracebacks_max_frames\n        self.tracebacks_code_width = tracebacks_code_width\n        self.locals_max_length = locals_max_length\n        self.locals_max_string = locals_max_string\n        self.keywords = keywords\n\n    def get_level_text(self, record: LogRecord) -> Text:\n        \"\"\"Get the level name from the record.\n\n        Args:\n            record (LogRecord): LogRecord instance.\n\n        Returns:\n            Text: A tuple of the style and level name.\n        \"\"\"\n        level_name = record.levelname\n        level_text = Text.styled(\n            level_name.ljust(8), f\"logging.level.{level_name.lower()}\"\n        )\n        return level_text\n\n    def emit(self, record: LogRecord) -> None:\n        \"\"\"Invoked by logging.\"\"\"\n        message = self.format(record)\n        traceback = None\n        if (\n            self.rich_tracebacks\n            and record.exc_info\n            and record.exc_info != (None, None, None)\n        ):\n            exc_type, exc_value, exc_traceback = record.exc_info\n            assert exc_type is not None\n            assert exc_value is not None\n            traceback = Traceback.from_exception(\n                exc_type,\n                exc_value,\n                exc_traceback,\n                width=self.tracebacks_width,\n                code_width=self.tracebacks_code_width,\n                extra_lines=self.tracebacks_extra_lines,\n                theme=self.tracebacks_theme,\n                word_wrap=self.tracebacks_word_wrap,\n                show_locals=self.tracebacks_show_locals,\n                locals_max_length=self.locals_max_length,\n                locals_max_string=self.locals_max_string,\n                suppress=self.tracebacks_suppress,\n                max_frames=self.tracebacks_max_frames,\n            )\n            message = record.getMessage()\n            if self.formatter:\n                record.message = record.getMessage()\n                formatter = self.formatter\n                if hasattr(formatter, \"usesTime\") and formatter.usesTime():\n                    record.asctime = formatter.formatTime(record, formatter.datefmt)\n                message = formatter.formatMessage(record)\n\n        message_renderable = self.render_message(record, message)\n        log_renderable = self.render(\n            record=record, traceback=traceback, message_renderable=message_renderable\n        )\n        if isinstance(self.console.file, NullFile):\n            # Handles pythonw, where stdout/stderr are null, and we return NullFile\n            # instance from Console.file. In this case, we still want to make a log record\n            # even though we won't be writing anything to a file.\n            self.handleError(record)\n        else:\n            try:\n                self.console.print(log_renderable)\n            except Exception:\n                self.handleError(record)\n\n    def render_message(self, record: LogRecord, message: str) -> \"ConsoleRenderable\":\n        \"\"\"Render message text in to Text.\n\n        Args:\n            record (LogRecord): logging Record.\n            message (str): String containing log message.\n\n        Returns:\n            ConsoleRenderable: Renderable to display log message.\n        \"\"\"\n        use_markup = getattr(record, \"markup\", self.markup)\n        message_text = Text.from_markup(message) if use_markup else Text(message)\n\n        highlighter = getattr(record, \"highlighter\", self.highlighter)\n        if highlighter:\n            message_text = highlighter(message_text)\n\n        if self.keywords is None:\n            self.keywords = self.KEYWORDS\n\n        if self.keywords:\n            message_text.highlight_words(self.keywords, \"logging.keyword\")\n\n        return message_text\n\n    def render(\n        self,\n        *,\n        record: LogRecord,\n        traceback: Optional[Traceback],\n        message_renderable: \"ConsoleRenderable\",\n    ) -> \"ConsoleRenderable\":\n        \"\"\"Render log for display.\n\n        Args:\n            record (LogRecord): logging Record.\n            traceback (Optional[Traceback]): Traceback instance or None for no Traceback.\n            message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.\n\n        Returns:\n            ConsoleRenderable: Renderable to display log.\n        \"\"\"\n        path = Path(record.pathname).name\n        level = self.get_level_text(record)\n        time_format = None if self.formatter is None else self.formatter.datefmt\n        log_time = datetime.fromtimestamp(record.created)\n\n        log_renderable = self._log_render(\n            self.console,\n            [message_renderable] if not traceback else [message_renderable, traceback],\n            log_time=log_time,\n            time_format=time_format,\n            level=level,\n            path=path,\n            line_no=record.lineno,\n            link_path=record.pathname if self.enable_link_path else None,\n        )\n        return log_renderable\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from time import sleep\n\n    FORMAT = \"%(message)s\"\n    # FORMAT = \"%(asctime)-15s - %(levelname)s - %(message)s\"\n    logging.basicConfig(\n        level=\"NOTSET\",\n        format=FORMAT,\n        datefmt=\"[%X]\",\n        handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],\n    )\n    log = logging.getLogger(\"rich\")\n\n    log.info(\"Server starting...\")\n    log.info(\"Listening on http://127.0.0.1:8080\")\n    sleep(1)\n\n    log.info(\"GET /index.html 200 1298\")\n    log.info(\"GET /imgs/backgrounds/back1.jpg 200 54386\")\n    log.info(\"GET /css/styles.css 200 54386\")\n    log.warning(\"GET /favicon.ico 404 242\")\n    sleep(1)\n\n    log.debug(\n        \"JSONRPC request\\n--> %r\\n<-- %r\",\n        {\n            \"version\": \"1.1\",\n            \"method\": \"confirmFruitPurchase\",\n            \"params\": [[\"apple\", \"orange\", \"mangoes\", \"pomelo\"], 1.123],\n            \"id\": \"194521489\",\n        },\n        {\"version\": \"1.1\", \"result\": True, \"error\": None, \"id\": \"194521489\"},\n    )\n    log.debug(\n        \"Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer\"\n    )\n    log.error(\"Unable to find 'pomelo' in database!\")\n    log.info(\"POST /jsonrpc/ 200 65532\")\n    log.info(\"POST /admin/ 401 42234\")\n    log.warning(\"password was rejected for admin site.\")\n\n    def divide() -> None:\n        number = 1\n        divisor = 0\n        foos = [\"foo\"] * 100\n        log.debug(\"in divide\")\n        try:\n            number / divisor\n        except:\n            log.exception(\"An error of some kind occurred!\")\n\n    divide()\n    sleep(1)\n    log.critical(\"Out of memory!\")\n    log.info(\"Server exited with code=-1\")\n    log.info(\"[bold]EXITING...[/bold]\", extra=dict(markup=True))\n"
  },
  {
    "path": "src/pip/_vendor/rich/markup.py",
    "content": "import re\nfrom ast import literal_eval\nfrom operator import attrgetter\nfrom typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union\n\nfrom ._emoji_replace import _emoji_replace\nfrom .emoji import EmojiVariant\nfrom .errors import MarkupError\nfrom .style import Style\nfrom .text import Span, Text\n\nRE_TAGS = re.compile(\n    r\"\"\"((\\\\*)\\[([a-z#/@][^[]*?)])\"\"\",\n    re.VERBOSE,\n)\n\nRE_HANDLER = re.compile(r\"^([\\w.]*?)(\\(.*?\\))?$\")\n\n\nclass Tag(NamedTuple):\n    \"\"\"A tag in console markup.\"\"\"\n\n    name: str\n    \"\"\"The tag name. e.g. 'bold'.\"\"\"\n    parameters: Optional[str]\n    \"\"\"Any additional parameters after the name.\"\"\"\n\n    def __str__(self) -> str:\n        return (\n            self.name if self.parameters is None else f\"{self.name} {self.parameters}\"\n        )\n\n    @property\n    def markup(self) -> str:\n        \"\"\"Get the string representation of this tag.\"\"\"\n        return (\n            f\"[{self.name}]\"\n            if self.parameters is None\n            else f\"[{self.name}={self.parameters}]\"\n        )\n\n\n_ReStringMatch = Match[str]  # regex match object\n_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub\n_EscapeSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re\n\n\ndef escape(\n    markup: str,\n    _escape: _EscapeSubMethod = re.compile(r\"(\\\\*)(\\[[a-z#/@][^[]*?])\").sub,\n) -> str:\n    \"\"\"Escapes text so that it won't be interpreted as markup.\n\n    Args:\n        markup (str): Content to be inserted in to markup.\n\n    Returns:\n        str: Markup with square brackets escaped.\n    \"\"\"\n\n    def escape_backslashes(match: Match[str]) -> str:\n        \"\"\"Called by re.sub replace matches.\"\"\"\n        backslashes, text = match.groups()\n        return f\"{backslashes}{backslashes}\\\\{text}\"\n\n    markup = _escape(escape_backslashes, markup)\n    if markup.endswith(\"\\\\\") and not markup.endswith(\"\\\\\\\\\"):\n        return markup + \"\\\\\"\n\n    return markup\n\n\ndef _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:\n    \"\"\"Parse markup in to an iterable of tuples of (position, text, tag).\n\n    Args:\n        markup (str): A string containing console markup\n\n    \"\"\"\n    position = 0\n    _divmod = divmod\n    _Tag = Tag\n    for match in RE_TAGS.finditer(markup):\n        full_text, escapes, tag_text = match.groups()\n        start, end = match.span()\n        if start > position:\n            yield start, markup[position:start], None\n        if escapes:\n            backslashes, escaped = _divmod(len(escapes), 2)\n            if backslashes:\n                # Literal backslashes\n                yield start, \"\\\\\" * backslashes, None\n                start += backslashes * 2\n            if escaped:\n                # Escape of tag\n                yield start, full_text[len(escapes) :], None\n                position = end\n                continue\n        text, equals, parameters = tag_text.partition(\"=\")\n        yield start, None, _Tag(text, parameters if equals else None)\n        position = end\n    if position < len(markup):\n        yield position, markup[position:], None\n\n\ndef render(\n    markup: str,\n    style: Union[str, Style] = \"\",\n    emoji: bool = True,\n    emoji_variant: Optional[EmojiVariant] = None,\n) -> Text:\n    \"\"\"Render console markup in to a Text instance.\n\n    Args:\n        markup (str): A string containing console markup.\n        style: (Union[str, Style]): The style to use.\n        emoji (bool, optional): Also render emoji code. Defaults to True.\n        emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n\n\n    Raises:\n        MarkupError: If there is a syntax error in the markup.\n\n    Returns:\n        Text: A test instance.\n    \"\"\"\n    emoji_replace = _emoji_replace\n    if \"[\" not in markup:\n        return Text(\n            emoji_replace(markup, default_variant=emoji_variant) if emoji else markup,\n            style=style,\n        )\n    text = Text(style=style)\n    append = text.append\n    normalize = Style.normalize\n\n    style_stack: List[Tuple[int, Tag]] = []\n    pop = style_stack.pop\n\n    spans: List[Span] = []\n    append_span = spans.append\n\n    _Span = Span\n    _Tag = Tag\n\n    def pop_style(style_name: str) -> Tuple[int, Tag]:\n        \"\"\"Pop tag matching given style name.\"\"\"\n        for index, (_, tag) in enumerate(reversed(style_stack), 1):\n            if tag.name == style_name:\n                return pop(-index)\n        raise KeyError(style_name)\n\n    for position, plain_text, tag in _parse(markup):\n        if plain_text is not None:\n            # Handle open brace escapes, where the brace is not part of a tag.\n            plain_text = plain_text.replace(\"\\\\[\", \"[\")\n            append(emoji_replace(plain_text) if emoji else plain_text)\n        elif tag is not None:\n            if tag.name.startswith(\"/\"):  # Closing tag\n                style_name = tag.name[1:].strip()\n\n                if style_name:  # explicit close\n                    style_name = normalize(style_name)\n                    try:\n                        start, open_tag = pop_style(style_name)\n                    except KeyError:\n                        raise MarkupError(\n                            f\"closing tag '{tag.markup}' at position {position} doesn't match any open tag\"\n                        ) from None\n                else:  # implicit close\n                    try:\n                        start, open_tag = pop()\n                    except IndexError:\n                        raise MarkupError(\n                            f\"closing tag '[/]' at position {position} has nothing to close\"\n                        ) from None\n\n                if open_tag.name.startswith(\"@\"):\n                    if open_tag.parameters:\n                        handler_name = \"\"\n                        parameters = open_tag.parameters.strip()\n                        handler_match = RE_HANDLER.match(parameters)\n                        if handler_match is not None:\n                            handler_name, match_parameters = handler_match.groups()\n                            parameters = (\n                                \"()\" if match_parameters is None else match_parameters\n                            )\n\n                        try:\n                            meta_params = literal_eval(parameters)\n                        except SyntaxError as error:\n                            raise MarkupError(\n                                f\"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}\"\n                            )\n                        except Exception as error:\n                            raise MarkupError(\n                                f\"error parsing {open_tag.parameters!r}; {error}\"\n                            ) from None\n\n                        if handler_name:\n                            meta_params = (\n                                handler_name,\n                                meta_params\n                                if isinstance(meta_params, tuple)\n                                else (meta_params,),\n                            )\n\n                    else:\n                        meta_params = ()\n\n                    append_span(\n                        _Span(\n                            start, len(text), Style(meta={open_tag.name: meta_params})\n                        )\n                    )\n                else:\n                    append_span(_Span(start, len(text), str(open_tag)))\n\n            else:  # Opening tag\n                normalized_tag = _Tag(normalize(tag.name), tag.parameters)\n                style_stack.append((len(text), normalized_tag))\n\n    text_length = len(text)\n    while style_stack:\n        start, tag = style_stack.pop()\n        style = str(tag)\n        if style:\n            append_span(_Span(start, text_length, style))\n\n    text.spans = sorted(spans[::-1], key=attrgetter(\"start\"))\n    return text\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    MARKUP = [\n        \"[red]Hello World[/red]\",\n        \"[magenta]Hello [b]World[/b]\",\n        \"[bold]Bold[italic] bold and italic [/bold]italic[/italic]\",\n        \"Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog\",\n        \":warning-emoji: [bold red blink] DANGER![/]\",\n    ]\n\n    from pip._vendor.rich import print\n    from pip._vendor.rich.table import Table\n\n    grid = Table(\"Markup\", \"Result\", padding=(0, 1))\n\n    for markup in MARKUP:\n        grid.add_row(Text(markup), markup)\n\n    print(grid)\n"
  },
  {
    "path": "src/pip/_vendor/rich/measure.py",
    "content": "from operator import itemgetter\nfrom typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence\n\nfrom . import errors\nfrom .protocol import is_renderable, rich_cast\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType\n\n\nclass Measurement(NamedTuple):\n    \"\"\"Stores the minimum and maximum widths (in characters) required to render an object.\"\"\"\n\n    minimum: int\n    \"\"\"Minimum number of cells required to render.\"\"\"\n    maximum: int\n    \"\"\"Maximum number of cells required to render.\"\"\"\n\n    @property\n    def span(self) -> int:\n        \"\"\"Get difference between maximum and minimum.\"\"\"\n        return self.maximum - self.minimum\n\n    def normalize(self) -> \"Measurement\":\n        \"\"\"Get measurement that ensures that minimum <= maximum and minimum >= 0\n\n        Returns:\n            Measurement: A normalized measurement.\n        \"\"\"\n        minimum, maximum = self\n        minimum = min(max(0, minimum), maximum)\n        return Measurement(max(0, minimum), max(0, max(minimum, maximum)))\n\n    def with_maximum(self, width: int) -> \"Measurement\":\n        \"\"\"Get a RenderableWith where the widths are <= width.\n\n        Args:\n            width (int): Maximum desired width.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        minimum, maximum = self\n        return Measurement(min(minimum, width), min(maximum, width))\n\n    def with_minimum(self, width: int) -> \"Measurement\":\n        \"\"\"Get a RenderableWith where the widths are >= width.\n\n        Args:\n            width (int): Minimum desired width.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        minimum, maximum = self\n        width = max(0, width)\n        return Measurement(max(minimum, width), max(maximum, width))\n\n    def clamp(\n        self, min_width: Optional[int] = None, max_width: Optional[int] = None\n    ) -> \"Measurement\":\n        \"\"\"Clamp a measurement within the specified range.\n\n        Args:\n            min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None.\n            max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        measurement = self\n        if min_width is not None:\n            measurement = measurement.with_minimum(min_width)\n        if max_width is not None:\n            measurement = measurement.with_maximum(max_width)\n        return measurement\n\n    @classmethod\n    def get(\n        cls, console: \"Console\", options: \"ConsoleOptions\", renderable: \"RenderableType\"\n    ) -> \"Measurement\":\n        \"\"\"Get a measurement for a renderable.\n\n        Args:\n            console (~rich.console.Console): Console instance.\n            options (~rich.console.ConsoleOptions): Console options.\n            renderable (RenderableType): An object that may be rendered with Rich.\n\n        Raises:\n            errors.NotRenderableError: If the object is not renderable.\n\n        Returns:\n            Measurement: Measurement object containing range of character widths required to render the object.\n        \"\"\"\n        _max_width = options.max_width\n        if _max_width < 1:\n            return Measurement(0, 0)\n        if isinstance(renderable, str):\n            renderable = console.render_str(\n                renderable, markup=options.markup, highlight=False\n            )\n        renderable = rich_cast(renderable)\n        if is_renderable(renderable):\n            get_console_width: Optional[\n                Callable[[\"Console\", \"ConsoleOptions\"], \"Measurement\"]\n            ] = getattr(renderable, \"__rich_measure__\", None)\n            if get_console_width is not None:\n                render_width = (\n                    get_console_width(console, options)\n                    .normalize()\n                    .with_maximum(_max_width)\n                )\n                if render_width.maximum < 1:\n                    return Measurement(0, 0)\n                return render_width.normalize()\n            else:\n                return Measurement(0, _max_width)\n        else:\n            raise errors.NotRenderableError(\n                f\"Unable to get render width for {renderable!r}; \"\n                \"a str, Segment, or object with __rich_console__ method is required\"\n            )\n\n\ndef measure_renderables(\n    console: \"Console\",\n    options: \"ConsoleOptions\",\n    renderables: Sequence[\"RenderableType\"],\n) -> \"Measurement\":\n    \"\"\"Get a measurement that would fit a number of renderables.\n\n    Args:\n        console (~rich.console.Console): Console instance.\n        options (~rich.console.ConsoleOptions): Console options.\n        renderables (Iterable[RenderableType]): One or more renderable objects.\n\n    Returns:\n        Measurement: Measurement object containing range of character widths required to\n            contain all given renderables.\n    \"\"\"\n    if not renderables:\n        return Measurement(0, 0)\n    get_measurement = Measurement.get\n    measurements = [\n        get_measurement(console, options, renderable) for renderable in renderables\n    ]\n    measured_width = Measurement(\n        max(measurements, key=itemgetter(0)).minimum,\n        max(measurements, key=itemgetter(1)).maximum,\n    )\n    return measured_width\n"
  },
  {
    "path": "src/pip/_vendor/rich/padding.py",
    "content": "from typing import TYPE_CHECKING, List, Optional, Tuple, Union\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        RenderableType,\n        RenderResult,\n    )\n\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style\n\nPaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]\n\n\nclass Padding(JupyterMixin):\n    \"\"\"Draw space around content.\n\n    Example:\n        >>> print(Padding(\"Hello\", (2, 4), style=\"on blue\"))\n\n    Args:\n        renderable (RenderableType): String or other renderable.\n        pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders.\n            May be specified with 1, 2, or 4 integers (CSS style).\n        style (Union[str, Style], optional): Style for padding characters. Defaults to \"none\".\n        expand (bool, optional): Expand padding to fit available width. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        pad: \"PaddingDimensions\" = (0, 0, 0, 0),\n        *,\n        style: Union[str, Style] = \"none\",\n        expand: bool = True,\n    ):\n        self.renderable = renderable\n        self.top, self.right, self.bottom, self.left = self.unpack(pad)\n        self.style = style\n        self.expand = expand\n\n    @classmethod\n    def indent(cls, renderable: \"RenderableType\", level: int) -> \"Padding\":\n        \"\"\"Make padding instance to render an indent.\n\n        Args:\n            renderable (RenderableType): String or other renderable.\n            level (int): Number of characters to indent.\n\n        Returns:\n            Padding: A Padding instance.\n        \"\"\"\n\n        return Padding(renderable, pad=(0, 0, 0, level), expand=False)\n\n    @staticmethod\n    def unpack(pad: \"PaddingDimensions\") -> Tuple[int, int, int, int]:\n        \"\"\"Unpack padding specified in CSS style.\"\"\"\n        if isinstance(pad, int):\n            return (pad, pad, pad, pad)\n        if len(pad) == 1:\n            _pad = pad[0]\n            return (_pad, _pad, _pad, _pad)\n        if len(pad) == 2:\n            pad_top, pad_right = pad\n            return (pad_top, pad_right, pad_top, pad_right)\n        if len(pad) == 4:\n            top, right, bottom, left = pad\n            return (top, right, bottom, left)\n        raise ValueError(f\"1, 2 or 4 integers required for padding; {len(pad)} given\")\n\n    def __repr__(self) -> str:\n        return f\"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style)\n        if self.expand:\n            width = options.max_width\n        else:\n            width = min(\n                Measurement.get(console, options, self.renderable).maximum\n                + self.left\n                + self.right,\n                options.max_width,\n            )\n        render_options = options.update_width(width - self.left - self.right)\n        if render_options.height is not None:\n            render_options = render_options.update_height(\n                height=render_options.height - self.top - self.bottom\n            )\n        lines = console.render_lines(\n            self.renderable, render_options, style=style, pad=True\n        )\n        _Segment = Segment\n\n        left = _Segment(\" \" * self.left, style) if self.left else None\n        right = (\n            [_Segment(f'{\" \" * self.right}', style), _Segment.line()]\n            if self.right\n            else [_Segment.line()]\n        )\n        blank_line: Optional[List[Segment]] = None\n        if self.top:\n            blank_line = [_Segment(f'{\" \" * width}\\n', style)]\n            yield from blank_line * self.top\n        if left:\n            for line in lines:\n                yield left\n                yield from line\n                yield from right\n        else:\n            for line in lines:\n                yield from line\n                yield from right\n        if self.bottom:\n            blank_line = blank_line or [_Segment(f'{\" \" * width}\\n', style)]\n            yield from blank_line * self.bottom\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        max_width = options.max_width\n        extra_width = self.left + self.right\n        if max_width - extra_width < 1:\n            return Measurement(max_width, max_width)\n        measure_min, measure_max = Measurement.get(console, options, self.renderable)\n        measurement = Measurement(measure_min + extra_width, measure_max + extra_width)\n        measurement = measurement.with_maximum(max_width)\n        return measurement\n\n\nif __name__ == \"__main__\":  #  pragma: no cover\n    from pip._vendor.rich import print\n\n    print(Padding(\"Hello, World\", (2, 4), style=\"on blue\"))\n"
  },
  {
    "path": "src/pip/_vendor/rich/pager.py",
    "content": "from abc import ABC, abstractmethod\nfrom typing import Any\n\n\nclass Pager(ABC):\n    \"\"\"Base class for a pager.\"\"\"\n\n    @abstractmethod\n    def show(self, content: str) -> None:\n        \"\"\"Show content in pager.\n\n        Args:\n            content (str): Content to be displayed.\n        \"\"\"\n\n\nclass SystemPager(Pager):\n    \"\"\"Uses the pager installed on the system.\"\"\"\n\n    def _pager(self, content: str) -> Any:  #  pragma: no cover\n        return __import__(\"pydoc\").pager(content)\n\n    def show(self, content: str) -> None:\n        \"\"\"Use the same pager used by pydoc.\"\"\"\n        self._pager(content)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .__main__ import make_test_card\n    from .console import Console\n\n    console = Console()\n    with console.pager(styles=True):\n        console.print(make_test_card())\n"
  },
  {
    "path": "src/pip/_vendor/rich/palette.py",
    "content": "from math import sqrt\nfrom functools import lru_cache\nfrom typing import Sequence, Tuple, TYPE_CHECKING\n\nfrom .color_triplet import ColorTriplet\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.table import Table\n\n\nclass Palette:\n    \"\"\"A palette of available colors.\"\"\"\n\n    def __init__(self, colors: Sequence[Tuple[int, int, int]]):\n        self._colors = colors\n\n    def __getitem__(self, number: int) -> ColorTriplet:\n        return ColorTriplet(*self._colors[number])\n\n    def __rich__(self) -> \"Table\":\n        from pip._vendor.rich.color import Color\n        from pip._vendor.rich.style import Style\n        from pip._vendor.rich.text import Text\n        from pip._vendor.rich.table import Table\n\n        table = Table(\n            \"index\",\n            \"RGB\",\n            \"Color\",\n            title=\"Palette\",\n            caption=f\"{len(self._colors)} colors\",\n            highlight=True,\n            caption_justify=\"right\",\n        )\n        for index, color in enumerate(self._colors):\n            table.add_row(\n                str(index),\n                repr(color),\n                Text(\" \" * 16, style=Style(bgcolor=Color.from_rgb(*color))),\n            )\n        return table\n\n    # This is somewhat inefficient and needs caching\n    @lru_cache(maxsize=1024)\n    def match(self, color: Tuple[int, int, int]) -> int:\n        \"\"\"Find a color from a palette that most closely matches a given color.\n\n        Args:\n            color (Tuple[int, int, int]): RGB components in range 0 > 255.\n\n        Returns:\n            int: Index of closes matching color.\n        \"\"\"\n        red1, green1, blue1 = color\n        _sqrt = sqrt\n        get_color = self._colors.__getitem__\n\n        def get_color_distance(index: int) -> float:\n            \"\"\"Get the distance to a color.\"\"\"\n            red2, green2, blue2 = get_color(index)\n            red_mean = (red1 + red2) // 2\n            red = red1 - red2\n            green = green1 - green2\n            blue = blue1 - blue2\n            return _sqrt(\n                (((512 + red_mean) * red * red) >> 8)\n                + 4 * green * green\n                + (((767 - red_mean) * blue * blue) >> 8)\n            )\n\n        min_index = min(range(len(self._colors)), key=get_color_distance)\n        return min_index\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import colorsys\n    from typing import Iterable\n    from pip._vendor.rich.color import Color\n    from pip._vendor.rich.console import Console, ConsoleOptions\n    from pip._vendor.rich.segment import Segment\n    from pip._vendor.rich.style import Style\n\n    class ColorBox:\n        def __rich_console__(\n            self, console: Console, options: ConsoleOptions\n        ) -> Iterable[Segment]:\n            height = console.size.height - 3\n            for y in range(0, height):\n                for x in range(options.max_width):\n                    h = x / options.max_width\n                    l = y / (height + 1)\n                    r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)\n                    r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0)\n                    bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)\n                    color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)\n                    yield Segment(\"▄\", Style(color=color, bgcolor=bgcolor))\n                yield Segment.line()\n\n    console = Console()\n    console.print(ColorBox())\n"
  },
  {
    "path": "src/pip/_vendor/rich/panel.py",
    "content": "from typing import TYPE_CHECKING, Optional\n\nfrom .align import AlignMethod\nfrom .box import ROUNDED, Box\nfrom .cells import cell_len\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement, measure_renderables\nfrom .padding import Padding, PaddingDimensions\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\n\nclass Panel(JupyterMixin):\n    \"\"\"A console renderable that draws a border around its contents.\n\n    Example:\n        >>> console.print(Panel(\"Hello, World!\"))\n\n    Args:\n        renderable (RenderableType): A console renderable object.\n        box (Box): A Box instance that defines the look of the border (see :ref:`appendix_box`. Defaults to box.ROUNDED.\n        title (Optional[TextType], optional): Optional title displayed in panel header. Defaults to None.\n        title_align (AlignMethod, optional): Alignment of title. Defaults to \"center\".\n        subtitle (Optional[TextType], optional): Optional subtitle displayed in panel footer. Defaults to None.\n        subtitle_align (AlignMethod, optional): Alignment of subtitle. Defaults to \"center\".\n        safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        expand (bool, optional): If True the panel will stretch to fill the console width, otherwise it will be sized to fit the contents. Defaults to True.\n        style (str, optional): The style of the panel (border and contents). Defaults to \"none\".\n        border_style (str, optional): The style of the border. Defaults to \"none\".\n        width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect.\n        height (Optional[int], optional): Optional height of panel. Defaults to None to auto-detect.\n        padding (Optional[PaddingDimensions]): Optional padding around renderable. Defaults to 0.\n        highlight (bool, optional): Enable automatic highlighting of panel title (if str). Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        box: Box = ROUNDED,\n        *,\n        title: Optional[TextType] = None,\n        title_align: AlignMethod = \"center\",\n        subtitle: Optional[TextType] = None,\n        subtitle_align: AlignMethod = \"center\",\n        safe_box: Optional[bool] = None,\n        expand: bool = True,\n        style: StyleType = \"none\",\n        border_style: StyleType = \"none\",\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        padding: PaddingDimensions = (0, 1),\n        highlight: bool = False,\n    ) -> None:\n        self.renderable = renderable\n        self.box = box\n        self.title = title\n        self.title_align: AlignMethod = title_align\n        self.subtitle = subtitle\n        self.subtitle_align = subtitle_align\n        self.safe_box = safe_box\n        self.expand = expand\n        self.style = style\n        self.border_style = border_style\n        self.width = width\n        self.height = height\n        self.padding = padding\n        self.highlight = highlight\n\n    @classmethod\n    def fit(\n        cls,\n        renderable: \"RenderableType\",\n        box: Box = ROUNDED,\n        *,\n        title: Optional[TextType] = None,\n        title_align: AlignMethod = \"center\",\n        subtitle: Optional[TextType] = None,\n        subtitle_align: AlignMethod = \"center\",\n        safe_box: Optional[bool] = None,\n        style: StyleType = \"none\",\n        border_style: StyleType = \"none\",\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        padding: PaddingDimensions = (0, 1),\n        highlight: bool = False,\n    ) -> \"Panel\":\n        \"\"\"An alternative constructor that sets expand=False.\"\"\"\n        return cls(\n            renderable,\n            box,\n            title=title,\n            title_align=title_align,\n            subtitle=subtitle,\n            subtitle_align=subtitle_align,\n            safe_box=safe_box,\n            style=style,\n            border_style=border_style,\n            width=width,\n            height=height,\n            padding=padding,\n            highlight=highlight,\n            expand=False,\n        )\n\n    @property\n    def _title(self) -> Optional[Text]:\n        if self.title:\n            title_text = (\n                Text.from_markup(self.title)\n                if isinstance(self.title, str)\n                else self.title.copy()\n            )\n            title_text.end = \"\"\n            title_text.plain = title_text.plain.replace(\"\\n\", \" \")\n            title_text.no_wrap = True\n            title_text.expand_tabs()\n            title_text.pad(1)\n            return title_text\n        return None\n\n    @property\n    def _subtitle(self) -> Optional[Text]:\n        if self.subtitle:\n            subtitle_text = (\n                Text.from_markup(self.subtitle)\n                if isinstance(self.subtitle, str)\n                else self.subtitle.copy()\n            )\n            subtitle_text.end = \"\"\n            subtitle_text.plain = subtitle_text.plain.replace(\"\\n\", \" \")\n            subtitle_text.no_wrap = True\n            subtitle_text.expand_tabs()\n            subtitle_text.pad(1)\n            return subtitle_text\n        return None\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        _padding = Padding.unpack(self.padding)\n        renderable = (\n            Padding(self.renderable, _padding) if any(_padding) else self.renderable\n        )\n        style = console.get_style(self.style)\n        border_style = style + console.get_style(self.border_style)\n        width = (\n            options.max_width\n            if self.width is None\n            else min(options.max_width, self.width)\n        )\n\n        safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box\n        box = self.box.substitute(options, safe=safe_box)\n\n        def align_text(\n            text: Text, width: int, align: str, character: str, style: Style\n        ) -> Text:\n            \"\"\"Gets new aligned text.\n\n            Args:\n                text (Text): Title or subtitle text.\n                width (int): Desired width.\n                align (str): Alignment.\n                character (str): Character for alignment.\n                style (Style): Border style\n\n            Returns:\n                Text: New text instance\n            \"\"\"\n            text = text.copy()\n            text.truncate(width)\n            excess_space = width - cell_len(text.plain)\n            if text.style:\n                text.stylize(console.get_style(text.style))\n\n            if excess_space:\n                if align == \"left\":\n                    return Text.assemble(\n                        text,\n                        (character * excess_space, style),\n                        no_wrap=True,\n                        end=\"\",\n                    )\n                elif align == \"center\":\n                    left = excess_space // 2\n                    return Text.assemble(\n                        (character * left, style),\n                        text,\n                        (character * (excess_space - left), style),\n                        no_wrap=True,\n                        end=\"\",\n                    )\n                else:\n                    return Text.assemble(\n                        (character * excess_space, style),\n                        text,\n                        no_wrap=True,\n                        end=\"\",\n                    )\n            return text\n\n        title_text = self._title\n        if title_text is not None:\n            title_text.stylize_before(border_style)\n\n        child_width = (\n            width - 2\n            if self.expand\n            else console.measure(\n                renderable, options=options.update_width(width - 2)\n            ).maximum\n        )\n        child_height = self.height or options.height or None\n        if child_height:\n            child_height -= 2\n        if title_text is not None:\n            child_width = min(\n                options.max_width - 2, max(child_width, title_text.cell_len + 2)\n            )\n\n        width = child_width + 2\n        child_options = options.update(\n            width=child_width, height=child_height, highlight=self.highlight\n        )\n        lines = console.render_lines(renderable, child_options, style=style)\n\n        line_start = Segment(box.mid_left, border_style)\n        line_end = Segment(f\"{box.mid_right}\", border_style)\n        new_line = Segment.line()\n        if title_text is None or width <= 4:\n            yield Segment(box.get_top([width - 2]), border_style)\n        else:\n            title_text = align_text(\n                title_text,\n                width - 4,\n                self.title_align,\n                box.top,\n                border_style,\n            )\n            yield Segment(box.top_left + box.top, border_style)\n            yield from console.render(title_text, child_options.update_width(width - 4))\n            yield Segment(box.top + box.top_right, border_style)\n\n        yield new_line\n        for line in lines:\n            yield line_start\n            yield from line\n            yield line_end\n            yield new_line\n\n        subtitle_text = self._subtitle\n        if subtitle_text is not None:\n            subtitle_text.stylize_before(border_style)\n\n        if subtitle_text is None or width <= 4:\n            yield Segment(box.get_bottom([width - 2]), border_style)\n        else:\n            subtitle_text = align_text(\n                subtitle_text,\n                width - 4,\n                self.subtitle_align,\n                box.bottom,\n                border_style,\n            )\n            yield Segment(box.bottom_left + box.bottom, border_style)\n            yield from console.render(\n                subtitle_text, child_options.update_width(width - 4)\n            )\n            yield Segment(box.bottom + box.bottom_right, border_style)\n\n        yield new_line\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        _title = self._title\n        _, right, _, left = Padding.unpack(self.padding)\n        padding = left + right\n        renderables = [self.renderable, _title] if _title else [self.renderable]\n\n        if self.width is None:\n            width = (\n                measure_renderables(\n                    console,\n                    options.update_width(options.max_width - padding - 2),\n                    renderables,\n                ).maximum\n                + padding\n                + 2\n            )\n        else:\n            width = self.width\n        return Measurement(width, width)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    c = Console()\n\n    from .box import DOUBLE, ROUNDED\n    from .padding import Padding\n\n    p = Panel(\n        \"Hello, World!\",\n        title=\"rich.Panel\",\n        style=\"white on blue\",\n        box=DOUBLE,\n        padding=1,\n    )\n\n    c.print()\n    c.print(p)\n"
  },
  {
    "path": "src/pip/_vendor/rich/pretty.py",
    "content": "import builtins\nimport collections\nimport dataclasses\nimport inspect\nimport os\nimport reprlib\nimport sys\nfrom array import array\nfrom collections import Counter, UserDict, UserList, defaultdict, deque\nfrom dataclasses import dataclass, fields, is_dataclass\nfrom inspect import isclass\nfrom itertools import islice\nfrom types import MappingProxyType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    DefaultDict,\n    Deque,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n)\n\nfrom pip._vendor.rich.repr import RichReprResult\n\ntry:\n    import attr as _attr_module\n\n    _has_attrs = hasattr(_attr_module, \"ib\")\nexcept ImportError:  # pragma: no cover\n    _has_attrs = False\n\nfrom . import get_console\nfrom ._loop import loop_last\nfrom ._pick import pick_bool\nfrom .abc import RichRenderable\nfrom .cells import cell_len\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin, JupyterRenderable\nfrom .measure import Measurement\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        HighlighterType,\n        JustifyMethod,\n        OverflowMethod,\n        RenderResult,\n    )\n\n\ndef _is_attr_object(obj: Any) -> bool:\n    \"\"\"Check if an object was created with attrs module.\"\"\"\n    return _has_attrs and _attr_module.has(type(obj))\n\n\ndef _get_attr_fields(obj: Any) -> Sequence[\"_attr_module.Attribute[Any]\"]:\n    \"\"\"Get fields for an attrs object.\"\"\"\n    return _attr_module.fields(type(obj)) if _has_attrs else []\n\n\ndef _is_dataclass_repr(obj: object) -> bool:\n    \"\"\"Check if an instance of a dataclass contains the default repr.\n\n    Args:\n        obj (object): A dataclass instance.\n\n    Returns:\n        bool: True if the default repr is used, False if there is a custom repr.\n    \"\"\"\n    # Digging in to a lot of internals here\n    # Catching all exceptions in case something is missing on a non CPython implementation\n    try:\n        return obj.__repr__.__code__.co_filename in (\n            dataclasses.__file__,\n            reprlib.__file__,\n        )\n    except Exception:  # pragma: no coverage\n        return False\n\n\n_dummy_namedtuple = collections.namedtuple(\"_dummy_namedtuple\", [])\n\n\ndef _has_default_namedtuple_repr(obj: object) -> bool:\n    \"\"\"Check if an instance of namedtuple contains the default repr\n\n    Args:\n        obj (object): A namedtuple\n\n    Returns:\n        bool: True if the default repr is used, False if there's a custom repr.\n    \"\"\"\n    obj_file = None\n    try:\n        obj_file = inspect.getfile(obj.__repr__)\n    except (OSError, TypeError):\n        # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.\n        # TypeError trapped defensively, in case of object without filename slips through.\n        pass\n    default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__)\n    return obj_file == default_repr_file\n\n\ndef _ipy_display_hook(\n    value: Any,\n    console: Optional[\"Console\"] = None,\n    overflow: \"OverflowMethod\" = \"ignore\",\n    crop: bool = False,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> Union[str, None]:\n    # needed here to prevent circular import:\n    from .console import ConsoleRenderable\n\n    # always skip rich generated jupyter renderables or None values\n    if _safe_isinstance(value, JupyterRenderable) or value is None:\n        return None\n\n    console = console or get_console()\n\n    with console.capture() as capture:\n        # certain renderables should start on a new line\n        if _safe_isinstance(value, ConsoleRenderable):\n            console.line()\n        console.print(\n            (\n                value\n                if _safe_isinstance(value, RichRenderable)\n                else Pretty(\n                    value,\n                    overflow=overflow,\n                    indent_guides=indent_guides,\n                    max_length=max_length,\n                    max_string=max_string,\n                    max_depth=max_depth,\n                    expand_all=expand_all,\n                    margin=12,\n                )\n            ),\n            crop=crop,\n            new_line_start=True,\n            end=\"\",\n        )\n    # strip trailing newline, not usually part of a text repr\n    # I'm not sure if this should be prevented at a lower level\n    return capture.get().rstrip(\"\\n\")\n\n\ndef _safe_isinstance(\n    obj: object, class_or_tuple: Union[type, Tuple[type, ...]]\n) -> bool:\n    \"\"\"isinstance can fail in rare cases, for example types with no __class__\"\"\"\n    try:\n        return isinstance(obj, class_or_tuple)\n    except Exception:\n        return False\n\n\ndef install(\n    console: Optional[\"Console\"] = None,\n    overflow: \"OverflowMethod\" = \"ignore\",\n    crop: bool = False,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> None:\n    \"\"\"Install automatic pretty printing in the Python REPL.\n\n    Args:\n        console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.\n        overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to \"ignore\".\n        crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n        max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n    \"\"\"\n    from pip._vendor.rich import get_console\n\n    console = console or get_console()\n    assert console is not None\n\n    def display_hook(value: Any) -> None:\n        \"\"\"Replacement sys.displayhook which prettifies objects with Rich.\"\"\"\n        if value is not None:\n            assert console is not None\n            builtins._ = None  # type: ignore[attr-defined]\n            console.print(\n                (\n                    value\n                    if _safe_isinstance(value, RichRenderable)\n                    else Pretty(\n                        value,\n                        overflow=overflow,\n                        indent_guides=indent_guides,\n                        max_length=max_length,\n                        max_string=max_string,\n                        max_depth=max_depth,\n                        expand_all=expand_all,\n                    )\n                ),\n                crop=crop,\n            )\n            builtins._ = value  # type: ignore[attr-defined]\n\n    try:\n        ip = get_ipython()  # type: ignore[name-defined]\n    except NameError:\n        sys.displayhook = display_hook\n    else:\n        from IPython.core.formatters import BaseFormatter\n\n        class RichFormatter(BaseFormatter):  # type: ignore[misc]\n            pprint: bool = True\n\n            def __call__(self, value: Any) -> Any:\n                if self.pprint:\n                    return _ipy_display_hook(\n                        value,\n                        console=get_console(),\n                        overflow=overflow,\n                        indent_guides=indent_guides,\n                        max_length=max_length,\n                        max_string=max_string,\n                        max_depth=max_depth,\n                        expand_all=expand_all,\n                    )\n                else:\n                    return repr(value)\n\n        # replace plain text formatter with rich formatter\n        rich_formatter = RichFormatter()\n        ip.display_formatter.formatters[\"text/plain\"] = rich_formatter\n\n\nclass Pretty(JupyterMixin):\n    \"\"\"A rich renderable that pretty prints an object.\n\n    Args:\n        _object (Any): An object to pretty print.\n        highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.\n        indent_size (int, optional): Number of spaces in indent. Defaults to 4.\n        justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.\n        overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.\n        no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n        max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n        margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.\n        insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        _object: Any,\n        highlighter: Optional[\"HighlighterType\"] = None,\n        *,\n        indent_size: int = 4,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = False,\n        indent_guides: bool = False,\n        max_length: Optional[int] = None,\n        max_string: Optional[int] = None,\n        max_depth: Optional[int] = None,\n        expand_all: bool = False,\n        margin: int = 0,\n        insert_line: bool = False,\n    ) -> None:\n        self._object = _object\n        self.highlighter = highlighter or ReprHighlighter()\n        self.indent_size = indent_size\n        self.justify: Optional[\"JustifyMethod\"] = justify\n        self.overflow: Optional[\"OverflowMethod\"] = overflow\n        self.no_wrap = no_wrap\n        self.indent_guides = indent_guides\n        self.max_length = max_length\n        self.max_string = max_string\n        self.max_depth = max_depth\n        self.expand_all = expand_all\n        self.margin = margin\n        self.insert_line = insert_line\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        pretty_str = pretty_repr(\n            self._object,\n            max_width=options.max_width - self.margin,\n            indent_size=self.indent_size,\n            max_length=self.max_length,\n            max_string=self.max_string,\n            max_depth=self.max_depth,\n            expand_all=self.expand_all,\n        )\n        pretty_text = Text.from_ansi(\n            pretty_str,\n            justify=self.justify or options.justify,\n            overflow=self.overflow or options.overflow,\n            no_wrap=pick_bool(self.no_wrap, options.no_wrap),\n            style=\"pretty\",\n        )\n        pretty_text = (\n            self.highlighter(pretty_text)\n            if pretty_text\n            else Text(\n                f\"{type(self._object)}.__repr__ returned empty string\",\n                style=\"dim italic\",\n            )\n        )\n        if self.indent_guides and not options.ascii_only:\n            pretty_text = pretty_text.with_indent_guides(\n                self.indent_size, style=\"repr.indent\"\n            )\n        if self.insert_line and \"\\n\" in pretty_text:\n            yield \"\"\n        yield pretty_text\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        pretty_str = pretty_repr(\n            self._object,\n            max_width=options.max_width,\n            indent_size=self.indent_size,\n            max_length=self.max_length,\n            max_string=self.max_string,\n            max_depth=self.max_depth,\n            expand_all=self.expand_all,\n        )\n        text_width = (\n            max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0\n        )\n        return Measurement(text_width, text_width)\n\n\ndef _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:\n    return (\n        f\"defaultdict({_object.default_factory!r}, {{\",\n        \"})\",\n        f\"defaultdict({_object.default_factory!r}, {{}})\",\n    )\n\n\ndef _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]:\n    if _object.maxlen is None:\n        return (\"deque([\", \"])\", \"deque()\")\n    return (\n        \"deque([\",\n        f\"], maxlen={_object.maxlen})\",\n        f\"deque(maxlen={_object.maxlen})\",\n    )\n\n\ndef _get_braces_for_array(_object: \"array[Any]\") -> Tuple[str, str, str]:\n    return (f\"array({_object.typecode!r}, [\", \"])\", f\"array({_object.typecode!r})\")\n\n\n_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {\n    os._Environ: lambda _object: (\"environ({\", \"})\", \"environ({})\"),\n    array: _get_braces_for_array,\n    defaultdict: _get_braces_for_defaultdict,\n    Counter: lambda _object: (\"Counter({\", \"})\", \"Counter()\"),\n    deque: _get_braces_for_deque,\n    dict: lambda _object: (\"{\", \"}\", \"{}\"),\n    UserDict: lambda _object: (\"{\", \"}\", \"{}\"),\n    frozenset: lambda _object: (\"frozenset({\", \"})\", \"frozenset()\"),\n    list: lambda _object: (\"[\", \"]\", \"[]\"),\n    UserList: lambda _object: (\"[\", \"]\", \"[]\"),\n    set: lambda _object: (\"{\", \"}\", \"set()\"),\n    tuple: lambda _object: (\"(\", \")\", \"()\"),\n    MappingProxyType: lambda _object: (\"mappingproxy({\", \"})\", \"mappingproxy({})\"),\n}\n_CONTAINERS = tuple(_BRACES.keys())\n_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)\n\n\ndef is_expandable(obj: Any) -> bool:\n    \"\"\"Check if an object may be expanded by pretty print.\"\"\"\n    return (\n        _safe_isinstance(obj, _CONTAINERS)\n        or (is_dataclass(obj))\n        or (hasattr(obj, \"__rich_repr__\"))\n        or _is_attr_object(obj)\n    ) and not isclass(obj)\n\n\n@dataclass\nclass Node:\n    \"\"\"A node in a repr tree. May be atomic or a container.\"\"\"\n\n    key_repr: str = \"\"\n    value_repr: str = \"\"\n    open_brace: str = \"\"\n    close_brace: str = \"\"\n    empty: str = \"\"\n    last: bool = False\n    is_tuple: bool = False\n    is_namedtuple: bool = False\n    children: Optional[List[\"Node\"]] = None\n    key_separator: str = \": \"\n    separator: str = \", \"\n\n    def iter_tokens(self) -> Iterable[str]:\n        \"\"\"Generate tokens for this node.\"\"\"\n        if self.key_repr:\n            yield self.key_repr\n            yield self.key_separator\n        if self.value_repr:\n            yield self.value_repr\n        elif self.children is not None:\n            if self.children:\n                yield self.open_brace\n                if self.is_tuple and not self.is_namedtuple and len(self.children) == 1:\n                    yield from self.children[0].iter_tokens()\n                    yield \",\"\n                else:\n                    for child in self.children:\n                        yield from child.iter_tokens()\n                        if not child.last:\n                            yield self.separator\n                yield self.close_brace\n            else:\n                yield self.empty\n\n    def check_length(self, start_length: int, max_length: int) -> bool:\n        \"\"\"Check the length fits within a limit.\n\n        Args:\n            start_length (int): Starting length of the line (indent, prefix, suffix).\n            max_length (int): Maximum length.\n\n        Returns:\n            bool: True if the node can be rendered within max length, otherwise False.\n        \"\"\"\n        total_length = start_length\n        for token in self.iter_tokens():\n            total_length += cell_len(token)\n            if total_length > max_length:\n                return False\n        return True\n\n    def __str__(self) -> str:\n        repr_text = \"\".join(self.iter_tokens())\n        return repr_text\n\n    def render(\n        self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False\n    ) -> str:\n        \"\"\"Render the node to a pretty repr.\n\n        Args:\n            max_width (int, optional): Maximum width of the repr. Defaults to 80.\n            indent_size (int, optional): Size of indents. Defaults to 4.\n            expand_all (bool, optional): Expand all levels. Defaults to False.\n\n        Returns:\n            str: A repr string of the original object.\n        \"\"\"\n        lines = [_Line(node=self, is_root=True)]\n        line_no = 0\n        while line_no < len(lines):\n            line = lines[line_no]\n            if line.expandable and not line.expanded:\n                if expand_all or not line.check_length(max_width):\n                    lines[line_no : line_no + 1] = line.expand(indent_size)\n            line_no += 1\n\n        repr_str = \"\\n\".join(str(line) for line in lines)\n        return repr_str\n\n\n@dataclass\nclass _Line:\n    \"\"\"A line in repr output.\"\"\"\n\n    parent: Optional[\"_Line\"] = None\n    is_root: bool = False\n    node: Optional[Node] = None\n    text: str = \"\"\n    suffix: str = \"\"\n    whitespace: str = \"\"\n    expanded: bool = False\n    last: bool = False\n\n    @property\n    def expandable(self) -> bool:\n        \"\"\"Check if the line may be expanded.\"\"\"\n        return bool(self.node is not None and self.node.children)\n\n    def check_length(self, max_length: int) -> bool:\n        \"\"\"Check this line fits within a given number of cells.\"\"\"\n        start_length = (\n            len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)\n        )\n        assert self.node is not None\n        return self.node.check_length(start_length, max_length)\n\n    def expand(self, indent_size: int) -> Iterable[\"_Line\"]:\n        \"\"\"Expand this line by adding children on their own line.\"\"\"\n        node = self.node\n        assert node is not None\n        whitespace = self.whitespace\n        assert node.children\n        if node.key_repr:\n            new_line = yield _Line(\n                text=f\"{node.key_repr}{node.key_separator}{node.open_brace}\",\n                whitespace=whitespace,\n            )\n        else:\n            new_line = yield _Line(text=node.open_brace, whitespace=whitespace)\n        child_whitespace = self.whitespace + \" \" * indent_size\n        tuple_of_one = node.is_tuple and len(node.children) == 1\n        for last, child in loop_last(node.children):\n            separator = \",\" if tuple_of_one else node.separator\n            line = _Line(\n                parent=new_line,\n                node=child,\n                whitespace=child_whitespace,\n                suffix=separator,\n                last=last and not tuple_of_one,\n            )\n            yield line\n\n        yield _Line(\n            text=node.close_brace,\n            whitespace=whitespace,\n            suffix=self.suffix,\n            last=self.last,\n        )\n\n    def __str__(self) -> str:\n        if self.last:\n            return f\"{self.whitespace}{self.text}{self.node or ''}\"\n        else:\n            return (\n                f\"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}\"\n            )\n\n\ndef _is_namedtuple(obj: Any) -> bool:\n    \"\"\"Checks if an object is most likely a namedtuple. It is possible\n    to craft an object that passes this check and isn't a namedtuple, but\n    there is only a minuscule chance of this happening unintentionally.\n\n    Args:\n        obj (Any): The object to test\n\n    Returns:\n        bool: True if the object is a namedtuple. False otherwise.\n    \"\"\"\n    try:\n        fields = getattr(obj, \"_fields\", None)\n    except Exception:\n        # Being very defensive - if we cannot get the attr then its not a namedtuple\n        return False\n    return isinstance(obj, tuple) and isinstance(fields, tuple)\n\n\ndef traverse(\n    _object: Any,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n) -> Node:\n    \"\"\"Traverse object and generate a tree.\n\n    Args:\n        _object (Any): Object to be traversed.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n            Defaults to None.\n        max_depth (int, optional): Maximum depth of data structures, or None for no maximum.\n            Defaults to None.\n\n    Returns:\n        Node: The root of a tree structure which can be used to render a pretty repr.\n    \"\"\"\n\n    def to_repr(obj: Any) -> str:\n        \"\"\"Get repr string for an object, but catch errors.\"\"\"\n        if (\n            max_string is not None\n            and _safe_isinstance(obj, (bytes, str))\n            and len(obj) > max_string\n        ):\n            truncated = len(obj) - max_string\n            obj_repr = f\"{obj[:max_string]!r}+{truncated}\"\n        else:\n            try:\n                obj_repr = repr(obj)\n            except Exception as error:\n                obj_repr = f\"<repr-error {str(error)!r}>\"\n        return obj_repr\n\n    visited_ids: Set[int] = set()\n    push_visited = visited_ids.add\n    pop_visited = visited_ids.remove\n\n    def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:\n        \"\"\"Walk the object depth first.\"\"\"\n\n        obj_id = id(obj)\n        if obj_id in visited_ids:\n            # Recursion detected\n            return Node(value_repr=\"...\")\n\n        obj_type = type(obj)\n        children: List[Node]\n        reached_max_depth = max_depth is not None and depth >= max_depth\n\n        def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:\n            for arg in rich_args:\n                if _safe_isinstance(arg, tuple):\n                    if len(arg) == 3:\n                        key, child, default = arg\n                        if default == child:\n                            continue\n                        yield key, child\n                    elif len(arg) == 2:\n                        key, child = arg\n                        yield key, child\n                    elif len(arg) == 1:\n                        yield arg[0]\n                else:\n                    yield arg\n\n        try:\n            fake_attributes = hasattr(\n                obj, \"awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492\"\n            )\n        except Exception:\n            fake_attributes = False\n\n        rich_repr_result: Optional[RichReprResult] = None\n        if not fake_attributes:\n            try:\n                if hasattr(obj, \"__rich_repr__\") and not isclass(obj):\n                    rich_repr_result = obj.__rich_repr__()\n            except Exception:\n                pass\n\n        if rich_repr_result is not None:\n            push_visited(obj_id)\n            angular = getattr(obj.__rich_repr__, \"angular\", False)\n            args = list(iter_rich_args(rich_repr_result))\n            class_name = obj.__class__.__name__\n\n            if args:\n                children = []\n                append = children.append\n\n                if reached_max_depth:\n                    if angular:\n                        node = Node(value_repr=f\"<{class_name}...>\")\n                    else:\n                        node = Node(value_repr=f\"{class_name}(...)\")\n                else:\n                    if angular:\n                        node = Node(\n                            open_brace=f\"<{class_name} \",\n                            close_brace=\">\",\n                            children=children,\n                            last=root,\n                            separator=\" \",\n                        )\n                    else:\n                        node = Node(\n                            open_brace=f\"{class_name}(\",\n                            close_brace=\")\",\n                            children=children,\n                            last=root,\n                        )\n                    for last, arg in loop_last(args):\n                        if _safe_isinstance(arg, tuple):\n                            key, child = arg\n                            child_node = _traverse(child, depth=depth + 1)\n                            child_node.last = last\n                            child_node.key_repr = key\n                            child_node.key_separator = \"=\"\n                            append(child_node)\n                        else:\n                            child_node = _traverse(arg, depth=depth + 1)\n                            child_node.last = last\n                            append(child_node)\n            else:\n                node = Node(\n                    value_repr=f\"<{class_name}>\" if angular else f\"{class_name}()\",\n                    children=[],\n                    last=root,\n                )\n            pop_visited(obj_id)\n        elif _is_attr_object(obj) and not fake_attributes:\n            push_visited(obj_id)\n            children = []\n            append = children.append\n\n            attr_fields = _get_attr_fields(obj)\n            if attr_fields:\n                if reached_max_depth:\n                    node = Node(value_repr=f\"{obj.__class__.__name__}(...)\")\n                else:\n                    node = Node(\n                        open_brace=f\"{obj.__class__.__name__}(\",\n                        close_brace=\")\",\n                        children=children,\n                        last=root,\n                    )\n\n                    def iter_attrs() -> (\n                        Iterable[Tuple[str, Any, Optional[Callable[[Any], str]]]]\n                    ):\n                        \"\"\"Iterate over attr fields and values.\"\"\"\n                        for attr in attr_fields:\n                            if attr.repr:\n                                try:\n                                    value = getattr(obj, attr.name)\n                                except Exception as error:\n                                    # Can happen, albeit rarely\n                                    yield (attr.name, error, None)\n                                else:\n                                    yield (\n                                        attr.name,\n                                        value,\n                                        attr.repr if callable(attr.repr) else None,\n                                    )\n\n                    for last, (name, value, repr_callable) in loop_last(iter_attrs()):\n                        if repr_callable:\n                            child_node = Node(value_repr=str(repr_callable(value)))\n                        else:\n                            child_node = _traverse(value, depth=depth + 1)\n                        child_node.last = last\n                        child_node.key_repr = name\n                        child_node.key_separator = \"=\"\n                        append(child_node)\n            else:\n                node = Node(\n                    value_repr=f\"{obj.__class__.__name__}()\", children=[], last=root\n                )\n            pop_visited(obj_id)\n        elif (\n            is_dataclass(obj)\n            and not _safe_isinstance(obj, type)\n            and not fake_attributes\n            and _is_dataclass_repr(obj)\n        ):\n            push_visited(obj_id)\n            children = []\n            append = children.append\n            if reached_max_depth:\n                node = Node(value_repr=f\"{obj.__class__.__name__}(...)\")\n            else:\n                node = Node(\n                    open_brace=f\"{obj.__class__.__name__}(\",\n                    close_brace=\")\",\n                    children=children,\n                    last=root,\n                    empty=f\"{obj.__class__.__name__}()\",\n                )\n\n                for last, field in loop_last(\n                    field\n                    for field in fields(obj)\n                    if field.repr and hasattr(obj, field.name)\n                ):\n                    child_node = _traverse(getattr(obj, field.name), depth=depth + 1)\n                    child_node.key_repr = field.name\n                    child_node.last = last\n                    child_node.key_separator = \"=\"\n                    append(child_node)\n\n            pop_visited(obj_id)\n        elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):\n            push_visited(obj_id)\n            class_name = obj.__class__.__name__\n            if reached_max_depth:\n                # If we've reached the max depth, we still show the class name, but not its contents\n                node = Node(\n                    value_repr=f\"{class_name}(...)\",\n                )\n            else:\n                children = []\n                append = children.append\n                node = Node(\n                    open_brace=f\"{class_name}(\",\n                    close_brace=\")\",\n                    children=children,\n                    empty=f\"{class_name}()\",\n                )\n                for last, (key, value) in loop_last(obj._asdict().items()):\n                    child_node = _traverse(value, depth=depth + 1)\n                    child_node.key_repr = key\n                    child_node.last = last\n                    child_node.key_separator = \"=\"\n                    append(child_node)\n            pop_visited(obj_id)\n        elif _safe_isinstance(obj, _CONTAINERS):\n            for container_type in _CONTAINERS:\n                if _safe_isinstance(obj, container_type):\n                    obj_type = container_type\n                    break\n\n            push_visited(obj_id)\n\n            open_brace, close_brace, empty = _BRACES[obj_type](obj)\n\n            if reached_max_depth:\n                node = Node(value_repr=f\"{open_brace}...{close_brace}\")\n            elif obj_type.__repr__ != type(obj).__repr__:\n                node = Node(value_repr=to_repr(obj), last=root)\n            elif obj:\n                children = []\n                node = Node(\n                    open_brace=open_brace,\n                    close_brace=close_brace,\n                    children=children,\n                    last=root,\n                )\n                append = children.append\n                num_items = len(obj)\n                last_item_index = num_items - 1\n\n                if _safe_isinstance(obj, _MAPPING_CONTAINERS):\n                    iter_items = iter(obj.items())\n                    if max_length is not None:\n                        iter_items = islice(iter_items, max_length)\n                    for index, (key, child) in enumerate(iter_items):\n                        child_node = _traverse(child, depth=depth + 1)\n                        child_node.key_repr = to_repr(key)\n                        child_node.last = index == last_item_index\n                        append(child_node)\n                else:\n                    iter_values = iter(obj)\n                    if max_length is not None:\n                        iter_values = islice(iter_values, max_length)\n                    for index, child in enumerate(iter_values):\n                        child_node = _traverse(child, depth=depth + 1)\n                        child_node.last = index == last_item_index\n                        append(child_node)\n                if max_length is not None and num_items > max_length:\n                    append(Node(value_repr=f\"... +{num_items - max_length}\", last=True))\n            else:\n                node = Node(empty=empty, children=[], last=root)\n\n            pop_visited(obj_id)\n        else:\n            node = Node(value_repr=to_repr(obj), last=root)\n        node.is_tuple = type(obj) == tuple\n        node.is_namedtuple = _is_namedtuple(obj)\n        return node\n\n    node = _traverse(_object, root=True)\n    return node\n\n\ndef pretty_repr(\n    _object: Any,\n    *,\n    max_width: int = 80,\n    indent_size: int = 4,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> str:\n    \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n    Args:\n        _object (Any): Object to repr.\n        max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n        indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n            Defaults to None.\n        max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n            Defaults to None.\n        expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n    Returns:\n        str: A possibly multi-line representation of the object.\n    \"\"\"\n\n    if _safe_isinstance(_object, Node):\n        node = _object\n    else:\n        node = traverse(\n            _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n        )\n    repr_str: str = node.render(\n        max_width=max_width, indent_size=indent_size, expand_all=expand_all\n    )\n    return repr_str\n\n\ndef pprint(\n    _object: Any,\n    *,\n    console: Optional[\"Console\"] = None,\n    indent_guides: bool = True,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> None:\n    \"\"\"A convenience function for pretty printing.\n\n    Args:\n        _object (Any): Object to pretty print.\n        console (Console, optional): Console instance, or None to use default. Defaults to None.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.\n        max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to True.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n    \"\"\"\n    _console = get_console() if console is None else console\n    _console.print(\n        Pretty(\n            _object,\n            max_length=max_length,\n            max_string=max_string,\n            max_depth=max_depth,\n            indent_guides=indent_guides,\n            expand_all=expand_all,\n            overflow=\"ignore\",\n        ),\n        soft_wrap=True,\n    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    class BrokenRepr:\n        def __repr__(self) -> str:\n            1 / 0\n            return \"this will fail\"\n\n    from typing import NamedTuple\n\n    class StockKeepingUnit(NamedTuple):\n        name: str\n        description: str\n        price: float\n        category: str\n        reviews: List[str]\n\n    d = defaultdict(int)\n    d[\"foo\"] = 5\n    data = {\n        \"foo\": [\n            1,\n            \"Hello World!\",\n            100.123,\n            323.232,\n            432324.0,\n            {5, 6, 7, (1, 2, 3, 4), 8},\n        ],\n        \"bar\": frozenset({1, 2, 3}),\n        \"defaultdict\": defaultdict(\n            list, {\"crumble\": [\"apple\", \"rhubarb\", \"butter\", \"sugar\", \"flour\"]}\n        ),\n        \"counter\": Counter(\n            [\n                \"apple\",\n                \"orange\",\n                \"pear\",\n                \"kumquat\",\n                \"kumquat\",\n                \"durian\" * 100,\n            ]\n        ),\n        \"atomic\": (False, True, None),\n        \"namedtuple\": StockKeepingUnit(\n            \"Sparkling British Spring Water\",\n            \"Carbonated spring water\",\n            0.9,\n            \"water\",\n            [\"its amazing!\", \"its terrible!\"],\n        ),\n        \"Broken\": BrokenRepr(),\n    }\n    data[\"foo\"].append(data)  # type: ignore[attr-defined]\n\n    from pip._vendor.rich import print\n\n    print(Pretty(data, indent_guides=True, max_string=20))\n\n    class Thing:\n        def __repr__(self) -> str:\n            return \"Hello\\x1b[38;5;239m World!\"\n\n    print(Pretty(Thing()))\n"
  },
  {
    "path": "src/pip/_vendor/rich/progress.py",
    "content": "from __future__ import annotations\n\nimport io\nimport typing\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom collections import deque\nfrom dataclasses import dataclass, field\nfrom datetime import timedelta\nfrom io import RawIOBase, UnsupportedOperation\nfrom math import ceil\nfrom mmap import mmap\nfrom operator import length_hint\nfrom os import PathLike, stat\nfrom threading import Event, RLock, Thread\nfrom types import TracebackType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    BinaryIO,\n    Callable,\n    ContextManager,\n    Deque,\n    Dict,\n    Generic,\n    Iterable,\n    List,\n    Literal,\n    NamedTuple,\n    NewType,\n    Optional,\n    TextIO,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n)\n\nif TYPE_CHECKING:\n    # Can be replaced with `from typing import Self` in Python 3.11+\n    from typing_extensions import Self  # pragma: no cover\n\nfrom . import filesize, get_console\nfrom .console import Console, Group, JustifyMethod, RenderableType\nfrom .highlighter import Highlighter\nfrom .jupyter import JupyterMixin\nfrom .live import Live\nfrom .progress_bar import ProgressBar\nfrom .spinner import Spinner\nfrom .style import StyleType\nfrom .table import Column, Table\nfrom .text import Text, TextType\n\nTaskID = NewType(\"TaskID\", int)\n\nProgressType = TypeVar(\"ProgressType\")\n\nGetTimeCallable = Callable[[], float]\n\n\n_I = typing.TypeVar(\"_I\", TextIO, BinaryIO)\n\n\nclass _TrackThread(Thread):\n    \"\"\"A thread to periodically update progress.\"\"\"\n\n    def __init__(self, progress: \"Progress\", task_id: \"TaskID\", update_period: float):\n        self.progress = progress\n        self.task_id = task_id\n        self.update_period = update_period\n        self.done = Event()\n\n        self.completed = 0\n        super().__init__(daemon=True)\n\n    def run(self) -> None:\n        task_id = self.task_id\n        advance = self.progress.advance\n        update_period = self.update_period\n        last_completed = 0\n        wait = self.done.wait\n        while not wait(update_period) and self.progress.live.is_started:\n            completed = self.completed\n            if last_completed != completed:\n                advance(task_id, completed - last_completed)\n                last_completed = completed\n\n        self.progress.update(self.task_id, completed=self.completed, refresh=True)\n\n    def __enter__(self) -> \"_TrackThread\":\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.done.set()\n        self.join()\n\n\ndef track(\n    sequence: Iterable[ProgressType],\n    description: str = \"Working...\",\n    total: Optional[float] = None,\n    completed: int = 0,\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    update_period: float = 0.1,\n    disable: bool = False,\n    show_speed: bool = True,\n) -> Iterable[ProgressType]:\n    \"\"\"Track progress by iterating over a sequence.\n\n    You can also track progress of an iterable, which might require that you additionally specify ``total``.\n\n    Args:\n        sequence (Iterable[ProgressType]): Values you wish to iterate over and track progress.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Working\".\n        total: (float, optional): Total number of steps. Default is len(sequence).\n        completed (int, optional): Number of steps completed so far. Defaults to 0.\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.\n        disable (bool, optional): Disable display of progress.\n        show_speed (bool, optional): Show speed if total isn't known. Defaults to True.\n    Returns:\n        Iterable[ProgressType]: An iterable of the values in the sequence.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            TaskProgressColumn(show_speed=show_speed),\n            TimeRemainingColumn(elapsed_when_finished=True),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    with progress:\n        yield from progress.track(\n            sequence,\n            total=total,\n            completed=completed,\n            description=description,\n            update_period=update_period,\n        )\n\n\nclass _Reader(RawIOBase, BinaryIO):\n    \"\"\"A reader that tracks progress while it's being read from.\"\"\"\n\n    def __init__(\n        self,\n        handle: BinaryIO,\n        progress: \"Progress\",\n        task: TaskID,\n        close_handle: bool = True,\n    ) -> None:\n        self.handle = handle\n        self.progress = progress\n        self.task = task\n        self.close_handle = close_handle\n        self._closed = False\n\n    def __enter__(self) -> \"_Reader\":\n        self.handle.__enter__()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.close()\n\n    def __iter__(self) -> BinaryIO:\n        return self\n\n    def __next__(self) -> bytes:\n        line = next(self.handle)\n        self.progress.advance(self.task, advance=len(line))\n        return line\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    def fileno(self) -> int:\n        return self.handle.fileno()\n\n    def isatty(self) -> bool:\n        return self.handle.isatty()\n\n    @property\n    def mode(self) -> str:\n        return self.handle.mode\n\n    @property\n    def name(self) -> str:\n        return self.handle.name\n\n    def readable(self) -> bool:\n        return self.handle.readable()\n\n    def seekable(self) -> bool:\n        return self.handle.seekable()\n\n    def writable(self) -> bool:\n        return False\n\n    def read(self, size: int = -1) -> bytes:\n        block = self.handle.read(size)\n        self.progress.advance(self.task, advance=len(block))\n        return block\n\n    def readinto(self, b: Union[bytearray, memoryview, mmap]):  # type: ignore[no-untyped-def, override]\n        n = self.handle.readinto(b)  # type: ignore[attr-defined]\n        self.progress.advance(self.task, advance=n)\n        return n\n\n    def readline(self, size: int = -1) -> bytes:  # type: ignore[override]\n        line = self.handle.readline(size)\n        self.progress.advance(self.task, advance=len(line))\n        return line\n\n    def readlines(self, hint: int = -1) -> List[bytes]:\n        lines = self.handle.readlines(hint)\n        self.progress.advance(self.task, advance=sum(map(len, lines)))\n        return lines\n\n    def close(self) -> None:\n        if self.close_handle:\n            self.handle.close()\n        self._closed = True\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        pos = self.handle.seek(offset, whence)\n        self.progress.update(self.task, completed=pos)\n        return pos\n\n    def tell(self) -> int:\n        return self.handle.tell()\n\n    def write(self, s: Any) -> int:\n        raise UnsupportedOperation(\"write\")\n\n    def writelines(self, lines: Iterable[Any]) -> None:\n        raise UnsupportedOperation(\"writelines\")\n\n\nclass _ReadContext(ContextManager[_I], Generic[_I]):\n    \"\"\"A utility class to handle a context for both a reader and a progress.\"\"\"\n\n    def __init__(self, progress: \"Progress\", reader: _I) -> None:\n        self.progress = progress\n        self.reader: _I = reader\n\n    def __enter__(self) -> _I:\n        self.progress.start()\n        return self.reader.__enter__()\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.progress.stop()\n        self.reader.__exit__(exc_type, exc_val, exc_tb)\n\n\ndef wrap_file(\n    file: BinaryIO,\n    total: int,\n    *,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[BinaryIO]:\n    \"\"\"Read bytes from a file while tracking progress.\n\n    Args:\n        file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.\n        total (int): Total number of bytes to read.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Reading\".\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        disable (bool, optional): Disable display of progress.\n    Returns:\n        ContextManager[BinaryIO]: A context manager yielding a progress reader.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            DownloadColumn(),\n            TimeRemainingColumn(),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    reader = progress.wrap_file(file, total=total, description=description)\n    return _ReadContext(progress, reader)\n\n\n@typing.overload\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Union[Literal[\"rt\"], Literal[\"r\"]],\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[TextIO]:\n    pass\n\n\n@typing.overload\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Literal[\"rb\"],\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[BinaryIO]:\n    pass\n\n\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Union[Literal[\"rb\"], Literal[\"rt\"], Literal[\"r\"]] = \"r\",\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:\n    \"\"\"Read bytes from a file while tracking progress.\n\n    Args:\n        path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.\n        mode (str): The mode to use to open the file. Only supports \"r\", \"rb\" or \"rt\".\n        buffering (int): The buffering strategy to use, see :func:`io.open`.\n        encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.\n        errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.\n        newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`\n        total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Reading\".\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        disable (bool, optional): Disable display of progress.\n        encoding (str, optional): The encoding to use when reading in text mode.\n\n    Returns:\n        ContextManager[BinaryIO]: A context manager yielding a progress reader.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            DownloadColumn(),\n            TimeRemainingColumn(),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    reader = progress.open(\n        file,\n        mode=mode,\n        buffering=buffering,\n        encoding=encoding,\n        errors=errors,\n        newline=newline,\n        total=total,\n        description=description,\n    )\n    return _ReadContext(progress, reader)  # type: ignore[return-value, type-var]\n\n\nclass ProgressColumn(ABC):\n    \"\"\"Base class for a widget to use in progress display.\"\"\"\n\n    max_refresh: Optional[float] = None\n\n    def __init__(self, table_column: Optional[Column] = None) -> None:\n        self._table_column = table_column\n        self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}\n        self._update_time: Optional[float] = None\n\n    def get_table_column(self) -> Column:\n        \"\"\"Get a table column, used to build tasks table.\"\"\"\n        return self._table_column or Column()\n\n    def __call__(self, task: \"Task\") -> RenderableType:\n        \"\"\"Called by the Progress object to return a renderable for the given task.\n\n        Args:\n            task (Task): An object containing information regarding the task.\n\n        Returns:\n            RenderableType: Anything renderable (including str).\n        \"\"\"\n        current_time = task.get_time()\n        if self.max_refresh is not None and not task.completed:\n            try:\n                timestamp, renderable = self._renderable_cache[task.id]\n            except KeyError:\n                pass\n            else:\n                if timestamp + self.max_refresh > current_time:\n                    return renderable\n\n        renderable = self.render(task)\n        self._renderable_cache[task.id] = (current_time, renderable)\n        return renderable\n\n    @abstractmethod\n    def render(self, task: \"Task\") -> RenderableType:\n        \"\"\"Should return a renderable object.\"\"\"\n\n\nclass RenderableColumn(ProgressColumn):\n    \"\"\"A column to insert an arbitrary column.\n\n    Args:\n        renderable (RenderableType, optional): Any renderable. Defaults to empty string.\n    \"\"\"\n\n    def __init__(\n        self, renderable: RenderableType = \"\", *, table_column: Optional[Column] = None\n    ):\n        self.renderable = renderable\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> RenderableType:\n        return self.renderable\n\n\nclass SpinnerColumn(ProgressColumn):\n    \"\"\"A column with a 'spinner' animation.\n\n    Args:\n        spinner_name (str, optional): Name of spinner animation. Defaults to \"dots\".\n        style (StyleType, optional): Style of spinner. Defaults to \"progress.spinner\".\n        speed (float, optional): Speed factor of spinner. Defaults to 1.0.\n        finished_text (TextType, optional): Text used when task is finished. Defaults to \" \".\n    \"\"\"\n\n    def __init__(\n        self,\n        spinner_name: str = \"dots\",\n        style: Optional[StyleType] = \"progress.spinner\",\n        speed: float = 1.0,\n        finished_text: TextType = \" \",\n        table_column: Optional[Column] = None,\n    ):\n        self.spinner = Spinner(spinner_name, style=style, speed=speed)\n        self.finished_text = (\n            Text.from_markup(finished_text)\n            if isinstance(finished_text, str)\n            else finished_text\n        )\n        super().__init__(table_column=table_column)\n\n    def set_spinner(\n        self,\n        spinner_name: str,\n        spinner_style: Optional[StyleType] = \"progress.spinner\",\n        speed: float = 1.0,\n    ) -> None:\n        \"\"\"Set a new spinner.\n\n        Args:\n            spinner_name (str): Spinner name, see python -m rich.spinner.\n            spinner_style (Optional[StyleType], optional): Spinner style. Defaults to \"progress.spinner\".\n            speed (float, optional): Speed factor of spinner. Defaults to 1.0.\n        \"\"\"\n        self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)\n\n    def render(self, task: \"Task\") -> RenderableType:\n        text = (\n            self.finished_text\n            if task.finished\n            else self.spinner.render(task.get_time())\n        )\n        return text\n\n\nclass TextColumn(ProgressColumn):\n    \"\"\"A column containing text.\"\"\"\n\n    def __init__(\n        self,\n        text_format: str,\n        style: StyleType = \"none\",\n        justify: JustifyMethod = \"left\",\n        markup: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        table_column: Optional[Column] = None,\n    ) -> None:\n        self.text_format = text_format\n        self.justify: JustifyMethod = justify\n        self.style = style\n        self.markup = markup\n        self.highlighter = highlighter\n        super().__init__(table_column=table_column or Column(no_wrap=True))\n\n    def render(self, task: \"Task\") -> Text:\n        _text = self.text_format.format(task=task)\n        if self.markup:\n            text = Text.from_markup(_text, style=self.style, justify=self.justify)\n        else:\n            text = Text(_text, style=self.style, justify=self.justify)\n        if self.highlighter:\n            self.highlighter.highlight(text)\n        return text\n\n\nclass BarColumn(ProgressColumn):\n    \"\"\"Renders a visual progress bar.\n\n    Args:\n        bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n    \"\"\"\n\n    def __init__(\n        self,\n        bar_width: Optional[int] = 40,\n        style: StyleType = \"bar.back\",\n        complete_style: StyleType = \"bar.complete\",\n        finished_style: StyleType = \"bar.finished\",\n        pulse_style: StyleType = \"bar.pulse\",\n        table_column: Optional[Column] = None,\n    ) -> None:\n        self.bar_width = bar_width\n        self.style = style\n        self.complete_style = complete_style\n        self.finished_style = finished_style\n        self.pulse_style = pulse_style\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> ProgressBar:\n        \"\"\"Gets a progress bar widget for a task.\"\"\"\n        return ProgressBar(\n            total=max(0, task.total) if task.total is not None else None,\n            completed=max(0, task.completed),\n            width=None if self.bar_width is None else max(1, self.bar_width),\n            pulse=not task.started,\n            animation_time=task.get_time(),\n            style=self.style,\n            complete_style=self.complete_style,\n            finished_style=self.finished_style,\n            pulse_style=self.pulse_style,\n        )\n\n\nclass TimeElapsedColumn(ProgressColumn):\n    \"\"\"Renders time elapsed.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show time elapsed.\"\"\"\n        elapsed = task.finished_time if task.finished else task.elapsed\n        if elapsed is None:\n            return Text(\"-:--:--\", style=\"progress.elapsed\")\n        delta = timedelta(seconds=max(0, int(elapsed)))\n        return Text(str(delta), style=\"progress.elapsed\")\n\n\nclass TaskProgressColumn(TextColumn):\n    \"\"\"Show task progress as a percentage.\n\n    Args:\n        text_format (str, optional): Format for percentage display. Defaults to \"[progress.percentage]{task.percentage:>3.0f}%\".\n        text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to \"\".\n        style (StyleType, optional): Style of output. Defaults to \"none\".\n        justify (JustifyMethod, optional): Text justification. Defaults to \"left\".\n        markup (bool, optional): Enable markup. Defaults to True.\n        highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.\n        table_column (Optional[Column], optional): Table Column to use. Defaults to None.\n        show_speed (bool, optional): Show speed if total is unknown. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        text_format: str = \"[progress.percentage]{task.percentage:>3.0f}%\",\n        text_format_no_percentage: str = \"\",\n        style: StyleType = \"none\",\n        justify: JustifyMethod = \"left\",\n        markup: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        table_column: Optional[Column] = None,\n        show_speed: bool = False,\n    ) -> None:\n        self.text_format_no_percentage = text_format_no_percentage\n        self.show_speed = show_speed\n        super().__init__(\n            text_format=text_format,\n            style=style,\n            justify=justify,\n            markup=markup,\n            highlighter=highlighter,\n            table_column=table_column,\n        )\n\n    @classmethod\n    def render_speed(cls, speed: Optional[float]) -> Text:\n        \"\"\"Render the speed in iterations per second.\n\n        Args:\n            task (Task): A Task object.\n\n        Returns:\n            Text: Text object containing the task speed.\n        \"\"\"\n        if speed is None:\n            return Text(\"\", style=\"progress.percentage\")\n        unit, suffix = filesize.pick_unit_and_suffix(\n            int(speed),\n            [\"\", \"×10³\", \"×10⁶\", \"×10⁹\", \"×10¹²\"],\n            1000,\n        )\n        data_speed = speed / unit\n        return Text(f\"{data_speed:.1f}{suffix} it/s\", style=\"progress.percentage\")\n\n    def render(self, task: \"Task\") -> Text:\n        if task.total is None and self.show_speed:\n            return self.render_speed(task.finished_speed or task.speed)\n        text_format = (\n            self.text_format_no_percentage if task.total is None else self.text_format\n        )\n        _text = text_format.format(task=task)\n        if self.markup:\n            text = Text.from_markup(_text, style=self.style, justify=self.justify)\n        else:\n            text = Text(_text, style=self.style, justify=self.justify)\n        if self.highlighter:\n            self.highlighter.highlight(text)\n        return text\n\n\nclass TimeRemainingColumn(ProgressColumn):\n    \"\"\"Renders estimated time remaining.\n\n    Args:\n        compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.\n        elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.\n    \"\"\"\n\n    # Only refresh twice a second to prevent jitter\n    max_refresh = 0.5\n\n    def __init__(\n        self,\n        compact: bool = False,\n        elapsed_when_finished: bool = False,\n        table_column: Optional[Column] = None,\n    ):\n        self.compact = compact\n        self.elapsed_when_finished = elapsed_when_finished\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show time remaining.\"\"\"\n        if self.elapsed_when_finished and task.finished:\n            task_time = task.finished_time\n            style = \"progress.elapsed\"\n        else:\n            task_time = task.time_remaining\n            style = \"progress.remaining\"\n\n        if task.total is None:\n            return Text(\"\", style=style)\n\n        if task_time is None:\n            return Text(\"--:--\" if self.compact else \"-:--:--\", style=style)\n\n        # Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py\n        minutes, seconds = divmod(int(task_time), 60)\n        hours, minutes = divmod(minutes, 60)\n\n        if self.compact and not hours:\n            formatted = f\"{minutes:02d}:{seconds:02d}\"\n        else:\n            formatted = f\"{hours:d}:{minutes:02d}:{seconds:02d}\"\n\n        return Text(formatted, style=style)\n\n\nclass FileSizeColumn(ProgressColumn):\n    \"\"\"Renders completed filesize.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data completed.\"\"\"\n        data_size = filesize.decimal(int(task.completed))\n        return Text(data_size, style=\"progress.filesize\")\n\n\nclass TotalFileSizeColumn(ProgressColumn):\n    \"\"\"Renders total filesize.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data completed.\"\"\"\n        data_size = filesize.decimal(int(task.total)) if task.total is not None else \"\"\n        return Text(data_size, style=\"progress.filesize.total\")\n\n\nclass MofNCompleteColumn(ProgressColumn):\n    \"\"\"Renders completed count/total, e.g. '  10/1000'.\n\n    Best for bounded tasks with int quantities.\n\n    Space pads the completed count so that progress length does not change as task progresses\n    past powers of 10.\n\n    Args:\n        separator (str, optional): Text to separate completed and total values. Defaults to \"/\".\n    \"\"\"\n\n    def __init__(self, separator: str = \"/\", table_column: Optional[Column] = None):\n        self.separator = separator\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show completed/total.\"\"\"\n        completed = int(task.completed)\n        total = int(task.total) if task.total is not None else \"?\"\n        total_width = len(str(total))\n        return Text(\n            f\"{completed:{total_width}d}{self.separator}{total}\",\n            style=\"progress.download\",\n        )\n\n\nclass DownloadColumn(ProgressColumn):\n    \"\"\"Renders file size downloaded and total, e.g. '0.5/2.3 GB'.\n\n    Args:\n        binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self, binary_units: bool = False, table_column: Optional[Column] = None\n    ) -> None:\n        self.binary_units = binary_units\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Calculate common unit for completed and total.\"\"\"\n        completed = int(task.completed)\n\n        unit_and_suffix_calculation_base = (\n            int(task.total) if task.total is not None else completed\n        )\n        if self.binary_units:\n            unit, suffix = filesize.pick_unit_and_suffix(\n                unit_and_suffix_calculation_base,\n                [\"bytes\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"ZiB\", \"YiB\"],\n                1024,\n            )\n        else:\n            unit, suffix = filesize.pick_unit_and_suffix(\n                unit_and_suffix_calculation_base,\n                [\"bytes\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"],\n                1000,\n            )\n        precision = 0 if unit == 1 else 1\n\n        completed_ratio = completed / unit\n        completed_str = f\"{completed_ratio:,.{precision}f}\"\n\n        if task.total is not None:\n            total = int(task.total)\n            total_ratio = total / unit\n            total_str = f\"{total_ratio:,.{precision}f}\"\n        else:\n            total_str = \"?\"\n\n        download_status = f\"{completed_str}/{total_str} {suffix}\"\n        download_text = Text(download_status, style=\"progress.download\")\n        return download_text\n\n\nclass TransferSpeedColumn(ProgressColumn):\n    \"\"\"Renders human readable transfer speed.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data transfer speed.\"\"\"\n        speed = task.finished_speed or task.speed\n        if speed is None:\n            return Text(\"?\", style=\"progress.data.speed\")\n        data_speed = filesize.decimal(int(speed))\n        return Text(f\"{data_speed}/s\", style=\"progress.data.speed\")\n\n\nclass ProgressSample(NamedTuple):\n    \"\"\"Sample of progress for a given time.\"\"\"\n\n    timestamp: float\n    \"\"\"Timestamp of sample.\"\"\"\n    completed: float\n    \"\"\"Number of steps completed.\"\"\"\n\n\n@dataclass\nclass Task:\n    \"\"\"Information regarding a progress task.\n\n    This object should be considered read-only outside of the :class:`~Progress` class.\n\n    \"\"\"\n\n    id: TaskID\n    \"\"\"Task ID associated with this task (used in Progress methods).\"\"\"\n\n    description: str\n    \"\"\"str: Description of the task.\"\"\"\n\n    total: Optional[float]\n    \"\"\"Optional[float]: Total number of steps in this task.\"\"\"\n\n    completed: float\n    \"\"\"float: Number of steps completed\"\"\"\n\n    _get_time: GetTimeCallable\n    \"\"\"Callable to get the current time.\"\"\"\n\n    finished_time: Optional[float] = None\n    \"\"\"float: Time task was finished.\"\"\"\n\n    visible: bool = True\n    \"\"\"bool: Indicates if this task is visible in the progress display.\"\"\"\n\n    fields: Dict[str, Any] = field(default_factory=dict)\n    \"\"\"dict: Arbitrary fields passed in via Progress.update.\"\"\"\n\n    start_time: Optional[float] = field(default=None, init=False, repr=False)\n    \"\"\"Optional[float]: Time this task was started, or None if not started.\"\"\"\n\n    stop_time: Optional[float] = field(default=None, init=False, repr=False)\n    \"\"\"Optional[float]: Time this task was stopped, or None if not stopped.\"\"\"\n\n    finished_speed: Optional[float] = None\n    \"\"\"Optional[float]: The last speed for a finished task.\"\"\"\n\n    _progress: Deque[ProgressSample] = field(\n        default_factory=lambda: deque(maxlen=1000), init=False, repr=False\n    )\n\n    _lock: RLock = field(repr=False, default_factory=RLock)\n    \"\"\"Thread lock.\"\"\"\n\n    def get_time(self) -> float:\n        \"\"\"float: Get the current time, in seconds.\"\"\"\n        return self._get_time()\n\n    @property\n    def started(self) -> bool:\n        \"\"\"bool: Check if the task as started.\"\"\"\n        return self.start_time is not None\n\n    @property\n    def remaining(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get the number of steps remaining, if a non-None total was set.\"\"\"\n        if self.total is None:\n            return None\n        return self.total - self.completed\n\n    @property\n    def elapsed(self) -> Optional[float]:\n        \"\"\"Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started.\"\"\"\n        if self.start_time is None:\n            return None\n        if self.stop_time is not None:\n            return self.stop_time - self.start_time\n        return self.get_time() - self.start_time\n\n    @property\n    def finished(self) -> bool:\n        \"\"\"Check if the task has finished.\"\"\"\n        return self.finished_time is not None\n\n    @property\n    def percentage(self) -> float:\n        \"\"\"float: Get progress of task as a percentage. If a None total was set, returns 0\"\"\"\n        if not self.total:\n            return 0.0\n        completed = (self.completed / self.total) * 100.0\n        completed = min(100.0, max(0.0, completed))\n        return completed\n\n    @property\n    def speed(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get the estimated speed in steps per second.\"\"\"\n        if self.start_time is None:\n            return None\n        with self._lock:\n            progress = self._progress\n            if not progress:\n                return None\n            total_time = progress[-1].timestamp - progress[0].timestamp\n            if total_time == 0:\n                return None\n            iter_progress = iter(progress)\n            next(iter_progress)\n            total_completed = sum(sample.completed for sample in iter_progress)\n            speed = total_completed / total_time\n            return speed\n\n    @property\n    def time_remaining(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get estimated time to completion, or ``None`` if no data.\"\"\"\n        if self.finished:\n            return 0.0\n        speed = self.speed\n        if not speed:\n            return None\n        remaining = self.remaining\n        if remaining is None:\n            return None\n        estimate = ceil(remaining / speed)\n        return estimate\n\n    def _reset(self) -> None:\n        \"\"\"Reset progress.\"\"\"\n        self._progress.clear()\n        self.finished_time = None\n        self.finished_speed = None\n\n\nclass Progress(JupyterMixin):\n    \"\"\"Renders an auto-updating progress bar(s).\n\n    Args:\n        console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.\n        auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.\n        refresh_per_second (Optional[float], optional): Number of times per second to refresh the progress information or None to use default (10). Defaults to None.\n        speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.\n        redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.\n        get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.\n        disable (bool, optional): Disable progress display. Defaults to False\n        expand (bool, optional): Expand tasks table to fit width. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        *columns: Union[str, ProgressColumn],\n        console: Optional[Console] = None,\n        auto_refresh: bool = True,\n        refresh_per_second: float = 10,\n        speed_estimate_period: float = 30.0,\n        transient: bool = False,\n        redirect_stdout: bool = True,\n        redirect_stderr: bool = True,\n        get_time: Optional[GetTimeCallable] = None,\n        disable: bool = False,\n        expand: bool = False,\n    ) -> None:\n        assert refresh_per_second > 0, \"refresh_per_second must be > 0\"\n        self._lock = RLock()\n        self.columns = columns or self.get_default_columns()\n        self.speed_estimate_period = speed_estimate_period\n\n        self.disable = disable\n        self.expand = expand\n        self._tasks: Dict[TaskID, Task] = {}\n        self._task_index: TaskID = TaskID(0)\n        self.live = Live(\n            console=console or get_console(),\n            auto_refresh=auto_refresh,\n            refresh_per_second=refresh_per_second,\n            transient=transient,\n            redirect_stdout=redirect_stdout,\n            redirect_stderr=redirect_stderr,\n            get_renderable=self.get_renderable,\n        )\n        self.get_time = get_time or self.console.get_time\n        self.print = self.console.print\n        self.log = self.console.log\n\n    @classmethod\n    def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:\n        \"\"\"Get the default columns used for a new Progress instance:\n           - a text column for the description (TextColumn)\n           - the bar itself (BarColumn)\n           - a text column showing completion percentage (TextColumn)\n           - an estimated-time-remaining column (TimeRemainingColumn)\n        If the Progress instance is created without passing a columns argument,\n        the default columns defined here will be used.\n\n        You can also create a Progress instance using custom columns before\n        and/or after the defaults, as in this example:\n\n            progress = Progress(\n                SpinnerColumn(),\n                *Progress.get_default_columns(),\n                \"Elapsed:\",\n                TimeElapsedColumn(),\n            )\n\n        This code shows the creation of a Progress display, containing\n        a spinner to the left, the default columns, and a labeled elapsed\n        time column.\n        \"\"\"\n        return (\n            TextColumn(\"[progress.description]{task.description}\"),\n            BarColumn(),\n            TaskProgressColumn(),\n            TimeRemainingColumn(),\n        )\n\n    @property\n    def console(self) -> Console:\n        return self.live.console\n\n    @property\n    def tasks(self) -> List[Task]:\n        \"\"\"Get a list of Task instances.\"\"\"\n        with self._lock:\n            return list(self._tasks.values())\n\n    @property\n    def task_ids(self) -> List[TaskID]:\n        \"\"\"A list of task IDs.\"\"\"\n        with self._lock:\n            return list(self._tasks.keys())\n\n    @property\n    def finished(self) -> bool:\n        \"\"\"Check if all tasks have been completed.\"\"\"\n        with self._lock:\n            if not self._tasks:\n                return True\n            return all(task.finished for task in self._tasks.values())\n\n    def start(self) -> None:\n        \"\"\"Start the progress display.\"\"\"\n        if not self.disable:\n            self.live.start(refresh=True)\n\n    def stop(self) -> None:\n        \"\"\"Stop the progress display.\"\"\"\n        self.live.stop()\n        if not self.console.is_interactive and not self.console.is_jupyter:\n            self.console.print()\n\n    def __enter__(self) -> Self:\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n    def track(\n        self,\n        sequence: Iterable[ProgressType],\n        total: Optional[float] = None,\n        completed: int = 0,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Working...\",\n        update_period: float = 0.1,\n    ) -> Iterable[ProgressType]:\n        \"\"\"Track progress by iterating over a sequence.\n\n        You can also track progress of an iterable, which might require that you additionally specify ``total``.\n\n        Args:\n            sequence (Iterable[ProgressType]): Values you want to iterate over and track progress.\n            total: (float, optional): Total number of steps. Default is len(sequence).\n            completed (int, optional): Number of steps completed so far. Defaults to 0.\n            task_id: (TaskID): Task to track. Default is new task.\n            description: (str, optional): Description of task, if new task is created.\n            update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.\n\n        Returns:\n            Iterable[ProgressType]: An iterable of values taken from the provided sequence.\n        \"\"\"\n        if total is None:\n            total = float(length_hint(sequence)) or None\n\n        if task_id is None:\n            task_id = self.add_task(description, total=total, completed=completed)\n        else:\n            self.update(task_id, total=total, completed=completed)\n\n        if self.live.auto_refresh:\n            with _TrackThread(self, task_id, update_period) as track_thread:\n                for value in sequence:\n                    yield value\n                    track_thread.completed += 1\n        else:\n            advance = self.advance\n            refresh = self.refresh\n            for value in sequence:\n                yield value\n                advance(task_id, 1)\n                refresh()\n\n    def wrap_file(\n        self,\n        file: BinaryIO,\n        total: Optional[int] = None,\n        *,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> BinaryIO:\n        \"\"\"Track progress file reading from a binary file.\n\n        Args:\n            file (BinaryIO): A file-like object opened in binary mode.\n            total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.\n            task_id (TaskID): Task to track. Default is new task.\n            description (str, optional): Description of task, if new task is created.\n\n        Returns:\n            BinaryIO: A readable file-like object in binary mode.\n\n        Raises:\n            ValueError: When no total value can be extracted from the arguments or the task.\n        \"\"\"\n        # attempt to recover the total from the task\n        total_bytes: Optional[float] = None\n        if total is not None:\n            total_bytes = total\n        elif task_id is not None:\n            with self._lock:\n                total_bytes = self._tasks[task_id].total\n        if total_bytes is None:\n            raise ValueError(\n                f\"unable to get the total number of bytes, please specify 'total'\"\n            )\n\n        # update total of task or create new task\n        if task_id is None:\n            task_id = self.add_task(description, total=total_bytes)\n        else:\n            self.update(task_id, total=total_bytes)\n\n        return _Reader(file, self, task_id, close_handle=False)\n\n    @typing.overload\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Literal[\"rb\"],\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> BinaryIO:\n        pass\n\n    @typing.overload\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Union[Literal[\"r\"], Literal[\"rt\"]],\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> TextIO:\n        pass\n\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Union[Literal[\"rb\"], Literal[\"rt\"], Literal[\"r\"]] = \"r\",\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> Union[BinaryIO, TextIO]:\n        \"\"\"Track progress while reading from a binary file.\n\n        Args:\n            path (Union[str, PathLike[str]]): The path to the file to read.\n            mode (str): The mode to use to open the file. Only supports \"r\", \"rb\" or \"rt\".\n            buffering (int): The buffering strategy to use, see :func:`io.open`.\n            encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.\n            errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.\n            newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.\n            total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.\n            task_id (TaskID): Task to track. Default is new task.\n            description (str, optional): Description of task, if new task is created.\n\n        Returns:\n            BinaryIO: A readable file-like object in binary mode.\n\n        Raises:\n            ValueError: When an invalid mode is given.\n        \"\"\"\n        # normalize the mode (always rb, rt)\n        _mode = \"\".join(sorted(mode, reverse=False))\n        if _mode not in (\"br\", \"rt\", \"r\"):\n            raise ValueError(f\"invalid mode {mode!r}\")\n\n        # patch buffering to provide the same behaviour as the builtin `open`\n        line_buffering = buffering == 1\n        if _mode == \"br\" and buffering == 1:\n            warnings.warn(\n                \"line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used\",\n                RuntimeWarning,\n            )\n            buffering = -1\n        elif _mode in (\"rt\", \"r\"):\n            if buffering == 0:\n                raise ValueError(\"can't have unbuffered text I/O\")\n            elif buffering == 1:\n                buffering = -1\n\n        # attempt to get the total with `os.stat`\n        if total is None:\n            total = stat(file).st_size\n\n        # update total of task or create new task\n        if task_id is None:\n            task_id = self.add_task(description, total=total)\n        else:\n            self.update(task_id, total=total)\n\n        # open the file in binary mode,\n        handle = io.open(file, \"rb\", buffering=buffering)\n        reader = _Reader(handle, self, task_id, close_handle=True)\n\n        # wrap the reader in a `TextIOWrapper` if text mode\n        if mode in (\"r\", \"rt\"):\n            return io.TextIOWrapper(\n                reader,\n                encoding=encoding,\n                errors=errors,\n                newline=newline,\n                line_buffering=line_buffering,\n            )\n\n        return reader\n\n    def start_task(self, task_id: TaskID) -> None:\n        \"\"\"Start a task.\n\n        Starts a task (used when calculating elapsed time). You may need to call this manually,\n        if you called ``add_task`` with ``start=False``.\n\n        Args:\n            task_id (TaskID): ID of task.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            if task.start_time is None:\n                task.start_time = self.get_time()\n\n    def stop_task(self, task_id: TaskID) -> None:\n        \"\"\"Stop a task.\n\n        This will freeze the elapsed time on the task.\n\n        Args:\n            task_id (TaskID): ID of task.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            current_time = self.get_time()\n            if task.start_time is None:\n                task.start_time = current_time\n            task.stop_time = current_time\n\n    def update(\n        self,\n        task_id: TaskID,\n        *,\n        total: Optional[float] = None,\n        completed: Optional[float] = None,\n        advance: Optional[float] = None,\n        description: Optional[str] = None,\n        visible: Optional[bool] = None,\n        refresh: bool = False,\n        **fields: Any,\n    ) -> None:\n        \"\"\"Update information associated with a task.\n\n        Args:\n            task_id (TaskID): Task id (returned by add_task).\n            total (float, optional): Updates task.total if not None.\n            completed (float, optional): Updates task.completed if not None.\n            advance (float, optional): Add a value to task.completed if not None.\n            description (str, optional): Change task description if not None.\n            visible (bool, optional): Set visible flag if not None.\n            refresh (bool): Force a refresh of progress information. Default is False.\n            **fields (Any): Additional data fields required for rendering.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            completed_start = task.completed\n\n            if total is not None and total != task.total:\n                task.total = total\n                task._reset()\n            if advance is not None:\n                task.completed += advance\n            if completed is not None:\n                task.completed = completed\n            if description is not None:\n                task.description = description\n            if visible is not None:\n                task.visible = visible\n            task.fields.update(fields)\n            update_completed = task.completed - completed_start\n\n            current_time = self.get_time()\n            old_sample_time = current_time - self.speed_estimate_period\n            _progress = task._progress\n\n            popleft = _progress.popleft\n            while _progress and _progress[0].timestamp < old_sample_time:\n                popleft()\n            if update_completed > 0:\n                _progress.append(ProgressSample(current_time, update_completed))\n            if (\n                task.total is not None\n                and task.completed >= task.total\n                and task.finished_time is None\n            ):\n                task.finished_time = task.elapsed\n\n        if refresh:\n            self.refresh()\n\n    def reset(\n        self,\n        task_id: TaskID,\n        *,\n        start: bool = True,\n        total: Optional[float] = None,\n        completed: int = 0,\n        visible: Optional[bool] = None,\n        description: Optional[str] = None,\n        **fields: Any,\n    ) -> None:\n        \"\"\"Reset a task so completed is 0 and the clock is reset.\n\n        Args:\n            task_id (TaskID): ID of task.\n            start (bool, optional): Start the task after reset. Defaults to True.\n            total (float, optional): New total steps in task, or None to use current total. Defaults to None.\n            completed (int, optional): Number of steps completed. Defaults to 0.\n            visible (bool, optional): Enable display of the task. Defaults to True.\n            description (str, optional): Change task description if not None. Defaults to None.\n            **fields (str): Additional data fields required for rendering.\n        \"\"\"\n        current_time = self.get_time()\n        with self._lock:\n            task = self._tasks[task_id]\n            task._reset()\n            task.start_time = current_time if start else None\n            if total is not None:\n                task.total = total\n            task.completed = completed\n            if visible is not None:\n                task.visible = visible\n            if fields:\n                task.fields = fields\n            if description is not None:\n                task.description = description\n            task.finished_time = None\n        self.refresh()\n\n    def advance(self, task_id: TaskID, advance: float = 1) -> None:\n        \"\"\"Advance task by a number of steps.\n\n        Args:\n            task_id (TaskID): ID of task.\n            advance (float): Number of steps to advance. Default is 1.\n        \"\"\"\n        current_time = self.get_time()\n        with self._lock:\n            task = self._tasks[task_id]\n            completed_start = task.completed\n            task.completed += advance\n            update_completed = task.completed - completed_start\n            old_sample_time = current_time - self.speed_estimate_period\n            _progress = task._progress\n\n            popleft = _progress.popleft\n            while _progress and _progress[0].timestamp < old_sample_time:\n                popleft()\n            while len(_progress) > 1000:\n                popleft()\n            _progress.append(ProgressSample(current_time, update_completed))\n            if (\n                task.total is not None\n                and task.completed >= task.total\n                and task.finished_time is None\n            ):\n                task.finished_time = task.elapsed\n                task.finished_speed = task.speed\n\n    def refresh(self) -> None:\n        \"\"\"Refresh (render) the progress information.\"\"\"\n        if not self.disable and self.live.is_started:\n            self.live.refresh()\n\n    def get_renderable(self) -> RenderableType:\n        \"\"\"Get a renderable for the progress display.\"\"\"\n        renderable = Group(*self.get_renderables())\n        return renderable\n\n    def get_renderables(self) -> Iterable[RenderableType]:\n        \"\"\"Get a number of renderables for the progress display.\"\"\"\n        table = self.make_tasks_table(self.tasks)\n        yield table\n\n    def make_tasks_table(self, tasks: Iterable[Task]) -> Table:\n        \"\"\"Get a table to render the Progress display.\n\n        Args:\n            tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.\n\n        Returns:\n            Table: A table instance.\n        \"\"\"\n        table_columns = (\n            (\n                Column(no_wrap=True)\n                if isinstance(_column, str)\n                else _column.get_table_column().copy()\n            )\n            for _column in self.columns\n        )\n        table = Table.grid(*table_columns, padding=(0, 1), expand=self.expand)\n\n        for task in tasks:\n            if task.visible:\n                table.add_row(\n                    *(\n                        (\n                            column.format(task=task)\n                            if isinstance(column, str)\n                            else column(task)\n                        )\n                        for column in self.columns\n                    )\n                )\n        return table\n\n    def __rich__(self) -> RenderableType:\n        \"\"\"Makes the Progress class itself renderable.\"\"\"\n        with self._lock:\n            return self.get_renderable()\n\n    def add_task(\n        self,\n        description: str,\n        start: bool = True,\n        total: Optional[float] = 100.0,\n        completed: int = 0,\n        visible: bool = True,\n        **fields: Any,\n    ) -> TaskID:\n        \"\"\"Add a new 'task' to the Progress display.\n\n        Args:\n            description (str): A description of the task.\n            start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,\n                you will need to call `start` manually. Defaults to True.\n            total (float, optional): Number of total steps in the progress if known.\n                Set to None to render a pulsing animation. Defaults to 100.\n            completed (int, optional): Number of steps completed so far. Defaults to 0.\n            visible (bool, optional): Enable display of the task. Defaults to True.\n            **fields (str): Additional data fields required for rendering.\n\n        Returns:\n            TaskID: An ID you can use when calling `update`.\n        \"\"\"\n        with self._lock:\n            task = Task(\n                self._task_index,\n                description,\n                total,\n                completed,\n                visible=visible,\n                fields=fields,\n                _get_time=self.get_time,\n                _lock=self._lock,\n            )\n            self._tasks[self._task_index] = task\n            if start:\n                self.start_task(self._task_index)\n            new_task_index = self._task_index\n            self._task_index = TaskID(int(self._task_index) + 1)\n        self.refresh()\n        return new_task_index\n\n    def remove_task(self, task_id: TaskID) -> None:\n        \"\"\"Delete a task if it exists.\n\n        Args:\n            task_id (TaskID): A task ID.\n\n        \"\"\"\n        with self._lock:\n            del self._tasks[task_id]\n\n\nif __name__ == \"__main__\":  # pragma: no coverage\n    import random\n    import time\n\n    from .panel import Panel\n    from .rule import Rule\n    from .syntax import Syntax\n    from .table import Table\n\n    syntax = Syntax(\n        '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value''',\n        \"python\",\n        line_numbers=True,\n    )\n\n    table = Table(\"foo\", \"bar\", \"baz\")\n    table.add_row(\"1\", \"2\", \"3\")\n\n    progress_renderables = [\n        \"Text may be printed while the progress bars are rendering.\",\n        Panel(\"In fact, [i]any[/i] renderable will work\"),\n        \"Such as [magenta]tables[/]...\",\n        table,\n        \"Pretty printed structures...\",\n        {\"type\": \"example\", \"text\": \"Pretty printed\"},\n        \"Syntax...\",\n        syntax,\n        Rule(\"Give it a try!\"),\n    ]\n\n    from itertools import cycle\n\n    examples = cycle(progress_renderables)\n\n    console = Console(record=True)\n\n    with Progress(\n        SpinnerColumn(),\n        *Progress.get_default_columns(),\n        TimeElapsedColumn(),\n        console=console,\n        transient=False,\n    ) as progress:\n        task1 = progress.add_task(\"[red]Downloading\", total=1000)\n        task2 = progress.add_task(\"[green]Processing\", total=1000)\n        task3 = progress.add_task(\"[yellow]Thinking\", total=None)\n\n        while not progress.finished:\n            progress.update(task1, advance=0.5)\n            progress.update(task2, advance=0.3)\n            time.sleep(0.01)\n            if random.randint(0, 100) < 1:\n                progress.log(next(examples))\n"
  },
  {
    "path": "src/pip/_vendor/rich/progress_bar.py",
    "content": "import math\nfrom functools import lru_cache\nfrom time import monotonic\nfrom typing import Iterable, List, Optional\n\nfrom .color import Color, blend_rgb\nfrom .color_triplet import ColorTriplet\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleType\n\n# Number of characters before 'pulse' animation repeats\nPULSE_SIZE = 20\n\n\nclass ProgressBar(JupyterMixin):\n    \"\"\"Renders a (progress) bar. Used by rich.progress.\n\n    Args:\n        total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.\n        completed (float, optional): Number of steps completed. Defaults to 0.\n        width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.\n        pulse (bool, optional): Enable pulse effect. Defaults to False. Will pulse if a None total was passed.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        animation_time (Optional[float], optional): Time in seconds to use for animation, or None to use system time.\n    \"\"\"\n\n    def __init__(\n        self,\n        total: Optional[float] = 100.0,\n        completed: float = 0,\n        width: Optional[int] = None,\n        pulse: bool = False,\n        style: StyleType = \"bar.back\",\n        complete_style: StyleType = \"bar.complete\",\n        finished_style: StyleType = \"bar.finished\",\n        pulse_style: StyleType = \"bar.pulse\",\n        animation_time: Optional[float] = None,\n    ):\n        self.total = total\n        self.completed = completed\n        self.width = width\n        self.pulse = pulse\n        self.style = style\n        self.complete_style = complete_style\n        self.finished_style = finished_style\n        self.pulse_style = pulse_style\n        self.animation_time = animation_time\n\n        self._pulse_segments: Optional[List[Segment]] = None\n\n    def __repr__(self) -> str:\n        return f\"<Bar {self.completed!r} of {self.total!r}>\"\n\n    @property\n    def percentage_completed(self) -> Optional[float]:\n        \"\"\"Calculate percentage complete.\"\"\"\n        if self.total is None:\n            return None\n        completed = (self.completed / self.total) * 100.0\n        completed = min(100, max(0.0, completed))\n        return completed\n\n    @lru_cache(maxsize=16)\n    def _get_pulse_segments(\n        self,\n        fore_style: Style,\n        back_style: Style,\n        color_system: str,\n        no_color: bool,\n        ascii: bool = False,\n    ) -> List[Segment]:\n        \"\"\"Get a list of segments to render a pulse animation.\n\n        Returns:\n            List[Segment]: A list of segments, one segment per character.\n        \"\"\"\n        bar = \"-\" if ascii else \"━\"\n        segments: List[Segment] = []\n        if color_system not in (\"standard\", \"eight_bit\", \"truecolor\") or no_color:\n            segments += [Segment(bar, fore_style)] * (PULSE_SIZE // 2)\n            segments += [Segment(\" \" if no_color else bar, back_style)] * (\n                PULSE_SIZE - (PULSE_SIZE // 2)\n            )\n            return segments\n\n        append = segments.append\n        fore_color = (\n            fore_style.color.get_truecolor()\n            if fore_style.color\n            else ColorTriplet(255, 0, 255)\n        )\n        back_color = (\n            back_style.color.get_truecolor()\n            if back_style.color\n            else ColorTriplet(0, 0, 0)\n        )\n        cos = math.cos\n        pi = math.pi\n        _Segment = Segment\n        _Style = Style\n        from_triplet = Color.from_triplet\n\n        for index in range(PULSE_SIZE):\n            position = index / PULSE_SIZE\n            fade = 0.5 + cos(position * pi * 2) / 2.0\n            color = blend_rgb(fore_color, back_color, cross_fade=fade)\n            append(_Segment(bar, _Style(color=from_triplet(color))))\n        return segments\n\n    def update(self, completed: float, total: Optional[float] = None) -> None:\n        \"\"\"Update progress with new values.\n\n        Args:\n            completed (float): Number of steps completed.\n            total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None.\n        \"\"\"\n        self.completed = completed\n        self.total = total if total is not None else self.total\n\n    def _render_pulse(\n        self, console: Console, width: int, ascii: bool = False\n    ) -> Iterable[Segment]:\n        \"\"\"Renders the pulse animation.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Width in characters of pulse animation.\n\n        Returns:\n            RenderResult: [description]\n\n        Yields:\n            Iterator[Segment]: Segments to render pulse\n        \"\"\"\n        fore_style = console.get_style(self.pulse_style, default=\"white\")\n        back_style = console.get_style(self.style, default=\"black\")\n\n        pulse_segments = self._get_pulse_segments(\n            fore_style, back_style, console.color_system, console.no_color, ascii=ascii\n        )\n        segment_count = len(pulse_segments)\n        current_time = (\n            monotonic() if self.animation_time is None else self.animation_time\n        )\n        segments = pulse_segments * (int(width / segment_count) + 2)\n        offset = int(-current_time * 15) % segment_count\n        segments = segments[offset : offset + width]\n        yield from segments\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = min(self.width or options.max_width, options.max_width)\n        ascii = options.legacy_windows or options.ascii_only\n        should_pulse = self.pulse or self.total is None\n        if should_pulse:\n            yield from self._render_pulse(console, width, ascii=ascii)\n            return\n\n        completed: Optional[float] = (\n            min(self.total, max(0, self.completed)) if self.total is not None else None\n        )\n\n        bar = \"-\" if ascii else \"━\"\n        half_bar_right = \" \" if ascii else \"╸\"\n        half_bar_left = \" \" if ascii else \"╺\"\n        complete_halves = (\n            int(width * 2 * completed / self.total)\n            if self.total and completed is not None\n            else width * 2\n        )\n        bar_count = complete_halves // 2\n        half_bar_count = complete_halves % 2\n        style = console.get_style(self.style)\n        is_finished = self.total is None or self.completed >= self.total\n        complete_style = console.get_style(\n            self.finished_style if is_finished else self.complete_style\n        )\n        _Segment = Segment\n        if bar_count:\n            yield _Segment(bar * bar_count, complete_style)\n        if half_bar_count:\n            yield _Segment(half_bar_right * half_bar_count, complete_style)\n\n        if not console.no_color:\n            remaining_bars = width - bar_count - half_bar_count\n            if remaining_bars and console.color_system is not None:\n                if not half_bar_count and bar_count:\n                    yield _Segment(half_bar_left, style)\n                    remaining_bars -= 1\n                if remaining_bars:\n                    yield _Segment(bar * remaining_bars, style)\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return (\n            Measurement(self.width, self.width)\n            if self.width is not None\n            else Measurement(4, options.max_width)\n        )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    console = Console()\n    bar = ProgressBar(width=50, total=100)\n\n    import time\n\n    console.show_cursor(False)\n    for n in range(0, 101, 1):\n        bar.update(n)\n        console.print(bar)\n        console.file.write(\"\\r\")\n        time.sleep(0.05)\n    console.show_cursor(True)\n    console.print()\n"
  },
  {
    "path": "src/pip/_vendor/rich/prompt.py",
    "content": "from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload\n\nfrom . import get_console\nfrom .console import Console\nfrom .text import Text, TextType\n\nPromptType = TypeVar(\"PromptType\")\nDefaultType = TypeVar(\"DefaultType\")\n\n\nclass PromptError(Exception):\n    \"\"\"Exception base class for prompt related errors.\"\"\"\n\n\nclass InvalidResponse(PromptError):\n    \"\"\"Exception to indicate a response was invalid. Raise this within process_response() to indicate an error\n    and provide an error message.\n\n    Args:\n        message (Union[str, Text]): Error message.\n    \"\"\"\n\n    def __init__(self, message: TextType) -> None:\n        self.message = message\n\n    def __rich__(self) -> TextType:\n        return self.message\n\n\nclass PromptBase(Generic[PromptType]):\n    \"\"\"Ask the user for input until a valid response is received. This is the base class, see one of\n    the concrete classes for examples.\n\n    Args:\n        prompt (TextType, optional): Prompt text. Defaults to \"\".\n        console (Console, optional): A Console instance or None to use global console. Defaults to None.\n        password (bool, optional): Enable password input. Defaults to False.\n        choices (List[str], optional): A list of valid choices. Defaults to None.\n        case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.\n        show_default (bool, optional): Show default in prompt. Defaults to True.\n        show_choices (bool, optional): Show choices in prompt. Defaults to True.\n    \"\"\"\n\n    response_type: type = str\n\n    validate_error_message = \"[prompt.invalid]Please enter a valid value\"\n    illegal_choice_message = (\n        \"[prompt.invalid.choice]Please select one of the available options\"\n    )\n    prompt_suffix = \": \"\n\n    choices: Optional[List[str]] = None\n\n    def __init__(\n        self,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n    ) -> None:\n        self.console = console or get_console()\n        self.prompt = (\n            Text.from_markup(prompt, style=\"prompt\")\n            if isinstance(prompt, str)\n            else prompt\n        )\n        self.password = password\n        if choices is not None:\n            self.choices = choices\n        self.case_sensitive = case_sensitive\n        self.show_default = show_default\n        self.show_choices = show_choices\n\n    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: DefaultType,\n        stream: Optional[TextIO] = None,\n    ) -> Union[DefaultType, PromptType]:\n        ...\n\n    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n        stream: Optional[TextIO] = None,\n    ) -> PromptType:\n        ...\n\n    @classmethod\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: Any = ...,\n        stream: Optional[TextIO] = None,\n    ) -> Any:\n        \"\"\"Shortcut to construct and run a prompt loop and return the result.\n\n        Example:\n            >>> filename = Prompt.ask(\"Enter a filename\")\n\n        Args:\n            prompt (TextType, optional): Prompt text. Defaults to \"\".\n            console (Console, optional): A Console instance or None to use global console. Defaults to None.\n            password (bool, optional): Enable password input. Defaults to False.\n            choices (List[str], optional): A list of valid choices. Defaults to None.\n            case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.\n            show_default (bool, optional): Show default in prompt. Defaults to True.\n            show_choices (bool, optional): Show choices in prompt. Defaults to True.\n            stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.\n        \"\"\"\n        _prompt = cls(\n            prompt,\n            console=console,\n            password=password,\n            choices=choices,\n            case_sensitive=case_sensitive,\n            show_default=show_default,\n            show_choices=show_choices,\n        )\n        return _prompt(default=default, stream=stream)\n\n    def render_default(self, default: DefaultType) -> Text:\n        \"\"\"Turn the supplied default in to a Text instance.\n\n        Args:\n            default (DefaultType): Default value.\n\n        Returns:\n            Text: Text containing rendering of default value.\n        \"\"\"\n        return Text(f\"({default})\", \"prompt.default\")\n\n    def make_prompt(self, default: DefaultType) -> Text:\n        \"\"\"Make prompt text.\n\n        Args:\n            default (DefaultType): Default value.\n\n        Returns:\n            Text: Text to display in prompt.\n        \"\"\"\n        prompt = self.prompt.copy()\n        prompt.end = \"\"\n\n        if self.show_choices and self.choices:\n            _choices = \"/\".join(self.choices)\n            choices = f\"[{_choices}]\"\n            prompt.append(\" \")\n            prompt.append(choices, \"prompt.choices\")\n\n        if (\n            default != ...\n            and self.show_default\n            and isinstance(default, (str, self.response_type))\n        ):\n            prompt.append(\" \")\n            _default = self.render_default(default)\n            prompt.append(_default)\n\n        prompt.append(self.prompt_suffix)\n\n        return prompt\n\n    @classmethod\n    def get_input(\n        cls,\n        console: Console,\n        prompt: TextType,\n        password: bool,\n        stream: Optional[TextIO] = None,\n    ) -> str:\n        \"\"\"Get input from user.\n\n        Args:\n            console (Console): Console instance.\n            prompt (TextType): Prompt text.\n            password (bool): Enable password entry.\n\n        Returns:\n            str: String from user.\n        \"\"\"\n        return console.input(prompt, password=password, stream=stream)\n\n    def check_choice(self, value: str) -> bool:\n        \"\"\"Check value is in the list of valid choices.\n\n        Args:\n            value (str): Value entered by user.\n\n        Returns:\n            bool: True if choice was valid, otherwise False.\n        \"\"\"\n        assert self.choices is not None\n        if self.case_sensitive:\n            return value.strip() in self.choices\n        return value.strip().lower() in [choice.lower() for choice in self.choices]\n\n    def process_response(self, value: str) -> PromptType:\n        \"\"\"Process response from user, convert to prompt type.\n\n        Args:\n            value (str): String typed by user.\n\n        Raises:\n            InvalidResponse: If ``value`` is invalid.\n\n        Returns:\n            PromptType: The value to be returned from ask method.\n        \"\"\"\n        value = value.strip()\n        try:\n            return_value: PromptType = self.response_type(value)\n        except ValueError:\n            raise InvalidResponse(self.validate_error_message)\n\n        if self.choices is not None:\n            if not self.check_choice(value):\n                raise InvalidResponse(self.illegal_choice_message)\n\n            if not self.case_sensitive:\n                # return the original choice, not the lower case version\n                return_value = self.response_type(\n                    self.choices[\n                        [choice.lower() for choice in self.choices].index(value.lower())\n                    ]\n                )\n        return return_value\n\n    def on_validate_error(self, value: str, error: InvalidResponse) -> None:\n        \"\"\"Called to handle validation error.\n\n        Args:\n            value (str): String entered by user.\n            error (InvalidResponse): Exception instance the initiated the error.\n        \"\"\"\n        self.console.print(error)\n\n    def pre_prompt(self) -> None:\n        \"\"\"Hook to display something before the prompt.\"\"\"\n\n    @overload\n    def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType:\n        ...\n\n    @overload\n    def __call__(\n        self, *, default: DefaultType, stream: Optional[TextIO] = None\n    ) -> Union[PromptType, DefaultType]:\n        ...\n\n    def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any:\n        \"\"\"Run the prompt loop.\n\n        Args:\n            default (Any, optional): Optional default value.\n\n        Returns:\n            PromptType: Processed value.\n        \"\"\"\n        while True:\n            self.pre_prompt()\n            prompt = self.make_prompt(default)\n            value = self.get_input(self.console, prompt, self.password, stream=stream)\n            if value == \"\" and default != ...:\n                return default\n            try:\n                return_value = self.process_response(value)\n            except InvalidResponse as error:\n                self.on_validate_error(value, error)\n                continue\n            else:\n                return return_value\n\n\nclass Prompt(PromptBase[str]):\n    \"\"\"A prompt that returns a str.\n\n    Example:\n        >>> name = Prompt.ask(\"Enter your name\")\n\n\n    \"\"\"\n\n    response_type = str\n\n\nclass IntPrompt(PromptBase[int]):\n    \"\"\"A prompt that returns an integer.\n\n    Example:\n        >>> burrito_count = IntPrompt.ask(\"How many burritos do you want to order\")\n\n    \"\"\"\n\n    response_type = int\n    validate_error_message = \"[prompt.invalid]Please enter a valid integer number\"\n\n\nclass FloatPrompt(PromptBase[float]):\n    \"\"\"A prompt that returns a float.\n\n    Example:\n        >>> temperature = FloatPrompt.ask(\"Enter desired temperature\")\n\n    \"\"\"\n\n    response_type = float\n    validate_error_message = \"[prompt.invalid]Please enter a number\"\n\n\nclass Confirm(PromptBase[bool]):\n    \"\"\"A yes / no confirmation prompt.\n\n    Example:\n        >>> if Confirm.ask(\"Continue\"):\n                run_job()\n\n    \"\"\"\n\n    response_type = bool\n    validate_error_message = \"[prompt.invalid]Please enter Y or N\"\n    choices: List[str] = [\"y\", \"n\"]\n\n    def render_default(self, default: DefaultType) -> Text:\n        \"\"\"Render the default as (y) or (n) rather than True/False.\"\"\"\n        yes, no = self.choices\n        return Text(f\"({yes})\" if default else f\"({no})\", style=\"prompt.default\")\n\n    def process_response(self, value: str) -> bool:\n        \"\"\"Convert choices to a bool.\"\"\"\n        value = value.strip().lower()\n        if value not in self.choices:\n            raise InvalidResponse(self.validate_error_message)\n        return value == self.choices[0]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich import print\n\n    if Confirm.ask(\"Run [i]prompt[/i] tests?\", default=True):\n        while True:\n            result = IntPrompt.ask(\n                \":rocket: Enter a number between [b]1[/b] and [b]10[/b]\", default=5\n            )\n            if result >= 1 and result <= 10:\n                break\n            print(\":pile_of_poo: [prompt.invalid]Number must be between 1 and 10\")\n        print(f\"number={result}\")\n\n        while True:\n            password = Prompt.ask(\n                \"Please enter a password [cyan](must be at least 5 characters)\",\n                password=True,\n            )\n            if len(password) >= 5:\n                break\n            print(\"[prompt.invalid]password too short\")\n        print(f\"password={password!r}\")\n\n        fruit = Prompt.ask(\"Enter a fruit\", choices=[\"apple\", \"orange\", \"pear\"])\n        print(f\"fruit={fruit!r}\")\n\n        doggie = Prompt.ask(\n            \"What's the best Dog? (Case INSENSITIVE)\",\n            choices=[\"Border Terrier\", \"Collie\", \"Labradoodle\"],\n            case_sensitive=False,\n        )\n        print(f\"doggie={doggie!r}\")\n\n    else:\n        print(\"[b]OK :loudly_crying_face:\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/protocol.py",
    "content": "from typing import Any, cast, Set, TYPE_CHECKING\nfrom inspect import isclass\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import RenderableType\n\n_GIBBERISH = \"\"\"aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf\"\"\"\n\n\ndef is_renderable(check_object: Any) -> bool:\n    \"\"\"Check if an object may be rendered by Rich.\"\"\"\n    return (\n        isinstance(check_object, str)\n        or hasattr(check_object, \"__rich__\")\n        or hasattr(check_object, \"__rich_console__\")\n    )\n\n\ndef rich_cast(renderable: object) -> \"RenderableType\":\n    \"\"\"Cast an object to a renderable by calling __rich__ if present.\n\n    Args:\n        renderable (object): A potentially renderable object\n\n    Returns:\n        object: The result of recursively calling __rich__.\n    \"\"\"\n    from pip._vendor.rich.console import RenderableType\n\n    rich_visited_set: Set[type] = set()  # Prevent potential infinite loop\n    while hasattr(renderable, \"__rich__\") and not isclass(renderable):\n        # Detect object which claim to have all the attributes\n        if hasattr(renderable, _GIBBERISH):\n            return repr(renderable)\n        cast_method = getattr(renderable, \"__rich__\")\n        renderable = cast_method()\n        renderable_type = type(renderable)\n        if renderable_type in rich_visited_set:\n            break\n        rich_visited_set.add(renderable_type)\n\n    return cast(RenderableType, renderable)\n"
  },
  {
    "path": "src/pip/_vendor/rich/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/rich/region.py",
    "content": "from typing import NamedTuple\n\n\nclass Region(NamedTuple):\n    \"\"\"Defines a rectangular region of the screen.\"\"\"\n\n    x: int\n    y: int\n    width: int\n    height: int\n"
  },
  {
    "path": "src/pip/_vendor/rich/repr.py",
    "content": "import inspect\nfrom functools import partial\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n    overload,\n)\n\nT = TypeVar(\"T\")\n\n\nResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]\nRichReprResult = Result\n\n\nclass ReprError(Exception):\n    \"\"\"An error occurred when attempting to build a repr.\"\"\"\n\n\n@overload\ndef auto(cls: Optional[Type[T]]) -> Type[T]:\n    ...\n\n\n@overload\ndef auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:\n    ...\n\n\ndef auto(\n    cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None\n) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:\n    \"\"\"Class decorator to create __repr__ from __rich_repr__\"\"\"\n\n    def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]:\n        def auto_repr(self: T) -> str:\n            \"\"\"Create repr string from __rich_repr__\"\"\"\n            repr_str: List[str] = []\n            append = repr_str.append\n\n            angular: bool = getattr(self.__rich_repr__, \"angular\", False)  # type: ignore[attr-defined]\n            for arg in self.__rich_repr__():  # type: ignore[attr-defined]\n                if isinstance(arg, tuple):\n                    if len(arg) == 1:\n                        append(repr(arg[0]))\n                    else:\n                        key, value, *default = arg\n                        if key is None:\n                            append(repr(value))\n                        else:\n                            if default and default[0] == value:\n                                continue\n                            append(f\"{key}={value!r}\")\n                else:\n                    append(repr(arg))\n            if angular:\n                return f\"<{self.__class__.__name__} {' '.join(repr_str)}>\"\n            else:\n                return f\"{self.__class__.__name__}({', '.join(repr_str)})\"\n\n        def auto_rich_repr(self: Type[T]) -> Result:\n            \"\"\"Auto generate __rich_rep__ from signature of __init__\"\"\"\n            try:\n                signature = inspect.signature(self.__init__)\n                for name, param in signature.parameters.items():\n                    if param.kind == param.POSITIONAL_ONLY:\n                        yield getattr(self, name)\n                    elif param.kind in (\n                        param.POSITIONAL_OR_KEYWORD,\n                        param.KEYWORD_ONLY,\n                    ):\n                        if param.default is param.empty:\n                            yield getattr(self, param.name)\n                        else:\n                            yield param.name, getattr(self, param.name), param.default\n            except Exception as error:\n                raise ReprError(\n                    f\"Failed to auto generate __rich_repr__; {error}\"\n                ) from None\n\n        if not hasattr(cls, \"__rich_repr__\"):\n            auto_rich_repr.__doc__ = \"Build a rich repr\"\n            cls.__rich_repr__ = auto_rich_repr  # type: ignore[attr-defined]\n\n        auto_repr.__doc__ = \"Return repr(self)\"\n        cls.__repr__ = auto_repr  # type: ignore[assignment]\n        if angular is not None:\n            cls.__rich_repr__.angular = angular  # type: ignore[attr-defined]\n        return cls\n\n    if cls is None:\n        return partial(do_replace, angular=angular)\n    else:\n        return do_replace(cls, angular=angular)\n\n\n@overload\ndef rich_repr(cls: Optional[Type[T]]) -> Type[T]:\n    ...\n\n\n@overload\ndef rich_repr(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:\n    ...\n\n\ndef rich_repr(\n    cls: Optional[Type[T]] = None, *, angular: bool = False\n) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:\n    if cls is None:\n        return auto(angular=angular)\n    else:\n        return auto(cls)\n\n\nif __name__ == \"__main__\":\n\n    @auto\n    class Foo:\n        def __rich_repr__(self) -> Result:\n            yield \"foo\"\n            yield \"bar\", {\"shopping\": [\"eggs\", \"ham\", \"pineapple\"]}\n            yield \"buy\", \"hand sanitizer\"\n\n    foo = Foo()\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n\n    console.rule(\"Standard repr\")\n    console.print(foo)\n\n    console.print(foo, width=60)\n    console.print(foo, width=30)\n\n    console.rule(\"Angular repr\")\n    Foo.__rich_repr__.angular = True  # type: ignore[attr-defined]\n\n    console.print(foo)\n\n    console.print(foo, width=60)\n    console.print(foo, width=30)\n"
  },
  {
    "path": "src/pip/_vendor/rich/rule.py",
    "content": "from typing import Union\n\nfrom .align import AlignMethod\nfrom .cells import cell_len, set_cell_size\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .style import Style\nfrom .text import Text\n\n\nclass Rule(JupyterMixin):\n    \"\"\"A console renderable to draw a horizontal rule (line).\n\n    Args:\n        title (Union[str, Text], optional): Text to render in the rule. Defaults to \"\".\n        characters (str, optional): Character(s) used to draw the line. Defaults to \"─\".\n        style (StyleType, optional): Style of Rule. Defaults to \"rule.line\".\n        end (str, optional): Character at end of Rule. defaults to \"\\\\\\\\n\"\n        align (str, optional): How to align the title, one of \"left\", \"center\", or \"right\". Defaults to \"center\".\n    \"\"\"\n\n    def __init__(\n        self,\n        title: Union[str, Text] = \"\",\n        *,\n        characters: str = \"─\",\n        style: Union[str, Style] = \"rule.line\",\n        end: str = \"\\n\",\n        align: AlignMethod = \"center\",\n    ) -> None:\n        if cell_len(characters) < 1:\n            raise ValueError(\n                \"'characters' argument must have a cell width of at least 1\"\n            )\n        if align not in (\"left\", \"center\", \"right\"):\n            raise ValueError(\n                f'invalid value for align, expected \"left\", \"center\", \"right\" (not {align!r})'\n            )\n        self.title = title\n        self.characters = characters\n        self.style = style\n        self.end = end\n        self.align = align\n\n    def __repr__(self) -> str:\n        return f\"Rule({self.title!r}, {self.characters!r})\"\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = options.max_width\n\n        characters = (\n            \"-\"\n            if (options.ascii_only and not self.characters.isascii())\n            else self.characters\n        )\n\n        chars_len = cell_len(characters)\n        if not self.title:\n            yield self._rule_line(chars_len, width)\n            return\n\n        if isinstance(self.title, Text):\n            title_text = self.title\n        else:\n            title_text = console.render_str(self.title, style=\"rule.text\")\n\n        title_text.plain = title_text.plain.replace(\"\\n\", \" \")\n        title_text.expand_tabs()\n\n        required_space = 4 if self.align == \"center\" else 2\n        truncate_width = max(0, width - required_space)\n        if not truncate_width:\n            yield self._rule_line(chars_len, width)\n            return\n\n        rule_text = Text(end=self.end)\n        if self.align == \"center\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            side_width = (width - cell_len(title_text.plain)) // 2\n            left = Text(characters * (side_width // chars_len + 1))\n            left.truncate(side_width - 1)\n            right_length = width - cell_len(left.plain) - cell_len(title_text.plain)\n            right = Text(characters * (side_width // chars_len + 1))\n            right.truncate(right_length)\n            rule_text.append(left.plain + \" \", self.style)\n            rule_text.append(title_text)\n            rule_text.append(\" \" + right.plain, self.style)\n        elif self.align == \"left\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            rule_text.append(title_text)\n            rule_text.append(\" \")\n            rule_text.append(characters * (width - rule_text.cell_len), self.style)\n        elif self.align == \"right\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            rule_text.append(characters * (width - title_text.cell_len - 1), self.style)\n            rule_text.append(\" \")\n            rule_text.append(title_text)\n\n        rule_text.plain = set_cell_size(rule_text.plain, width)\n        yield rule_text\n\n    def _rule_line(self, chars_len: int, width: int) -> Text:\n        rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)\n        rule_text.truncate(width)\n        rule_text.plain = set_cell_size(rule_text.plain, width)\n        return rule_text\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return Measurement(1, 1)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sys\n\n    from pip._vendor.rich.console import Console\n\n    try:\n        text = sys.argv[1]\n    except IndexError:\n        text = \"Hello, World\"\n    console = Console()\n    console.print(Rule(title=text))\n\n    console = Console()\n    console.print(Rule(\"foo\"), width=4)\n"
  },
  {
    "path": "src/pip/_vendor/rich/scope.py",
    "content": "from collections.abc import Mapping\nfrom typing import TYPE_CHECKING, Any, Optional, Tuple\n\nfrom .highlighter import ReprHighlighter\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import ConsoleRenderable\n\n\ndef render_scope(\n    scope: \"Mapping[str, Any]\",\n    *,\n    title: Optional[TextType] = None,\n    sort_keys: bool = True,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n) -> \"ConsoleRenderable\":\n    \"\"\"Render python variables in a given scope.\n\n    Args:\n        scope (Mapping): A mapping containing variable names and values.\n        title (str, optional): Optional title. Defaults to None.\n        sort_keys (bool, optional): Enable sorting of items. Defaults to True.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n\n    Returns:\n        ConsoleRenderable: A renderable object.\n    \"\"\"\n    highlighter = ReprHighlighter()\n    items_table = Table.grid(padding=(0, 1), expand=False)\n    items_table.add_column(justify=\"right\")\n\n    def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n        \"\"\"Sort special variables first, then alphabetically.\"\"\"\n        key, _ = item\n        return (not key.startswith(\"__\"), key.lower())\n\n    items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items()\n    for key, value in items:\n        key_text = Text.assemble(\n            (key, \"scope.key.special\" if key.startswith(\"__\") else \"scope.key\"),\n            (\" =\", \"scope.equals\"),\n        )\n        items_table.add_row(\n            key_text,\n            Pretty(\n                value,\n                highlighter=highlighter,\n                indent_guides=indent_guides,\n                max_length=max_length,\n                max_string=max_string,\n            ),\n        )\n    return Panel.fit(\n        items_table,\n        title=title,\n        border_style=\"scope.border\",\n        padding=(0, 1),\n    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich import print\n\n    print()\n\n    def test(foo: float, bar: float) -> None:\n        list_of_things = [1, 2, 3, None, 4, True, False, \"Hello World\"]\n        dict_of_things = {\n            \"version\": \"1.1\",\n            \"method\": \"confirmFruitPurchase\",\n            \"params\": [[\"apple\", \"orange\", \"mangoes\", \"pomelo\"], 1.123],\n            \"id\": \"194521489\",\n        }\n        print(render_scope(locals(), title=\"[i]locals\", sort_keys=False))\n\n    test(20.3423, 3.1427)\n    print()\n"
  },
  {
    "path": "src/pip/_vendor/rich/screen.py",
    "content": "from typing import Optional, TYPE_CHECKING\n\nfrom .segment import Segment\nfrom .style import StyleType\nfrom ._loop import loop_last\n\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        RenderResult,\n        RenderableType,\n        Group,\n    )\n\n\nclass Screen:\n    \"\"\"A renderable that fills the terminal screen and crops excess.\n\n    Args:\n        renderable (RenderableType): Child renderable.\n        style (StyleType, optional): Optional background style. Defaults to None.\n    \"\"\"\n\n    renderable: \"RenderableType\"\n\n    def __init__(\n        self,\n        *renderables: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        application_mode: bool = False,\n    ) -> None:\n        from pip._vendor.rich.console import Group\n\n        self.renderable = Group(*renderables)\n        self.style = style\n        self.application_mode = application_mode\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        width, height = options.size\n        style = console.get_style(self.style) if self.style else None\n        render_options = options.update(width=width, height=height)\n        lines = console.render_lines(\n            self.renderable or \"\", render_options, style=style, pad=True\n        )\n        lines = Segment.set_shape(lines, width, height, style=style)\n        new_line = Segment(\"\\n\\r\") if self.application_mode else Segment.line()\n        for last, line in loop_last(lines):\n            yield from line\n            if not last:\n                yield new_line\n"
  },
  {
    "path": "src/pip/_vendor/rich/segment.py",
    "content": "from enum import IntEnum\nfrom functools import lru_cache\nfrom itertools import filterfalse\nfrom logging import getLogger\nfrom operator import attrgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom .cells import (\n    _is_single_cell_widths,\n    cached_cell_len,\n    cell_len,\n    get_character_cell_size,\n    set_cell_size,\n)\nfrom .repr import Result, rich_repr\nfrom .style import Style\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\nlog = getLogger(\"rich\")\n\n\nclass ControlType(IntEnum):\n    \"\"\"Non-printable control codes which typically translate to ANSI codes.\"\"\"\n\n    BELL = 1\n    CARRIAGE_RETURN = 2\n    HOME = 3\n    CLEAR = 4\n    SHOW_CURSOR = 5\n    HIDE_CURSOR = 6\n    ENABLE_ALT_SCREEN = 7\n    DISABLE_ALT_SCREEN = 8\n    CURSOR_UP = 9\n    CURSOR_DOWN = 10\n    CURSOR_FORWARD = 11\n    CURSOR_BACKWARD = 12\n    CURSOR_MOVE_TO_COLUMN = 13\n    CURSOR_MOVE_TO = 14\n    ERASE_IN_LINE = 15\n    SET_WINDOW_TITLE = 16\n\n\nControlCode = Union[\n    Tuple[ControlType],\n    Tuple[ControlType, Union[int, str]],\n    Tuple[ControlType, int, int],\n]\n\n\n@rich_repr()\nclass Segment(NamedTuple):\n    \"\"\"A piece of text with associated style. Segments are produced by the Console render process and\n    are ultimately converted in to strings to be written to the terminal.\n\n    Args:\n        text (str): A piece of text.\n        style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.\n        control (Tuple[ControlCode], optional): Optional sequence of control codes.\n\n    Attributes:\n        cell_length (int): The cell length of this Segment.\n    \"\"\"\n\n    text: str\n    style: Optional[Style] = None\n    control: Optional[Sequence[ControlCode]] = None\n\n    @property\n    def cell_length(self) -> int:\n        \"\"\"The number of terminal cells required to display self.text.\n\n        Returns:\n            int: A number of cells.\n        \"\"\"\n        text, _style, control = self\n        return 0 if control else cell_len(text)\n\n    def __rich_repr__(self) -> Result:\n        yield self.text\n        if self.control is None:\n            if self.style is not None:\n                yield self.style\n        else:\n            yield self.style\n            yield self.control\n\n    def __bool__(self) -> bool:\n        \"\"\"Check if the segment contains text.\"\"\"\n        return bool(self.text)\n\n    @property\n    def is_control(self) -> bool:\n        \"\"\"Check if the segment contains control codes.\"\"\"\n        return self.control is not None\n\n    @classmethod\n    @lru_cache(1024 * 16)\n    def _split_cells(cls, segment: \"Segment\", cut: int) -> Tuple[\"Segment\", \"Segment\"]:\n        \"\"\"Split a segment in to two at a given cell position.\n\n        Note that splitting a double-width character, may result in that character turning\n        into two spaces.\n\n        Args:\n            segment (Segment): A segment to split.\n            cut (int): A cell position to cut on.\n\n        Returns:\n            A tuple of two segments.\n        \"\"\"\n        text, style, control = segment\n        _Segment = Segment\n        cell_length = segment.cell_length\n        if cut >= cell_length:\n            return segment, _Segment(\"\", style, control)\n\n        cell_size = get_character_cell_size\n\n        pos = int((cut / cell_length) * len(text))\n\n        while True:\n            before = text[:pos]\n            cell_pos = cell_len(before)\n            out_by = cell_pos - cut\n            if not out_by:\n                return (\n                    _Segment(before, style, control),\n                    _Segment(text[pos:], style, control),\n                )\n            if out_by == -1 and cell_size(text[pos]) == 2:\n                return (\n                    _Segment(text[:pos] + \" \", style, control),\n                    _Segment(\" \" + text[pos + 1 :], style, control),\n                )\n            if out_by == +1 and cell_size(text[pos - 1]) == 2:\n                return (\n                    _Segment(text[: pos - 1] + \" \", style, control),\n                    _Segment(\" \" + text[pos:], style, control),\n                )\n            if cell_pos < cut:\n                pos += 1\n            else:\n                pos -= 1\n\n    def split_cells(self, cut: int) -> Tuple[\"Segment\", \"Segment\"]:\n        \"\"\"Split segment in to two segments at the specified column.\n\n        If the cut point falls in the middle of a 2-cell wide character then it is replaced\n        by two spaces, to preserve the display width of the parent segment.\n\n        Args:\n            cut (int): Offset within the segment to cut.\n\n        Returns:\n            Tuple[Segment, Segment]: Two segments.\n        \"\"\"\n        text, style, control = self\n        assert cut >= 0\n\n        if _is_single_cell_widths(text):\n            # Fast path with all 1 cell characters\n            if cut >= len(text):\n                return self, Segment(\"\", style, control)\n            return (\n                Segment(text[:cut], style, control),\n                Segment(text[cut:], style, control),\n            )\n\n        return self._split_cells(self, cut)\n\n    @classmethod\n    def line(cls) -> \"Segment\":\n        \"\"\"Make a new line segment.\"\"\"\n        return cls(\"\\n\")\n\n    @classmethod\n    def apply_style(\n        cls,\n        segments: Iterable[\"Segment\"],\n        style: Optional[Style] = None,\n        post_style: Optional[Style] = None,\n    ) -> Iterable[\"Segment\"]:\n        \"\"\"Apply style(s) to an iterable of segments.\n\n        Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``.\n\n        Args:\n            segments (Iterable[Segment]): Segments to process.\n            style (Style, optional): Base style. Defaults to None.\n            post_style (Style, optional): Style to apply on top of segment style. Defaults to None.\n\n        Returns:\n            Iterable[Segments]: A new iterable of segments (possibly the same iterable).\n        \"\"\"\n        result_segments = segments\n        if style:\n            apply = style.__add__\n            result_segments = (\n                cls(text, None if control else apply(_style), control)\n                for text, _style, control in result_segments\n            )\n        if post_style:\n            result_segments = (\n                cls(\n                    text,\n                    (\n                        None\n                        if control\n                        else (_style + post_style if _style else post_style)\n                    ),\n                    control,\n                )\n                for text, _style, control in result_segments\n            )\n        return result_segments\n\n    @classmethod\n    def filter_control(\n        cls, segments: Iterable[\"Segment\"], is_control: bool = False\n    ) -> Iterable[\"Segment\"]:\n        \"\"\"Filter segments by ``is_control`` attribute.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of Segment instances.\n            is_control (bool, optional): is_control flag to match in search.\n\n        Returns:\n            Iterable[Segment]: And iterable of Segment instances.\n\n        \"\"\"\n        if is_control:\n            return filter(attrgetter(\"control\"), segments)\n        else:\n            return filterfalse(attrgetter(\"control\"), segments)\n\n    @classmethod\n    def split_lines(cls, segments: Iterable[\"Segment\"]) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Split a sequence of segments in to a list of lines.\n\n        Args:\n            segments (Iterable[Segment]): Segments potentially containing line feeds.\n\n        Yields:\n            Iterable[List[Segment]]: Iterable of segment lists, one per line.\n        \"\"\"\n        line: List[Segment] = []\n        append = line.append\n\n        for segment in segments:\n            if \"\\n\" in segment.text and not segment.control:\n                text, style, _ = segment\n                while text:\n                    _text, new_line, text = text.partition(\"\\n\")\n                    if _text:\n                        append(cls(_text, style))\n                    if new_line:\n                        yield line\n                        line = []\n                        append = line.append\n            else:\n                append(segment)\n        if line:\n            yield line\n\n    @classmethod\n    def split_and_crop_lines(\n        cls,\n        segments: Iterable[\"Segment\"],\n        length: int,\n        style: Optional[Style] = None,\n        pad: bool = True,\n        include_new_lines: bool = True,\n    ) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Split segments in to lines, and crop lines greater than a given length.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of segments, probably\n                generated from console.render.\n            length (int): Desired line length.\n            style (Style, optional): Style to use for any padding.\n            pad (bool): Enable padding of lines that are less than `length`.\n\n        Returns:\n            Iterable[List[Segment]]: An iterable of lines of segments.\n        \"\"\"\n        line: List[Segment] = []\n        append = line.append\n\n        adjust_line_length = cls.adjust_line_length\n        new_line_segment = cls(\"\\n\")\n\n        for segment in segments:\n            if \"\\n\" in segment.text and not segment.control:\n                text, segment_style, _ = segment\n                while text:\n                    _text, new_line, text = text.partition(\"\\n\")\n                    if _text:\n                        append(cls(_text, segment_style))\n                    if new_line:\n                        cropped_line = adjust_line_length(\n                            line, length, style=style, pad=pad\n                        )\n                        if include_new_lines:\n                            cropped_line.append(new_line_segment)\n                        yield cropped_line\n                        line.clear()\n            else:\n                append(segment)\n        if line:\n            yield adjust_line_length(line, length, style=style, pad=pad)\n\n    @classmethod\n    def adjust_line_length(\n        cls,\n        line: List[\"Segment\"],\n        length: int,\n        style: Optional[Style] = None,\n        pad: bool = True,\n    ) -> List[\"Segment\"]:\n        \"\"\"Adjust a line to a given width (cropping or padding as required).\n\n        Args:\n            segments (Iterable[Segment]): A list of segments in a single line.\n            length (int): The desired width of the line.\n            style (Style, optional): The style of padding if used (space on the end). Defaults to None.\n            pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.\n\n        Returns:\n            List[Segment]: A line of segments with the desired length.\n        \"\"\"\n        line_length = sum(segment.cell_length for segment in line)\n        new_line: List[Segment]\n\n        if line_length < length:\n            if pad:\n                new_line = line + [cls(\" \" * (length - line_length), style)]\n            else:\n                new_line = line[:]\n        elif line_length > length:\n            new_line = []\n            append = new_line.append\n            line_length = 0\n            for segment in line:\n                segment_length = segment.cell_length\n                if line_length + segment_length < length or segment.control:\n                    append(segment)\n                    line_length += segment_length\n                else:\n                    text, segment_style, _ = segment\n                    text = set_cell_size(text, length - line_length)\n                    append(cls(text, segment_style))\n                    break\n        else:\n            new_line = line[:]\n        return new_line\n\n    @classmethod\n    def get_line_length(cls, line: List[\"Segment\"]) -> int:\n        \"\"\"Get the length of list of segments.\n\n        Args:\n            line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\\\\\n' characters),\n\n        Returns:\n            int: The length of the line.\n        \"\"\"\n        _cell_len = cell_len\n        return sum(_cell_len(text) for text, style, control in line if not control)\n\n    @classmethod\n    def get_shape(cls, lines: List[List[\"Segment\"]]) -> Tuple[int, int]:\n        \"\"\"Get the shape (enclosing rectangle) of a list of lines.\n\n        Args:\n            lines (List[List[Segment]]): A list of lines (no '\\\\\\\\n' characters).\n\n        Returns:\n            Tuple[int, int]: Width and height in characters.\n        \"\"\"\n        get_line_length = cls.get_line_length\n        max_width = max(get_line_length(line) for line in lines) if lines else 0\n        return (max_width, len(lines))\n\n    @classmethod\n    def set_shape(\n        cls,\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: Optional[int] = None,\n        style: Optional[Style] = None,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Set the shape of a list of lines (enclosing rectangle).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style, optional): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        _height = height or len(lines)\n\n        blank = (\n            [cls(\" \" * width + \"\\n\", style)] if new_lines else [cls(\" \" * width, style)]\n        )\n\n        adjust_line_length = cls.adjust_line_length\n        shaped_lines = lines[:_height]\n        shaped_lines[:] = [\n            adjust_line_length(line, width, style=style) for line in lines\n        ]\n        if len(shaped_lines) < _height:\n            shaped_lines.extend([blank] * (_height - len(shaped_lines)))\n        return shaped_lines\n\n    @classmethod\n    def align_top(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns lines to top (adds extra lines to bottom as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        lines = lines + [[blank]] * extra_lines\n        return lines\n\n    @classmethod\n    def align_bottom(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns render to bottom (adds extra lines above as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added. Defaults to None.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        lines = [[blank]] * extra_lines + lines\n        return lines\n\n    @classmethod\n    def align_middle(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns lines to middle (adds extra lines to above and below as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        top_lines = extra_lines // 2\n        bottom_lines = extra_lines - top_lines\n        lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines\n        return lines\n\n    @classmethod\n    def simplify(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Simplify an iterable of segments by combining contiguous segments with the same style.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of segments.\n\n        Returns:\n            Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.\n        \"\"\"\n        iter_segments = iter(segments)\n        try:\n            last_segment = next(iter_segments)\n        except StopIteration:\n            return\n\n        _Segment = Segment\n        for segment in iter_segments:\n            if last_segment.style == segment.style and not segment.control:\n                last_segment = _Segment(\n                    last_segment.text + segment.text, last_segment.style\n                )\n            else:\n                yield last_segment\n                last_segment = segment\n        yield last_segment\n\n    @classmethod\n    def strip_links(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all links from an iterable of styles.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with link removed.\n        \"\"\"\n        for segment in segments:\n            if segment.control or segment.style is None:\n                yield segment\n            else:\n                text, style, _control = segment\n                yield cls(text, style.update_link(None) if style else None)\n\n    @classmethod\n    def strip_styles(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all styles from an iterable of segments.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with styles replace with None\n        \"\"\"\n        for text, _style, control in segments:\n            yield cls(text, None, control)\n\n    @classmethod\n    def remove_color(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all color from an iterable of segments.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with colorless style.\n        \"\"\"\n\n        cache: Dict[Style, Style] = {}\n        for text, style, control in segments:\n            if style:\n                colorless_style = cache.get(style)\n                if colorless_style is None:\n                    colorless_style = style.without_color\n                    cache[style] = colorless_style\n                yield cls(text, colorless_style, control)\n            else:\n                yield cls(text, None, control)\n\n    @classmethod\n    def divide(\n        cls, segments: Iterable[\"Segment\"], cuts: Iterable[int]\n    ) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Divides an iterable of segments in to portions.\n\n        Args:\n            cuts (Iterable[int]): Cell positions where to divide.\n\n        Yields:\n            [Iterable[List[Segment]]]: An iterable of Segments in List.\n        \"\"\"\n        split_segments: List[\"Segment\"] = []\n        add_segment = split_segments.append\n\n        iter_cuts = iter(cuts)\n\n        while True:\n            cut = next(iter_cuts, -1)\n            if cut == -1:\n                return\n            if cut != 0:\n                break\n            yield []\n        pos = 0\n\n        segments_clear = split_segments.clear\n        segments_copy = split_segments.copy\n\n        _cell_len = cached_cell_len\n        for segment in segments:\n            text, _style, control = segment\n            while text:\n                end_pos = pos if control else pos + _cell_len(text)\n                if end_pos < cut:\n                    add_segment(segment)\n                    pos = end_pos\n                    break\n\n                if end_pos == cut:\n                    add_segment(segment)\n                    yield segments_copy()\n                    segments_clear()\n                    pos = end_pos\n\n                    cut = next(iter_cuts, -1)\n                    if cut == -1:\n                        if split_segments:\n                            yield segments_copy()\n                        return\n\n                    break\n\n                else:\n                    before, segment = segment.split_cells(cut - pos)\n                    text, _style, control = segment\n                    add_segment(before)\n                    yield segments_copy()\n                    segments_clear()\n                    pos = cut\n\n                cut = next(iter_cuts, -1)\n                if cut == -1:\n                    if split_segments:\n                        yield segments_copy()\n                    return\n\n        yield segments_copy()\n\n\nclass Segments:\n    \"\"\"A simple renderable to render an iterable of segments. This class may be useful if\n    you want to print segments outside of a __rich_console__ method.\n\n    Args:\n        segments (Iterable[Segment]): An iterable of segments.\n        new_lines (bool, optional): Add new lines between segments. Defaults to False.\n    \"\"\"\n\n    def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None:\n        self.segments = list(segments)\n        self.new_lines = new_lines\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.new_lines:\n            line = Segment.line()\n            for segment in self.segments:\n                yield segment\n                yield line\n        else:\n            yield from self.segments\n\n\nclass SegmentLines:\n    def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None:\n        \"\"\"A simple renderable containing a number of lines of segments. May be used as an intermediate\n        in rendering process.\n\n        Args:\n            lines (Iterable[List[Segment]]): Lists of segments forming lines.\n            new_lines (bool, optional): Insert new lines after each line. Defaults to False.\n        \"\"\"\n        self.lines = list(lines)\n        self.new_lines = new_lines\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.new_lines:\n            new_line = Segment.line()\n            for line in self.lines:\n                yield from line\n                yield new_line\n        else:\n            for line in self.lines:\n                yield from line\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.syntax import Syntax\n    from pip._vendor.rich.text import Text\n\n    code = \"\"\"from rich.console import Console\nconsole = Console()\ntext = Text.from_markup(\"Hello, [bold magenta]World[/]!\")\nconsole.print(text)\"\"\"\n\n    text = Text.from_markup(\"Hello, [bold magenta]World[/]!\")\n\n    console = Console()\n\n    console.rule(\"rich.Segment\")\n    console.print(\n        \"A Segment is the last step in the Rich render process before generating text with ANSI codes.\"\n    )\n    console.print(\"\\nConsider the following code:\\n\")\n    console.print(Syntax(code, \"python\", line_numbers=True))\n    console.print()\n    console.print(\n        \"When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\\n\"\n    )\n    fragments = list(console.render(text))\n    console.print(fragments)\n    console.print()\n    console.print(\"The Segments are then processed to produce the following output:\\n\")\n    console.print(text)\n    console.print(\n        \"\\nYou will only need to know this if you are implementing your own Rich renderables.\"\n    )\n"
  },
  {
    "path": "src/pip/_vendor/rich/spinner.py",
    "content": "from typing import TYPE_CHECKING, List, Optional, Union, cast\n\nfrom ._spinners import SPINNERS\nfrom .measure import Measurement\nfrom .table import Table\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n    from .style import StyleType\n\n\nclass Spinner:\n    \"\"\"A spinner animation.\n\n    Args:\n        name (str): Name of spinner (run python -m rich.spinner).\n        text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to \"\".\n        style (StyleType, optional): Style for spinner animation. Defaults to None.\n        speed (float, optional): Speed factor for animation. Defaults to 1.0.\n\n    Raises:\n        KeyError: If name isn't one of the supported spinner animations.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        text: \"RenderableType\" = \"\",\n        *,\n        style: Optional[\"StyleType\"] = None,\n        speed: float = 1.0,\n    ) -> None:\n        try:\n            spinner = SPINNERS[name]\n        except KeyError:\n            raise KeyError(f\"no spinner called {name!r}\")\n        self.text: \"Union[RenderableType, Text]\" = (\n            Text.from_markup(text) if isinstance(text, str) else text\n        )\n        self.name = name\n        self.frames = cast(List[str], spinner[\"frames\"])[:]\n        self.interval = cast(float, spinner[\"interval\"])\n        self.start_time: Optional[float] = None\n        self.style = style\n        self.speed = speed\n        self.frame_no_offset: float = 0.0\n        self._update_speed = 0.0\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        yield self.render(console.get_time())\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        text = self.render(0)\n        return Measurement.get(console, options, text)\n\n    def render(self, time: float) -> \"RenderableType\":\n        \"\"\"Render the spinner for a given time.\n\n        Args:\n            time (float): Time in seconds.\n\n        Returns:\n            RenderableType: A renderable containing animation frame.\n        \"\"\"\n        if self.start_time is None:\n            self.start_time = time\n\n        frame_no = ((time - self.start_time) * self.speed) / (\n            self.interval / 1000.0\n        ) + self.frame_no_offset\n        frame = Text(\n            self.frames[int(frame_no) % len(self.frames)], style=self.style or \"\"\n        )\n\n        if self._update_speed:\n            self.frame_no_offset = frame_no\n            self.start_time = time\n            self.speed = self._update_speed\n            self._update_speed = 0.0\n\n        if not self.text:\n            return frame\n        elif isinstance(self.text, (str, Text)):\n            return Text.assemble(frame, \" \", self.text)\n        else:\n            table = Table.grid(padding=1)\n            table.add_row(frame, self.text)\n            return table\n\n    def update(\n        self,\n        *,\n        text: \"RenderableType\" = \"\",\n        style: Optional[\"StyleType\"] = None,\n        speed: Optional[float] = None,\n    ) -> None:\n        \"\"\"Updates attributes of a spinner after it has been started.\n\n        Args:\n            text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to \"\".\n            style (StyleType, optional): Style for spinner animation. Defaults to None.\n            speed (float, optional): Speed factor for animation. Defaults to None.\n        \"\"\"\n        if text:\n            self.text = Text.from_markup(text) if isinstance(text, str) else text\n        if style:\n            self.style = style\n        if speed:\n            self._update_speed = speed\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from time import sleep\n\n    from .console import Group\n    from .live import Live\n\n    all_spinners = Group(\n        *[\n            Spinner(spinner_name, text=Text(repr(spinner_name), style=\"green\"))\n            for spinner_name in sorted(SPINNERS.keys())\n        ]\n    )\n\n    with Live(all_spinners, refresh_per_second=20) as live:\n        while True:\n            sleep(0.1)\n"
  },
  {
    "path": "src/pip/_vendor/rich/status.py",
    "content": "from types import TracebackType\nfrom typing import Optional, Type\n\nfrom .console import Console, RenderableType\nfrom .jupyter import JupyterMixin\nfrom .live import Live\nfrom .spinner import Spinner\nfrom .style import StyleType\n\n\nclass Status(JupyterMixin):\n    \"\"\"Displays a status indicator with a 'spinner' animation.\n\n    Args:\n        status (RenderableType): A status renderable (str or Text typically).\n        console (Console, optional): Console instance to use, or None for global console. Defaults to None.\n        spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to \"dots\".\n        spinner_style (StyleType, optional): Style of spinner. Defaults to \"status.spinner\".\n        speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.\n        refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.\n    \"\"\"\n\n    def __init__(\n        self,\n        status: RenderableType,\n        *,\n        console: Optional[Console] = None,\n        spinner: str = \"dots\",\n        spinner_style: StyleType = \"status.spinner\",\n        speed: float = 1.0,\n        refresh_per_second: float = 12.5,\n    ):\n        self.status = status\n        self.spinner_style = spinner_style\n        self.speed = speed\n        self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed)\n        self._live = Live(\n            self.renderable,\n            console=console,\n            refresh_per_second=refresh_per_second,\n            transient=True,\n        )\n\n    @property\n    def renderable(self) -> Spinner:\n        return self._spinner\n\n    @property\n    def console(self) -> \"Console\":\n        \"\"\"Get the Console used by the Status objects.\"\"\"\n        return self._live.console\n\n    def update(\n        self,\n        status: Optional[RenderableType] = None,\n        *,\n        spinner: Optional[str] = None,\n        spinner_style: Optional[StyleType] = None,\n        speed: Optional[float] = None,\n    ) -> None:\n        \"\"\"Update status.\n\n        Args:\n            status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None.\n            spinner (Optional[str], optional): New spinner or None for no change. Defaults to None.\n            spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None.\n            speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None.\n        \"\"\"\n        if status is not None:\n            self.status = status\n        if spinner_style is not None:\n            self.spinner_style = spinner_style\n        if speed is not None:\n            self.speed = speed\n        if spinner is not None:\n            self._spinner = Spinner(\n                spinner, text=self.status, style=self.spinner_style, speed=self.speed\n            )\n            self._live.update(self.renderable, refresh=True)\n        else:\n            self._spinner.update(\n                text=self.status, style=self.spinner_style, speed=self.speed\n            )\n\n    def start(self) -> None:\n        \"\"\"Start the status animation.\"\"\"\n        self._live.start()\n\n    def stop(self) -> None:\n        \"\"\"Stop the spinner animation.\"\"\"\n        self._live.stop()\n\n    def __rich__(self) -> RenderableType:\n        return self.renderable\n\n    def __enter__(self) -> \"Status\":\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from time import sleep\n\n    from .console import Console\n\n    console = Console()\n    with console.status(\"[magenta]Covid detector booting up\") as status:\n        sleep(3)\n        console.log(\"Importing advanced AI\")\n        sleep(3)\n        console.log(\"Advanced Covid AI Ready\")\n        sleep(3)\n        status.update(status=\"[bold blue] Scanning for Covid\", spinner=\"earth\")\n        sleep(3)\n        console.log(\"Found 10,000,000,000 copies of Covid32.exe\")\n        sleep(3)\n        status.update(\n            status=\"[bold red]Moving Covid32.exe to Trash\",\n            spinner=\"bouncingBall\",\n            spinner_style=\"yellow\",\n        )\n        sleep(5)\n    console.print(\"[bold green]Covid deleted successfully\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/style.py",
    "content": "import sys\nfrom functools import lru_cache\nfrom operator import attrgetter\nfrom pickle import dumps, loads\nfrom random import randint\nfrom typing import Any, Dict, Iterable, List, Optional, Type, Union, cast\n\nfrom . import errors\nfrom .color import Color, ColorParseError, ColorSystem, blend_rgb\nfrom .repr import Result, rich_repr\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme\n\n_hash_getter = attrgetter(\n    \"_color\", \"_bgcolor\", \"_attributes\", \"_set_attributes\", \"_link\", \"_meta\"\n)\n\n# Style instances and style definitions are often interchangeable\nStyleType = Union[str, \"Style\"]\n\n\nclass _Bit:\n    \"\"\"A descriptor to get/set a style attribute bit.\"\"\"\n\n    __slots__ = [\"bit\"]\n\n    def __init__(self, bit_no: int) -> None:\n        self.bit = 1 << bit_no\n\n    def __get__(self, obj: \"Style\", objtype: Type[\"Style\"]) -> Optional[bool]:\n        if obj._set_attributes & self.bit:\n            return obj._attributes & self.bit != 0\n        return None\n\n\n@rich_repr\nclass Style:\n    \"\"\"A terminal style.\n\n    A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such\n    as bold, italic etc. The attributes have 3 states: they can either be on\n    (``True``), off (``False``), or not set (``None``).\n\n    Args:\n        color (Union[Color, str], optional): Color of terminal text. Defaults to None.\n        bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.\n        bold (bool, optional): Enable bold text. Defaults to None.\n        dim (bool, optional): Enable dim text. Defaults to None.\n        italic (bool, optional): Enable italic text. Defaults to None.\n        underline (bool, optional): Enable underlined text. Defaults to None.\n        blink (bool, optional): Enabled blinking text. Defaults to None.\n        blink2 (bool, optional): Enable fast blinking text. Defaults to None.\n        reverse (bool, optional): Enabled reverse text. Defaults to None.\n        conceal (bool, optional): Enable concealed text. Defaults to None.\n        strike (bool, optional): Enable strikethrough text. Defaults to None.\n        underline2 (bool, optional): Enable doubly underlined text. Defaults to None.\n        frame (bool, optional): Enable framed text. Defaults to None.\n        encircle (bool, optional): Enable encircled text. Defaults to None.\n        overline (bool, optional): Enable overlined text. Defaults to None.\n        link (str, link): Link URL. Defaults to None.\n\n    \"\"\"\n\n    _color: Optional[Color]\n    _bgcolor: Optional[Color]\n    _attributes: int\n    _set_attributes: int\n    _hash: Optional[int]\n    _null: bool\n    _meta: Optional[bytes]\n\n    __slots__ = [\n        \"_color\",\n        \"_bgcolor\",\n        \"_attributes\",\n        \"_set_attributes\",\n        \"_link\",\n        \"_link_id\",\n        \"_ansi\",\n        \"_style_definition\",\n        \"_hash\",\n        \"_null\",\n        \"_meta\",\n    ]\n\n    # maps bits on to SGR parameter\n    _style_map = {\n        0: \"1\",\n        1: \"2\",\n        2: \"3\",\n        3: \"4\",\n        4: \"5\",\n        5: \"6\",\n        6: \"7\",\n        7: \"8\",\n        8: \"9\",\n        9: \"21\",\n        10: \"51\",\n        11: \"52\",\n        12: \"53\",\n    }\n\n    STYLE_ATTRIBUTES = {\n        \"dim\": \"dim\",\n        \"d\": \"dim\",\n        \"bold\": \"bold\",\n        \"b\": \"bold\",\n        \"italic\": \"italic\",\n        \"i\": \"italic\",\n        \"underline\": \"underline\",\n        \"u\": \"underline\",\n        \"blink\": \"blink\",\n        \"blink2\": \"blink2\",\n        \"reverse\": \"reverse\",\n        \"r\": \"reverse\",\n        \"conceal\": \"conceal\",\n        \"c\": \"conceal\",\n        \"strike\": \"strike\",\n        \"s\": \"strike\",\n        \"underline2\": \"underline2\",\n        \"uu\": \"underline2\",\n        \"frame\": \"frame\",\n        \"encircle\": \"encircle\",\n        \"overline\": \"overline\",\n        \"o\": \"overline\",\n    }\n\n    def __init__(\n        self,\n        *,\n        color: Optional[Union[Color, str]] = None,\n        bgcolor: Optional[Union[Color, str]] = None,\n        bold: Optional[bool] = None,\n        dim: Optional[bool] = None,\n        italic: Optional[bool] = None,\n        underline: Optional[bool] = None,\n        blink: Optional[bool] = None,\n        blink2: Optional[bool] = None,\n        reverse: Optional[bool] = None,\n        conceal: Optional[bool] = None,\n        strike: Optional[bool] = None,\n        underline2: Optional[bool] = None,\n        frame: Optional[bool] = None,\n        encircle: Optional[bool] = None,\n        overline: Optional[bool] = None,\n        link: Optional[str] = None,\n        meta: Optional[Dict[str, Any]] = None,\n    ):\n        self._ansi: Optional[str] = None\n        self._style_definition: Optional[str] = None\n\n        def _make_color(color: Union[Color, str]) -> Color:\n            return color if isinstance(color, Color) else Color.parse(color)\n\n        self._color = None if color is None else _make_color(color)\n        self._bgcolor = None if bgcolor is None else _make_color(bgcolor)\n        self._set_attributes = sum(\n            (\n                bold is not None,\n                dim is not None and 2,\n                italic is not None and 4,\n                underline is not None and 8,\n                blink is not None and 16,\n                blink2 is not None and 32,\n                reverse is not None and 64,\n                conceal is not None and 128,\n                strike is not None and 256,\n                underline2 is not None and 512,\n                frame is not None and 1024,\n                encircle is not None and 2048,\n                overline is not None and 4096,\n            )\n        )\n        self._attributes = (\n            sum(\n                (\n                    bold and 1 or 0,\n                    dim and 2 or 0,\n                    italic and 4 or 0,\n                    underline and 8 or 0,\n                    blink and 16 or 0,\n                    blink2 and 32 or 0,\n                    reverse and 64 or 0,\n                    conceal and 128 or 0,\n                    strike and 256 or 0,\n                    underline2 and 512 or 0,\n                    frame and 1024 or 0,\n                    encircle and 2048 or 0,\n                    overline and 4096 or 0,\n                )\n            )\n            if self._set_attributes\n            else 0\n        )\n\n        self._link = link\n        self._meta = None if meta is None else dumps(meta)\n        self._link_id = (\n            f\"{randint(0, 999999)}{hash(self._meta)}\" if (link or meta) else \"\"\n        )\n        self._hash: Optional[int] = None\n        self._null = not (self._set_attributes or color or bgcolor or link or meta)\n\n    @classmethod\n    def null(cls) -> \"Style\":\n        \"\"\"Create an 'null' style, equivalent to Style(), but more performant.\"\"\"\n        return NULL_STYLE\n\n    @classmethod\n    def from_color(\n        cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None\n    ) -> \"Style\":\n        \"\"\"Create a new style with colors and no attributes.\n\n        Returns:\n            color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.\n            bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.\n        \"\"\"\n        style: Style = cls.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = color\n        style._bgcolor = bgcolor\n        style._set_attributes = 0\n        style._attributes = 0\n        style._link = None\n        style._link_id = \"\"\n        style._meta = None\n        style._null = not (color or bgcolor)\n        style._hash = None\n        return style\n\n    @classmethod\n    def from_meta(cls, meta: Optional[Dict[str, Any]]) -> \"Style\":\n        \"\"\"Create a new style with meta data.\n\n        Returns:\n            meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.\n        \"\"\"\n        style: Style = cls.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = None\n        style._bgcolor = None\n        style._set_attributes = 0\n        style._attributes = 0\n        style._link = None\n        style._meta = dumps(meta)\n        style._link_id = f\"{randint(0, 999999)}{hash(style._meta)}\"\n        style._hash = None\n        style._null = not (meta)\n        return style\n\n    @classmethod\n    def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> \"Style\":\n        \"\"\"Create a blank style with meta information.\n\n        Example:\n            style = Style.on(click=self.on_click)\n\n        Args:\n            meta (Optional[Dict[str, Any]], optional): An optional dict of meta information.\n            **handlers (Any): Keyword arguments are translated in to handlers.\n\n        Returns:\n            Style: A Style with meta information attached.\n        \"\"\"\n        meta = {} if meta is None else meta\n        meta.update({f\"@{key}\": value for key, value in handlers.items()})\n        return cls.from_meta(meta)\n\n    bold = _Bit(0)\n    dim = _Bit(1)\n    italic = _Bit(2)\n    underline = _Bit(3)\n    blink = _Bit(4)\n    blink2 = _Bit(5)\n    reverse = _Bit(6)\n    conceal = _Bit(7)\n    strike = _Bit(8)\n    underline2 = _Bit(9)\n    frame = _Bit(10)\n    encircle = _Bit(11)\n    overline = _Bit(12)\n\n    @property\n    def link_id(self) -> str:\n        \"\"\"Get a link id, used in ansi code for links.\"\"\"\n        return self._link_id\n\n    def __str__(self) -> str:\n        \"\"\"Re-generate style definition from attributes.\"\"\"\n        if self._style_definition is None:\n            attributes: List[str] = []\n            append = attributes.append\n            bits = self._set_attributes\n            if bits & 0b0000000001111:\n                if bits & 1:\n                    append(\"bold\" if self.bold else \"not bold\")\n                if bits & (1 << 1):\n                    append(\"dim\" if self.dim else \"not dim\")\n                if bits & (1 << 2):\n                    append(\"italic\" if self.italic else \"not italic\")\n                if bits & (1 << 3):\n                    append(\"underline\" if self.underline else \"not underline\")\n            if bits & 0b0000111110000:\n                if bits & (1 << 4):\n                    append(\"blink\" if self.blink else \"not blink\")\n                if bits & (1 << 5):\n                    append(\"blink2\" if self.blink2 else \"not blink2\")\n                if bits & (1 << 6):\n                    append(\"reverse\" if self.reverse else \"not reverse\")\n                if bits & (1 << 7):\n                    append(\"conceal\" if self.conceal else \"not conceal\")\n                if bits & (1 << 8):\n                    append(\"strike\" if self.strike else \"not strike\")\n            if bits & 0b1111000000000:\n                if bits & (1 << 9):\n                    append(\"underline2\" if self.underline2 else \"not underline2\")\n                if bits & (1 << 10):\n                    append(\"frame\" if self.frame else \"not frame\")\n                if bits & (1 << 11):\n                    append(\"encircle\" if self.encircle else \"not encircle\")\n                if bits & (1 << 12):\n                    append(\"overline\" if self.overline else \"not overline\")\n            if self._color is not None:\n                append(self._color.name)\n            if self._bgcolor is not None:\n                append(\"on\")\n                append(self._bgcolor.name)\n            if self._link:\n                append(\"link\")\n                append(self._link)\n            self._style_definition = \" \".join(attributes) or \"none\"\n        return self._style_definition\n\n    def __bool__(self) -> bool:\n        \"\"\"A Style is false if it has no attributes, colors, or links.\"\"\"\n        return not self._null\n\n    def _make_ansi_codes(self, color_system: ColorSystem) -> str:\n        \"\"\"Generate ANSI codes for this style.\n\n        Args:\n            color_system (ColorSystem): Color system.\n\n        Returns:\n            str: String containing codes.\n        \"\"\"\n\n        if self._ansi is None:\n            sgr: List[str] = []\n            append = sgr.append\n            _style_map = self._style_map\n            attributes = self._attributes & self._set_attributes\n            if attributes:\n                if attributes & 1:\n                    append(_style_map[0])\n                if attributes & 2:\n                    append(_style_map[1])\n                if attributes & 4:\n                    append(_style_map[2])\n                if attributes & 8:\n                    append(_style_map[3])\n                if attributes & 0b0000111110000:\n                    for bit in range(4, 9):\n                        if attributes & (1 << bit):\n                            append(_style_map[bit])\n                if attributes & 0b1111000000000:\n                    for bit in range(9, 13):\n                        if attributes & (1 << bit):\n                            append(_style_map[bit])\n            if self._color is not None:\n                sgr.extend(self._color.downgrade(color_system).get_ansi_codes())\n            if self._bgcolor is not None:\n                sgr.extend(\n                    self._bgcolor.downgrade(color_system).get_ansi_codes(\n                        foreground=False\n                    )\n                )\n            self._ansi = \";\".join(sgr)\n        return self._ansi\n\n    @classmethod\n    @lru_cache(maxsize=1024)\n    def normalize(cls, style: str) -> str:\n        \"\"\"Normalize a style definition so that styles with the same effect have the same string\n        representation.\n\n        Args:\n            style (str): A style definition.\n\n        Returns:\n            str: Normal form of style definition.\n        \"\"\"\n        try:\n            return str(cls.parse(style))\n        except errors.StyleSyntaxError:\n            return style.strip().lower()\n\n    @classmethod\n    def pick_first(cls, *values: Optional[StyleType]) -> StyleType:\n        \"\"\"Pick first non-None style.\"\"\"\n        for value in values:\n            if value is not None:\n                return value\n        raise ValueError(\"expected at least one non-None style\")\n\n    def __rich_repr__(self) -> Result:\n        yield \"color\", self.color, None\n        yield \"bgcolor\", self.bgcolor, None\n        yield \"bold\", self.bold, None,\n        yield \"dim\", self.dim, None,\n        yield \"italic\", self.italic, None\n        yield \"underline\", self.underline, None,\n        yield \"blink\", self.blink, None\n        yield \"blink2\", self.blink2, None\n        yield \"reverse\", self.reverse, None\n        yield \"conceal\", self.conceal, None\n        yield \"strike\", self.strike, None\n        yield \"underline2\", self.underline2, None\n        yield \"frame\", self.frame, None\n        yield \"encircle\", self.encircle, None\n        yield \"link\", self.link, None\n        if self._meta:\n            yield \"meta\", self.meta\n\n    def __eq__(self, other: Any) -> bool:\n        if not isinstance(other, Style):\n            return NotImplemented\n        return self.__hash__() == other.__hash__()\n\n    def __ne__(self, other: Any) -> bool:\n        if not isinstance(other, Style):\n            return NotImplemented\n        return self.__hash__() != other.__hash__()\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n        self._hash = hash(_hash_getter(self))\n        return self._hash\n\n    @property\n    def color(self) -> Optional[Color]:\n        \"\"\"The foreground color or None if it is not set.\"\"\"\n        return self._color\n\n    @property\n    def bgcolor(self) -> Optional[Color]:\n        \"\"\"The background color or None if it is not set.\"\"\"\n        return self._bgcolor\n\n    @property\n    def link(self) -> Optional[str]:\n        \"\"\"Link text, if set.\"\"\"\n        return self._link\n\n    @property\n    def transparent_background(self) -> bool:\n        \"\"\"Check if the style specified a transparent background.\"\"\"\n        return self.bgcolor is None or self.bgcolor.is_default\n\n    @property\n    def background_style(self) -> \"Style\":\n        \"\"\"A Style with background only.\"\"\"\n        return Style(bgcolor=self.bgcolor)\n\n    @property\n    def meta(self) -> Dict[str, Any]:\n        \"\"\"Get meta information (can not be changed after construction).\"\"\"\n        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))\n\n    @property\n    def without_color(self) -> \"Style\":\n        \"\"\"Get a copy of the style with color removed.\"\"\"\n        if self._null:\n            return NULL_STYLE\n        style: Style = self.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = None\n        style._bgcolor = None\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = self._link\n        style._link_id = f\"{randint(0, 999999)}\" if self._link else \"\"\n        style._null = False\n        style._meta = None\n        style._hash = None\n        return style\n\n    @classmethod\n    @lru_cache(maxsize=4096)\n    def parse(cls, style_definition: str) -> \"Style\":\n        \"\"\"Parse a style definition.\n\n        Args:\n            style_definition (str): A string containing a style.\n\n        Raises:\n            errors.StyleSyntaxError: If the style definition syntax is invalid.\n\n        Returns:\n            `Style`: A Style instance.\n        \"\"\"\n        if style_definition.strip() == \"none\" or not style_definition:\n            return cls.null()\n\n        STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES\n        color: Optional[str] = None\n        bgcolor: Optional[str] = None\n        attributes: Dict[str, Optional[Any]] = {}\n        link: Optional[str] = None\n\n        words = iter(style_definition.split())\n        for original_word in words:\n            word = original_word.lower()\n            if word == \"on\":\n                word = next(words, \"\")\n                if not word:\n                    raise errors.StyleSyntaxError(\"color expected after 'on'\")\n                try:\n                    Color.parse(word)\n                except ColorParseError as error:\n                    raise errors.StyleSyntaxError(\n                        f\"unable to parse {word!r} as background color; {error}\"\n                    ) from None\n                bgcolor = word\n\n            elif word == \"not\":\n                word = next(words, \"\")\n                attribute = STYLE_ATTRIBUTES.get(word)\n                if attribute is None:\n                    raise errors.StyleSyntaxError(\n                        f\"expected style attribute after 'not', found {word!r}\"\n                    )\n                attributes[attribute] = False\n\n            elif word == \"link\":\n                word = next(words, \"\")\n                if not word:\n                    raise errors.StyleSyntaxError(\"URL expected after 'link'\")\n                link = word\n\n            elif word in STYLE_ATTRIBUTES:\n                attributes[STYLE_ATTRIBUTES[word]] = True\n\n            else:\n                try:\n                    Color.parse(word)\n                except ColorParseError as error:\n                    raise errors.StyleSyntaxError(\n                        f\"unable to parse {word!r} as color; {error}\"\n                    ) from None\n                color = word\n        style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)\n        return style\n\n    @lru_cache(maxsize=1024)\n    def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:\n        \"\"\"Get a CSS style rule.\"\"\"\n        theme = theme or DEFAULT_TERMINAL_THEME\n        css: List[str] = []\n        append = css.append\n\n        color = self.color\n        bgcolor = self.bgcolor\n        if self.reverse:\n            color, bgcolor = bgcolor, color\n        if self.dim:\n            foreground_color = (\n                theme.foreground_color if color is None else color.get_truecolor(theme)\n            )\n            color = Color.from_triplet(\n                blend_rgb(foreground_color, theme.background_color, 0.5)\n            )\n        if color is not None:\n            theme_color = color.get_truecolor(theme)\n            append(f\"color: {theme_color.hex}\")\n            append(f\"text-decoration-color: {theme_color.hex}\")\n        if bgcolor is not None:\n            theme_color = bgcolor.get_truecolor(theme, foreground=False)\n            append(f\"background-color: {theme_color.hex}\")\n        if self.bold:\n            append(\"font-weight: bold\")\n        if self.italic:\n            append(\"font-style: italic\")\n        if self.underline:\n            append(\"text-decoration: underline\")\n        if self.strike:\n            append(\"text-decoration: line-through\")\n        if self.overline:\n            append(\"text-decoration: overline\")\n        return \"; \".join(css)\n\n    @classmethod\n    def combine(cls, styles: Iterable[\"Style\"]) -> \"Style\":\n        \"\"\"Combine styles and get result.\n\n        Args:\n            styles (Iterable[Style]): Styles to combine.\n\n        Returns:\n            Style: A new style instance.\n        \"\"\"\n        iter_styles = iter(styles)\n        return sum(iter_styles, next(iter_styles))\n\n    @classmethod\n    def chain(cls, *styles: \"Style\") -> \"Style\":\n        \"\"\"Combine styles from positional argument in to a single style.\n\n        Args:\n            *styles (Iterable[Style]): Styles to combine.\n\n        Returns:\n            Style: A new style instance.\n        \"\"\"\n        iter_styles = iter(styles)\n        return sum(iter_styles, next(iter_styles))\n\n    def copy(self) -> \"Style\":\n        \"\"\"Get a copy of this style.\n\n        Returns:\n            Style: A new Style instance with identical attributes.\n        \"\"\"\n        if self._null:\n            return NULL_STYLE\n        style: Style = self.__new__(Style)\n        style._ansi = self._ansi\n        style._style_definition = self._style_definition\n        style._color = self._color\n        style._bgcolor = self._bgcolor\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = self._link\n        style._link_id = f\"{randint(0, 999999)}\" if self._link else \"\"\n        style._hash = self._hash\n        style._null = False\n        style._meta = self._meta\n        return style\n\n    @lru_cache(maxsize=128)\n    def clear_meta_and_links(self) -> \"Style\":\n        \"\"\"Get a copy of this style with link and meta information removed.\n\n        Returns:\n            Style: New style object.\n        \"\"\"\n        if self._null:\n            return NULL_STYLE\n        style: Style = self.__new__(Style)\n        style._ansi = self._ansi\n        style._style_definition = self._style_definition\n        style._color = self._color\n        style._bgcolor = self._bgcolor\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = None\n        style._link_id = \"\"\n        style._hash = None\n        style._null = False\n        style._meta = None\n        return style\n\n    def update_link(self, link: Optional[str] = None) -> \"Style\":\n        \"\"\"Get a copy with a different value for link.\n\n        Args:\n            link (str, optional): New value for link. Defaults to None.\n\n        Returns:\n            Style: A new Style instance.\n        \"\"\"\n        style: Style = self.__new__(Style)\n        style._ansi = self._ansi\n        style._style_definition = self._style_definition\n        style._color = self._color\n        style._bgcolor = self._bgcolor\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = link\n        style._link_id = f\"{randint(0, 999999)}\" if link else \"\"\n        style._hash = None\n        style._null = False\n        style._meta = self._meta\n        return style\n\n    def render(\n        self,\n        text: str = \"\",\n        *,\n        color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,\n        legacy_windows: bool = False,\n    ) -> str:\n        \"\"\"Render the ANSI codes for the style.\n\n        Args:\n            text (str, optional): A string to style. Defaults to \"\".\n            color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.\n\n        Returns:\n            str: A string containing ANSI style codes.\n        \"\"\"\n        if not text or color_system is None:\n            return text\n        attrs = self._ansi or self._make_ansi_codes(color_system)\n        rendered = f\"\\x1b[{attrs}m{text}\\x1b[0m\" if attrs else text\n        if self._link and not legacy_windows:\n            rendered = (\n                f\"\\x1b]8;id={self._link_id};{self._link}\\x1b\\\\{rendered}\\x1b]8;;\\x1b\\\\\"\n            )\n        return rendered\n\n    def test(self, text: Optional[str] = None) -> None:\n        \"\"\"Write text with style directly to terminal.\n\n        This method is for testing purposes only.\n\n        Args:\n            text (Optional[str], optional): Text to style or None for style name.\n\n        \"\"\"\n        text = text or str(self)\n        sys.stdout.write(f\"{self.render(text)}\\n\")\n\n    @lru_cache(maxsize=1024)\n    def _add(self, style: Optional[\"Style\"]) -> \"Style\":\n        if style is None or style._null:\n            return self\n        if self._null:\n            return style\n        new_style: Style = self.__new__(Style)\n        new_style._ansi = None\n        new_style._style_definition = None\n        new_style._color = style._color or self._color\n        new_style._bgcolor = style._bgcolor or self._bgcolor\n        new_style._attributes = (self._attributes & ~style._set_attributes) | (\n            style._attributes & style._set_attributes\n        )\n        new_style._set_attributes = self._set_attributes | style._set_attributes\n        new_style._link = style._link or self._link\n        new_style._link_id = style._link_id or self._link_id\n        new_style._null = style._null\n        if self._meta and style._meta:\n            new_style._meta = dumps({**self.meta, **style.meta})\n        else:\n            new_style._meta = self._meta or style._meta\n        new_style._hash = None\n        return new_style\n\n    def __add__(self, style: Optional[\"Style\"]) -> \"Style\":\n        combined_style = self._add(style)\n        return combined_style.copy() if combined_style.link else combined_style\n\n\nNULL_STYLE = Style()\n\n\nclass StyleStack:\n    \"\"\"A stack of styles.\"\"\"\n\n    __slots__ = [\"_stack\"]\n\n    def __init__(self, default_style: \"Style\") -> None:\n        self._stack: List[Style] = [default_style]\n\n    def __repr__(self) -> str:\n        return f\"<stylestack {self._stack!r}>\"\n\n    @property\n    def current(self) -> Style:\n        \"\"\"Get the Style at the top of the stack.\"\"\"\n        return self._stack[-1]\n\n    def push(self, style: Style) -> None:\n        \"\"\"Push a new style on to the stack.\n\n        Args:\n            style (Style): New style to combine with current style.\n        \"\"\"\n        self._stack.append(self._stack[-1] + style)\n\n    def pop(self) -> Style:\n        \"\"\"Pop last style and discard.\n\n        Returns:\n            Style: New current style (also available as stack.current)\n        \"\"\"\n        self._stack.pop()\n        return self._stack[-1]\n"
  },
  {
    "path": "src/pip/_vendor/rich/styled.py",
    "content": "from typing import TYPE_CHECKING\n\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult, RenderableType\n\n\nclass Styled:\n    \"\"\"Apply a style to a renderable.\n\n    Args:\n        renderable (RenderableType): Any renderable.\n        style (StyleType): A style to apply across the entire renderable.\n    \"\"\"\n\n    def __init__(self, renderable: \"RenderableType\", style: \"StyleType\") -> None:\n        self.renderable = renderable\n        self.style = style\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style)\n        rendered_segments = console.render(self.renderable, options)\n        segments = Segment.apply_style(rendered_segments, style)\n        return segments\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        return Measurement.get(console, options, self.renderable)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich import print\n    from pip._vendor.rich.panel import Panel\n\n    panel = Styled(Panel(\"hello\"), \"on blue\")\n    print(panel)\n"
  },
  {
    "path": "src/pip/_vendor/rich/syntax.py",
    "content": "from __future__ import annotations\n\nimport os.path\nimport re\nimport sys\nimport textwrap\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom pip._vendor.pygments.lexer import Lexer\nfrom pip._vendor.pygments.lexers import get_lexer_by_name, guess_lexer_for_filename\nfrom pip._vendor.pygments.style import Style as PygmentsStyle\nfrom pip._vendor.pygments.styles import get_style_by_name\nfrom pip._vendor.pygments.token import (\n    Comment,\n    Error,\n    Generic,\n    Keyword,\n    Name,\n    Number,\n    Operator,\n    String,\n    Token,\n    Whitespace,\n)\nfrom pip._vendor.pygments.util import ClassNotFound\n\nfrom pip._vendor.rich.containers import Lines\nfrom pip._vendor.rich.padding import Padding, PaddingDimensions\n\nfrom ._loop import loop_first\nfrom .cells import cell_len\nfrom .color import Color, blend_rgb\nfrom .console import Console, ConsoleOptions, JustifyMethod, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment, Segments\nfrom .style import Style, StyleType\nfrom .text import Text\n\nTokenType = Tuple[str, ...]\n\nWINDOWS = sys.platform == \"win32\"\nDEFAULT_THEME = \"monokai\"\n\n# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py\n# A few modifications were made\n\nANSI_LIGHT: Dict[TokenType, Style] = {\n    Token: Style(),\n    Whitespace: Style(color=\"white\"),\n    Comment: Style(dim=True),\n    Comment.Preproc: Style(color=\"cyan\"),\n    Keyword: Style(color=\"blue\"),\n    Keyword.Type: Style(color=\"cyan\"),\n    Operator.Word: Style(color=\"magenta\"),\n    Name.Builtin: Style(color=\"cyan\"),\n    Name.Function: Style(color=\"green\"),\n    Name.Namespace: Style(color=\"cyan\", underline=True),\n    Name.Class: Style(color=\"green\", underline=True),\n    Name.Exception: Style(color=\"cyan\"),\n    Name.Decorator: Style(color=\"magenta\", bold=True),\n    Name.Variable: Style(color=\"red\"),\n    Name.Constant: Style(color=\"red\"),\n    Name.Attribute: Style(color=\"cyan\"),\n    Name.Tag: Style(color=\"bright_blue\"),\n    String: Style(color=\"yellow\"),\n    Number: Style(color=\"blue\"),\n    Generic.Deleted: Style(color=\"bright_red\"),\n    Generic.Inserted: Style(color=\"green\"),\n    Generic.Heading: Style(bold=True),\n    Generic.Subheading: Style(color=\"magenta\", bold=True),\n    Generic.Prompt: Style(bold=True),\n    Generic.Error: Style(color=\"bright_red\"),\n    Error: Style(color=\"red\", underline=True),\n}\n\nANSI_DARK: Dict[TokenType, Style] = {\n    Token: Style(),\n    Whitespace: Style(color=\"bright_black\"),\n    Comment: Style(dim=True),\n    Comment.Preproc: Style(color=\"bright_cyan\"),\n    Keyword: Style(color=\"bright_blue\"),\n    Keyword.Type: Style(color=\"bright_cyan\"),\n    Operator.Word: Style(color=\"bright_magenta\"),\n    Name.Builtin: Style(color=\"bright_cyan\"),\n    Name.Function: Style(color=\"bright_green\"),\n    Name.Namespace: Style(color=\"bright_cyan\", underline=True),\n    Name.Class: Style(color=\"bright_green\", underline=True),\n    Name.Exception: Style(color=\"bright_cyan\"),\n    Name.Decorator: Style(color=\"bright_magenta\", bold=True),\n    Name.Variable: Style(color=\"bright_red\"),\n    Name.Constant: Style(color=\"bright_red\"),\n    Name.Attribute: Style(color=\"bright_cyan\"),\n    Name.Tag: Style(color=\"bright_blue\"),\n    String: Style(color=\"yellow\"),\n    Number: Style(color=\"bright_blue\"),\n    Generic.Deleted: Style(color=\"bright_red\"),\n    Generic.Inserted: Style(color=\"bright_green\"),\n    Generic.Heading: Style(bold=True),\n    Generic.Subheading: Style(color=\"bright_magenta\", bold=True),\n    Generic.Prompt: Style(bold=True),\n    Generic.Error: Style(color=\"bright_red\"),\n    Error: Style(color=\"red\", underline=True),\n}\n\nRICH_SYNTAX_THEMES = {\"ansi_light\": ANSI_LIGHT, \"ansi_dark\": ANSI_DARK}\nNUMBERS_COLUMN_DEFAULT_PADDING = 2\n\n\nclass SyntaxTheme(ABC):\n    \"\"\"Base class for a syntax theme.\"\"\"\n\n    @abstractmethod\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Get a style for a given Pygments token.\"\"\"\n        raise NotImplementedError  # pragma: no cover\n\n    @abstractmethod\n    def get_background_style(self) -> Style:\n        \"\"\"Get the background color.\"\"\"\n        raise NotImplementedError  # pragma: no cover\n\n\nclass PygmentsSyntaxTheme(SyntaxTheme):\n    \"\"\"Syntax theme that delegates to Pygments theme.\"\"\"\n\n    def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:\n        self._style_cache: Dict[TokenType, Style] = {}\n        if isinstance(theme, str):\n            try:\n                self._pygments_style_class = get_style_by_name(theme)\n            except ClassNotFound:\n                self._pygments_style_class = get_style_by_name(\"default\")\n        else:\n            self._pygments_style_class = theme\n\n        self._background_color = self._pygments_style_class.background_color\n        self._background_style = Style(bgcolor=self._background_color)\n\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Get a style from a Pygments class.\"\"\"\n        try:\n            return self._style_cache[token_type]\n        except KeyError:\n            try:\n                pygments_style = self._pygments_style_class.style_for_token(token_type)\n            except KeyError:\n                style = Style.null()\n            else:\n                color = pygments_style[\"color\"]\n                bgcolor = pygments_style[\"bgcolor\"]\n                style = Style(\n                    color=\"#\" + color if color else \"#000000\",\n                    bgcolor=\"#\" + bgcolor if bgcolor else self._background_color,\n                    bold=pygments_style[\"bold\"],\n                    italic=pygments_style[\"italic\"],\n                    underline=pygments_style[\"underline\"],\n                )\n            self._style_cache[token_type] = style\n        return style\n\n    def get_background_style(self) -> Style:\n        return self._background_style\n\n\nclass ANSISyntaxTheme(SyntaxTheme):\n    \"\"\"Syntax theme to use standard colors.\"\"\"\n\n    def __init__(self, style_map: Dict[TokenType, Style]) -> None:\n        self.style_map = style_map\n        self._missing_style = Style.null()\n        self._background_style = Style.null()\n        self._style_cache: Dict[TokenType, Style] = {}\n\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Look up style in the style map.\"\"\"\n        try:\n            return self._style_cache[token_type]\n        except KeyError:\n            # Styles form a hierarchy\n            # We need to go from most to least specific\n            # e.g. (\"foo\", \"bar\", \"baz\") to (\"foo\", \"bar\")  to (\"foo\",)\n            get_style = self.style_map.get\n            token = tuple(token_type)\n            style = self._missing_style\n            while token:\n                _style = get_style(token)\n                if _style is not None:\n                    style = _style\n                    break\n                token = token[:-1]\n            self._style_cache[token_type] = style\n            return style\n\n    def get_background_style(self) -> Style:\n        return self._background_style\n\n\nSyntaxPosition = Tuple[int, int]\n\n\nclass _SyntaxHighlightRange(NamedTuple):\n    \"\"\"\n    A range to highlight in a Syntax object.\n    `start` and `end` are 2-integers tuples, where the first integer is the line number\n    (starting from 1) and the second integer is the column index (starting from 0).\n    \"\"\"\n\n    style: StyleType\n    start: SyntaxPosition\n    end: SyntaxPosition\n    style_before: bool = False\n\n\nclass PaddingProperty:\n    \"\"\"Descriptor to get and set padding.\"\"\"\n\n    def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]:\n        \"\"\"Space around the Syntax.\"\"\"\n        return obj._padding\n\n    def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None:\n        obj._padding = Padding.unpack(padding)\n\n\nclass Syntax(JupyterMixin):\n    \"\"\"Construct a Syntax object to render syntax highlighted code.\n\n    Args:\n        code (str): Code to highlight.\n        lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)\n        theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to \"monokai\".\n        dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.\n        line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.\n        start_line (int, optional): Starting number for line numbers. Defaults to 1.\n        line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.\n            A value of None in the tuple indicates the range is open in that direction.\n        highlight_lines (Set[int]): A set of line numbers to highlight.\n        code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.\n        tab_size (int, optional): Size of tabs. Defaults to 4.\n        word_wrap (bool, optional): Enable word wrapping.\n        background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.\n        indent_guides (bool, optional): Show indent guides. Defaults to False.\n        padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).\n    \"\"\"\n\n    _pygments_style_class: Type[PygmentsStyle]\n    _theme: SyntaxTheme\n\n    @classmethod\n    def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:\n        \"\"\"Get a syntax theme instance.\"\"\"\n        if isinstance(name, SyntaxTheme):\n            return name\n        theme: SyntaxTheme\n        if name in RICH_SYNTAX_THEMES:\n            theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])\n        else:\n            theme = PygmentsSyntaxTheme(name)\n        return theme\n\n    def __init__(\n        self,\n        code: str,\n        lexer: Union[Lexer, str],\n        *,\n        theme: Union[str, SyntaxTheme] = DEFAULT_THEME,\n        dedent: bool = False,\n        line_numbers: bool = False,\n        start_line: int = 1,\n        line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,\n        highlight_lines: Optional[Set[int]] = None,\n        code_width: Optional[int] = None,\n        tab_size: int = 4,\n        word_wrap: bool = False,\n        background_color: Optional[str] = None,\n        indent_guides: bool = False,\n        padding: PaddingDimensions = 0,\n    ) -> None:\n        self.code = code\n        self._lexer = lexer\n        self.dedent = dedent\n        self.line_numbers = line_numbers\n        self.start_line = start_line\n        self.line_range = line_range\n        self.highlight_lines = highlight_lines or set()\n        self.code_width = code_width\n        self.tab_size = tab_size\n        self.word_wrap = word_wrap\n        self.background_color = background_color\n        self.background_style = (\n            Style(bgcolor=background_color) if background_color else Style()\n        )\n        self.indent_guides = indent_guides\n        self._padding = Padding.unpack(padding)\n\n        self._theme = self.get_theme(theme)\n        self._stylized_ranges: List[_SyntaxHighlightRange] = []\n\n    padding = PaddingProperty()\n\n    @classmethod\n    def from_path(\n        cls,\n        path: str,\n        encoding: str = \"utf-8\",\n        lexer: Optional[Union[Lexer, str]] = None,\n        theme: Union[str, SyntaxTheme] = DEFAULT_THEME,\n        dedent: bool = False,\n        line_numbers: bool = False,\n        line_range: Optional[Tuple[int, int]] = None,\n        start_line: int = 1,\n        highlight_lines: Optional[Set[int]] = None,\n        code_width: Optional[int] = None,\n        tab_size: int = 4,\n        word_wrap: bool = False,\n        background_color: Optional[str] = None,\n        indent_guides: bool = False,\n        padding: PaddingDimensions = 0,\n    ) -> \"Syntax\":\n        \"\"\"Construct a Syntax object from a file.\n\n        Args:\n            path (str): Path to file to highlight.\n            encoding (str): Encoding of file.\n            lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.\n            theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to \"emacs\".\n            dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.\n            line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.\n            start_line (int, optional): Starting number for line numbers. Defaults to 1.\n            line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.\n            highlight_lines (Set[int]): A set of line numbers to highlight.\n            code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.\n            tab_size (int, optional): Size of tabs. Defaults to 4.\n            word_wrap (bool, optional): Enable word wrapping of code.\n            background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.\n            indent_guides (bool, optional): Show indent guides. Defaults to False.\n            padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).\n\n        Returns:\n            [Syntax]: A Syntax object that may be printed to the console\n        \"\"\"\n        code = Path(path).read_text(encoding=encoding)\n\n        if not lexer:\n            lexer = cls.guess_lexer(path, code=code)\n\n        return cls(\n            code,\n            lexer,\n            theme=theme,\n            dedent=dedent,\n            line_numbers=line_numbers,\n            line_range=line_range,\n            start_line=start_line,\n            highlight_lines=highlight_lines,\n            code_width=code_width,\n            tab_size=tab_size,\n            word_wrap=word_wrap,\n            background_color=background_color,\n            indent_guides=indent_guides,\n            padding=padding,\n        )\n\n    @classmethod\n    def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:\n        \"\"\"Guess the alias of the Pygments lexer to use based on a path and an optional string of code.\n        If code is supplied, it will use a combination of the code and the filename to determine the\n        best lexer to use. For example, if the file is ``index.html`` and the file contains Django\n        templating syntax, then \"html+django\" will be returned. If the file is ``index.html``, and no\n        templating language is used, the \"html\" lexer will be used. If no string of code\n        is supplied, the lexer will be chosen based on the file extension..\n\n        Args:\n            path (AnyStr): The path to the file containing the code you wish to know the lexer for.\n            code (str, optional): Optional string of code that will be used as a fallback if no lexer\n                is found for the supplied path.\n\n        Returns:\n            str: The name of the Pygments lexer that best matches the supplied path/code.\n        \"\"\"\n        lexer: Optional[Lexer] = None\n        lexer_name = \"default\"\n        if code:\n            try:\n                lexer = guess_lexer_for_filename(path, code)\n            except ClassNotFound:\n                pass\n\n        if not lexer:\n            try:\n                _, ext = os.path.splitext(path)\n                if ext:\n                    extension = ext.lstrip(\".\").lower()\n                    lexer = get_lexer_by_name(extension)\n            except ClassNotFound:\n                pass\n\n        if lexer:\n            if lexer.aliases:\n                lexer_name = lexer.aliases[0]\n            else:\n                lexer_name = lexer.name\n\n        return lexer_name\n\n    def _get_base_style(self) -> Style:\n        \"\"\"Get the base style.\"\"\"\n        default_style = self._theme.get_background_style() + self.background_style\n        return default_style\n\n    def _get_token_color(self, token_type: TokenType) -> Optional[Color]:\n        \"\"\"Get a color (if any) for the given token.\n\n        Args:\n            token_type (TokenType): A token type tuple from Pygments.\n\n        Returns:\n            Optional[Color]: Color from theme, or None for no color.\n        \"\"\"\n        style = self._theme.get_style_for_token(token_type)\n        return style.color\n\n    @property\n    def lexer(self) -> Optional[Lexer]:\n        \"\"\"The lexer for this syntax, or None if no lexer was found.\n\n        Tries to find the lexer by name if a string was passed to the constructor.\n        \"\"\"\n\n        if isinstance(self._lexer, Lexer):\n            return self._lexer\n        try:\n            return get_lexer_by_name(\n                self._lexer,\n                stripnl=False,\n                ensurenl=True,\n                tabsize=self.tab_size,\n            )\n        except ClassNotFound:\n            return None\n\n    @property\n    def default_lexer(self) -> Lexer:\n        \"\"\"A Pygments Lexer to use if one is not specified or invalid.\"\"\"\n        return get_lexer_by_name(\n            \"text\",\n            stripnl=False,\n            ensurenl=True,\n            tabsize=self.tab_size,\n        )\n\n    def highlight(\n        self,\n        code: str,\n        line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,\n    ) -> Text:\n        \"\"\"Highlight code and return a Text instance.\n\n        Args:\n            code (str): Code to highlight.\n            line_range(Tuple[int, int], optional): Optional line range to highlight.\n\n        Returns:\n            Text: A text instance containing highlighted syntax.\n        \"\"\"\n\n        base_style = self._get_base_style()\n        justify: JustifyMethod = (\n            \"default\" if base_style.transparent_background else \"left\"\n        )\n\n        text = Text(\n            justify=justify,\n            style=base_style,\n            tab_size=self.tab_size,\n            no_wrap=not self.word_wrap,\n        )\n        _get_theme_style = self._theme.get_style_for_token\n\n        lexer = self.lexer or self.default_lexer\n\n        if lexer is None:\n            text.append(code)\n        else:\n            if line_range:\n                # More complicated path to only stylize a portion of the code\n                # This speeds up further operations as there are less spans to process\n                line_start, line_end = line_range\n\n                def line_tokenize() -> Iterable[Tuple[Any, str]]:\n                    \"\"\"Split tokens to one per line.\"\"\"\n                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point\n\n                    for token_type, token in lexer.get_tokens(code):\n                        while token:\n                            line_token, new_line, token = token.partition(\"\\n\")\n                            yield token_type, line_token + new_line\n\n                def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:\n                    \"\"\"Convert tokens to spans.\"\"\"\n                    tokens = iter(line_tokenize())\n                    line_no = 0\n                    _line_start = line_start - 1 if line_start else 0\n\n                    # Skip over tokens until line start\n                    while line_no < _line_start:\n                        try:\n                            _token_type, token = next(tokens)\n                        except StopIteration:\n                            break\n                        yield (token, None)\n                        if token.endswith(\"\\n\"):\n                            line_no += 1\n                    # Generate spans until line end\n                    for token_type, token in tokens:\n                        yield (token, _get_theme_style(token_type))\n                        if token.endswith(\"\\n\"):\n                            line_no += 1\n                            if line_end and line_no >= line_end:\n                                break\n\n                text.append_tokens(tokens_to_spans())\n\n            else:\n                text.append_tokens(\n                    (token, _get_theme_style(token_type))\n                    for token_type, token in lexer.get_tokens(code)\n                )\n            if self.background_color is not None:\n                text.stylize(f\"on {self.background_color}\")\n\n        if self._stylized_ranges:\n            self._apply_stylized_ranges(text)\n\n        return text\n\n    def stylize_range(\n        self,\n        style: StyleType,\n        start: SyntaxPosition,\n        end: SyntaxPosition,\n        style_before: bool = False,\n    ) -> None:\n        \"\"\"\n        Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.\n        Line numbers are 1-based, while column indexes are 0-based.\n\n        Args:\n            style (StyleType): The style to apply.\n            start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.\n            end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.\n            style_before (bool): Apply the style before any existing styles.\n        \"\"\"\n        self._stylized_ranges.append(\n            _SyntaxHighlightRange(style, start, end, style_before)\n        )\n\n    def _get_line_numbers_color(self, blend: float = 0.3) -> Color:\n        background_style = self._theme.get_background_style() + self.background_style\n        background_color = background_style.bgcolor\n        if background_color is None or background_color.is_system_defined:\n            return Color.default()\n        foreground_color = self._get_token_color(Token.Text)\n        if foreground_color is None or foreground_color.is_system_defined:\n            return foreground_color or Color.default()\n        new_color = blend_rgb(\n            background_color.get_truecolor(),\n            foreground_color.get_truecolor(),\n            cross_fade=blend,\n        )\n        return Color.from_triplet(new_color)\n\n    @property\n    def _numbers_column_width(self) -> int:\n        \"\"\"Get the number of characters used to render the numbers column.\"\"\"\n        column_width = 0\n        if self.line_numbers:\n            column_width = (\n                len(str(self.start_line + self.code.count(\"\\n\")))\n                + NUMBERS_COLUMN_DEFAULT_PADDING\n            )\n        return column_width\n\n    def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:\n        \"\"\"Get background, number, and highlight styles for line numbers.\"\"\"\n        background_style = self._get_base_style()\n        if background_style.transparent_background:\n            return Style.null(), Style(dim=True), Style.null()\n        if console.color_system in (\"256\", \"truecolor\"):\n            number_style = Style.chain(\n                background_style,\n                self._theme.get_style_for_token(Token.Text),\n                Style(color=self._get_line_numbers_color()),\n                self.background_style,\n            )\n            highlight_number_style = Style.chain(\n                background_style,\n                self._theme.get_style_for_token(Token.Text),\n                Style(bold=True, color=self._get_line_numbers_color(0.9)),\n                self.background_style,\n            )\n        else:\n            number_style = background_style + Style(dim=True)\n            highlight_number_style = background_style + Style(dim=False)\n        return background_style, number_style, highlight_number_style\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        _, right, _, left = self.padding\n        padding = left + right\n        if self.code_width is not None:\n            width = self.code_width + self._numbers_column_width + padding + 1\n            return Measurement(self._numbers_column_width, width)\n        lines = self.code.splitlines()\n        width = (\n            self._numbers_column_width\n            + padding\n            + (max(cell_len(line) for line in lines) if lines else 0)\n        )\n        if self.line_numbers:\n            width += 1\n        return Measurement(self._numbers_column_width, width)\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        segments = Segments(self._get_syntax(console, options))\n        if any(self.padding):\n            yield Padding(segments, style=self._get_base_style(), pad=self.padding)\n        else:\n            yield segments\n\n    def _get_syntax(\n        self,\n        console: Console,\n        options: ConsoleOptions,\n    ) -> Iterable[Segment]:\n        \"\"\"\n        Get the Segments for the Syntax object, excluding any vertical/horizontal padding\n        \"\"\"\n        transparent_background = self._get_base_style().transparent_background\n        _pad_top, pad_right, _pad_bottom, pad_left = self.padding\n        horizontal_padding = pad_left + pad_right\n        code_width = (\n            (\n                (options.max_width - self._numbers_column_width - 1)\n                if self.line_numbers\n                else options.max_width\n            )\n            - horizontal_padding\n            if self.code_width is None\n            else self.code_width\n        )\n        code_width = max(0, code_width)\n\n        ends_on_nl, processed_code = self._process_code(self.code)\n        text = self.highlight(processed_code, self.line_range)\n\n        if not self.line_numbers and not self.word_wrap and not self.line_range:\n            if not ends_on_nl:\n                text.remove_suffix(\"\\n\")\n            # Simple case of just rendering text\n            style = (\n                self._get_base_style()\n                + self._theme.get_style_for_token(Comment)\n                + Style(dim=True)\n                + self.background_style\n            )\n            if self.indent_guides and not options.ascii_only:\n                text = text.with_indent_guides(self.tab_size, style=style)\n                text.overflow = \"crop\"\n            if style.transparent_background:\n                yield from console.render(\n                    text, options=options.update(width=code_width)\n                )\n            else:\n                syntax_lines = console.render_lines(\n                    text,\n                    options.update(width=code_width, height=None, justify=\"left\"),\n                    style=self.background_style,\n                    pad=True,\n                    new_lines=True,\n                )\n                for syntax_line in syntax_lines:\n                    yield from syntax_line\n            return\n\n        start_line, end_line = self.line_range or (None, None)\n        line_offset = 0\n        if start_line:\n            line_offset = max(0, start_line - 1)\n        lines: Union[List[Text], Lines] = text.split(\"\\n\", allow_blank=ends_on_nl)\n        if self.line_range:\n            if line_offset > len(lines):\n                return\n            lines = lines[line_offset:end_line]\n\n        if self.indent_guides and not options.ascii_only:\n            style = (\n                self._get_base_style()\n                + self._theme.get_style_for_token(Comment)\n                + Style(dim=True)\n                + self.background_style\n            )\n            lines = (\n                Text(\"\\n\")\n                .join(lines)\n                .with_indent_guides(self.tab_size, style=style + Style(italic=False))\n                .split(\"\\n\", allow_blank=True)\n            )\n\n        numbers_column_width = self._numbers_column_width\n        render_options = options.update(width=code_width)\n\n        highlight_line = self.highlight_lines.__contains__\n        _Segment = Segment\n        new_line = _Segment(\"\\n\")\n\n        line_pointer = \"> \" if options.legacy_windows else \"❱ \"\n\n        (\n            background_style,\n            number_style,\n            highlight_number_style,\n        ) = self._get_number_styles(console)\n\n        for line_no, line in enumerate(lines, self.start_line + line_offset):\n            if self.word_wrap:\n                wrapped_lines = console.render_lines(\n                    line,\n                    render_options.update(height=None, justify=\"left\"),\n                    style=background_style,\n                    pad=not transparent_background,\n                )\n            else:\n                segments = list(line.render(console, end=\"\"))\n                if options.no_wrap:\n                    wrapped_lines = [segments]\n                else:\n                    wrapped_lines = [\n                        _Segment.adjust_line_length(\n                            segments,\n                            render_options.max_width,\n                            style=background_style,\n                            pad=not transparent_background,\n                        )\n                    ]\n\n            if self.line_numbers:\n                wrapped_line_left_pad = _Segment(\n                    \" \" * numbers_column_width + \" \", background_style\n                )\n                for first, wrapped_line in loop_first(wrapped_lines):\n                    if first:\n                        line_column = str(line_no).rjust(numbers_column_width - 2) + \" \"\n                        if highlight_line(line_no):\n                            yield _Segment(line_pointer, Style(color=\"red\"))\n                            yield _Segment(line_column, highlight_number_style)\n                        else:\n                            yield _Segment(\"  \", highlight_number_style)\n                            yield _Segment(line_column, number_style)\n                    else:\n                        yield wrapped_line_left_pad\n                    yield from wrapped_line\n                    yield new_line\n            else:\n                for wrapped_line in wrapped_lines:\n                    yield from wrapped_line\n                    yield new_line\n\n    def _apply_stylized_ranges(self, text: Text) -> None:\n        \"\"\"\n        Apply stylized ranges to a text instance,\n        using the given code to determine the right portion to apply the style to.\n\n        Args:\n            text (Text): Text instance to apply the style to.\n        \"\"\"\n        code = text.plain\n        newlines_offsets = [\n            # Let's add outer boundaries at each side of the list:\n            0,\n            # N.B. using \"\\n\" here is much faster than using metacharacters such as \"^\" or \"\\Z\":\n            *[\n                match.start() + 1\n                for match in re.finditer(\"\\n\", code, flags=re.MULTILINE)\n            ],\n            len(code) + 1,\n        ]\n\n        for stylized_range in self._stylized_ranges:\n            start = _get_code_index_for_syntax_position(\n                newlines_offsets, stylized_range.start\n            )\n            end = _get_code_index_for_syntax_position(\n                newlines_offsets, stylized_range.end\n            )\n            if start is not None and end is not None:\n                if stylized_range.style_before:\n                    text.stylize_before(stylized_range.style, start, end)\n                else:\n                    text.stylize(stylized_range.style, start, end)\n\n    def _process_code(self, code: str) -> Tuple[bool, str]:\n        \"\"\"\n        Applies various processing to a raw code string\n        (normalises it so it always ends with a line return, dedents it if necessary, etc.)\n\n        Args:\n            code (str): The raw code string to process\n\n        Returns:\n            Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,\n                while the string is the processed code.\n        \"\"\"\n        ends_on_nl = code.endswith(\"\\n\")\n        processed_code = code if ends_on_nl else code + \"\\n\"\n        processed_code = (\n            textwrap.dedent(processed_code) if self.dedent else processed_code\n        )\n        processed_code = processed_code.expandtabs(self.tab_size)\n        return ends_on_nl, processed_code\n\n\ndef _get_code_index_for_syntax_position(\n    newlines_offsets: Sequence[int], position: SyntaxPosition\n) -> Optional[int]:\n    \"\"\"\n    Returns the index of the code string for the given positions.\n\n    Args:\n        newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.\n        position (SyntaxPosition): The position to search for.\n\n    Returns:\n        Optional[int]: The index of the code string for this position, or `None`\n            if the given position's line number is out of range (if it's the column that is out of range\n            we silently clamp its value so that it reaches the end of the line)\n    \"\"\"\n    lines_count = len(newlines_offsets)\n\n    line_number, column_index = position\n    if line_number > lines_count or len(newlines_offsets) < (line_number + 1):\n        return None  # `line_number` is out of range\n    line_index = line_number - 1\n    line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1\n    # If `column_index` is out of range: let's silently clamp it:\n    column_index = min(line_length, column_index)\n    return newlines_offsets[line_index] + column_index\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import argparse\n    import sys\n\n    parser = argparse.ArgumentParser(\n        description=\"Render syntax to the console with Rich\"\n    )\n    parser.add_argument(\n        \"path\",\n        metavar=\"PATH\",\n        help=\"path to file, or - for stdin\",\n    )\n    parser.add_argument(\n        \"-c\",\n        \"--force-color\",\n        dest=\"force_color\",\n        action=\"store_true\",\n        default=None,\n        help=\"force color for non-terminals\",\n    )\n    parser.add_argument(\n        \"-i\",\n        \"--indent-guides\",\n        dest=\"indent_guides\",\n        action=\"store_true\",\n        default=False,\n        help=\"display indent guides\",\n    )\n    parser.add_argument(\n        \"-l\",\n        \"--line-numbers\",\n        dest=\"line_numbers\",\n        action=\"store_true\",\n        help=\"render line numbers\",\n    )\n    parser.add_argument(\n        \"-w\",\n        \"--width\",\n        type=int,\n        dest=\"width\",\n        default=None,\n        help=\"width of output (default will auto-detect)\",\n    )\n    parser.add_argument(\n        \"-r\",\n        \"--wrap\",\n        dest=\"word_wrap\",\n        action=\"store_true\",\n        default=False,\n        help=\"word wrap long lines\",\n    )\n    parser.add_argument(\n        \"-s\",\n        \"--soft-wrap\",\n        action=\"store_true\",\n        dest=\"soft_wrap\",\n        default=False,\n        help=\"enable soft wrapping mode\",\n    )\n    parser.add_argument(\n        \"-t\", \"--theme\", dest=\"theme\", default=\"monokai\", help=\"pygments theme\"\n    )\n    parser.add_argument(\n        \"-b\",\n        \"--background-color\",\n        dest=\"background_color\",\n        default=None,\n        help=\"Override background color\",\n    )\n    parser.add_argument(\n        \"-x\",\n        \"--lexer\",\n        default=None,\n        dest=\"lexer_name\",\n        help=\"Lexer name\",\n    )\n    parser.add_argument(\n        \"-p\", \"--padding\", type=int, default=0, dest=\"padding\", help=\"Padding\"\n    )\n    parser.add_argument(\n        \"--highlight-line\",\n        type=int,\n        default=None,\n        dest=\"highlight_line\",\n        help=\"The line number (not index!) to highlight\",\n    )\n    args = parser.parse_args()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console(force_terminal=args.force_color, width=args.width)\n\n    if args.path == \"-\":\n        code = sys.stdin.read()\n        syntax = Syntax(\n            code=code,\n            lexer=args.lexer_name,\n            line_numbers=args.line_numbers,\n            word_wrap=args.word_wrap,\n            theme=args.theme,\n            background_color=args.background_color,\n            indent_guides=args.indent_guides,\n            padding=args.padding,\n            highlight_lines={args.highlight_line},\n        )\n    else:\n        syntax = Syntax.from_path(\n            args.path,\n            lexer=args.lexer_name,\n            line_numbers=args.line_numbers,\n            word_wrap=args.word_wrap,\n            theme=args.theme,\n            background_color=args.background_color,\n            indent_guides=args.indent_guides,\n            padding=args.padding,\n            highlight_lines={args.highlight_line},\n        )\n    console.print(syntax, soft_wrap=args.soft_wrap)\n"
  },
  {
    "path": "src/pip/_vendor/rich/table.py",
    "content": "from dataclasses import dataclass, field, replace\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom . import box, errors\nfrom ._loop import loop_first_last, loop_last\nfrom ._pick import pick_bool\nfrom ._ratio import ratio_distribute, ratio_reduce\nfrom .align import VerticalAlignMethod\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .padding import Padding, PaddingDimensions\nfrom .protocol import is_renderable\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        JustifyMethod,\n        OverflowMethod,\n        RenderableType,\n        RenderResult,\n    )\n\n\n@dataclass\nclass Column:\n    \"\"\"Defines a column within a ~Table.\n\n    Args:\n        title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.\n        caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.\n        width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.\n        min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.\n        box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.\n        safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).\n        collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.\n        pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.\n        expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n        show_header (bool, optional): Show a header row. Defaults to True.\n        show_footer (bool, optional): Show a footer row. Defaults to False.\n        show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.\n        show_lines (bool, optional): Draw lines between every row. Defaults to False.\n        leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.\n        style (Union[str, Style], optional): Default style for the table. Defaults to \"none\".\n        row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.\n        header_style (Union[str, Style], optional): Style of the header. Defaults to \"table.header\".\n        footer_style (Union[str, Style], optional): Style of the footer. Defaults to \"table.footer\".\n        border_style (Union[str, Style], optional): Style of the border. Defaults to None.\n        title_style (Union[str, Style], optional): Style of the title. Defaults to None.\n        caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.\n        title_justify (str, optional): Justify method for title. Defaults to \"center\".\n        caption_justify (str, optional): Justify method for caption. Defaults to \"center\".\n        highlight (bool, optional): Highlight cell contents (if str). Defaults to False.\n    \"\"\"\n\n    header: \"RenderableType\" = \"\"\n    \"\"\"RenderableType: Renderable for the header (typically a string)\"\"\"\n\n    footer: \"RenderableType\" = \"\"\n    \"\"\"RenderableType: Renderable for the footer (typically a string)\"\"\"\n\n    header_style: StyleType = \"\"\n    \"\"\"StyleType: The style of the header.\"\"\"\n\n    footer_style: StyleType = \"\"\n    \"\"\"StyleType: The style of the footer.\"\"\"\n\n    style: StyleType = \"\"\n    \"\"\"StyleType: The style of the column.\"\"\"\n\n    justify: \"JustifyMethod\" = \"left\"\n    \"\"\"str: How to justify text within the column (\"left\", \"center\", \"right\", or \"full\")\"\"\"\n\n    vertical: \"VerticalAlignMethod\" = \"top\"\n    \"\"\"str: How to vertically align content (\"top\", \"middle\", or \"bottom\")\"\"\"\n\n    overflow: \"OverflowMethod\" = \"ellipsis\"\n    \"\"\"str: Overflow method.\"\"\"\n\n    width: Optional[int] = None\n    \"\"\"Optional[int]: Width of the column, or ``None`` (default) to auto calculate width.\"\"\"\n\n    min_width: Optional[int] = None\n    \"\"\"Optional[int]: Minimum width of column, or ``None`` for no minimum. Defaults to None.\"\"\"\n\n    max_width: Optional[int] = None\n    \"\"\"Optional[int]: Maximum width of column, or ``None`` for no maximum. Defaults to None.\"\"\"\n\n    ratio: Optional[int] = None\n    \"\"\"Optional[int]: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents.\"\"\"\n\n    no_wrap: bool = False\n    \"\"\"bool: Prevent wrapping of text within the column. Defaults to ``False``.\"\"\"\n\n    highlight: bool = False\n    \"\"\"bool: Apply highlighter to column. Defaults to ``False``.\"\"\"\n\n    _index: int = 0\n    \"\"\"Index of column.\"\"\"\n\n    _cells: List[\"RenderableType\"] = field(default_factory=list)\n\n    def copy(self) -> \"Column\":\n        \"\"\"Return a copy of this Column.\"\"\"\n        return replace(self, _cells=[])\n\n    @property\n    def cells(self) -> Iterable[\"RenderableType\"]:\n        \"\"\"Get all cells in the column, not including header.\"\"\"\n        yield from self._cells\n\n    @property\n    def flexible(self) -> bool:\n        \"\"\"Check if this column is flexible.\"\"\"\n        return self.ratio is not None\n\n\n@dataclass\nclass Row:\n    \"\"\"Information regarding a row.\"\"\"\n\n    style: Optional[StyleType] = None\n    \"\"\"Style to apply to row.\"\"\"\n\n    end_section: bool = False\n    \"\"\"Indicated end of section, which will force a line beneath the row.\"\"\"\n\n\nclass _Cell(NamedTuple):\n    \"\"\"A single cell in a table.\"\"\"\n\n    style: StyleType\n    \"\"\"Style to apply to cell.\"\"\"\n    renderable: \"RenderableType\"\n    \"\"\"Cell renderable.\"\"\"\n    vertical: VerticalAlignMethod\n    \"\"\"Cell vertical alignment.\"\"\"\n\n\nclass Table(JupyterMixin):\n    \"\"\"A console renderable to draw a table.\n\n    Args:\n        *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.\n        title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.\n        caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.\n        width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.\n        min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.\n        box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.\n        safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).\n        collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.\n        pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.\n        expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n        show_header (bool, optional): Show a header row. Defaults to True.\n        show_footer (bool, optional): Show a footer row. Defaults to False.\n        show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.\n        show_lines (bool, optional): Draw lines between every row. Defaults to False.\n        leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.\n        style (Union[str, Style], optional): Default style for the table. Defaults to \"none\".\n        row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.\n        header_style (Union[str, Style], optional): Style of the header. Defaults to \"table.header\".\n        footer_style (Union[str, Style], optional): Style of the footer. Defaults to \"table.footer\".\n        border_style (Union[str, Style], optional): Style of the border. Defaults to None.\n        title_style (Union[str, Style], optional): Style of the title. Defaults to None.\n        caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.\n        title_justify (str, optional): Justify method for title. Defaults to \"center\".\n        caption_justify (str, optional): Justify method for caption. Defaults to \"center\".\n        highlight (bool, optional): Highlight cell contents (if str). Defaults to False.\n    \"\"\"\n\n    columns: List[Column]\n    rows: List[Row]\n\n    def __init__(\n        self,\n        *headers: Union[Column, str],\n        title: Optional[TextType] = None,\n        caption: Optional[TextType] = None,\n        width: Optional[int] = None,\n        min_width: Optional[int] = None,\n        box: Optional[box.Box] = box.HEAVY_HEAD,\n        safe_box: Optional[bool] = None,\n        padding: PaddingDimensions = (0, 1),\n        collapse_padding: bool = False,\n        pad_edge: bool = True,\n        expand: bool = False,\n        show_header: bool = True,\n        show_footer: bool = False,\n        show_edge: bool = True,\n        show_lines: bool = False,\n        leading: int = 0,\n        style: StyleType = \"none\",\n        row_styles: Optional[Iterable[StyleType]] = None,\n        header_style: Optional[StyleType] = \"table.header\",\n        footer_style: Optional[StyleType] = \"table.footer\",\n        border_style: Optional[StyleType] = None,\n        title_style: Optional[StyleType] = None,\n        caption_style: Optional[StyleType] = None,\n        title_justify: \"JustifyMethod\" = \"center\",\n        caption_justify: \"JustifyMethod\" = \"center\",\n        highlight: bool = False,\n    ) -> None:\n        self.columns: List[Column] = []\n        self.rows: List[Row] = []\n        self.title = title\n        self.caption = caption\n        self.width = width\n        self.min_width = min_width\n        self.box = box\n        self.safe_box = safe_box\n        self._padding = Padding.unpack(padding)\n        self.pad_edge = pad_edge\n        self._expand = expand\n        self.show_header = show_header\n        self.show_footer = show_footer\n        self.show_edge = show_edge\n        self.show_lines = show_lines\n        self.leading = leading\n        self.collapse_padding = collapse_padding\n        self.style = style\n        self.header_style = header_style or \"\"\n        self.footer_style = footer_style or \"\"\n        self.border_style = border_style\n        self.title_style = title_style\n        self.caption_style = caption_style\n        self.title_justify: \"JustifyMethod\" = title_justify\n        self.caption_justify: \"JustifyMethod\" = caption_justify\n        self.highlight = highlight\n        self.row_styles: Sequence[StyleType] = list(row_styles or [])\n        append_column = self.columns.append\n        for header in headers:\n            if isinstance(header, str):\n                self.add_column(header=header)\n            else:\n                header._index = len(self.columns)\n                append_column(header)\n\n    @classmethod\n    def grid(\n        cls,\n        *headers: Union[Column, str],\n        padding: PaddingDimensions = 0,\n        collapse_padding: bool = True,\n        pad_edge: bool = False,\n        expand: bool = False,\n    ) -> \"Table\":\n        \"\"\"Get a table with no lines, headers, or footer.\n\n        Args:\n            *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.\n            padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0.\n            collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True.\n            pad_edge (bool, optional): Enable padding around edges of table. Defaults to False.\n            expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n\n        Returns:\n            Table: A table instance.\n        \"\"\"\n        return cls(\n            *headers,\n            box=None,\n            padding=padding,\n            collapse_padding=collapse_padding,\n            show_header=False,\n            show_footer=False,\n            show_edge=False,\n            pad_edge=pad_edge,\n            expand=expand,\n        )\n\n    @property\n    def expand(self) -> bool:\n        \"\"\"Setting a non-None self.width implies expand.\"\"\"\n        return self._expand or self.width is not None\n\n    @expand.setter\n    def expand(self, expand: bool) -> None:\n        \"\"\"Set expand.\"\"\"\n        self._expand = expand\n\n    @property\n    def _extra_width(self) -> int:\n        \"\"\"Get extra width to add to cell content.\"\"\"\n        width = 0\n        if self.box and self.show_edge:\n            width += 2\n        if self.box:\n            width += len(self.columns) - 1\n        return width\n\n    @property\n    def row_count(self) -> int:\n        \"\"\"Get the current number of rows.\"\"\"\n        return len(self.rows)\n\n    def get_row_style(self, console: \"Console\", index: int) -> StyleType:\n        \"\"\"Get the current row style.\"\"\"\n        style = Style.null()\n        if self.row_styles:\n            style += console.get_style(self.row_styles[index % len(self.row_styles)])\n        row_style = self.rows[index].style\n        if row_style is not None:\n            style += console.get_style(row_style)\n        return style\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        max_width = options.max_width\n        if self.width is not None:\n            max_width = self.width\n        if max_width < 0:\n            return Measurement(0, 0)\n\n        extra_width = self._extra_width\n        max_width = sum(\n            self._calculate_column_widths(\n                console, options.update_width(max_width - extra_width)\n            )\n        )\n        _measure_column = self._measure_column\n\n        measurements = [\n            _measure_column(console, options.update_width(max_width), column)\n            for column in self.columns\n        ]\n        minimum_width = (\n            sum(measurement.minimum for measurement in measurements) + extra_width\n        )\n        maximum_width = (\n            sum(measurement.maximum for measurement in measurements) + extra_width\n            if (self.width is None)\n            else self.width\n        )\n        measurement = Measurement(minimum_width, maximum_width)\n        measurement = measurement.clamp(self.min_width)\n        return measurement\n\n    @property\n    def padding(self) -> Tuple[int, int, int, int]:\n        \"\"\"Get cell padding.\"\"\"\n        return self._padding\n\n    @padding.setter\n    def padding(self, padding: PaddingDimensions) -> \"Table\":\n        \"\"\"Set cell padding.\"\"\"\n        self._padding = Padding.unpack(padding)\n        return self\n\n    def add_column(\n        self,\n        header: \"RenderableType\" = \"\",\n        footer: \"RenderableType\" = \"\",\n        *,\n        header_style: Optional[StyleType] = None,\n        highlight: Optional[bool] = None,\n        footer_style: Optional[StyleType] = None,\n        style: Optional[StyleType] = None,\n        justify: \"JustifyMethod\" = \"left\",\n        vertical: \"VerticalAlignMethod\" = \"top\",\n        overflow: \"OverflowMethod\" = \"ellipsis\",\n        width: Optional[int] = None,\n        min_width: Optional[int] = None,\n        max_width: Optional[int] = None,\n        ratio: Optional[int] = None,\n        no_wrap: bool = False,\n    ) -> None:\n        \"\"\"Add a column to the table.\n\n        Args:\n            header (RenderableType, optional): Text or renderable for the header.\n                Defaults to \"\".\n            footer (RenderableType, optional): Text or renderable for the footer.\n                Defaults to \"\".\n            header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None.\n            highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object.\n            footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None.\n            style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None.\n            justify (JustifyMethod, optional): Alignment for cells. Defaults to \"left\".\n            vertical (VerticalAlignMethod, optional): Vertical alignment, one of \"top\", \"middle\", or \"bottom\". Defaults to \"top\".\n            overflow (OverflowMethod): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to \"ellipsis\".\n            width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None.\n            min_width (Optional[int], optional): Minimum width of column, or ``None`` for no minimum. Defaults to None.\n            max_width (Optional[int], optional): Maximum width of column, or ``None`` for no maximum. Defaults to None.\n            ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None.\n            no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column.\n        \"\"\"\n\n        column = Column(\n            _index=len(self.columns),\n            header=header,\n            footer=footer,\n            header_style=header_style or \"\",\n            highlight=highlight if highlight is not None else self.highlight,\n            footer_style=footer_style or \"\",\n            style=style or \"\",\n            justify=justify,\n            vertical=vertical,\n            overflow=overflow,\n            width=width,\n            min_width=min_width,\n            max_width=max_width,\n            ratio=ratio,\n            no_wrap=no_wrap,\n        )\n        self.columns.append(column)\n\n    def add_row(\n        self,\n        *renderables: Optional[\"RenderableType\"],\n        style: Optional[StyleType] = None,\n        end_section: bool = False,\n    ) -> None:\n        \"\"\"Add a row of renderables.\n\n        Args:\n            *renderables (None or renderable): Each cell in a row must be a renderable object (including str),\n                or ``None`` for a blank cell.\n            style (StyleType, optional): An optional style to apply to the entire row. Defaults to None.\n            end_section (bool, optional): End a section and draw a line. Defaults to False.\n\n        Raises:\n            errors.NotRenderableError: If you add something that can't be rendered.\n        \"\"\"\n\n        def add_cell(column: Column, renderable: \"RenderableType\") -> None:\n            column._cells.append(renderable)\n\n        cell_renderables: List[Optional[\"RenderableType\"]] = list(renderables)\n\n        columns = self.columns\n        if len(cell_renderables) < len(columns):\n            cell_renderables = [\n                *cell_renderables,\n                *[None] * (len(columns) - len(cell_renderables)),\n            ]\n        for index, renderable in enumerate(cell_renderables):\n            if index == len(columns):\n                column = Column(_index=index, highlight=self.highlight)\n                for _ in self.rows:\n                    add_cell(column, Text(\"\"))\n                self.columns.append(column)\n            else:\n                column = columns[index]\n            if renderable is None:\n                add_cell(column, \"\")\n            elif is_renderable(renderable):\n                add_cell(column, renderable)\n            else:\n                raise errors.NotRenderableError(\n                    f\"unable to render {type(renderable).__name__}; a string or other renderable object is required\"\n                )\n        self.rows.append(Row(style=style, end_section=end_section))\n\n    def add_section(self) -> None:\n        \"\"\"Add a new section (draw a line after current row).\"\"\"\n\n        if self.rows:\n            self.rows[-1].end_section = True\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if not self.columns:\n            yield Segment(\"\\n\")\n            return\n\n        max_width = options.max_width\n        if self.width is not None:\n            max_width = self.width\n\n        extra_width = self._extra_width\n        widths = self._calculate_column_widths(\n            console, options.update_width(max_width - extra_width)\n        )\n        table_width = sum(widths) + extra_width\n\n        render_options = options.update(\n            width=table_width, highlight=self.highlight, height=None\n        )\n\n        def render_annotation(\n            text: TextType, style: StyleType, justify: \"JustifyMethod\" = \"center\"\n        ) -> \"RenderResult\":\n            render_text = (\n                console.render_str(text, style=style, highlight=False)\n                if isinstance(text, str)\n                else text\n            )\n            return console.render(\n                render_text, options=render_options.update(justify=justify)\n            )\n\n        if self.title:\n            yield from render_annotation(\n                self.title,\n                style=Style.pick_first(self.title_style, \"table.title\"),\n                justify=self.title_justify,\n            )\n        yield from self._render(console, render_options, widths)\n        if self.caption:\n            yield from render_annotation(\n                self.caption,\n                style=Style.pick_first(self.caption_style, \"table.caption\"),\n                justify=self.caption_justify,\n            )\n\n    def _calculate_column_widths(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> List[int]:\n        \"\"\"Calculate the widths of each column, including padding, not including borders.\"\"\"\n        max_width = options.max_width\n        columns = self.columns\n        width_ranges = [\n            self._measure_column(console, options, column) for column in columns\n        ]\n        widths = [_range.maximum or 1 for _range in width_ranges]\n        get_padding_width = self._get_padding_width\n        extra_width = self._extra_width\n        if self.expand:\n            ratios = [col.ratio or 0 for col in columns if col.flexible]\n            if any(ratios):\n                fixed_widths = [\n                    0 if column.flexible else _range.maximum\n                    for _range, column in zip(width_ranges, columns)\n                ]\n                flex_minimum = [\n                    (column.width or 1) + get_padding_width(column._index)\n                    for column in columns\n                    if column.flexible\n                ]\n                flexible_width = max_width - sum(fixed_widths)\n                flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum)\n                iter_flex_widths = iter(flex_widths)\n                for index, column in enumerate(columns):\n                    if column.flexible:\n                        widths[index] = fixed_widths[index] + next(iter_flex_widths)\n        table_width = sum(widths)\n\n        if table_width > max_width:\n            widths = self._collapse_widths(\n                widths,\n                [(column.width is None and not column.no_wrap) for column in columns],\n                max_width,\n            )\n            table_width = sum(widths)\n            # last resort, reduce columns evenly\n            if table_width > max_width:\n                excess_width = table_width - max_width\n                widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths)\n                table_width = sum(widths)\n\n            width_ranges = [\n                self._measure_column(console, options.update_width(width), column)\n                for width, column in zip(widths, columns)\n            ]\n            widths = [_range.maximum or 0 for _range in width_ranges]\n\n        if (table_width < max_width and self.expand) or (\n            self.min_width is not None and table_width < (self.min_width - extra_width)\n        ):\n            _max_width = (\n                max_width\n                if self.min_width is None\n                else min(self.min_width - extra_width, max_width)\n            )\n            pad_widths = ratio_distribute(_max_width - table_width, widths)\n            widths = [_width + pad for _width, pad in zip(widths, pad_widths)]\n\n        return widths\n\n    @classmethod\n    def _collapse_widths(\n        cls, widths: List[int], wrapable: List[bool], max_width: int\n    ) -> List[int]:\n        \"\"\"Reduce widths so that the total is under max_width.\n\n        Args:\n            widths (List[int]): List of widths.\n            wrapable (List[bool]): List of booleans that indicate if a column may shrink.\n            max_width (int): Maximum width to reduce to.\n\n        Returns:\n            List[int]: A new list of widths.\n        \"\"\"\n        total_width = sum(widths)\n        excess_width = total_width - max_width\n        if any(wrapable):\n            while total_width and excess_width > 0:\n                max_column = max(\n                    width for width, allow_wrap in zip(widths, wrapable) if allow_wrap\n                )\n                second_max_column = max(\n                    width if allow_wrap and width != max_column else 0\n                    for width, allow_wrap in zip(widths, wrapable)\n                )\n                column_difference = max_column - second_max_column\n                ratios = [\n                    (1 if (width == max_column and allow_wrap) else 0)\n                    for width, allow_wrap in zip(widths, wrapable)\n                ]\n                if not any(ratios) or not column_difference:\n                    break\n                max_reduce = [min(excess_width, column_difference)] * len(widths)\n                widths = ratio_reduce(excess_width, ratios, max_reduce, widths)\n\n                total_width = sum(widths)\n                excess_width = total_width - max_width\n        return widths\n\n    def _get_cells(\n        self, console: \"Console\", column_index: int, column: Column\n    ) -> Iterable[_Cell]:\n        \"\"\"Get all the cells with padding and optional header.\"\"\"\n\n        collapse_padding = self.collapse_padding\n        pad_edge = self.pad_edge\n        padding = self.padding\n        any_padding = any(padding)\n\n        first_column = column_index == 0\n        last_column = column_index == len(self.columns) - 1\n\n        _padding_cache: Dict[Tuple[bool, bool], Tuple[int, int, int, int]] = {}\n\n        def get_padding(first_row: bool, last_row: bool) -> Tuple[int, int, int, int]:\n            cached = _padding_cache.get((first_row, last_row))\n            if cached:\n                return cached\n            top, right, bottom, left = padding\n\n            if collapse_padding:\n                if not first_column:\n                    left = max(0, left - right)\n                if not last_row:\n                    bottom = max(0, top - bottom)\n\n            if not pad_edge:\n                if first_column:\n                    left = 0\n                if last_column:\n                    right = 0\n                if first_row:\n                    top = 0\n                if last_row:\n                    bottom = 0\n            _padding = (top, right, bottom, left)\n            _padding_cache[(first_row, last_row)] = _padding\n            return _padding\n\n        raw_cells: List[Tuple[StyleType, \"RenderableType\"]] = []\n        _append = raw_cells.append\n        get_style = console.get_style\n        if self.show_header:\n            header_style = get_style(self.header_style or \"\") + get_style(\n                column.header_style\n            )\n            _append((header_style, column.header))\n        cell_style = get_style(column.style or \"\")\n        for cell in column.cells:\n            _append((cell_style, cell))\n        if self.show_footer:\n            footer_style = get_style(self.footer_style or \"\") + get_style(\n                column.footer_style\n            )\n            _append((footer_style, column.footer))\n\n        if any_padding:\n            _Padding = Padding\n            for first, last, (style, renderable) in loop_first_last(raw_cells):\n                yield _Cell(\n                    style,\n                    _Padding(renderable, get_padding(first, last)),\n                    getattr(renderable, \"vertical\", None) or column.vertical,\n                )\n        else:\n            for style, renderable in raw_cells:\n                yield _Cell(\n                    style,\n                    renderable,\n                    getattr(renderable, \"vertical\", None) or column.vertical,\n                )\n\n    def _get_padding_width(self, column_index: int) -> int:\n        \"\"\"Get extra width from padding.\"\"\"\n        _, pad_right, _, pad_left = self.padding\n        if self.collapse_padding:\n            if column_index > 0:\n                pad_left = max(0, pad_left - pad_right)\n        return pad_left + pad_right\n\n    def _measure_column(\n        self,\n        console: \"Console\",\n        options: \"ConsoleOptions\",\n        column: Column,\n    ) -> Measurement:\n        \"\"\"Get the minimum and maximum width of the column.\"\"\"\n\n        max_width = options.max_width\n        if max_width < 1:\n            return Measurement(0, 0)\n\n        padding_width = self._get_padding_width(column._index)\n\n        if column.width is not None:\n            # Fixed width column\n            return Measurement(\n                column.width + padding_width, column.width + padding_width\n            ).with_maximum(max_width)\n        # Flexible column, we need to measure contents\n        min_widths: List[int] = []\n        max_widths: List[int] = []\n        append_min = min_widths.append\n        append_max = max_widths.append\n        get_render_width = Measurement.get\n        for cell in self._get_cells(console, column._index, column):\n            _min, _max = get_render_width(console, options, cell.renderable)\n            append_min(_min)\n            append_max(_max)\n\n        measurement = Measurement(\n            max(min_widths) if min_widths else 1,\n            max(max_widths) if max_widths else max_width,\n        ).with_maximum(max_width)\n        measurement = measurement.clamp(\n            None if column.min_width is None else column.min_width + padding_width,\n            None if column.max_width is None else column.max_width + padding_width,\n        )\n        return measurement\n\n    def _render(\n        self, console: \"Console\", options: \"ConsoleOptions\", widths: List[int]\n    ) -> \"RenderResult\":\n        table_style = console.get_style(self.style or \"\")\n\n        border_style = table_style + console.get_style(self.border_style or \"\")\n        _column_cells = (\n            self._get_cells(console, column_index, column)\n            for column_index, column in enumerate(self.columns)\n        )\n        row_cells: List[Tuple[_Cell, ...]] = list(zip(*_column_cells))\n        _box = (\n            self.box.substitute(\n                options, safe=pick_bool(self.safe_box, console.safe_box)\n            )\n            if self.box\n            else None\n        )\n        _box = _box.get_plain_headed_box() if _box and not self.show_header else _box\n\n        new_line = Segment.line()\n\n        columns = self.columns\n        show_header = self.show_header\n        show_footer = self.show_footer\n        show_edge = self.show_edge\n        show_lines = self.show_lines\n        leading = self.leading\n\n        _Segment = Segment\n        if _box:\n            box_segments = [\n                (\n                    _Segment(_box.head_left, border_style),\n                    _Segment(_box.head_right, border_style),\n                    _Segment(_box.head_vertical, border_style),\n                ),\n                (\n                    _Segment(_box.mid_left, border_style),\n                    _Segment(_box.mid_right, border_style),\n                    _Segment(_box.mid_vertical, border_style),\n                ),\n                (\n                    _Segment(_box.foot_left, border_style),\n                    _Segment(_box.foot_right, border_style),\n                    _Segment(_box.foot_vertical, border_style),\n                ),\n            ]\n            if show_edge:\n                yield _Segment(_box.get_top(widths), border_style)\n                yield new_line\n        else:\n            box_segments = []\n\n        get_row_style = self.get_row_style\n        get_style = console.get_style\n\n        for index, (first, last, row_cell) in enumerate(loop_first_last(row_cells)):\n            header_row = first and show_header\n            footer_row = last and show_footer\n            row = (\n                self.rows[index - show_header]\n                if (not header_row and not footer_row)\n                else None\n            )\n            max_height = 1\n            cells: List[List[List[Segment]]] = []\n            if header_row or footer_row:\n                row_style = Style.null()\n            else:\n                row_style = get_style(\n                    get_row_style(console, index - 1 if show_header else index)\n                )\n            for width, cell, column in zip(widths, row_cell, columns):\n                render_options = options.update(\n                    width=width,\n                    justify=column.justify,\n                    no_wrap=column.no_wrap,\n                    overflow=column.overflow,\n                    height=None,\n                    highlight=column.highlight,\n                )\n                lines = console.render_lines(\n                    cell.renderable,\n                    render_options,\n                    style=get_style(cell.style) + row_style,\n                )\n                max_height = max(max_height, len(lines))\n                cells.append(lines)\n\n            row_height = max(len(cell) for cell in cells)\n\n            def align_cell(\n                cell: List[List[Segment]],\n                vertical: \"VerticalAlignMethod\",\n                width: int,\n                style: Style,\n            ) -> List[List[Segment]]:\n                if header_row:\n                    vertical = \"bottom\"\n                elif footer_row:\n                    vertical = \"top\"\n\n                if vertical == \"top\":\n                    return _Segment.align_top(cell, width, row_height, style)\n                elif vertical == \"middle\":\n                    return _Segment.align_middle(cell, width, row_height, style)\n                return _Segment.align_bottom(cell, width, row_height, style)\n\n            cells[:] = [\n                _Segment.set_shape(\n                    align_cell(\n                        cell,\n                        _cell.vertical,\n                        width,\n                        get_style(_cell.style) + row_style,\n                    ),\n                    width,\n                    max_height,\n                )\n                for width, _cell, cell, column in zip(widths, row_cell, cells, columns)\n            ]\n\n            if _box:\n                if last and show_footer:\n                    yield _Segment(\n                        _box.get_row(widths, \"foot\", edge=show_edge), border_style\n                    )\n                    yield new_line\n                left, right, _divider = box_segments[0 if first else (2 if last else 1)]\n\n                # If the column divider is whitespace also style it with the row background\n                divider = (\n                    _divider\n                    if _divider.text.strip()\n                    else _Segment(\n                        _divider.text, row_style.background_style + _divider.style\n                    )\n                )\n                for line_no in range(max_height):\n                    if show_edge:\n                        yield left\n                    for last_cell, rendered_cell in loop_last(cells):\n                        yield from rendered_cell[line_no]\n                        if not last_cell:\n                            yield divider\n                    if show_edge:\n                        yield right\n                    yield new_line\n            else:\n                for line_no in range(max_height):\n                    for rendered_cell in cells:\n                        yield from rendered_cell[line_no]\n                    yield new_line\n            if _box and first and show_header:\n                yield _Segment(\n                    _box.get_row(widths, \"head\", edge=show_edge), border_style\n                )\n                yield new_line\n            end_section = row and row.end_section\n            if _box and (show_lines or leading or end_section):\n                if (\n                    not last\n                    and not (show_footer and index >= len(row_cells) - 2)\n                    and not (show_header and header_row)\n                ):\n                    if leading:\n                        yield _Segment(\n                            _box.get_row(widths, \"mid\", edge=show_edge) * leading,\n                            border_style,\n                        )\n                    else:\n                        yield _Segment(\n                            _box.get_row(widths, \"row\", edge=show_edge), border_style\n                        )\n                    yield new_line\n\n        if _box and show_edge:\n            yield _Segment(_box.get_bottom(widths), border_style)\n            yield new_line\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.highlighter import ReprHighlighter\n\n    from ._timer import timer\n\n    with timer(\"Table render\"):\n        table = Table(\n            title=\"Star Wars Movies\",\n            caption=\"Rich example table\",\n            caption_justify=\"right\",\n        )\n\n        table.add_column(\n            \"Released\", header_style=\"bright_cyan\", style=\"cyan\", no_wrap=True\n        )\n        table.add_column(\"Title\", style=\"magenta\")\n        table.add_column(\"Box Office\", justify=\"right\", style=\"green\")\n\n        table.add_row(\n            \"Dec 20, 2019\",\n            \"Star Wars: The Rise of Skywalker\",\n            \"$952,110,690\",\n        )\n        table.add_row(\"May 25, 2018\", \"Solo: A Star Wars Story\", \"$393,151,347\")\n        table.add_row(\n            \"Dec 15, 2017\",\n            \"Star Wars Ep. V111: The Last Jedi\",\n            \"$1,332,539,889\",\n            style=\"on black\",\n            end_section=True,\n        )\n        table.add_row(\n            \"Dec 16, 2016\",\n            \"Rogue One: A Star Wars Story\",\n            \"$1,332,439,889\",\n        )\n\n        def header(text: str) -> None:\n            console.print()\n            console.rule(highlight(text))\n            console.print()\n\n        console = Console()\n        highlight = ReprHighlighter()\n        header(\"Example Table\")\n        console.print(table, justify=\"center\")\n\n        table.expand = True\n        header(\"expand=True\")\n        console.print(table)\n\n        table.width = 50\n        header(\"width=50\")\n\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        header(\"row_styles=['dim', 'none']\")\n\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        table.leading = 1\n        header(\"leading=1, row_styles=['dim', 'none']\")\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        table.show_lines = True\n        table.leading = 0\n        header(\"show_lines=True, row_styles=['dim', 'none']\")\n        console.print(table, justify=\"center\")\n"
  },
  {
    "path": "src/pip/_vendor/rich/terminal_theme.py",
    "content": "from typing import List, Optional, Tuple\n\nfrom .color_triplet import ColorTriplet\nfrom .palette import Palette\n\n_ColorTuple = Tuple[int, int, int]\n\n\nclass TerminalTheme:\n    \"\"\"A color theme used when exporting console content.\n\n    Args:\n        background (Tuple[int, int, int]): The background color.\n        foreground (Tuple[int, int, int]): The foreground (text) color.\n        normal (List[Tuple[int, int, int]]): A list of 8 normal intensity colors.\n        bright (List[Tuple[int, int, int]], optional): A list of 8 bright colors, or None\n            to repeat normal intensity. Defaults to None.\n    \"\"\"\n\n    def __init__(\n        self,\n        background: _ColorTuple,\n        foreground: _ColorTuple,\n        normal: List[_ColorTuple],\n        bright: Optional[List[_ColorTuple]] = None,\n    ) -> None:\n        self.background_color = ColorTriplet(*background)\n        self.foreground_color = ColorTriplet(*foreground)\n        self.ansi_colors = Palette(normal + (bright or normal))\n\n\nDEFAULT_TERMINAL_THEME = TerminalTheme(\n    (255, 255, 255),\n    (0, 0, 0),\n    [\n        (0, 0, 0),\n        (128, 0, 0),\n        (0, 128, 0),\n        (128, 128, 0),\n        (0, 0, 128),\n        (128, 0, 128),\n        (0, 128, 128),\n        (192, 192, 192),\n    ],\n    [\n        (128, 128, 128),\n        (255, 0, 0),\n        (0, 255, 0),\n        (255, 255, 0),\n        (0, 0, 255),\n        (255, 0, 255),\n        (0, 255, 255),\n        (255, 255, 255),\n    ],\n)\n\nMONOKAI = TerminalTheme(\n    (12, 12, 12),\n    (217, 217, 217),\n    [\n        (26, 26, 26),\n        (244, 0, 95),\n        (152, 224, 36),\n        (253, 151, 31),\n        (157, 101, 255),\n        (244, 0, 95),\n        (88, 209, 235),\n        (196, 197, 181),\n        (98, 94, 76),\n    ],\n    [\n        (244, 0, 95),\n        (152, 224, 36),\n        (224, 213, 97),\n        (157, 101, 255),\n        (244, 0, 95),\n        (88, 209, 235),\n        (246, 246, 239),\n    ],\n)\nDIMMED_MONOKAI = TerminalTheme(\n    (25, 25, 25),\n    (185, 188, 186),\n    [\n        (58, 61, 67),\n        (190, 63, 72),\n        (135, 154, 59),\n        (197, 166, 53),\n        (79, 118, 161),\n        (133, 92, 141),\n        (87, 143, 164),\n        (185, 188, 186),\n        (136, 137, 135),\n    ],\n    [\n        (251, 0, 31),\n        (15, 114, 47),\n        (196, 112, 51),\n        (24, 109, 227),\n        (251, 0, 103),\n        (46, 112, 109),\n        (253, 255, 185),\n    ],\n)\nNIGHT_OWLISH = TerminalTheme(\n    (255, 255, 255),\n    (64, 63, 83),\n    [\n        (1, 22, 39),\n        (211, 66, 62),\n        (42, 162, 152),\n        (218, 170, 1),\n        (72, 118, 214),\n        (64, 63, 83),\n        (8, 145, 106),\n        (122, 129, 129),\n        (122, 129, 129),\n    ],\n    [\n        (247, 110, 110),\n        (73, 208, 197),\n        (218, 194, 107),\n        (92, 167, 228),\n        (105, 112, 152),\n        (0, 201, 144),\n        (152, 159, 177),\n    ],\n)\n\nSVG_EXPORT_THEME = TerminalTheme(\n    (41, 41, 41),\n    (197, 200, 198),\n    [\n        (75, 78, 85),\n        (204, 85, 90),\n        (152, 168, 75),\n        (208, 179, 68),\n        (96, 138, 177),\n        (152, 114, 159),\n        (104, 160, 179),\n        (197, 200, 198),\n        (154, 155, 153),\n    ],\n    [\n        (255, 38, 39),\n        (0, 130, 61),\n        (208, 132, 66),\n        (25, 132, 233),\n        (255, 44, 122),\n        (57, 130, 128),\n        (253, 253, 197),\n    ],\n)\n"
  },
  {
    "path": "src/pip/_vendor/rich/text.py",
    "content": "import re\nfrom functools import partial, reduce\nfrom math import gcd\nfrom operator import itemgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Pattern,\n    Tuple,\n    Union,\n)\n\nfrom ._loop import loop_last\nfrom ._pick import pick_bool\nfrom ._wrap import divide_line\nfrom .align import AlignMethod\nfrom .cells import cell_len, set_cell_size\nfrom .containers import Lines\nfrom .control import strip_control_codes\nfrom .emoji import EmojiVariant\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleType\n\nif TYPE_CHECKING:  # pragma: no cover\n    from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod\n\nDEFAULT_JUSTIFY: \"JustifyMethod\" = \"default\"\nDEFAULT_OVERFLOW: \"OverflowMethod\" = \"fold\"\n\n\n_re_whitespace = re.compile(r\"\\s+$\")\n\nTextType = Union[str, \"Text\"]\n\"\"\"A plain string or a :class:`Text` instance.\"\"\"\n\nGetStyleCallable = Callable[[str], Optional[StyleType]]\n\n\nclass Span(NamedTuple):\n    \"\"\"A marked up region in some text.\"\"\"\n\n    start: int\n    \"\"\"Span start index.\"\"\"\n    end: int\n    \"\"\"Span end index.\"\"\"\n    style: Union[str, Style]\n    \"\"\"Style associated with the span.\"\"\"\n\n    def __repr__(self) -> str:\n        return f\"Span({self.start}, {self.end}, {self.style!r})\"\n\n    def __bool__(self) -> bool:\n        return self.end > self.start\n\n    def split(self, offset: int) -> Tuple[\"Span\", Optional[\"Span\"]]:\n        \"\"\"Split a span in to 2 from a given offset.\"\"\"\n\n        if offset < self.start:\n            return self, None\n        if offset >= self.end:\n            return self, None\n\n        start, end, style = self\n        span1 = Span(start, min(end, offset), style)\n        span2 = Span(span1.end, end, style)\n        return span1, span2\n\n    def move(self, offset: int) -> \"Span\":\n        \"\"\"Move start and end by a given offset.\n\n        Args:\n            offset (int): Number of characters to add to start and end.\n\n        Returns:\n            TextSpan: A new TextSpan with adjusted position.\n        \"\"\"\n        start, end, style = self\n        return Span(start + offset, end + offset, style)\n\n    def right_crop(self, offset: int) -> \"Span\":\n        \"\"\"Crop the span at the given offset.\n\n        Args:\n            offset (int): A value between start and end.\n\n        Returns:\n            Span: A new (possibly smaller) span.\n        \"\"\"\n        start, end, style = self\n        if offset >= end:\n            return self\n        return Span(start, min(offset, end), style)\n\n    def extend(self, cells: int) -> \"Span\":\n        \"\"\"Extend the span by the given number of cells.\n\n        Args:\n            cells (int): Additional space to add to end of span.\n\n        Returns:\n            Span: A span.\n        \"\"\"\n        if cells:\n            start, end, style = self\n            return Span(start, end + cells, style)\n        else:\n            return self\n\n\nclass Text(JupyterMixin):\n    \"\"\"Text with color / style.\n\n    Args:\n        text (str, optional): Default unstyled text. Defaults to \"\".\n        style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n        justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n        overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n        no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.\n        end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n        tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.\n        spans (List[Span], optional). A list of predefined style spans. Defaults to None.\n    \"\"\"\n\n    __slots__ = [\n        \"_text\",\n        \"style\",\n        \"justify\",\n        \"overflow\",\n        \"no_wrap\",\n        \"end\",\n        \"tab_size\",\n        \"_spans\",\n        \"_length\",\n    ]\n\n    def __init__(\n        self,\n        text: str = \"\",\n        style: Union[str, Style] = \"\",\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: Optional[int] = None,\n        spans: Optional[List[Span]] = None,\n    ) -> None:\n        sanitized_text = strip_control_codes(text)\n        self._text = [sanitized_text]\n        self.style = style\n        self.justify: Optional[\"JustifyMethod\"] = justify\n        self.overflow: Optional[\"OverflowMethod\"] = overflow\n        self.no_wrap = no_wrap\n        self.end = end\n        self.tab_size = tab_size\n        self._spans: List[Span] = spans or []\n        self._length: int = len(sanitized_text)\n\n    def __len__(self) -> int:\n        return self._length\n\n    def __bool__(self) -> bool:\n        return bool(self._length)\n\n    def __str__(self) -> str:\n        return self.plain\n\n    def __repr__(self) -> str:\n        return f\"<text {self.plain!r} {self._spans!r} {self.style!r}>\"\n\n    def __add__(self, other: Any) -> \"Text\":\n        if isinstance(other, (str, Text)):\n            result = self.copy()\n            result.append(other)\n            return result\n        return NotImplemented\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Text):\n            return NotImplemented\n        return self.plain == other.plain and self._spans == other._spans\n\n    def __contains__(self, other: object) -> bool:\n        if isinstance(other, str):\n            return other in self.plain\n        elif isinstance(other, Text):\n            return other.plain in self.plain\n        return False\n\n    def __getitem__(self, slice: Union[int, slice]) -> \"Text\":\n        def get_text_at(offset: int) -> \"Text\":\n            _Span = Span\n            text = Text(\n                self.plain[offset],\n                spans=[\n                    _Span(0, 1, style)\n                    for start, end, style in self._spans\n                    if end > offset >= start\n                ],\n                end=\"\",\n            )\n            return text\n\n        if isinstance(slice, int):\n            return get_text_at(slice)\n        else:\n            start, stop, step = slice.indices(len(self.plain))\n            if step == 1:\n                lines = self.divide([start, stop])\n                return lines[1]\n            else:\n                # This would be a bit of work to implement efficiently\n                # For now, its not required\n                raise TypeError(\"slices with step!=1 are not supported\")\n\n    @property\n    def cell_len(self) -> int:\n        \"\"\"Get the number of cells required to render this text.\"\"\"\n        return cell_len(self.plain)\n\n    @property\n    def markup(self) -> str:\n        \"\"\"Get console markup to render this Text.\n\n        Returns:\n            str: A string potentially creating markup tags.\n        \"\"\"\n        from .markup import escape\n\n        output: List[str] = []\n\n        plain = self.plain\n        markup_spans = [\n            (0, False, self.style),\n            *((span.start, False, span.style) for span in self._spans),\n            *((span.end, True, span.style) for span in self._spans),\n            (len(plain), True, self.style),\n        ]\n        markup_spans.sort(key=itemgetter(0, 1))\n        position = 0\n        append = output.append\n        for offset, closing, style in markup_spans:\n            if offset > position:\n                append(escape(plain[position:offset]))\n                position = offset\n            if style:\n                append(f\"[/{style}]\" if closing else f\"[{style}]\")\n        markup = \"\".join(output)\n        return markup\n\n    @classmethod\n    def from_markup(\n        cls,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        emoji: bool = True,\n        emoji_variant: Optional[EmojiVariant] = None,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        end: str = \"\\n\",\n    ) -> \"Text\":\n        \"\"\"Create Text instance from markup.\n\n        Args:\n            text (str): A string containing console markup.\n            style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n            emoji (bool, optional): Also render emoji code. Defaults to True.\n            emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n\n        Returns:\n            Text: A Text instance with markup rendered.\n        \"\"\"\n        from .markup import render\n\n        rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)\n        rendered_text.justify = justify\n        rendered_text.overflow = overflow\n        rendered_text.end = end\n        return rendered_text\n\n    @classmethod\n    def from_ansi(\n        cls,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: Optional[int] = 8,\n    ) -> \"Text\":\n        \"\"\"Create a Text object from a string containing ANSI escape codes.\n\n        Args:\n            text (str): A string containing escape codes.\n            style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n            tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.\n        \"\"\"\n        from .ansi import AnsiDecoder\n\n        joiner = Text(\n            \"\\n\",\n            justify=justify,\n            overflow=overflow,\n            no_wrap=no_wrap,\n            end=end,\n            tab_size=tab_size,\n            style=style,\n        )\n        decoder = AnsiDecoder()\n        result = joiner.join(line for line in decoder.decode(text))\n        return result\n\n    @classmethod\n    def styled(\n        cls,\n        text: str,\n        style: StyleType = \"\",\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n    ) -> \"Text\":\n        \"\"\"Construct a Text instance with a pre-applied styled. A style applied in this way won't be used\n        to pad the text when it is justified.\n\n        Args:\n            text (str): A string containing console markup.\n            style (Union[str, Style]): Style to apply to the text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n\n        Returns:\n            Text: A text instance with a style applied to the entire string.\n        \"\"\"\n        styled_text = cls(text, justify=justify, overflow=overflow)\n        styled_text.stylize(style)\n        return styled_text\n\n    @classmethod\n    def assemble(\n        cls,\n        *parts: Union[str, \"Text\", Tuple[str, StyleType]],\n        style: Union[str, Style] = \"\",\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: int = 8,\n        meta: Optional[Dict[str, Any]] = None,\n    ) -> \"Text\":\n        \"\"\"Construct a text instance by combining a sequence of strings with optional styles.\n        The positional arguments should be either strings, or a tuple of string + style.\n\n        Args:\n            style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n            tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.\n            meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None\n\n        Returns:\n            Text: A new text instance.\n        \"\"\"\n        text = cls(\n            style=style,\n            justify=justify,\n            overflow=overflow,\n            no_wrap=no_wrap,\n            end=end,\n            tab_size=tab_size,\n        )\n        append = text.append\n        _Text = Text\n        for part in parts:\n            if isinstance(part, (_Text, str)):\n                append(part)\n            else:\n                append(*part)\n        if meta:\n            text.apply_meta(meta)\n        return text\n\n    @property\n    def plain(self) -> str:\n        \"\"\"Get the text as a single string.\"\"\"\n        if len(self._text) != 1:\n            self._text[:] = [\"\".join(self._text)]\n        return self._text[0]\n\n    @plain.setter\n    def plain(self, new_text: str) -> None:\n        \"\"\"Set the text to a new value.\"\"\"\n        if new_text != self.plain:\n            sanitized_text = strip_control_codes(new_text)\n            self._text[:] = [sanitized_text]\n            old_length = self._length\n            self._length = len(sanitized_text)\n            if old_length > self._length:\n                self._trim_spans()\n\n    @property\n    def spans(self) -> List[Span]:\n        \"\"\"Get a reference to the internal list of spans.\"\"\"\n        return self._spans\n\n    @spans.setter\n    def spans(self, spans: List[Span]) -> None:\n        \"\"\"Set spans.\"\"\"\n        self._spans = spans[:]\n\n    def blank_copy(self, plain: str = \"\") -> \"Text\":\n        \"\"\"Return a new Text instance with copied metadata (but not the string or spans).\"\"\"\n        copy_self = Text(\n            plain,\n            style=self.style,\n            justify=self.justify,\n            overflow=self.overflow,\n            no_wrap=self.no_wrap,\n            end=self.end,\n            tab_size=self.tab_size,\n        )\n        return copy_self\n\n    def copy(self) -> \"Text\":\n        \"\"\"Return a copy of this instance.\"\"\"\n        copy_self = Text(\n            self.plain,\n            style=self.style,\n            justify=self.justify,\n            overflow=self.overflow,\n            no_wrap=self.no_wrap,\n            end=self.end,\n            tab_size=self.tab_size,\n        )\n        copy_self._spans[:] = self._spans\n        return copy_self\n\n    def stylize(\n        self,\n        style: Union[str, Style],\n        start: int = 0,\n        end: Optional[int] = None,\n    ) -> None:\n        \"\"\"Apply a style to the text, or a portion of the text.\n\n        Args:\n            style (Union[str, Style]): Style instance or style definition to apply.\n            start (int): Start offset (negative indexing is supported). Defaults to 0.\n            end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.\n        \"\"\"\n        if style:\n            length = len(self)\n            if start < 0:\n                start = length + start\n            if end is None:\n                end = length\n            if end < 0:\n                end = length + end\n            if start >= length or end <= start:\n                # Span not in text or not valid\n                return\n            self._spans.append(Span(start, min(length, end), style))\n\n    def stylize_before(\n        self,\n        style: Union[str, Style],\n        start: int = 0,\n        end: Optional[int] = None,\n    ) -> None:\n        \"\"\"Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present.\n\n        Args:\n            style (Union[str, Style]): Style instance or style definition to apply.\n            start (int): Start offset (negative indexing is supported). Defaults to 0.\n            end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.\n        \"\"\"\n        if style:\n            length = len(self)\n            if start < 0:\n                start = length + start\n            if end is None:\n                end = length\n            if end < 0:\n                end = length + end\n            if start >= length or end <= start:\n                # Span not in text or not valid\n                return\n            self._spans.insert(0, Span(start, min(length, end), style))\n\n    def apply_meta(\n        self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None\n    ) -> None:\n        \"\"\"Apply metadata to the text, or a portion of the text.\n\n        Args:\n            meta (Dict[str, Any]): A dict of meta information.\n            start (int): Start offset (negative indexing is supported). Defaults to 0.\n            end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.\n\n        \"\"\"\n        style = Style.from_meta(meta)\n        self.stylize(style, start=start, end=end)\n\n    def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> \"Text\":\n        \"\"\"Apply event handlers (used by Textual project).\n\n        Example:\n            >>> from rich.text import Text\n            >>> text = Text(\"hello world\")\n            >>> text.on(click=\"view.toggle('world')\")\n\n        Args:\n            meta (Dict[str, Any]): Mapping of meta information.\n            **handlers: Keyword args are prefixed with \"@\" to defined handlers.\n\n        Returns:\n            Text: Self is returned to method may be chained.\n        \"\"\"\n        meta = {} if meta is None else meta\n        meta.update({f\"@{key}\": value for key, value in handlers.items()})\n        self.stylize(Style.from_meta(meta))\n        return self\n\n    def remove_suffix(self, suffix: str) -> None:\n        \"\"\"Remove a suffix if it exists.\n\n        Args:\n            suffix (str): Suffix to remove.\n        \"\"\"\n        if self.plain.endswith(suffix):\n            self.right_crop(len(suffix))\n\n    def get_style_at_offset(self, console: \"Console\", offset: int) -> Style:\n        \"\"\"Get the style of a character at give offset.\n\n        Args:\n            console (~Console): Console where text will be rendered.\n            offset (int): Offset in to text (negative indexing supported)\n\n        Returns:\n            Style: A Style instance.\n        \"\"\"\n        # TODO: This is a little inefficient, it is only used by full justify\n        if offset < 0:\n            offset = len(self) + offset\n        get_style = console.get_style\n        style = get_style(self.style).copy()\n        for start, end, span_style in self._spans:\n            if end > offset >= start:\n                style += get_style(span_style, default=\"\")\n        return style\n\n    def extend_style(self, spaces: int) -> None:\n        \"\"\"Extend the Text given number of spaces where the spaces have the same style as the last character.\n\n        Args:\n            spaces (int): Number of spaces to add to the Text.\n        \"\"\"\n        if spaces <= 0:\n            return\n        spans = self.spans\n        new_spaces = \" \" * spaces\n        if spans:\n            end_offset = len(self)\n            self._spans[:] = [\n                span.extend(spaces) if span.end >= end_offset else span\n                for span in spans\n            ]\n            self._text.append(new_spaces)\n            self._length += spaces\n        else:\n            self.plain += new_spaces\n\n    def highlight_regex(\n        self,\n        re_highlight: Union[Pattern[str], str],\n        style: Optional[Union[GetStyleCallable, StyleType]] = None,\n        *,\n        style_prefix: str = \"\",\n    ) -> int:\n        \"\"\"Highlight text with a regular expression, where group names are\n        translated to styles.\n\n        Args:\n            re_highlight (Union[re.Pattern, str]): A regular expression object or string.\n            style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable\n                which accepts the matched text and returns a style. Defaults to None.\n            style_prefix (str, optional): Optional prefix to add to style group names.\n\n        Returns:\n            int: Number of regex matches\n        \"\"\"\n        count = 0\n        append_span = self._spans.append\n        _Span = Span\n        plain = self.plain\n        if isinstance(re_highlight, str):\n            re_highlight = re.compile(re_highlight)\n        for match in re_highlight.finditer(plain):\n            get_span = match.span\n            if style:\n                start, end = get_span()\n                match_style = style(plain[start:end]) if callable(style) else style\n                if match_style is not None and end > start:\n                    append_span(_Span(start, end, match_style))\n\n            count += 1\n            for name in match.groupdict().keys():\n                start, end = get_span(name)\n                if start != -1 and end > start:\n                    append_span(_Span(start, end, f\"{style_prefix}{name}\"))\n        return count\n\n    def highlight_words(\n        self,\n        words: Iterable[str],\n        style: Union[str, Style],\n        *,\n        case_sensitive: bool = True,\n    ) -> int:\n        \"\"\"Highlight words with a style.\n\n        Args:\n            words (Iterable[str]): Words to highlight.\n            style (Union[str, Style]): Style to apply.\n            case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True.\n\n        Returns:\n            int: Number of words highlighted.\n        \"\"\"\n        re_words = \"|\".join(re.escape(word) for word in words)\n        add_span = self._spans.append\n        count = 0\n        _Span = Span\n        for match in re.finditer(\n            re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE\n        ):\n            start, end = match.span(0)\n            add_span(_Span(start, end, style))\n            count += 1\n        return count\n\n    def rstrip(self) -> None:\n        \"\"\"Strip whitespace from end of text.\"\"\"\n        self.plain = self.plain.rstrip()\n\n    def rstrip_end(self, size: int) -> None:\n        \"\"\"Remove whitespace beyond a certain width at the end of the text.\n\n        Args:\n            size (int): The desired size of the text.\n        \"\"\"\n        text_length = len(self)\n        if text_length > size:\n            excess = text_length - size\n            whitespace_match = _re_whitespace.search(self.plain)\n            if whitespace_match is not None:\n                whitespace_count = len(whitespace_match.group(0))\n                self.right_crop(min(whitespace_count, excess))\n\n    def set_length(self, new_length: int) -> None:\n        \"\"\"Set new length of the text, clipping or padding is required.\"\"\"\n        length = len(self)\n        if length != new_length:\n            if length < new_length:\n                self.pad_right(new_length - length)\n            else:\n                self.right_crop(length - new_length)\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Iterable[Segment]:\n        tab_size: int = console.tab_size if self.tab_size is None else self.tab_size\n        justify = self.justify or options.justify or DEFAULT_JUSTIFY\n\n        overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW\n\n        lines = self.wrap(\n            console,\n            options.max_width,\n            justify=justify,\n            overflow=overflow,\n            tab_size=tab_size or 8,\n            no_wrap=pick_bool(self.no_wrap, options.no_wrap, False),\n        )\n        all_lines = Text(\"\\n\").join(lines)\n        yield from all_lines.render(console, end=self.end)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        text = self.plain\n        lines = text.splitlines()\n        max_text_width = max(cell_len(line) for line in lines) if lines else 0\n        words = text.split()\n        min_text_width = (\n            max(cell_len(word) for word in words) if words else max_text_width\n        )\n        return Measurement(min_text_width, max_text_width)\n\n    def render(self, console: \"Console\", end: str = \"\") -> Iterable[\"Segment\"]:\n        \"\"\"Render the text as Segments.\n\n        Args:\n            console (Console): Console instance.\n            end (Optional[str], optional): Optional end character.\n\n        Returns:\n            Iterable[Segment]: Result of render that may be written to the console.\n        \"\"\"\n        _Segment = Segment\n        text = self.plain\n        if not self._spans:\n            yield Segment(text)\n            if end:\n                yield _Segment(end)\n            return\n        get_style = partial(console.get_style, default=Style.null())\n\n        enumerated_spans = list(enumerate(self._spans, 1))\n        style_map = {index: get_style(span.style) for index, span in enumerated_spans}\n        style_map[0] = get_style(self.style)\n\n        spans = [\n            (0, False, 0),\n            *((span.start, False, index) for index, span in enumerated_spans),\n            *((span.end, True, index) for index, span in enumerated_spans),\n            (len(text), True, 0),\n        ]\n        spans.sort(key=itemgetter(0, 1))\n\n        stack: List[int] = []\n        stack_append = stack.append\n        stack_pop = stack.remove\n\n        style_cache: Dict[Tuple[Style, ...], Style] = {}\n        style_cache_get = style_cache.get\n        combine = Style.combine\n\n        def get_current_style() -> Style:\n            \"\"\"Construct current style from stack.\"\"\"\n            styles = tuple(style_map[_style_id] for _style_id in sorted(stack))\n            cached_style = style_cache_get(styles)\n            if cached_style is not None:\n                return cached_style\n            current_style = combine(styles)\n            style_cache[styles] = current_style\n            return current_style\n\n        for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):\n            if leaving:\n                stack_pop(style_id)\n            else:\n                stack_append(style_id)\n            if next_offset > offset:\n                yield _Segment(text[offset:next_offset], get_current_style())\n        if end:\n            yield _Segment(end)\n\n    def join(self, lines: Iterable[\"Text\"]) -> \"Text\":\n        \"\"\"Join text together with this instance as the separator.\n\n        Args:\n            lines (Iterable[Text]): An iterable of Text instances to join.\n\n        Returns:\n            Text: A new text instance containing join text.\n        \"\"\"\n\n        new_text = self.blank_copy()\n\n        def iter_text() -> Iterable[\"Text\"]:\n            if self.plain:\n                for last, line in loop_last(lines):\n                    yield line\n                    if not last:\n                        yield self\n            else:\n                yield from lines\n\n        extend_text = new_text._text.extend\n        append_span = new_text._spans.append\n        extend_spans = new_text._spans.extend\n        offset = 0\n        _Span = Span\n\n        for text in iter_text():\n            extend_text(text._text)\n            if text.style:\n                append_span(_Span(offset, offset + len(text), text.style))\n            extend_spans(\n                _Span(offset + start, offset + end, style)\n                for start, end, style in text._spans\n            )\n            offset += len(text)\n        new_text._length = offset\n        return new_text\n\n    def expand_tabs(self, tab_size: Optional[int] = None) -> None:\n        \"\"\"Converts tabs to spaces.\n\n        Args:\n            tab_size (int, optional): Size of tabs. Defaults to 8.\n\n        \"\"\"\n        if \"\\t\" not in self.plain:\n            return\n        if tab_size is None:\n            tab_size = self.tab_size\n        if tab_size is None:\n            tab_size = 8\n\n        new_text: List[Text] = []\n        append = new_text.append\n\n        for line in self.split(\"\\n\", include_separator=True):\n            if \"\\t\" not in line.plain:\n                append(line)\n            else:\n                cell_position = 0\n                parts = line.split(\"\\t\", include_separator=True)\n                for part in parts:\n                    if part.plain.endswith(\"\\t\"):\n                        part._text[-1] = part._text[-1][:-1] + \" \"\n                        cell_position += part.cell_len\n                        tab_remainder = cell_position % tab_size\n                        if tab_remainder:\n                            spaces = tab_size - tab_remainder\n                            part.extend_style(spaces)\n                            cell_position += spaces\n                    else:\n                        cell_position += part.cell_len\n                    append(part)\n\n        result = Text(\"\").join(new_text)\n\n        self._text = [result.plain]\n        self._length = len(self.plain)\n        self._spans[:] = result._spans\n\n    def truncate(\n        self,\n        max_width: int,\n        *,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        pad: bool = False,\n    ) -> None:\n        \"\"\"Truncate text if it is longer that a given width.\n\n        Args:\n            max_width (int): Maximum number of characters in text.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None, to use self.overflow.\n            pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False.\n        \"\"\"\n        _overflow = overflow or self.overflow or DEFAULT_OVERFLOW\n        if _overflow != \"ignore\":\n            length = cell_len(self.plain)\n            if length > max_width:\n                if _overflow == \"ellipsis\":\n                    self.plain = set_cell_size(self.plain, max_width - 1) + \"…\"\n                else:\n                    self.plain = set_cell_size(self.plain, max_width)\n            if pad and length < max_width:\n                spaces = max_width - length\n                self._text = [f\"{self.plain}{' ' * spaces}\"]\n                self._length = len(self.plain)\n\n    def _trim_spans(self) -> None:\n        \"\"\"Remove or modify any spans that are over the end of the text.\"\"\"\n        max_offset = len(self.plain)\n        _Span = Span\n        self._spans[:] = [\n            (\n                span\n                if span.end < max_offset\n                else _Span(span.start, min(max_offset, span.end), span.style)\n            )\n            for span in self._spans\n            if span.start < max_offset\n        ]\n\n    def pad(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad left and right with a given number of characters.\n\n        Args:\n            count (int): Width of padding.\n            character (str): The character to pad with. Must be a string of length 1.\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            pad_characters = character * count\n            self.plain = f\"{pad_characters}{self.plain}{pad_characters}\"\n            _Span = Span\n            self._spans[:] = [\n                _Span(start + count, end + count, style)\n                for start, end, style in self._spans\n            ]\n\n    def pad_left(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad the left with a given character.\n\n        Args:\n            count (int): Number of characters to pad.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            self.plain = f\"{character * count}{self.plain}\"\n            _Span = Span\n            self._spans[:] = [\n                _Span(start + count, end + count, style)\n                for start, end, style in self._spans\n            ]\n\n    def pad_right(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad the right with a given character.\n\n        Args:\n            count (int): Number of characters to pad.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            self.plain = f\"{self.plain}{character * count}\"\n\n    def align(self, align: AlignMethod, width: int, character: str = \" \") -> None:\n        \"\"\"Align text to a given width.\n\n        Args:\n            align (AlignMethod): One of \"left\", \"center\", or \"right\".\n            width (int): Desired width.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        self.truncate(width)\n        excess_space = width - cell_len(self.plain)\n        if excess_space:\n            if align == \"left\":\n                self.pad_right(excess_space, character)\n            elif align == \"center\":\n                left = excess_space // 2\n                self.pad_left(left, character)\n                self.pad_right(excess_space - left, character)\n            else:\n                self.pad_left(excess_space, character)\n\n    def append(\n        self, text: Union[\"Text\", str], style: Optional[Union[str, \"Style\"]] = None\n    ) -> \"Text\":\n        \"\"\"Add text with an optional style.\n\n        Args:\n            text (Union[Text, str]): A str or Text to append.\n            style (str, optional): A style name. Defaults to None.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n\n        if not isinstance(text, (str, Text)):\n            raise TypeError(\"Only str or Text can be appended to Text\")\n\n        if len(text):\n            if isinstance(text, str):\n                sanitized_text = strip_control_codes(text)\n                self._text.append(sanitized_text)\n                offset = len(self)\n                text_length = len(sanitized_text)\n                if style:\n                    self._spans.append(Span(offset, offset + text_length, style))\n                self._length += text_length\n            elif isinstance(text, Text):\n                _Span = Span\n                if style is not None:\n                    raise ValueError(\n                        \"style must not be set when appending Text instance\"\n                    )\n                text_length = self._length\n                if text.style:\n                    self._spans.append(\n                        _Span(text_length, text_length + len(text), text.style)\n                    )\n                self._text.append(text.plain)\n                self._spans.extend(\n                    _Span(start + text_length, end + text_length, style)\n                    for start, end, style in text._spans.copy()\n                )\n                self._length += len(text)\n        return self\n\n    def append_text(self, text: \"Text\") -> \"Text\":\n        \"\"\"Append another Text instance. This method is more performant that Text.append, but\n        only works for Text.\n\n        Args:\n            text (Text): The Text instance to append to this instance.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n        _Span = Span\n        text_length = self._length\n        if text.style:\n            self._spans.append(_Span(text_length, text_length + len(text), text.style))\n        self._text.append(text.plain)\n        self._spans.extend(\n            _Span(start + text_length, end + text_length, style)\n            for start, end, style in text._spans.copy()\n        )\n        self._length += len(text)\n        return self\n\n    def append_tokens(\n        self, tokens: Iterable[Tuple[str, Optional[StyleType]]]\n    ) -> \"Text\":\n        \"\"\"Append iterable of str and style. Style may be a Style instance or a str style definition.\n\n        Args:\n            tokens (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n        append_text = self._text.append\n        append_span = self._spans.append\n        _Span = Span\n        offset = len(self)\n        for content, style in tokens:\n            content = strip_control_codes(content)\n            append_text(content)\n            if style:\n                append_span(_Span(offset, offset + len(content), style))\n            offset += len(content)\n        self._length = offset\n        return self\n\n    def copy_styles(self, text: \"Text\") -> None:\n        \"\"\"Copy styles from another Text instance.\n\n        Args:\n            text (Text): A Text instance to copy styles from, must be the same length.\n        \"\"\"\n        self._spans.extend(text._spans)\n\n    def split(\n        self,\n        separator: str = \"\\n\",\n        *,\n        include_separator: bool = False,\n        allow_blank: bool = False,\n    ) -> Lines:\n        \"\"\"Split rich text in to lines, preserving styles.\n\n        Args:\n            separator (str, optional): String to split on. Defaults to \"\\\\\\\\n\".\n            include_separator (bool, optional): Include the separator in the lines. Defaults to False.\n            allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.\n\n        Returns:\n            List[RichText]: A list of rich text, one per line of the original.\n        \"\"\"\n        assert separator, \"separator must not be empty\"\n\n        text = self.plain\n        if separator not in text:\n            return Lines([self.copy()])\n\n        if include_separator:\n            lines = self.divide(\n                match.end() for match in re.finditer(re.escape(separator), text)\n            )\n        else:\n\n            def flatten_spans() -> Iterable[int]:\n                for match in re.finditer(re.escape(separator), text):\n                    start, end = match.span()\n                    yield start\n                    yield end\n\n            lines = Lines(\n                line for line in self.divide(flatten_spans()) if line.plain != separator\n            )\n\n        if not allow_blank and text.endswith(separator):\n            lines.pop()\n\n        return lines\n\n    def divide(self, offsets: Iterable[int]) -> Lines:\n        \"\"\"Divide text in to a number of lines at given offsets.\n\n        Args:\n            offsets (Iterable[int]): Offsets used to divide text.\n\n        Returns:\n            Lines: New RichText instances between offsets.\n        \"\"\"\n        _offsets = list(offsets)\n\n        if not _offsets:\n            return Lines([self.copy()])\n\n        text = self.plain\n        text_length = len(text)\n        divide_offsets = [0, *_offsets, text_length]\n        line_ranges = list(zip(divide_offsets, divide_offsets[1:]))\n\n        style = self.style\n        justify = self.justify\n        overflow = self.overflow\n        _Text = Text\n        new_lines = Lines(\n            _Text(\n                text[start:end],\n                style=style,\n                justify=justify,\n                overflow=overflow,\n            )\n            for start, end in line_ranges\n        )\n        if not self._spans:\n            return new_lines\n\n        _line_appends = [line._spans.append for line in new_lines._lines]\n        line_count = len(line_ranges)\n        _Span = Span\n\n        for span_start, span_end, style in self._spans:\n            lower_bound = 0\n            upper_bound = line_count\n            start_line_no = (lower_bound + upper_bound) // 2\n\n            while True:\n                line_start, line_end = line_ranges[start_line_no]\n                if span_start < line_start:\n                    upper_bound = start_line_no - 1\n                elif span_start > line_end:\n                    lower_bound = start_line_no + 1\n                else:\n                    break\n                start_line_no = (lower_bound + upper_bound) // 2\n\n            if span_end < line_end:\n                end_line_no = start_line_no\n            else:\n                end_line_no = lower_bound = start_line_no\n                upper_bound = line_count\n\n                while True:\n                    line_start, line_end = line_ranges[end_line_no]\n                    if span_end < line_start:\n                        upper_bound = end_line_no - 1\n                    elif span_end > line_end:\n                        lower_bound = end_line_no + 1\n                    else:\n                        break\n                    end_line_no = (lower_bound + upper_bound) // 2\n\n            for line_no in range(start_line_no, end_line_no + 1):\n                line_start, line_end = line_ranges[line_no]\n                new_start = max(0, span_start - line_start)\n                new_end = min(span_end - line_start, line_end - line_start)\n                if new_end > new_start:\n                    _line_appends[line_no](_Span(new_start, new_end, style))\n\n        return new_lines\n\n    def right_crop(self, amount: int = 1) -> None:\n        \"\"\"Remove a number of characters from the end of the text.\"\"\"\n        max_offset = len(self.plain) - amount\n        _Span = Span\n        self._spans[:] = [\n            (\n                span\n                if span.end < max_offset\n                else _Span(span.start, min(max_offset, span.end), span.style)\n            )\n            for span in self._spans\n            if span.start < max_offset\n        ]\n        self._text = [self.plain[:-amount]]\n        self._length -= amount\n\n    def wrap(\n        self,\n        console: \"Console\",\n        width: int,\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        tab_size: int = 8,\n        no_wrap: Optional[bool] = None,\n    ) -> Lines:\n        \"\"\"Word wrap the text.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Number of cells available per line.\n            justify (str, optional): Justify method: \"default\", \"left\", \"center\", \"full\", \"right\". Defaults to \"default\".\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n            tab_size (int, optional): Default tab size. Defaults to 8.\n            no_wrap (bool, optional): Disable wrapping, Defaults to False.\n\n        Returns:\n            Lines: Number of lines.\n        \"\"\"\n        wrap_justify = justify or self.justify or DEFAULT_JUSTIFY\n        wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW\n\n        no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == \"ignore\"\n\n        lines = Lines()\n        for line in self.split(allow_blank=True):\n            if \"\\t\" in line:\n                line.expand_tabs(tab_size)\n            if no_wrap:\n                new_lines = Lines([line])\n            else:\n                offsets = divide_line(str(line), width, fold=wrap_overflow == \"fold\")\n                new_lines = line.divide(offsets)\n            for line in new_lines:\n                line.rstrip_end(width)\n            if wrap_justify:\n                new_lines.justify(\n                    console, width, justify=wrap_justify, overflow=wrap_overflow\n                )\n            for line in new_lines:\n                line.truncate(width, overflow=wrap_overflow)\n            lines.extend(new_lines)\n        return lines\n\n    def fit(self, width: int) -> Lines:\n        \"\"\"Fit the text in to given width by chopping in to lines.\n\n        Args:\n            width (int): Maximum characters in a line.\n\n        Returns:\n            Lines: Lines container.\n        \"\"\"\n        lines: Lines = Lines()\n        append = lines.append\n        for line in self.split():\n            line.set_length(width)\n            append(line)\n        return lines\n\n    def detect_indentation(self) -> int:\n        \"\"\"Auto-detect indentation of code.\n\n        Returns:\n            int: Number of spaces used to indent code.\n        \"\"\"\n\n        _indentations = {\n            len(match.group(1))\n            for match in re.finditer(r\"^( *)(.*)$\", self.plain, flags=re.MULTILINE)\n        }\n\n        try:\n            indentation = (\n                reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1\n            )\n        except TypeError:\n            indentation = 1\n\n        return indentation\n\n    def with_indent_guides(\n        self,\n        indent_size: Optional[int] = None,\n        *,\n        character: str = \"│\",\n        style: StyleType = \"dim green\",\n    ) -> \"Text\":\n        \"\"\"Adds indent guide lines to text.\n\n        Args:\n            indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None.\n            character (str, optional): Character to use for indentation. Defaults to \"│\".\n            style (Union[Style, str], optional): Style of indent guides.\n\n        Returns:\n            Text: New text with indentation guides.\n        \"\"\"\n\n        _indent_size = self.detect_indentation() if indent_size is None else indent_size\n\n        text = self.copy()\n        text.expand_tabs()\n        indent_line = f\"{character}{' ' * (_indent_size - 1)}\"\n\n        re_indent = re.compile(r\"^( *)(.*)$\")\n        new_lines: List[Text] = []\n        add_line = new_lines.append\n        blank_lines = 0\n        for line in text.split(allow_blank=True):\n            match = re_indent.match(line.plain)\n            if not match or not match.group(2):\n                blank_lines += 1\n                continue\n            indent = match.group(1)\n            full_indents, remaining_space = divmod(len(indent), _indent_size)\n            new_indent = f\"{indent_line * full_indents}{' ' * remaining_space}\"\n            line.plain = new_indent + line.plain[len(new_indent) :]\n            line.stylize(style, 0, len(new_indent))\n            if blank_lines:\n                new_lines.extend([Text(new_indent, style=style)] * blank_lines)\n                blank_lines = 0\n            add_line(line)\n        if blank_lines:\n            new_lines.extend([Text(\"\", style=style)] * blank_lines)\n\n        new_text = text.blank_copy(\"\\n\").join(new_lines)\n        return new_text\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    text = Text(\n        \"\"\"\\nLorem 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.\\n\"\"\"\n    )\n    text.highlight_words([\"Lorem\"], \"bold\")\n    text.highlight_words([\"ipsum\"], \"italic\")\n\n    console = Console()\n\n    console.rule(\"justify='left'\")\n    console.print(text, style=\"red\")\n    console.print()\n\n    console.rule(\"justify='center'\")\n    console.print(text, style=\"green\", justify=\"center\")\n    console.print()\n\n    console.rule(\"justify='right'\")\n    console.print(text, style=\"blue\", justify=\"right\")\n    console.print()\n\n    console.rule(\"justify='full'\")\n    console.print(text, style=\"magenta\", justify=\"full\")\n    console.print()\n"
  },
  {
    "path": "src/pip/_vendor/rich/theme.py",
    "content": "import configparser\nfrom typing import IO, Dict, List, Mapping, Optional\n\nfrom .default_styles import DEFAULT_STYLES\nfrom .style import Style, StyleType\n\n\nclass Theme:\n    \"\"\"A container for style information, used by :class:`~rich.console.Console`.\n\n    Args:\n        styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles.\n        inherit (bool, optional): Inherit default styles. Defaults to True.\n    \"\"\"\n\n    styles: Dict[str, Style]\n\n    def __init__(\n        self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True\n    ):\n        self.styles = DEFAULT_STYLES.copy() if inherit else {}\n        if styles is not None:\n            self.styles.update(\n                {\n                    name: style if isinstance(style, Style) else Style.parse(style)\n                    for name, style in styles.items()\n                }\n            )\n\n    @property\n    def config(self) -> str:\n        \"\"\"Get contents of a config file for this theme.\"\"\"\n        config = \"[styles]\\n\" + \"\\n\".join(\n            f\"{name} = {style}\" for name, style in sorted(self.styles.items())\n        )\n        return config\n\n    @classmethod\n    def from_file(\n        cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True\n    ) -> \"Theme\":\n        \"\"\"Load a theme from a text mode file.\n\n        Args:\n            config_file (IO[str]): An open conf file.\n            source (str, optional): The filename of the open file. Defaults to None.\n            inherit (bool, optional): Inherit default styles. Defaults to True.\n\n        Returns:\n            Theme: A New theme instance.\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read_file(config_file, source=source)\n        styles = {name: Style.parse(value) for name, value in config.items(\"styles\")}\n        theme = Theme(styles, inherit=inherit)\n        return theme\n\n    @classmethod\n    def read(\n        cls, path: str, inherit: bool = True, encoding: Optional[str] = None\n    ) -> \"Theme\":\n        \"\"\"Read a theme from a path.\n\n        Args:\n            path (str): Path to a config file readable by Python configparser module.\n            inherit (bool, optional): Inherit default styles. Defaults to True.\n            encoding (str, optional): Encoding of the config file. Defaults to None.\n\n        Returns:\n            Theme: A new theme instance.\n        \"\"\"\n        with open(path, encoding=encoding) as config_file:\n            return cls.from_file(config_file, source=path, inherit=inherit)\n\n\nclass ThemeStackError(Exception):\n    \"\"\"Base exception for errors related to the theme stack.\"\"\"\n\n\nclass ThemeStack:\n    \"\"\"A stack of themes.\n\n    Args:\n        theme (Theme): A theme instance\n    \"\"\"\n\n    def __init__(self, theme: Theme) -> None:\n        self._entries: List[Dict[str, Style]] = [theme.styles]\n        self.get = self._entries[-1].get\n\n    def push_theme(self, theme: Theme, inherit: bool = True) -> None:\n        \"\"\"Push a theme on the top of the stack.\n\n        Args:\n            theme (Theme): A Theme instance.\n            inherit (boolean, optional): Inherit styles from current top of stack.\n        \"\"\"\n        styles: Dict[str, Style]\n        styles = (\n            {**self._entries[-1], **theme.styles} if inherit else theme.styles.copy()\n        )\n        self._entries.append(styles)\n        self.get = self._entries[-1].get\n\n    def pop_theme(self) -> None:\n        \"\"\"Pop (and discard) the top-most theme.\"\"\"\n        if len(self._entries) == 1:\n            raise ThemeStackError(\"Unable to pop base theme\")\n        self._entries.pop()\n        self.get = self._entries[-1].get\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    theme = Theme()\n    print(theme.config)\n"
  },
  {
    "path": "src/pip/_vendor/rich/themes.py",
    "content": "from .default_styles import DEFAULT_STYLES\nfrom .theme import Theme\n\n\nDEFAULT = Theme(DEFAULT_STYLES)\n"
  },
  {
    "path": "src/pip/_vendor/rich/traceback.py",
    "content": "import inspect\nimport linecache\nimport os\nimport sys\nfrom dataclasses import dataclass, field\nfrom itertools import islice\nfrom traceback import walk_tb\nfrom types import ModuleType, TracebackType\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom pip._vendor.pygments.lexers import guess_lexer_for_filename\nfrom pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String\nfrom pip._vendor.pygments.token import Text as TextToken\nfrom pip._vendor.pygments.token import Token\nfrom pip._vendor.pygments.util import ClassNotFound\n\nfrom . import pretty\nfrom ._loop import loop_first_last, loop_last\nfrom .columns import Columns\nfrom .console import (\n    Console,\n    ConsoleOptions,\n    ConsoleRenderable,\n    Group,\n    RenderResult,\n    group,\n)\nfrom .constrain import Constrain\nfrom .highlighter import RegexHighlighter, ReprHighlighter\nfrom .panel import Panel\nfrom .scope import render_scope\nfrom .style import Style\nfrom .syntax import Syntax, SyntaxPosition\nfrom .text import Text\nfrom .theme import Theme\n\nWINDOWS = sys.platform == \"win32\"\n\nLOCALS_MAX_LENGTH = 10\nLOCALS_MAX_STRING = 80\n\n\ndef _iter_syntax_lines(\n    start: SyntaxPosition, end: SyntaxPosition\n) -> Iterable[Tuple[int, int, int]]:\n    \"\"\"Yield start and end positions per line.\n\n    Args:\n        start: Start position.\n        end: End position.\n\n    Returns:\n        Iterable of (LINE, COLUMN1, COLUMN2).\n    \"\"\"\n\n    line1, column1 = start\n    line2, column2 = end\n\n    if line1 == line2:\n        yield line1, column1, column2\n    else:\n        for first, last, line_no in loop_first_last(range(line1, line2 + 1)):\n            if first:\n                yield line_no, column1, -1\n            elif last:\n                yield line_no, 0, column2\n            else:\n                yield line_no, 0, -1\n\n\ndef install(\n    *,\n    console: Optional[Console] = None,\n    width: Optional[int] = 100,\n    code_width: Optional[int] = 88,\n    extra_lines: int = 3,\n    theme: Optional[str] = None,\n    word_wrap: bool = False,\n    show_locals: bool = False,\n    locals_max_length: int = LOCALS_MAX_LENGTH,\n    locals_max_string: int = LOCALS_MAX_STRING,\n    locals_hide_dunder: bool = True,\n    locals_hide_sunder: Optional[bool] = None,\n    indent_guides: bool = True,\n    suppress: Iterable[Union[str, ModuleType]] = (),\n    max_frames: int = 100,\n) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:\n    \"\"\"Install a rich traceback handler.\n\n    Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.\n\n\n    Args:\n        console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.\n        width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.\n        code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88.\n        extra_lines (int, optional): Extra lines of code. Defaults to 3.\n        theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick\n            a theme appropriate for the platform.\n        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n        show_locals (bool, optional): Enable display of local variables. Defaults to False.\n        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to 10.\n        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n        locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n        locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n\n    Returns:\n        Callable: The previous exception handler that was replaced.\n\n    \"\"\"\n    traceback_console = Console(stderr=True) if console is None else console\n\n    locals_hide_sunder = (\n        True\n        if (traceback_console.is_jupyter and locals_hide_sunder is None)\n        else locals_hide_sunder\n    )\n\n    def excepthook(\n        type_: Type[BaseException],\n        value: BaseException,\n        traceback: Optional[TracebackType],\n    ) -> None:\n        exception_traceback = Traceback.from_exception(\n            type_,\n            value,\n            traceback,\n            width=width,\n            code_width=code_width,\n            extra_lines=extra_lines,\n            theme=theme,\n            word_wrap=word_wrap,\n            show_locals=show_locals,\n            locals_max_length=locals_max_length,\n            locals_max_string=locals_max_string,\n            locals_hide_dunder=locals_hide_dunder,\n            locals_hide_sunder=bool(locals_hide_sunder),\n            indent_guides=indent_guides,\n            suppress=suppress,\n            max_frames=max_frames,\n        )\n        traceback_console.print(exception_traceback)\n\n    def ipy_excepthook_closure(ip: Any) -> None:  # pragma: no cover\n        tb_data = {}  # store information about showtraceback call\n        default_showtraceback = ip.showtraceback  # keep reference of default traceback\n\n        def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:\n            \"\"\"wrap the default ip.showtraceback to store info for ip._showtraceback\"\"\"\n            nonlocal tb_data\n            tb_data = kwargs\n            default_showtraceback(*args, **kwargs)\n\n        def ipy_display_traceback(\n            *args: Any, is_syntax: bool = False, **kwargs: Any\n        ) -> None:\n            \"\"\"Internally called traceback from ip._showtraceback\"\"\"\n            nonlocal tb_data\n            exc_tuple = ip._get_exc_info()\n\n            # do not display trace on syntax error\n            tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]\n\n            # determine correct tb_offset\n            compiled = tb_data.get(\"running_compiled_code\", False)\n            tb_offset = tb_data.get(\"tb_offset\")\n            if tb_offset is None:\n                tb_offset = 1 if compiled else 0\n            # remove ipython internal frames from trace with tb_offset\n            for _ in range(tb_offset):\n                if tb is None:\n                    break\n                tb = tb.tb_next\n\n            excepthook(exc_tuple[0], exc_tuple[1], tb)\n            tb_data = {}  # clear data upon usage\n\n        # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work\n        # this is also what the ipython docs recommends to modify when subclassing InteractiveShell\n        ip._showtraceback = ipy_display_traceback\n        # add wrapper to capture tb_data\n        ip.showtraceback = ipy_show_traceback\n        ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(\n            *args, is_syntax=True, **kwargs\n        )\n\n    try:  # pragma: no cover\n        # if within ipython, use customized traceback\n        ip = get_ipython()  # type: ignore[name-defined]\n        ipy_excepthook_closure(ip)\n        return sys.excepthook\n    except Exception:\n        # otherwise use default system hook\n        old_excepthook = sys.excepthook\n        sys.excepthook = excepthook\n        return old_excepthook\n\n\n@dataclass\nclass Frame:\n    filename: str\n    lineno: int\n    name: str\n    line: str = \"\"\n    locals: Optional[Dict[str, pretty.Node]] = None\n    last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]] = None\n\n\n@dataclass\nclass _SyntaxError:\n    offset: int\n    filename: str\n    line: str\n    lineno: int\n    msg: str\n    notes: List[str] = field(default_factory=list)\n\n\n@dataclass\nclass Stack:\n    exc_type: str\n    exc_value: str\n    syntax_error: Optional[_SyntaxError] = None\n    is_cause: bool = False\n    frames: List[Frame] = field(default_factory=list)\n    notes: List[str] = field(default_factory=list)\n    is_group: bool = False\n    exceptions: List[\"Trace\"] = field(default_factory=list)\n\n\n@dataclass\nclass Trace:\n    stacks: List[Stack]\n\n\nclass PathHighlighter(RegexHighlighter):\n    highlights = [r\"(?P<dim>.*/)(?P<bold>.+)\"]\n\n\nclass Traceback:\n    \"\"\"A Console renderable that renders a traceback.\n\n    Args:\n        trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses\n            the last exception.\n        width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.\n        code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.\n        extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n        theme (str, optional): Override pygments theme used in traceback.\n        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n        show_locals (bool, optional): Enable display of local variables. Defaults to False.\n        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to 10.\n        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n        locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n        locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n\n    \"\"\"\n\n    LEXERS = {\n        \"\": \"text\",\n        \".py\": \"python\",\n        \".pxd\": \"cython\",\n        \".pyx\": \"cython\",\n        \".pxi\": \"pyrex\",\n    }\n\n    def __init__(\n        self,\n        trace: Optional[Trace] = None,\n        *,\n        width: Optional[int] = 100,\n        code_width: Optional[int] = 88,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        locals_hide_dunder: bool = True,\n        locals_hide_sunder: bool = False,\n        indent_guides: bool = True,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ):\n        if trace is None:\n            exc_type, exc_value, traceback = sys.exc_info()\n            if exc_type is None or exc_value is None or traceback is None:\n                raise ValueError(\n                    \"Value for 'trace' required if not called in except: block\"\n                )\n            trace = self.extract(\n                exc_type, exc_value, traceback, show_locals=show_locals\n            )\n        self.trace = trace\n        self.width = width\n        self.code_width = code_width\n        self.extra_lines = extra_lines\n        self.theme = Syntax.get_theme(theme or \"ansi_dark\")\n        self.word_wrap = word_wrap\n        self.show_locals = show_locals\n        self.indent_guides = indent_guides\n        self.locals_max_length = locals_max_length\n        self.locals_max_string = locals_max_string\n        self.locals_hide_dunder = locals_hide_dunder\n        self.locals_hide_sunder = locals_hide_sunder\n\n        self.suppress: Sequence[str] = []\n        for suppress_entity in suppress:\n            if not isinstance(suppress_entity, str):\n                assert (\n                    suppress_entity.__file__ is not None\n                ), f\"{suppress_entity!r} must be a module with '__file__' attribute\"\n                path = os.path.dirname(suppress_entity.__file__)\n            else:\n                path = suppress_entity\n            path = os.path.normpath(os.path.abspath(path))\n            self.suppress.append(path)\n        self.max_frames = max(4, max_frames) if max_frames > 0 else 0\n\n    @classmethod\n    def from_exception(\n        cls,\n        exc_type: Type[Any],\n        exc_value: BaseException,\n        traceback: Optional[TracebackType],\n        *,\n        width: Optional[int] = 100,\n        code_width: Optional[int] = 88,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        locals_hide_dunder: bool = True,\n        locals_hide_sunder: bool = False,\n        indent_guides: bool = True,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ) -> \"Traceback\":\n        \"\"\"Create a traceback from exception info\n\n        Args:\n            exc_type (Type[BaseException]): Exception type.\n            exc_value (BaseException): Exception value.\n            traceback (TracebackType): Python Traceback object.\n            width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.\n            code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.\n            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n            theme (str, optional): Override pygments theme used in traceback.\n            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n                Defaults to 10.\n            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n            locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n            locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n\n        Returns:\n            Traceback: A Traceback instance that may be printed.\n        \"\"\"\n        rich_traceback = cls.extract(\n            exc_type,\n            exc_value,\n            traceback,\n            show_locals=show_locals,\n            locals_max_length=locals_max_length,\n            locals_max_string=locals_max_string,\n            locals_hide_dunder=locals_hide_dunder,\n            locals_hide_sunder=locals_hide_sunder,\n        )\n\n        return cls(\n            rich_traceback,\n            width=width,\n            code_width=code_width,\n            extra_lines=extra_lines,\n            theme=theme,\n            word_wrap=word_wrap,\n            show_locals=show_locals,\n            indent_guides=indent_guides,\n            locals_max_length=locals_max_length,\n            locals_max_string=locals_max_string,\n            locals_hide_dunder=locals_hide_dunder,\n            locals_hide_sunder=locals_hide_sunder,\n            suppress=suppress,\n            max_frames=max_frames,\n        )\n\n    @classmethod\n    def extract(\n        cls,\n        exc_type: Type[BaseException],\n        exc_value: BaseException,\n        traceback: Optional[TracebackType],\n        *,\n        show_locals: bool = False,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        locals_hide_dunder: bool = True,\n        locals_hide_sunder: bool = False,\n        _visited_exceptions: Optional[Set[BaseException]] = None,\n    ) -> Trace:\n        \"\"\"Extract traceback information.\n\n        Args:\n            exc_type (Type[BaseException]): Exception type.\n            exc_value (BaseException): Exception value.\n            traceback (TracebackType): Python Traceback object.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n                Defaults to 10.\n            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n            locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n            locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n\n        Returns:\n            Trace: A Trace instance which you can use to construct a `Traceback`.\n        \"\"\"\n\n        stacks: List[Stack] = []\n        is_cause = False\n\n        from pip._vendor.rich import _IMPORT_CWD\n\n        notes: List[str] = getattr(exc_value, \"__notes__\", None) or []\n\n        grouped_exceptions: Set[BaseException] = (\n            set() if _visited_exceptions is None else _visited_exceptions\n        )\n\n        def safe_str(_object: Any) -> str:\n            \"\"\"Don't allow exceptions from __str__ to propagate.\"\"\"\n            try:\n                return str(_object)\n            except Exception:\n                return \"<exception str() failed>\"\n\n        while True:\n            stack = Stack(\n                exc_type=safe_str(exc_type.__name__),\n                exc_value=safe_str(exc_value),\n                is_cause=is_cause,\n                notes=notes,\n            )\n\n            if sys.version_info >= (3, 11):\n                if isinstance(exc_value, (BaseExceptionGroup, ExceptionGroup)):\n                    stack.is_group = True\n                    for exception in exc_value.exceptions:\n                        if exception in grouped_exceptions:\n                            continue\n                        grouped_exceptions.add(exception)\n                        stack.exceptions.append(\n                            Traceback.extract(\n                                type(exception),\n                                exception,\n                                exception.__traceback__,\n                                show_locals=show_locals,\n                                locals_max_length=locals_max_length,\n                                locals_hide_dunder=locals_hide_dunder,\n                                locals_hide_sunder=locals_hide_sunder,\n                                _visited_exceptions=grouped_exceptions,\n                            )\n                        )\n\n            if isinstance(exc_value, SyntaxError):\n                stack.syntax_error = _SyntaxError(\n                    offset=exc_value.offset or 0,\n                    filename=exc_value.filename or \"?\",\n                    lineno=exc_value.lineno or 0,\n                    line=exc_value.text or \"\",\n                    msg=exc_value.msg,\n                    notes=notes,\n                )\n\n            stacks.append(stack)\n            append = stack.frames.append\n\n            def get_locals(\n                iter_locals: Iterable[Tuple[str, object]],\n            ) -> Iterable[Tuple[str, object]]:\n                \"\"\"Extract locals from an iterator of key pairs.\"\"\"\n                if not (locals_hide_dunder or locals_hide_sunder):\n                    yield from iter_locals\n                    return\n                for key, value in iter_locals:\n                    if locals_hide_dunder and key.startswith(\"__\"):\n                        continue\n                    if locals_hide_sunder and key.startswith(\"_\"):\n                        continue\n                    yield key, value\n\n            for frame_summary, line_no in walk_tb(traceback):\n                filename = frame_summary.f_code.co_filename\n\n                last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]]\n                last_instruction = None\n                if sys.version_info >= (3, 11):\n                    instruction_index = frame_summary.f_lasti // 2\n                    instruction_position = next(\n                        islice(\n                            frame_summary.f_code.co_positions(),\n                            instruction_index,\n                            instruction_index + 1,\n                        )\n                    )\n                    (\n                        start_line,\n                        end_line,\n                        start_column,\n                        end_column,\n                    ) = instruction_position\n                    if (\n                        start_line is not None\n                        and end_line is not None\n                        and start_column is not None\n                        and end_column is not None\n                    ):\n                        last_instruction = (\n                            (start_line, start_column),\n                            (end_line, end_column),\n                        )\n\n                if filename and not filename.startswith(\"<\"):\n                    if not os.path.isabs(filename):\n                        filename = os.path.join(_IMPORT_CWD, filename)\n                if frame_summary.f_locals.get(\"_rich_traceback_omit\", False):\n                    continue\n\n                frame = Frame(\n                    filename=filename or \"?\",\n                    lineno=line_no,\n                    name=frame_summary.f_code.co_name,\n                    locals=(\n                        {\n                            key: pretty.traverse(\n                                value,\n                                max_length=locals_max_length,\n                                max_string=locals_max_string,\n                            )\n                            for key, value in get_locals(frame_summary.f_locals.items())\n                            if not (inspect.isfunction(value) or inspect.isclass(value))\n                        }\n                        if show_locals\n                        else None\n                    ),\n                    last_instruction=last_instruction,\n                )\n                append(frame)\n                if frame_summary.f_locals.get(\"_rich_traceback_guard\", False):\n                    del stack.frames[:]\n\n            if not grouped_exceptions:\n                cause = getattr(exc_value, \"__cause__\", None)\n                if cause is not None and cause is not exc_value:\n                    exc_type = cause.__class__\n                    exc_value = cause\n                    # __traceback__ can be None, e.g. for exceptions raised by the\n                    # 'multiprocessing' module\n                    traceback = cause.__traceback__\n                    is_cause = True\n                    continue\n\n                cause = exc_value.__context__\n                if cause is not None and not getattr(\n                    exc_value, \"__suppress_context__\", False\n                ):\n                    exc_type = cause.__class__\n                    exc_value = cause\n                    traceback = cause.__traceback__\n                    is_cause = False\n                    continue\n            # No cover, code is reached but coverage doesn't recognize it.\n            break  # pragma: no cover\n\n        trace = Trace(stacks=stacks)\n\n        return trace\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        theme = self.theme\n        background_style = theme.get_background_style()\n        token_style = theme.get_style_for_token\n\n        traceback_theme = Theme(\n            {\n                \"pretty\": token_style(TextToken),\n                \"pygments.text\": token_style(Token),\n                \"pygments.string\": token_style(String),\n                \"pygments.function\": token_style(Name.Function),\n                \"pygments.number\": token_style(Number),\n                \"repr.indent\": token_style(Comment) + Style(dim=True),\n                \"repr.str\": token_style(String),\n                \"repr.brace\": token_style(TextToken) + Style(bold=True),\n                \"repr.number\": token_style(Number),\n                \"repr.bool_true\": token_style(Keyword.Constant),\n                \"repr.bool_false\": token_style(Keyword.Constant),\n                \"repr.none\": token_style(Keyword.Constant),\n                \"scope.border\": token_style(String.Delimiter),\n                \"scope.equals\": token_style(Operator),\n                \"scope.key\": token_style(Name),\n                \"scope.key.special\": token_style(Name.Constant) + Style(dim=True),\n            },\n            inherit=False,\n        )\n\n        highlighter = ReprHighlighter()\n\n        @group()\n        def render_stack(stack: Stack, last: bool) -> RenderResult:\n            if stack.frames:\n                stack_renderable: ConsoleRenderable = Panel(\n                    self._render_stack(stack),\n                    title=\"[traceback.title]Traceback [dim](most recent call last)\",\n                    style=background_style,\n                    border_style=\"traceback.border\",\n                    expand=True,\n                    padding=(0, 1),\n                )\n                stack_renderable = Constrain(stack_renderable, self.width)\n                with console.use_theme(traceback_theme):\n                    yield stack_renderable\n\n            if stack.syntax_error is not None:\n                with console.use_theme(traceback_theme):\n                    yield Constrain(\n                        Panel(\n                            self._render_syntax_error(stack.syntax_error),\n                            style=background_style,\n                            border_style=\"traceback.border.syntax_error\",\n                            expand=True,\n                            padding=(0, 1),\n                            width=self.width,\n                        ),\n                        self.width,\n                    )\n                yield Text.assemble(\n                    (f\"{stack.exc_type}: \", \"traceback.exc_type\"),\n                    highlighter(stack.syntax_error.msg),\n                )\n            elif stack.exc_value:\n                yield Text.assemble(\n                    (f\"{stack.exc_type}: \", \"traceback.exc_type\"),\n                    highlighter(stack.exc_value),\n                )\n            else:\n                yield Text.assemble((f\"{stack.exc_type}\", \"traceback.exc_type\"))\n\n            for note in stack.notes:\n                yield Text.assemble((\"[NOTE] \", \"traceback.note\"), highlighter(note))\n\n            if stack.is_group:\n                for group_no, group_exception in enumerate(stack.exceptions, 1):\n                    grouped_exceptions: List[Group] = []\n                    for group_last, group_stack in loop_last(group_exception.stacks):\n                        grouped_exceptions.append(render_stack(group_stack, group_last))\n                    yield \"\"\n                    yield Constrain(\n                        Panel(\n                            Group(*grouped_exceptions),\n                            title=f\"Sub-exception #{group_no}\",\n                            border_style=\"traceback.group.border\",\n                        ),\n                        self.width,\n                    )\n\n            if not last:\n                if stack.is_cause:\n                    yield Text.from_markup(\n                        \"\\n[i]The above exception was the direct cause of the following exception:\\n\",\n                    )\n                else:\n                    yield Text.from_markup(\n                        \"\\n[i]During handling of the above exception, another exception occurred:\\n\",\n                    )\n\n        for last, stack in loop_last(reversed(self.trace.stacks)):\n            yield render_stack(stack, last)\n\n    @group()\n    def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:\n        highlighter = ReprHighlighter()\n        path_highlighter = PathHighlighter()\n        if syntax_error.filename != \"<stdin>\":\n            if os.path.exists(syntax_error.filename):\n                text = Text.assemble(\n                    (f\" {syntax_error.filename}\", \"pygments.string\"),\n                    (\":\", \"pygments.text\"),\n                    (str(syntax_error.lineno), \"pygments.number\"),\n                    style=\"pygments.text\",\n                )\n                yield path_highlighter(text)\n        syntax_error_text = highlighter(syntax_error.line.rstrip())\n        syntax_error_text.no_wrap = True\n        offset = min(syntax_error.offset - 1, len(syntax_error_text))\n        syntax_error_text.stylize(\"bold underline\", offset, offset)\n        syntax_error_text += Text.from_markup(\n            \"\\n\" + \" \" * offset + \"[traceback.offset]▲[/]\",\n            style=\"pygments.text\",\n        )\n        yield syntax_error_text\n\n    @classmethod\n    def _guess_lexer(cls, filename: str, code: str) -> str:\n        ext = os.path.splitext(filename)[-1]\n        if not ext:\n            # No extension, look at first line to see if it is a hashbang\n            # Note, this is an educated guess and not a guarantee\n            # If it fails, the only downside is that the code is highlighted strangely\n            new_line_index = code.index(\"\\n\")\n            first_line = code[:new_line_index] if new_line_index != -1 else code\n            if first_line.startswith(\"#!\") and \"python\" in first_line.lower():\n                return \"python\"\n        try:\n            return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name\n        except ClassNotFound:\n            return \"text\"\n\n    @group()\n    def _render_stack(self, stack: Stack) -> RenderResult:\n        path_highlighter = PathHighlighter()\n        theme = self.theme\n\n        def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:\n            if frame.locals:\n                yield render_scope(\n                    frame.locals,\n                    title=\"locals\",\n                    indent_guides=self.indent_guides,\n                    max_length=self.locals_max_length,\n                    max_string=self.locals_max_string,\n                )\n\n        exclude_frames: Optional[range] = None\n        if self.max_frames != 0:\n            exclude_frames = range(\n                self.max_frames // 2,\n                len(stack.frames) - self.max_frames // 2,\n            )\n\n        excluded = False\n        for frame_index, frame in enumerate(stack.frames):\n            if exclude_frames and frame_index in exclude_frames:\n                excluded = True\n                continue\n\n            if excluded:\n                assert exclude_frames is not None\n                yield Text(\n                    f\"\\n... {len(exclude_frames)} frames hidden ...\",\n                    justify=\"center\",\n                    style=\"traceback.error\",\n                )\n                excluded = False\n\n            first = frame_index == 0\n            frame_filename = frame.filename\n            suppressed = any(frame_filename.startswith(path) for path in self.suppress)\n\n            if os.path.exists(frame.filename):\n                text = Text.assemble(\n                    path_highlighter(Text(frame.filename, style=\"pygments.string\")),\n                    (\":\", \"pygments.text\"),\n                    (str(frame.lineno), \"pygments.number\"),\n                    \" in \",\n                    (frame.name, \"pygments.function\"),\n                    style=\"pygments.text\",\n                )\n            else:\n                text = Text.assemble(\n                    \"in \",\n                    (frame.name, \"pygments.function\"),\n                    (\":\", \"pygments.text\"),\n                    (str(frame.lineno), \"pygments.number\"),\n                    style=\"pygments.text\",\n                )\n            if not frame.filename.startswith(\"<\") and not first:\n                yield \"\"\n            yield text\n            if frame.filename.startswith(\"<\"):\n                yield from render_locals(frame)\n                continue\n            if not suppressed:\n                try:\n                    code_lines = linecache.getlines(frame.filename)\n                    code = \"\".join(code_lines)\n                    if not code:\n                        # code may be an empty string if the file doesn't exist, OR\n                        # if the traceback filename is generated dynamically\n                        continue\n                    lexer_name = self._guess_lexer(frame.filename, code)\n                    syntax = Syntax(\n                        code,\n                        lexer_name,\n                        theme=theme,\n                        line_numbers=True,\n                        line_range=(\n                            frame.lineno - self.extra_lines,\n                            frame.lineno + self.extra_lines,\n                        ),\n                        highlight_lines={frame.lineno},\n                        word_wrap=self.word_wrap,\n                        code_width=self.code_width,\n                        indent_guides=self.indent_guides,\n                        dedent=False,\n                    )\n                    yield \"\"\n                except Exception as error:\n                    yield Text.assemble(\n                        (f\"\\n{error}\", \"traceback.error\"),\n                    )\n                else:\n                    if frame.last_instruction is not None:\n                        start, end = frame.last_instruction\n\n                        # Stylize a line at a time\n                        # So that indentation isn't underlined (which looks bad)\n                        for line1, column1, column2 in _iter_syntax_lines(start, end):\n                            try:\n                                if column1 == 0:\n                                    line = code_lines[line1 - 1]\n                                    column1 = len(line) - len(line.lstrip())\n                                if column2 == -1:\n                                    column2 = len(code_lines[line1 - 1])\n                            except IndexError:\n                                # Being defensive here\n                                # If last_instruction reports a line out-of-bounds, we don't want to crash\n                                continue\n\n                            syntax.stylize_range(\n                                style=\"traceback.error_range\",\n                                start=(line1, column1),\n                                end=(line1, column2),\n                            )\n                    yield (\n                        Columns(\n                            [\n                                syntax,\n                                *render_locals(frame),\n                            ],\n                            padding=1,\n                        )\n                        if frame.locals\n                        else syntax\n                    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    install(show_locals=True)\n    import sys\n\n    def bar(\n        a: Any,\n    ) -> None:  # 这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑\n        one = 1\n        print(one / a)\n\n    def foo(a: Any) -> None:\n        _rich_traceback_guard = True\n        zed = {\n            \"characters\": {\n                \"Paul Atreides\",\n                \"Vladimir Harkonnen\",\n                \"Thufir Hawat\",\n                \"Duncan Idaho\",\n            },\n            \"atomic_types\": (None, False, True),\n        }\n        bar(a)\n\n    def error() -> None:\n        foo(0)\n\n    error()\n"
  },
  {
    "path": "src/pip/_vendor/rich/tree.py",
    "content": "from typing import Iterator, List, Optional, Tuple\n\nfrom ._loop import loop_first, loop_last\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleStack, StyleType\nfrom .styled import Styled\n\nGuideType = Tuple[str, str, str, str]\n\n\nclass Tree(JupyterMixin):\n    \"\"\"A renderable for a tree structure.\n\n    Attributes:\n        ASCII_GUIDES (GuideType): Guide lines used when Console.ascii_only is True.\n        TREE_GUIDES (List[GuideType, GuideType, GuideType]): Default guide lines.\n\n    Args:\n        label (RenderableType): The renderable or str for the tree label.\n        style (StyleType, optional): Style of this tree. Defaults to \"tree\".\n        guide_style (StyleType, optional): Style of the guide lines. Defaults to \"tree.line\".\n        expanded (bool, optional): Also display children. Defaults to True.\n        highlight (bool, optional): Highlight renderable (if str). Defaults to False.\n        hide_root (bool, optional): Hide the root node. Defaults to False.\n    \"\"\"\n\n    ASCII_GUIDES = (\"    \", \"|   \", \"+-- \", \"`-- \")\n    TREE_GUIDES = [\n        (\"    \", \"│   \", \"├── \", \"└── \"),\n        (\"    \", \"┃   \", \"┣━━ \", \"┗━━ \"),\n        (\"    \", \"║   \", \"╠══ \", \"╚══ \"),\n    ]\n\n    def __init__(\n        self,\n        label: RenderableType,\n        *,\n        style: StyleType = \"tree\",\n        guide_style: StyleType = \"tree.line\",\n        expanded: bool = True,\n        highlight: bool = False,\n        hide_root: bool = False,\n    ) -> None:\n        self.label = label\n        self.style = style\n        self.guide_style = guide_style\n        self.children: List[Tree] = []\n        self.expanded = expanded\n        self.highlight = highlight\n        self.hide_root = hide_root\n\n    def add(\n        self,\n        label: RenderableType,\n        *,\n        style: Optional[StyleType] = None,\n        guide_style: Optional[StyleType] = None,\n        expanded: bool = True,\n        highlight: Optional[bool] = False,\n    ) -> \"Tree\":\n        \"\"\"Add a child tree.\n\n        Args:\n            label (RenderableType): The renderable or str for the tree label.\n            style (StyleType, optional): Style of this tree. Defaults to \"tree\".\n            guide_style (StyleType, optional): Style of the guide lines. Defaults to \"tree.line\".\n            expanded (bool, optional): Also display children. Defaults to True.\n            highlight (Optional[bool], optional): Highlight renderable (if str). Defaults to False.\n\n        Returns:\n            Tree: A new child Tree, which may be further modified.\n        \"\"\"\n        node = Tree(\n            label,\n            style=self.style if style is None else style,\n            guide_style=self.guide_style if guide_style is None else guide_style,\n            expanded=expanded,\n            highlight=self.highlight if highlight is None else highlight,\n        )\n        self.children.append(node)\n        return node\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        stack: List[Iterator[Tuple[bool, Tree]]] = []\n        pop = stack.pop\n        push = stack.append\n        new_line = Segment.line()\n\n        get_style = console.get_style\n        null_style = Style.null()\n        guide_style = get_style(self.guide_style, default=\"\") or null_style\n        SPACE, CONTINUE, FORK, END = range(4)\n\n        _Segment = Segment\n\n        def make_guide(index: int, style: Style) -> Segment:\n            \"\"\"Make a Segment for a level of the guide lines.\"\"\"\n            if options.ascii_only:\n                line = self.ASCII_GUIDES[index]\n            else:\n                guide = 1 if style.bold else (2 if style.underline2 else 0)\n                line = self.TREE_GUIDES[0 if options.legacy_windows else guide][index]\n            return _Segment(line, style)\n\n        levels: List[Segment] = [make_guide(CONTINUE, guide_style)]\n        push(iter(loop_last([self])))\n\n        guide_style_stack = StyleStack(get_style(self.guide_style))\n        style_stack = StyleStack(get_style(self.style))\n        remove_guide_styles = Style(bold=False, underline2=False)\n\n        depth = 0\n\n        while stack:\n            stack_node = pop()\n            try:\n                last, node = next(stack_node)\n            except StopIteration:\n                levels.pop()\n                if levels:\n                    guide_style = levels[-1].style or null_style\n                    levels[-1] = make_guide(FORK, guide_style)\n                    guide_style_stack.pop()\n                    style_stack.pop()\n                continue\n            push(stack_node)\n            if last:\n                levels[-1] = make_guide(END, levels[-1].style or null_style)\n\n            guide_style = guide_style_stack.current + get_style(node.guide_style)\n            style = style_stack.current + get_style(node.style)\n            prefix = levels[(2 if self.hide_root else 1) :]\n            renderable_lines = console.render_lines(\n                Styled(node.label, style),\n                options.update(\n                    width=options.max_width\n                    - sum(level.cell_length for level in prefix),\n                    highlight=self.highlight,\n                    height=None,\n                ),\n                pad=options.justify is not None,\n            )\n\n            if not (depth == 0 and self.hide_root):\n                for first, line in loop_first(renderable_lines):\n                    if prefix:\n                        yield from _Segment.apply_style(\n                            prefix,\n                            style.background_style,\n                            post_style=remove_guide_styles,\n                        )\n                    yield from line\n                    yield new_line\n                    if first and prefix:\n                        prefix[-1] = make_guide(\n                            SPACE if last else CONTINUE, prefix[-1].style or null_style\n                        )\n\n            if node.expanded and node.children:\n                levels[-1] = make_guide(\n                    SPACE if last else CONTINUE, levels[-1].style or null_style\n                )\n                levels.append(\n                    make_guide(END if len(node.children) == 1 else FORK, guide_style)\n                )\n                style_stack.push(get_style(node.style))\n                guide_style_stack.push(get_style(node.guide_style))\n                push(iter(loop_last(node.children)))\n                depth += 1\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        stack: List[Iterator[Tree]] = [iter([self])]\n        pop = stack.pop\n        push = stack.append\n        minimum = 0\n        maximum = 0\n        measure = Measurement.get\n        level = 0\n        while stack:\n            iter_tree = pop()\n            try:\n                tree = next(iter_tree)\n            except StopIteration:\n                level -= 1\n                continue\n            push(iter_tree)\n            min_measure, max_measure = measure(console, options, tree.label)\n            indent = level * 4\n            minimum = max(min_measure + indent, minimum)\n            maximum = max(max_measure + indent, maximum)\n            if tree.expanded and tree.children:\n                push(iter(tree.children))\n                level += 1\n        return Measurement(minimum, maximum)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Group\n    from pip._vendor.rich.markdown import Markdown\n    from pip._vendor.rich.panel import Panel\n    from pip._vendor.rich.syntax import Syntax\n    from pip._vendor.rich.table import Table\n\n    table = Table(row_styles=[\"\", \"dim\"])\n\n    table.add_column(\"Released\", style=\"cyan\", no_wrap=True)\n    table.add_column(\"Title\", style=\"magenta\")\n    table.add_column(\"Box Office\", justify=\"right\", style=\"green\")\n\n    table.add_row(\"Dec 20, 2019\", \"Star Wars: The Rise of Skywalker\", \"$952,110,690\")\n    table.add_row(\"May 25, 2018\", \"Solo: A Star Wars Story\", \"$393,151,347\")\n    table.add_row(\"Dec 15, 2017\", \"Star Wars Ep. V111: The Last Jedi\", \"$1,332,539,889\")\n    table.add_row(\"Dec 16, 2016\", \"Rogue One: A Star Wars Story\", \"$1,332,439,889\")\n\n    code = \"\"\"\\\nclass Segment(NamedTuple):\n    text: str = \"\"\n    style: Optional[Style] = None\n    is_control: bool = False\n\"\"\"\n    syntax = Syntax(code, \"python\", theme=\"monokai\", line_numbers=True)\n\n    markdown = Markdown(\n        \"\"\"\\\n### example.md\n> Hello, World!\n>\n> Markdown _all_ the things\n\"\"\"\n    )\n\n    root = Tree(\"🌲 [b green]Rich Tree\", highlight=True, hide_root=True)\n\n    node = root.add(\":file_folder: Renderables\", guide_style=\"red\")\n    simple_node = node.add(\":file_folder: [bold yellow]Atomic\", guide_style=\"uu green\")\n    simple_node.add(Group(\"📄 Syntax\", syntax))\n    simple_node.add(Group(\"📄 Markdown\", Panel(markdown, border_style=\"green\")))\n\n    containers_node = node.add(\n        \":file_folder: [bold magenta]Containers\", guide_style=\"bold magenta\"\n    )\n    containers_node.expanded = True\n    panel = Panel.fit(\"Just a panel\", border_style=\"red\")\n    containers_node.add(Group(\"📄 Panels\", panel))\n\n    containers_node.add(Group(\"📄 [b magenta]Table\", table))\n\n    console = Console()\n\n    console.print(root)\n"
  },
  {
    "path": "src/pip/_vendor/tomli/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Taneli Hukkinen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/tomli/__init__.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\n__all__ = (\"loads\", \"load\", \"TOMLDecodeError\")\n__version__ = \"2.3.0\"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom ._parser import TOMLDecodeError, load, loads\n"
  },
  {
    "path": "src/pip/_vendor/tomli/_parser.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nimport sys\nfrom types import MappingProxyType\n\nfrom ._re import (\n    RE_DATETIME,\n    RE_LOCALTIME,\n    RE_NUMBER,\n    match_to_datetime,\n    match_to_localtime,\n    match_to_number,\n)\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n    from collections.abc import Iterable\n    from typing import IO, Any, Final\n\n    from ._types import Key, ParseFloat, Pos\n\n# Inline tables/arrays are implemented using recursion. Pathologically\n# nested documents cause pure Python to raise RecursionError (which is OK),\n# but mypyc binary wheels will crash unrecoverably (not OK). According to\n# mypyc docs this will be fixed in the future:\n# https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows\n# Before mypyc's fix is in, recursion needs to be limited by this library.\n# Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting\n# level, as it allows more nesting than pure Python, but still seems a far\n# lower number than where mypyc binaries crash.\nMAX_INLINE_NESTING: Final = sys.getrecursionlimit()\n\nASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\n\n# Neither of these sets include quotation mark or backslash. They are\n# currently handled as separate cases in the parser functions.\nILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset(\"\\t\")\nILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset(\"\\t\\n\")\n\nILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS\nILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n\nILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS\n\nTOML_WS: Final = frozenset(\" \\t\")\nTOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset(\"\\n\")\nBARE_KEY_CHARS: Final = frozenset(\n    \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789\" \"-_\"\n)\nKEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset(\"\\\"'\")\nHEXDIGIT_CHARS: Final = frozenset(\"abcdef\" \"ABCDEF\" \"0123456789\")\n\nBASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(\n    {\n        \"\\\\b\": \"\\u0008\",  # backspace\n        \"\\\\t\": \"\\u0009\",  # tab\n        \"\\\\n\": \"\\u000a\",  # linefeed\n        \"\\\\f\": \"\\u000c\",  # form feed\n        \"\\\\r\": \"\\u000d\",  # carriage return\n        '\\\\\"': \"\\u0022\",  # quote\n        \"\\\\\\\\\": \"\\u005c\",  # backslash\n    }\n)\n\n\nclass DEPRECATED_DEFAULT:\n    \"\"\"Sentinel to be used as default arg during deprecation\n    period of TOMLDecodeError's free-form arguments.\"\"\"\n\n\nclass TOMLDecodeError(ValueError):\n    \"\"\"An error raised if a document is not valid TOML.\n\n    Adds the following attributes to ValueError:\n    msg: The unformatted error message\n    doc: The TOML document being parsed\n    pos: The index of doc where parsing failed\n    lineno: The line corresponding to pos\n    colno: The column corresponding to pos\n    \"\"\"\n\n    def __init__(\n        self,\n        msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n        doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n        pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n        *args: Any,\n    ):\n        if (\n            args\n            or not isinstance(msg, str)\n            or not isinstance(doc, str)\n            or not isinstance(pos, int)\n        ):\n            import warnings\n\n            warnings.warn(\n                \"Free-form arguments for TOMLDecodeError are deprecated. \"\n                \"Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n            if pos is not DEPRECATED_DEFAULT:\n                args = pos, *args\n            if doc is not DEPRECATED_DEFAULT:\n                args = doc, *args\n            if msg is not DEPRECATED_DEFAULT:\n                args = msg, *args\n            ValueError.__init__(self, *args)\n            return\n\n        lineno = doc.count(\"\\n\", 0, pos) + 1\n        if lineno == 1:\n            colno = pos + 1\n        else:\n            colno = pos - doc.rindex(\"\\n\", 0, pos)\n\n        if pos >= len(doc):\n            coord_repr = \"end of document\"\n        else:\n            coord_repr = f\"line {lineno}, column {colno}\"\n        errmsg = f\"{msg} (at {coord_repr})\"\n        ValueError.__init__(self, errmsg)\n\n        self.msg = msg\n        self.doc = doc\n        self.pos = pos\n        self.lineno = lineno\n        self.colno = colno\n\n\ndef load(__fp: IO[bytes], *, parse_float: ParseFloat = float) -> dict[str, Any]:\n    \"\"\"Parse TOML from a binary file object.\"\"\"\n    b = __fp.read()\n    try:\n        s = b.decode()\n    except AttributeError:\n        raise TypeError(\n            \"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`\"\n        ) from None\n    return loads(s, parse_float=parse_float)\n\n\ndef loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901\n    \"\"\"Parse TOML from a string.\"\"\"\n\n    # The spec allows converting \"\\r\\n\" to \"\\n\", even in string\n    # literals. Let's do so to simplify parsing.\n    try:\n        src = __s.replace(\"\\r\\n\", \"\\n\")\n    except (AttributeError, TypeError):\n        raise TypeError(\n            f\"Expected str object, not '{type(__s).__qualname__}'\"\n        ) from None\n    pos = 0\n    out = Output()\n    header: Key = ()\n    parse_float = make_safe_parse_float(parse_float)\n\n    # Parse one statement at a time\n    # (typically means one line in TOML source)\n    while True:\n        # 1. Skip line leading whitespace\n        pos = skip_chars(src, pos, TOML_WS)\n\n        # 2. Parse rules. Expect one of the following:\n        #    - end of file\n        #    - end of line\n        #    - comment\n        #    - key/value pair\n        #    - append dict to list (and move to its namespace)\n        #    - create dict (and move to its namespace)\n        # Skip trailing whitespace when applicable.\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char == \"\\n\":\n            pos += 1\n            continue\n        if char in KEY_INITIAL_CHARS:\n            pos = key_value_rule(src, pos, out, header, parse_float)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char == \"[\":\n            try:\n                second_char: str | None = src[pos + 1]\n            except IndexError:\n                second_char = None\n            out.flags.finalize_pending()\n            if second_char == \"[\":\n                pos, header = create_list_rule(src, pos, out)\n            else:\n                pos, header = create_dict_rule(src, pos, out)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char != \"#\":\n            raise TOMLDecodeError(\"Invalid statement\", src, pos)\n\n        # 3. Skip comment\n        pos = skip_comment(src, pos)\n\n        # 4. Expect end of line or end of file\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char != \"\\n\":\n            raise TOMLDecodeError(\n                \"Expected newline or end of document after a statement\", src, pos\n            )\n        pos += 1\n\n    return out.data.dict\n\n\nclass Flags:\n    \"\"\"Flags that map to parsed keys/namespaces.\"\"\"\n\n    # Marks an immutable namespace (inline array or inline table).\n    FROZEN: Final = 0\n    # Marks a nest that has been explicitly created and can no longer\n    # be opened using the \"[table]\" syntax.\n    EXPLICIT_NEST: Final = 1\n\n    def __init__(self) -> None:\n        self._flags: dict[str, dict[Any, Any]] = {}\n        self._pending_flags: set[tuple[Key, int]] = set()\n\n    def add_pending(self, key: Key, flag: int) -> None:\n        self._pending_flags.add((key, flag))\n\n    def finalize_pending(self) -> None:\n        for key, flag in self._pending_flags:\n            self.set(key, flag, recursive=False)\n        self._pending_flags.clear()\n\n    def unset_all(self, key: Key) -> None:\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return\n            cont = cont[k][\"nested\"]\n        cont.pop(key[-1], None)\n\n    def set(self, key: Key, flag: int, *, recursive: bool) -> None:  # noqa: A003\n        cont = self._flags\n        key_parent, key_stem = key[:-1], key[-1]\n        for k in key_parent:\n            if k not in cont:\n                cont[k] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n            cont = cont[k][\"nested\"]\n        if key_stem not in cont:\n            cont[key_stem] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n        cont[key_stem][\"recursive_flags\" if recursive else \"flags\"].add(flag)\n\n    def is_(self, key: Key, flag: int) -> bool:\n        if not key:\n            return False  # document root has no flags\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return False\n            inner_cont = cont[k]\n            if flag in inner_cont[\"recursive_flags\"]:\n                return True\n            cont = inner_cont[\"nested\"]\n        key_stem = key[-1]\n        if key_stem in cont:\n            inner_cont = cont[key_stem]\n            return flag in inner_cont[\"flags\"] or flag in inner_cont[\"recursive_flags\"]\n        return False\n\n\nclass NestedDict:\n    def __init__(self) -> None:\n        # The parsed content of the TOML document\n        self.dict: dict[str, Any] = {}\n\n    def get_or_create_nest(\n        self,\n        key: Key,\n        *,\n        access_lists: bool = True,\n    ) -> dict[str, Any]:\n        cont: Any = self.dict\n        for k in key:\n            if k not in cont:\n                cont[k] = {}\n            cont = cont[k]\n            if access_lists and isinstance(cont, list):\n                cont = cont[-1]\n            if not isinstance(cont, dict):\n                raise KeyError(\"There is no nest behind this key\")\n        return cont  # type: ignore[no-any-return]\n\n    def append_nest_to_list(self, key: Key) -> None:\n        cont = self.get_or_create_nest(key[:-1])\n        last_key = key[-1]\n        if last_key in cont:\n            list_ = cont[last_key]\n            if not isinstance(list_, list):\n                raise KeyError(\"An object other than list found behind this key\")\n            list_.append({})\n        else:\n            cont[last_key] = [{}]\n\n\nclass Output:\n    def __init__(self) -> None:\n        self.data = NestedDict()\n        self.flags = Flags()\n\n\ndef skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:\n    try:\n        while src[pos] in chars:\n            pos += 1\n    except IndexError:\n        pass\n    return pos\n\n\ndef skip_until(\n    src: str,\n    pos: Pos,\n    expect: str,\n    *,\n    error_on: frozenset[str],\n    error_on_eof: bool,\n) -> Pos:\n    try:\n        new_pos = src.index(expect, pos)\n    except ValueError:\n        new_pos = len(src)\n        if error_on_eof:\n            raise TOMLDecodeError(f\"Expected {expect!r}\", src, new_pos) from None\n\n    if not error_on.isdisjoint(src[pos:new_pos]):\n        while src[pos] not in error_on:\n            pos += 1\n        raise TOMLDecodeError(f\"Found invalid character {src[pos]!r}\", src, pos)\n    return new_pos\n\n\ndef skip_comment(src: str, pos: Pos) -> Pos:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char == \"#\":\n        return skip_until(\n            src, pos + 1, \"\\n\", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False\n        )\n    return pos\n\n\ndef skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:\n    while True:\n        pos_before_skip = pos\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        pos = skip_comment(src, pos)\n        if pos == pos_before_skip:\n            return pos\n\n\ndef create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 1  # Skip \"[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):\n        raise TOMLDecodeError(f\"Cannot declare {key} twice\", src, pos)\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.get_or_create_nest(key)\n    except KeyError:\n        raise TOMLDecodeError(\"Cannot overwrite a value\", src, pos) from None\n\n    if not src.startswith(\"]\", pos):\n        raise TOMLDecodeError(\n            \"Expected ']' at the end of a table declaration\", src, pos\n        )\n    return pos + 1, key\n\n\ndef create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 2  # Skip \"[[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.FROZEN):\n        raise TOMLDecodeError(f\"Cannot mutate immutable namespace {key}\", src, pos)\n    # Free the namespace now that it points to another empty list item...\n    out.flags.unset_all(key)\n    # ...but this key precisely is still prohibited from table declaration\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.append_nest_to_list(key)\n    except KeyError:\n        raise TOMLDecodeError(\"Cannot overwrite a value\", src, pos) from None\n\n    if not src.startswith(\"]]\", pos):\n        raise TOMLDecodeError(\n            \"Expected ']]' at the end of an array declaration\", src, pos\n        )\n    return pos + 2, key\n\n\ndef key_value_rule(\n    src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat\n) -> Pos:\n    pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl=0)\n    key_parent, key_stem = key[:-1], key[-1]\n    abs_key_parent = header + key_parent\n\n    relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))\n    for cont_key in relative_path_cont_keys:\n        # Check that dotted key syntax does not redefine an existing table\n        if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):\n            raise TOMLDecodeError(f\"Cannot redefine namespace {cont_key}\", src, pos)\n        # Containers in the relative path can't be opened with the table syntax or\n        # dotted key/value syntax in following table sections.\n        out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)\n\n    if out.flags.is_(abs_key_parent, Flags.FROZEN):\n        raise TOMLDecodeError(\n            f\"Cannot mutate immutable namespace {abs_key_parent}\", src, pos\n        )\n\n    try:\n        nest = out.data.get_or_create_nest(abs_key_parent)\n    except KeyError:\n        raise TOMLDecodeError(\"Cannot overwrite a value\", src, pos) from None\n    if key_stem in nest:\n        raise TOMLDecodeError(\"Cannot overwrite a value\", src, pos)\n    # Mark inline table and array namespaces recursively immutable\n    if isinstance(value, (dict, list)):\n        out.flags.set(header + key, Flags.FROZEN, recursive=True)\n    nest[key_stem] = value\n    return pos\n\n\ndef parse_key_value_pair(\n    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, Key, Any]:\n    pos, key = parse_key(src, pos)\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char != \"=\":\n        raise TOMLDecodeError(\"Expected '=' after a key in a key/value pair\", src, pos)\n    pos += 1\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, value = parse_value(src, pos, parse_float, nest_lvl)\n    return pos, key, value\n\n\ndef parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:\n    pos, key_part = parse_key_part(src, pos)\n    key: Key = (key_part,)\n    pos = skip_chars(src, pos, TOML_WS)\n    while True:\n        try:\n            char: str | None = src[pos]\n        except IndexError:\n            char = None\n        if char != \".\":\n            return pos, key\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n        pos, key_part = parse_key_part(src, pos)\n        key += (key_part,)\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char in BARE_KEY_CHARS:\n        start_pos = pos\n        pos = skip_chars(src, pos, BARE_KEY_CHARS)\n        return pos, src[start_pos:pos]\n    if char == \"'\":\n        return parse_literal_str(src, pos)\n    if char == '\"':\n        return parse_one_line_basic_str(src, pos)\n    raise TOMLDecodeError(\"Invalid initial character for a key part\", src, pos)\n\n\ndef parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1\n    return parse_basic_str(src, pos, multiline=False)\n\n\ndef parse_array(\n    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, list[Any]]:\n    pos += 1\n    array: list[Any] = []\n\n    pos = skip_comments_and_array_ws(src, pos)\n    if src.startswith(\"]\", pos):\n        return pos + 1, array\n    while True:\n        pos, val = parse_value(src, pos, parse_float, nest_lvl)\n        array.append(val)\n        pos = skip_comments_and_array_ws(src, pos)\n\n        c = src[pos : pos + 1]\n        if c == \"]\":\n            return pos + 1, array\n        if c != \",\":\n            raise TOMLDecodeError(\"Unclosed array\", src, pos)\n        pos += 1\n\n        pos = skip_comments_and_array_ws(src, pos)\n        if src.startswith(\"]\", pos):\n            return pos + 1, array\n\n\ndef parse_inline_table(\n    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, dict[str, Any]]:\n    pos += 1\n    nested_dict = NestedDict()\n    flags = Flags()\n\n    pos = skip_chars(src, pos, TOML_WS)\n    if src.startswith(\"}\", pos):\n        return pos + 1, nested_dict.dict\n    while True:\n        pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)\n        key_parent, key_stem = key[:-1], key[-1]\n        if flags.is_(key, Flags.FROZEN):\n            raise TOMLDecodeError(f\"Cannot mutate immutable namespace {key}\", src, pos)\n        try:\n            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)\n        except KeyError:\n            raise TOMLDecodeError(\"Cannot overwrite a value\", src, pos) from None\n        if key_stem in nest:\n            raise TOMLDecodeError(f\"Duplicate inline table key {key_stem!r}\", src, pos)\n        nest[key_stem] = value\n        pos = skip_chars(src, pos, TOML_WS)\n        c = src[pos : pos + 1]\n        if c == \"}\":\n            return pos + 1, nested_dict.dict\n        if c != \",\":\n            raise TOMLDecodeError(\"Unclosed inline table\", src, pos)\n        if isinstance(value, (dict, list)):\n            flags.set(key, Flags.FROZEN, recursive=True)\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_basic_str_escape(\n    src: str, pos: Pos, *, multiline: bool = False\n) -> tuple[Pos, str]:\n    escape_id = src[pos : pos + 2]\n    pos += 2\n    if multiline and escape_id in {\"\\\\ \", \"\\\\\\t\", \"\\\\\\n\"}:\n        # Skip whitespace until next non-whitespace character or end of\n        # the doc. Error if non-whitespace is found before newline.\n        if escape_id != \"\\\\\\n\":\n            pos = skip_chars(src, pos, TOML_WS)\n            try:\n                char = src[pos]\n            except IndexError:\n                return pos, \"\"\n            if char != \"\\n\":\n                raise TOMLDecodeError(\"Unescaped '\\\\' in a string\", src, pos)\n            pos += 1\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        return pos, \"\"\n    if escape_id == \"\\\\u\":\n        return parse_hex_char(src, pos, 4)\n    if escape_id == \"\\\\U\":\n        return parse_hex_char(src, pos, 8)\n    try:\n        return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]\n    except KeyError:\n        raise TOMLDecodeError(\"Unescaped '\\\\' in a string\", src, pos) from None\n\n\ndef parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:\n    return parse_basic_str_escape(src, pos, multiline=True)\n\n\ndef parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:\n    hex_str = src[pos : pos + hex_len]\n    if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):\n        raise TOMLDecodeError(\"Invalid hex value\", src, pos)\n    pos += hex_len\n    hex_int = int(hex_str, 16)\n    if not is_unicode_scalar_value(hex_int):\n        raise TOMLDecodeError(\n            \"Escaped character is not a Unicode scalar value\", src, pos\n        )\n    return pos, chr(hex_int)\n\n\ndef parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1  # Skip starting apostrophe\n    start_pos = pos\n    pos = skip_until(\n        src, pos, \"'\", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True\n    )\n    return pos + 1, src[start_pos:pos]  # Skip ending apostrophe\n\n\ndef parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:\n    pos += 3\n    if src.startswith(\"\\n\", pos):\n        pos += 1\n\n    if literal:\n        delim = \"'\"\n        end_pos = skip_until(\n            src,\n            pos,\n            \"'''\",\n            error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,\n            error_on_eof=True,\n        )\n        result = src[pos:end_pos]\n        pos = end_pos + 3\n    else:\n        delim = '\"'\n        pos, result = parse_basic_str(src, pos, multiline=True)\n\n    # Add at maximum two extra apostrophes/quotes if the end sequence\n    # is 4 or 5 chars long instead of just 3.\n    if not src.startswith(delim, pos):\n        return pos, result\n    pos += 1\n    if not src.startswith(delim, pos):\n        return pos, result + delim\n    pos += 1\n    return pos, result + (delim * 2)\n\n\ndef parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:\n    if multiline:\n        error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape_multiline\n    else:\n        error_on = ILLEGAL_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape\n    result = \"\"\n    start_pos = pos\n    while True:\n        try:\n            char = src[pos]\n        except IndexError:\n            raise TOMLDecodeError(\"Unterminated string\", src, pos) from None\n        if char == '\"':\n            if not multiline:\n                return pos + 1, result + src[start_pos:pos]\n            if src.startswith('\"\"\"', pos):\n                return pos + 3, result + src[start_pos:pos]\n            pos += 1\n            continue\n        if char == \"\\\\\":\n            result += src[start_pos:pos]\n            pos, parsed_escape = parse_escapes(src, pos)\n            result += parsed_escape\n            start_pos = pos\n            continue\n        if char in error_on:\n            raise TOMLDecodeError(f\"Illegal character {char!r}\", src, pos)\n        pos += 1\n\n\ndef parse_value(  # noqa: C901\n    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, Any]:\n    if nest_lvl > MAX_INLINE_NESTING:\n        # Pure Python should have raised RecursionError already.\n        # This ensures mypyc binaries eventually do the same.\n        raise RecursionError(  # pragma: no cover\n            \"TOML inline arrays/tables are nested more than the allowed\"\n            f\" {MAX_INLINE_NESTING} levels\"\n        )\n\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n\n    # IMPORTANT: order conditions based on speed of checking and likelihood\n\n    # Basic strings\n    if char == '\"':\n        if src.startswith('\"\"\"', pos):\n            return parse_multiline_str(src, pos, literal=False)\n        return parse_one_line_basic_str(src, pos)\n\n    # Literal strings\n    if char == \"'\":\n        if src.startswith(\"'''\", pos):\n            return parse_multiline_str(src, pos, literal=True)\n        return parse_literal_str(src, pos)\n\n    # Booleans\n    if char == \"t\":\n        if src.startswith(\"true\", pos):\n            return pos + 4, True\n    if char == \"f\":\n        if src.startswith(\"false\", pos):\n            return pos + 5, False\n\n    # Arrays\n    if char == \"[\":\n        return parse_array(src, pos, parse_float, nest_lvl + 1)\n\n    # Inline tables\n    if char == \"{\":\n        return parse_inline_table(src, pos, parse_float, nest_lvl + 1)\n\n    # Dates and times\n    datetime_match = RE_DATETIME.match(src, pos)\n    if datetime_match:\n        try:\n            datetime_obj = match_to_datetime(datetime_match)\n        except ValueError as e:\n            raise TOMLDecodeError(\"Invalid date or datetime\", src, pos) from e\n        return datetime_match.end(), datetime_obj\n    localtime_match = RE_LOCALTIME.match(src, pos)\n    if localtime_match:\n        return localtime_match.end(), match_to_localtime(localtime_match)\n\n    # Integers and \"normal\" floats.\n    # The regex will greedily match any type starting with a decimal\n    # char, so needs to be located after handling of dates and times.\n    number_match = RE_NUMBER.match(src, pos)\n    if number_match:\n        return number_match.end(), match_to_number(number_match, parse_float)\n\n    # Special floats\n    first_three = src[pos : pos + 3]\n    if first_three in {\"inf\", \"nan\"}:\n        return pos + 3, parse_float(first_three)\n    first_four = src[pos : pos + 4]\n    if first_four in {\"-inf\", \"+inf\", \"-nan\", \"+nan\"}:\n        return pos + 4, parse_float(first_four)\n\n    raise TOMLDecodeError(\"Invalid value\", src, pos)\n\n\ndef is_unicode_scalar_value(codepoint: int) -> bool:\n    return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)\n\n\ndef make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:\n    \"\"\"A decorator to make `parse_float` safe.\n\n    `parse_float` must not return dicts or lists, because these types\n    would be mixed with parsed TOML tables and arrays, thus confusing\n    the parser. The returned decorated callable raises `ValueError`\n    instead of returning illegal types.\n    \"\"\"\n    # The default `float` callable never returns illegal types. Optimize it.\n    if parse_float is float:\n        return float\n\n    def safe_parse_float(float_str: str) -> Any:\n        float_value = parse_float(float_str)\n        if isinstance(float_value, (dict, list)):\n            raise ValueError(\"parse_float must not return dicts or lists\")\n        return float_value\n\n    return safe_parse_float\n"
  },
  {
    "path": "src/pip/_vendor/tomli/_re.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom datetime import date, datetime, time, timedelta, timezone, tzinfo\nfrom functools import lru_cache\nimport re\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n    from typing import Any, Final\n\n    from ._types import ParseFloat\n\n# E.g.\n# - 00:32:00.999999\n# - 00:32:00\n_TIME_RE_STR: Final = (\n    r\"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\\.([0-9]{1,6})[0-9]*)?\"\n)\n\nRE_NUMBER: Final = re.compile(\n    r\"\"\"\n0\n(?:\n    x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*   # hex\n    |\n    b[01](?:_?[01])*                 # bin\n    |\n    o[0-7](?:_?[0-7])*               # oct\n)\n|\n[+-]?(?:0|[1-9](?:_?[0-9])*)         # dec, integer part\n(?P<floatpart>\n    (?:\\.[0-9](?:_?[0-9])*)?         # optional fractional part\n    (?:[eE][+-]?[0-9](?:_?[0-9])*)?  # optional exponent part\n)\n\"\"\",\n    flags=re.VERBOSE,\n)\nRE_LOCALTIME: Final = re.compile(_TIME_RE_STR)\nRE_DATETIME: Final = re.compile(\n    rf\"\"\"\n([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27\n(?:\n    [Tt ]\n    {_TIME_RE_STR}\n    (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))?  # optional time offset\n)?\n\"\"\",\n    flags=re.VERBOSE,\n)\n\n\ndef match_to_datetime(match: re.Match[str]) -> datetime | date:\n    \"\"\"Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.\n\n    Raises ValueError if the match does not correspond to a valid date\n    or datetime.\n    \"\"\"\n    (\n        year_str,\n        month_str,\n        day_str,\n        hour_str,\n        minute_str,\n        sec_str,\n        micros_str,\n        zulu_time,\n        offset_sign_str,\n        offset_hour_str,\n        offset_minute_str,\n    ) = match.groups()\n    year, month, day = int(year_str), int(month_str), int(day_str)\n    if hour_str is None:\n        return date(year, month, day)\n    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    if offset_sign_str:\n        tz: tzinfo | None = cached_tz(\n            offset_hour_str, offset_minute_str, offset_sign_str\n        )\n    elif zulu_time:\n        tz = timezone.utc\n    else:  # local date-time\n        tz = None\n    return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)\n\n\n# No need to limit cache size. This is only ever called on input\n# that matched RE_DATETIME, so there is an implicit bound of\n# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.\n@lru_cache(maxsize=None)\ndef cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:\n    sign = 1 if sign_str == \"+\" else -1\n    return timezone(\n        timedelta(\n            hours=sign * int(hour_str),\n            minutes=sign * int(minute_str),\n        )\n    )\n\n\ndef match_to_localtime(match: re.Match[str]) -> time:\n    hour_str, minute_str, sec_str, micros_str = match.groups()\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    return time(int(hour_str), int(minute_str), int(sec_str), micros)\n\n\ndef match_to_number(match: re.Match[str], parse_float: ParseFloat) -> Any:\n    if match.group(\"floatpart\"):\n        return parse_float(match.group())\n    return int(match.group(), 0)\n"
  },
  {
    "path": "src/pip/_vendor/tomli/_types.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom typing import Any, Callable, Tuple\n\n# Type annotations\nParseFloat = Callable[[str], Any]\nKey = Tuple[str, ...]\nPos = int\n"
  },
  {
    "path": "src/pip/_vendor/tomli/py.typed",
    "content": "# Marker file for PEP 561\n"
  },
  {
    "path": "src/pip/_vendor/tomli_w/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Taneli Hukkinen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/tomli_w/__init__.py",
    "content": "__all__ = (\"dumps\", \"dump\")\n__version__ = \"1.2.0\"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom pip._vendor.tomli_w._writer import dump, dumps\n"
  },
  {
    "path": "src/pip/_vendor/tomli_w/_writer.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom datetime import date, datetime, time\nfrom types import MappingProxyType\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n    from collections.abc import Generator\n    from decimal import Decimal\n    from typing import IO, Any, Final\n\nASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\nILLEGAL_BASIC_STR_CHARS = frozenset('\"\\\\') | ASCII_CTRL - frozenset(\"\\t\")\nBARE_KEY_CHARS = frozenset(\n    \"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"0123456789\" \"-_\"\n)\nARRAY_TYPES = (list, tuple)\nMAX_LINE_LENGTH = 100\n\nCOMPACT_ESCAPES = MappingProxyType(\n    {\n        \"\\u0008\": \"\\\\b\",  # backspace\n        \"\\u000A\": \"\\\\n\",  # linefeed\n        \"\\u000C\": \"\\\\f\",  # form feed\n        \"\\u000D\": \"\\\\r\",  # carriage return\n        \"\\u0022\": '\\\\\"',  # quote\n        \"\\u005C\": \"\\\\\\\\\",  # backslash\n    }\n)\n\n\nclass Context:\n    def __init__(self, allow_multiline: bool, indent: int):\n        if indent < 0:\n            raise ValueError(\"Indent width must be non-negative\")\n        self.allow_multiline: Final = allow_multiline\n        # cache rendered inline tables (mapping from object id to rendered inline table)\n        self.inline_table_cache: Final[dict[int, str]] = {}\n        self.indent_str: Final = \" \" * indent\n\n\ndef dump(\n    obj: Mapping[str, Any],\n    fp: IO[bytes],\n    /,\n    *,\n    multiline_strings: bool = False,\n    indent: int = 4,\n) -> None:\n    ctx = Context(multiline_strings, indent)\n    for chunk in gen_table_chunks(obj, ctx, name=\"\"):\n        fp.write(chunk.encode())\n\n\ndef dumps(\n    obj: Mapping[str, Any], /, *, multiline_strings: bool = False, indent: int = 4\n) -> str:\n    ctx = Context(multiline_strings, indent)\n    return \"\".join(gen_table_chunks(obj, ctx, name=\"\"))\n\n\ndef gen_table_chunks(\n    table: Mapping[str, Any],\n    ctx: Context,\n    *,\n    name: str,\n    inside_aot: bool = False,\n) -> Generator[str, None, None]:\n    yielded = False\n    literals = []\n    tables: list[tuple[str, Any, bool]] = []  # => [(key, value, inside_aot)]\n    for k, v in table.items():\n        if isinstance(v, Mapping):\n            tables.append((k, v, False))\n        elif is_aot(v) and not all(is_suitable_inline_table(t, ctx) for t in v):\n            tables.extend((k, t, True) for t in v)\n        else:\n            literals.append((k, v))\n\n    if inside_aot or name and (literals or not tables):\n        yielded = True\n        yield f\"[[{name}]]\\n\" if inside_aot else f\"[{name}]\\n\"\n\n    if literals:\n        yielded = True\n        for k, v in literals:\n            yield f\"{format_key_part(k)} = {format_literal(v, ctx)}\\n\"\n\n    for k, v, in_aot in tables:\n        if yielded:\n            yield \"\\n\"\n        else:\n            yielded = True\n        key_part = format_key_part(k)\n        display_name = f\"{name}.{key_part}\" if name else key_part\n        yield from gen_table_chunks(v, ctx, name=display_name, inside_aot=in_aot)\n\n\ndef format_literal(obj: object, ctx: Context, *, nest_level: int = 0) -> str:\n    if isinstance(obj, bool):\n        return \"true\" if obj else \"false\"\n    if isinstance(obj, (int, float, date, datetime)):\n        return str(obj)\n    if isinstance(obj, time):\n        if obj.tzinfo:\n            raise ValueError(\"TOML does not support offset times\")\n        return str(obj)\n    if isinstance(obj, str):\n        return format_string(obj, allow_multiline=ctx.allow_multiline)\n    if isinstance(obj, ARRAY_TYPES):\n        return format_inline_array(obj, ctx, nest_level)\n    if isinstance(obj, Mapping):\n        return format_inline_table(obj, ctx)\n\n    # Lazy import to improve module import time\n    from decimal import Decimal\n\n    if isinstance(obj, Decimal):\n        return format_decimal(obj)\n    raise TypeError(\n        f\"Object of type '{type(obj).__qualname__}' is not TOML serializable\"\n    )\n\n\ndef format_decimal(obj: Decimal) -> str:\n    if obj.is_nan():\n        return \"nan\"\n    if obj.is_infinite():\n        return \"-inf\" if obj.is_signed() else \"inf\"\n    dec_str = str(obj).lower()\n    return dec_str if \".\" in dec_str or \"e\" in dec_str else dec_str + \".0\"\n\n\ndef format_inline_table(obj: Mapping, ctx: Context) -> str:\n    # check cache first\n    obj_id = id(obj)\n    if obj_id in ctx.inline_table_cache:\n        return ctx.inline_table_cache[obj_id]\n\n    if not obj:\n        rendered = \"{}\"\n    else:\n        rendered = (\n            \"{ \"\n            + \", \".join(\n                f\"{format_key_part(k)} = {format_literal(v, ctx)}\"\n                for k, v in obj.items()\n            )\n            + \" }\"\n        )\n    ctx.inline_table_cache[obj_id] = rendered\n    return rendered\n\n\ndef format_inline_array(obj: tuple | list, ctx: Context, nest_level: int) -> str:\n    if not obj:\n        return \"[]\"\n    item_indent = ctx.indent_str * (1 + nest_level)\n    closing_bracket_indent = ctx.indent_str * nest_level\n    return (\n        \"[\\n\"\n        + \",\\n\".join(\n            item_indent + format_literal(item, ctx, nest_level=nest_level + 1)\n            for item in obj\n        )\n        + f\",\\n{closing_bracket_indent}]\"\n    )\n\n\ndef format_key_part(part: str) -> str:\n    try:\n        only_bare_key_chars = BARE_KEY_CHARS.issuperset(part)\n    except TypeError:\n        raise TypeError(\n            f\"Invalid mapping key '{part}' of type '{type(part).__qualname__}'.\"\n            \" A string is required.\"\n        ) from None\n\n    if part and only_bare_key_chars:\n        return part\n    return format_string(part, allow_multiline=False)\n\n\ndef format_string(s: str, *, allow_multiline: bool) -> str:\n    do_multiline = allow_multiline and \"\\n\" in s\n    if do_multiline:\n        result = '\"\"\"\\n'\n        s = s.replace(\"\\r\\n\", \"\\n\")\n    else:\n        result = '\"'\n\n    pos = seq_start = 0\n    while True:\n        try:\n            char = s[pos]\n        except IndexError:\n            result += s[seq_start:pos]\n            if do_multiline:\n                return result + '\"\"\"'\n            return result + '\"'\n        if char in ILLEGAL_BASIC_STR_CHARS:\n            result += s[seq_start:pos]\n            if char in COMPACT_ESCAPES:\n                if do_multiline and char == \"\\n\":\n                    result += \"\\n\"\n                else:\n                    result += COMPACT_ESCAPES[char]\n            else:\n                result += \"\\\\u\" + hex(ord(char))[2:].rjust(4, \"0\")\n            seq_start = pos + 1\n        pos += 1\n\n\ndef is_aot(obj: Any) -> bool:\n    \"\"\"Decides if an object behaves as an array of tables (i.e. a nonempty list\n    of dicts).\"\"\"\n    return bool(\n        isinstance(obj, ARRAY_TYPES)\n        and obj\n        and all(isinstance(v, Mapping) for v in obj)\n    )\n\n\ndef is_suitable_inline_table(obj: Mapping, ctx: Context) -> bool:\n    \"\"\"Use heuristics to decide if the inline-style representation is a good\n    choice for a given table.\"\"\"\n    rendered_inline = f\"{ctx.indent_str}{format_inline_table(obj, ctx)},\"\n    return len(rendered_inline) <= MAX_LINE_LENGTH and \"\\n\" not in rendered_inline\n"
  },
  {
    "path": "src/pip/_vendor/tomli_w/py.typed",
    "content": "# Marker file for PEP 561\n"
  },
  {
    "path": "src/pip/_vendor/truststore/LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2022 Seth Michael Larson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/truststore/__init__.py",
    "content": "\"\"\"Verify certificates using native system trust stores\"\"\"\n\nimport sys as _sys\n\nif _sys.version_info < (3, 10):\n    raise ImportError(\"truststore requires Python 3.10 or later\")\n\n# Detect Python runtimes which don't implement SSLObject.get_unverified_chain() API\n# This API only became public in Python 3.13 but was available in CPython and PyPy since 3.10.\nif _sys.version_info < (3, 13) and _sys.implementation.name not in (\"cpython\", \"pypy\"):\n    try:\n        import ssl as _ssl\n    except ImportError:\n        raise ImportError(\"truststore requires the 'ssl' module\")\n    else:\n        _sslmem = _ssl.MemoryBIO()\n        _sslobj = _ssl.create_default_context().wrap_bio(\n            _sslmem,\n            _sslmem,\n        )\n        try:\n            while not hasattr(_sslobj, \"get_unverified_chain\"):\n                _sslobj = _sslobj._sslobj  # type: ignore[attr-defined]\n        except AttributeError:\n            raise ImportError(\n                \"truststore requires peer certificate chain APIs to be available\"\n            ) from None\n\n        del _ssl, _sslobj, _sslmem  # noqa: F821\n\nfrom ._api import SSLContext, extract_from_ssl, inject_into_ssl  # noqa: E402\n\ndel _api, _sys  # type: ignore[name-defined] # noqa: F821\n\n__all__ = [\"SSLContext\", \"inject_into_ssl\", \"extract_from_ssl\"]\n__version__ = \"0.10.4\"\n"
  },
  {
    "path": "src/pip/_vendor/truststore/_api.py",
    "content": "import contextlib\nimport os\nimport platform\nimport socket\nimport ssl\nimport sys\nimport threading\nimport typing\n\nimport _ssl\n\nfrom ._ssl_constants import (\n    _original_SSLContext,\n    _original_super_SSLContext,\n    _truststore_SSLContext_dunder_class,\n    _truststore_SSLContext_super_class,\n)\n\nif platform.system() == \"Windows\":\n    from ._windows import _configure_context, _verify_peercerts_impl\nelif platform.system() == \"Darwin\":\n    from ._macos import _configure_context, _verify_peercerts_impl\nelse:\n    from ._openssl import _configure_context, _verify_peercerts_impl\n\nif typing.TYPE_CHECKING:\n    from typing_extensions import Buffer\n\n# From typeshed/stdlib/ssl.pyi\n_StrOrBytesPath: typing.TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes]\n_PasswordType: typing.TypeAlias = str | bytes | typing.Callable[[], str | bytes]\n\n\ndef inject_into_ssl() -> None:\n    \"\"\"Injects the :class:`truststore.SSLContext` into the ``ssl``\n    module by replacing :class:`ssl.SSLContext`.\n    \"\"\"\n    setattr(ssl, \"SSLContext\", SSLContext)\n    # urllib3 holds on to its own reference of ssl.SSLContext\n    # so we need to replace that reference too.\n    try:\n        import pip._vendor.urllib3.util.ssl_ as urllib3_ssl\n\n        setattr(urllib3_ssl, \"SSLContext\", SSLContext)\n    except ImportError:\n        pass\n\n    # requests starting with 2.32.0 added a preloaded SSL context to improve concurrent performance;\n    # this unfortunately leads to a RecursionError, which can be avoided by patching the preloaded SSL context with\n    # the truststore patched instance\n    # also see https://github.com/psf/requests/pull/6667\n    try:\n        from pip._vendor.requests import adapters as requests_adapters\n\n        preloaded_context = getattr(requests_adapters, \"_preloaded_ssl_context\", None)\n        if preloaded_context is not None:\n            setattr(\n                requests_adapters,\n                \"_preloaded_ssl_context\",\n                SSLContext(ssl.PROTOCOL_TLS_CLIENT),\n            )\n    except ImportError:\n        pass\n\n\ndef extract_from_ssl() -> None:\n    \"\"\"Restores the :class:`ssl.SSLContext` class to its original state\"\"\"\n    setattr(ssl, \"SSLContext\", _original_SSLContext)\n    try:\n        import pip._vendor.urllib3.util.ssl_ as urllib3_ssl\n\n        urllib3_ssl.SSLContext = _original_SSLContext\n    except ImportError:\n        pass\n\n\nclass SSLContext(_truststore_SSLContext_super_class):  # type: ignore[misc]\n    \"\"\"SSLContext API that uses system certificates on all platforms\"\"\"\n\n    @property  # type: ignore[misc]\n    def __class__(self) -> type:\n        # Dirty hack to get around isinstance() checks\n        # for ssl.SSLContext instances in aiohttp/trustme\n        # when using non-CPython implementations.\n        return _truststore_SSLContext_dunder_class or SSLContext\n\n    def __init__(self, protocol: int = None) -> None:  # type: ignore[assignment]\n        self._ctx = _original_SSLContext(protocol)\n        self._ctx_lock = threading.Lock()\n\n        class TruststoreSSLObject(ssl.SSLObject):\n            # This object exists because wrap_bio() doesn't\n            # immediately do the handshake so we need to do\n            # certificate verifications after SSLObject.do_handshake()\n\n            def do_handshake(self) -> None:\n                ret = super().do_handshake()\n                _verify_peercerts(self, server_hostname=self.server_hostname)\n                return ret\n\n        self._ctx.sslobject_class = TruststoreSSLObject\n\n    def wrap_socket(\n        self,\n        sock: socket.socket,\n        server_side: bool = False,\n        do_handshake_on_connect: bool = True,\n        suppress_ragged_eofs: bool = True,\n        server_hostname: str | None = None,\n        session: ssl.SSLSession | None = None,\n    ) -> ssl.SSLSocket:\n\n        # We need to lock around the .__enter__()\n        # but we don't need to lock within the\n        # context manager, so we need to expand the\n        # syntactic sugar of the `with` statement.\n        with contextlib.ExitStack() as stack:\n            with self._ctx_lock:\n                stack.enter_context(_configure_context(self._ctx))\n\n            ssl_sock = self._ctx.wrap_socket(\n                sock,\n                server_side=server_side,\n                server_hostname=server_hostname,\n                do_handshake_on_connect=do_handshake_on_connect,\n                suppress_ragged_eofs=suppress_ragged_eofs,\n                session=session,\n            )\n        try:\n            _verify_peercerts(ssl_sock, server_hostname=server_hostname)\n        except Exception:\n            ssl_sock.close()\n            raise\n        return ssl_sock\n\n    def wrap_bio(\n        self,\n        incoming: ssl.MemoryBIO,\n        outgoing: ssl.MemoryBIO,\n        server_side: bool = False,\n        server_hostname: str | None = None,\n        session: ssl.SSLSession | None = None,\n    ) -> ssl.SSLObject:\n        with _configure_context(self._ctx):\n            ssl_obj = self._ctx.wrap_bio(\n                incoming,\n                outgoing,\n                server_hostname=server_hostname,\n                server_side=server_side,\n                session=session,\n            )\n        return ssl_obj\n\n    def load_verify_locations(\n        self,\n        cafile: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,\n        capath: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,\n        cadata: typing.Union[str, \"Buffer\", None] = None,\n    ) -> None:\n        return self._ctx.load_verify_locations(\n            cafile=cafile, capath=capath, cadata=cadata\n        )\n\n    def load_cert_chain(\n        self,\n        certfile: _StrOrBytesPath,\n        keyfile: _StrOrBytesPath | None = None,\n        password: _PasswordType | None = None,\n    ) -> None:\n        return self._ctx.load_cert_chain(\n            certfile=certfile, keyfile=keyfile, password=password\n        )\n\n    def load_default_certs(\n        self, purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH\n    ) -> None:\n        return self._ctx.load_default_certs(purpose)\n\n    def set_alpn_protocols(self, alpn_protocols: typing.Iterable[str]) -> None:\n        return self._ctx.set_alpn_protocols(alpn_protocols)\n\n    def set_npn_protocols(self, npn_protocols: typing.Iterable[str]) -> None:\n        return self._ctx.set_npn_protocols(npn_protocols)\n\n    def set_ciphers(self, __cipherlist: str) -> None:\n        return self._ctx.set_ciphers(__cipherlist)\n\n    def get_ciphers(self) -> typing.Any:\n        return self._ctx.get_ciphers()\n\n    def session_stats(self) -> dict[str, int]:\n        return self._ctx.session_stats()\n\n    def cert_store_stats(self) -> dict[str, int]:\n        raise NotImplementedError()\n\n    def set_default_verify_paths(self) -> None:\n        self._ctx.set_default_verify_paths()\n\n    @typing.overload\n    def get_ca_certs(\n        self, binary_form: typing.Literal[False] = ...\n    ) -> list[typing.Any]: ...\n\n    @typing.overload\n    def get_ca_certs(self, binary_form: typing.Literal[True] = ...) -> list[bytes]: ...\n\n    @typing.overload\n    def get_ca_certs(self, binary_form: bool = ...) -> typing.Any: ...\n\n    def get_ca_certs(self, binary_form: bool = False) -> list[typing.Any] | list[bytes]:\n        raise NotImplementedError()\n\n    @property\n    def check_hostname(self) -> bool:\n        return self._ctx.check_hostname\n\n    @check_hostname.setter\n    def check_hostname(self, value: bool) -> None:\n        self._ctx.check_hostname = value\n\n    @property\n    def hostname_checks_common_name(self) -> bool:\n        return self._ctx.hostname_checks_common_name\n\n    @hostname_checks_common_name.setter\n    def hostname_checks_common_name(self, value: bool) -> None:\n        self._ctx.hostname_checks_common_name = value\n\n    @property\n    def keylog_filename(self) -> str:\n        return self._ctx.keylog_filename\n\n    @keylog_filename.setter\n    def keylog_filename(self, value: str) -> None:\n        self._ctx.keylog_filename = value\n\n    @property\n    def maximum_version(self) -> ssl.TLSVersion:\n        return self._ctx.maximum_version\n\n    @maximum_version.setter\n    def maximum_version(self, value: ssl.TLSVersion) -> None:\n        _original_super_SSLContext.maximum_version.__set__(  # type: ignore[attr-defined]\n            self._ctx, value\n        )\n\n    @property\n    def minimum_version(self) -> ssl.TLSVersion:\n        return self._ctx.minimum_version\n\n    @minimum_version.setter\n    def minimum_version(self, value: ssl.TLSVersion) -> None:\n        _original_super_SSLContext.minimum_version.__set__(  # type: ignore[attr-defined]\n            self._ctx, value\n        )\n\n    @property\n    def options(self) -> ssl.Options:\n        return self._ctx.options\n\n    @options.setter\n    def options(self, value: ssl.Options) -> None:\n        _original_super_SSLContext.options.__set__(  # type: ignore[attr-defined]\n            self._ctx, value\n        )\n\n    @property\n    def post_handshake_auth(self) -> bool:\n        return self._ctx.post_handshake_auth\n\n    @post_handshake_auth.setter\n    def post_handshake_auth(self, value: bool) -> None:\n        self._ctx.post_handshake_auth = value\n\n    @property\n    def protocol(self) -> ssl._SSLMethod:\n        return self._ctx.protocol\n\n    @property\n    def security_level(self) -> int:\n        return self._ctx.security_level\n\n    @property\n    def verify_flags(self) -> ssl.VerifyFlags:\n        return self._ctx.verify_flags\n\n    @verify_flags.setter\n    def verify_flags(self, value: ssl.VerifyFlags) -> None:\n        _original_super_SSLContext.verify_flags.__set__(  # type: ignore[attr-defined]\n            self._ctx, value\n        )\n\n    @property\n    def verify_mode(self) -> ssl.VerifyMode:\n        return self._ctx.verify_mode\n\n    @verify_mode.setter\n    def verify_mode(self, value: ssl.VerifyMode) -> None:\n        _original_super_SSLContext.verify_mode.__set__(  # type: ignore[attr-defined]\n            self._ctx, value\n        )\n\n\n# Python 3.13+ makes get_unverified_chain() a public API that only returns DER\n# encoded certificates. We detect whether we need to call public_bytes() for 3.10->3.12\n# Pre-3.13 returned None instead of an empty list from get_unverified_chain()\nif sys.version_info >= (3, 13):\n\n    def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:\n        unverified_chain = sslobj.get_unverified_chain() or ()\n        return [\n            cert if isinstance(cert, bytes) else cert.public_bytes(_ssl.ENCODING_DER)\n            for cert in unverified_chain\n        ]\n\nelse:\n\n    def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:\n        unverified_chain = sslobj.get_unverified_chain() or ()  # type: ignore[attr-defined]\n        return [cert.public_bytes(_ssl.ENCODING_DER) for cert in unverified_chain]\n\n\ndef _verify_peercerts(\n    sock_or_sslobj: ssl.SSLSocket | ssl.SSLObject, server_hostname: str | None\n) -> None:\n    \"\"\"\n    Verifies the peer certificates from an SSLSocket or SSLObject\n    against the certificates in the OS trust store.\n    \"\"\"\n    sslobj: ssl.SSLObject = sock_or_sslobj  # type: ignore[assignment]\n    try:\n        while not hasattr(sslobj, \"get_unverified_chain\"):\n            sslobj = sslobj._sslobj  # type: ignore[attr-defined]\n    except AttributeError:\n        pass\n\n    cert_bytes = _get_unverified_chain_bytes(sslobj)\n    _verify_peercerts_impl(\n        sock_or_sslobj.context, cert_bytes, server_hostname=server_hostname\n    )\n"
  },
  {
    "path": "src/pip/_vendor/truststore/_macos.py",
    "content": "import contextlib\nimport ctypes\nimport platform\nimport ssl\nimport typing\nfrom ctypes import (\n    CDLL,\n    POINTER,\n    c_bool,\n    c_char_p,\n    c_int32,\n    c_long,\n    c_uint32,\n    c_ulong,\n    c_void_p,\n)\nfrom ctypes.util import find_library\n\nfrom ._ssl_constants import _set_ssl_context_verify_mode\n\n_mac_version = platform.mac_ver()[0]\n_mac_version_info = tuple(map(int, _mac_version.split(\".\")))\nif _mac_version_info < (10, 8):\n    raise ImportError(\n        f\"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}\"\n    )\n\n_is_macos_version_10_14_or_later = _mac_version_info >= (10, 14)\n\n\ndef _load_cdll(name: str, macos10_16_path: str) -> CDLL:\n    \"\"\"Loads a CDLL by name, falling back to known path on 10.16+\"\"\"\n    try:\n        # Big Sur is technically 11 but we use 10.16 due to the Big Sur\n        # beta being labeled as 10.16.\n        path: str | None\n        if _mac_version_info >= (10, 16):\n            path = macos10_16_path\n        else:\n            path = find_library(name)\n        if not path:\n            raise OSError  # Caught and reraised as 'ImportError'\n        return CDLL(path, use_errno=True)\n    except OSError:\n        raise ImportError(f\"The library {name} failed to load\") from None\n\n\nSecurity = _load_cdll(\n    \"Security\", \"/System/Library/Frameworks/Security.framework/Security\"\n)\nCoreFoundation = _load_cdll(\n    \"CoreFoundation\",\n    \"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation\",\n)\n\nBoolean = c_bool\nCFIndex = c_long\nCFStringEncoding = c_uint32\nCFData = c_void_p\nCFString = c_void_p\nCFArray = c_void_p\nCFMutableArray = c_void_p\nCFError = c_void_p\nCFType = c_void_p\nCFTypeID = c_ulong\nCFTypeRef = POINTER(CFType)\nCFAllocatorRef = c_void_p\n\nOSStatus = c_int32\n\nCFErrorRef = POINTER(CFError)\nCFDataRef = POINTER(CFData)\nCFStringRef = POINTER(CFString)\nCFArrayRef = POINTER(CFArray)\nCFMutableArrayRef = POINTER(CFMutableArray)\nCFArrayCallBacks = c_void_p\nCFOptionFlags = c_uint32\n\nSecCertificateRef = POINTER(c_void_p)\nSecPolicyRef = POINTER(c_void_p)\nSecTrustRef = POINTER(c_void_p)\nSecTrustResultType = c_uint32\nSecTrustOptionFlags = c_uint32\n\ntry:\n    Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]\n    Security.SecCertificateCreateWithData.restype = SecCertificateRef\n\n    Security.SecCertificateCopyData.argtypes = [SecCertificateRef]\n    Security.SecCertificateCopyData.restype = CFDataRef\n\n    Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n    Security.SecCopyErrorMessageString.restype = CFStringRef\n\n    Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]\n    Security.SecTrustSetAnchorCertificates.restype = OSStatus\n\n    Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean]\n    Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus\n\n    Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags]\n    Security.SecPolicyCreateRevocation.restype = SecPolicyRef\n\n    Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef]\n    Security.SecPolicyCreateSSL.restype = SecPolicyRef\n\n    Security.SecTrustCreateWithCertificates.argtypes = [\n        CFTypeRef,\n        CFTypeRef,\n        POINTER(SecTrustRef),\n    ]\n    Security.SecTrustCreateWithCertificates.restype = OSStatus\n\n    Security.SecTrustGetTrustResult.argtypes = [\n        SecTrustRef,\n        POINTER(SecTrustResultType),\n    ]\n    Security.SecTrustGetTrustResult.restype = OSStatus\n\n    Security.SecTrustEvaluate.argtypes = [\n        SecTrustRef,\n        POINTER(SecTrustResultType),\n    ]\n    Security.SecTrustEvaluate.restype = OSStatus\n\n    Security.SecTrustRef = SecTrustRef  # type: ignore[attr-defined]\n    Security.SecTrustResultType = SecTrustResultType  # type: ignore[attr-defined]\n    Security.OSStatus = OSStatus  # type: ignore[attr-defined]\n\n    kSecRevocationUseAnyAvailableMethod = 3\n    kSecRevocationRequirePositiveResponse = 8\n\n    CoreFoundation.CFRelease.argtypes = [CFTypeRef]\n    CoreFoundation.CFRelease.restype = None\n\n    CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]\n    CoreFoundation.CFGetTypeID.restype = CFTypeID\n\n    CoreFoundation.CFStringCreateWithCString.argtypes = [\n        CFAllocatorRef,\n        c_char_p,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringCreateWithCString.restype = CFStringRef\n\n    CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]\n    CoreFoundation.CFStringGetCStringPtr.restype = c_char_p\n\n    CoreFoundation.CFStringGetCString.argtypes = [\n        CFStringRef,\n        c_char_p,\n        CFIndex,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringGetCString.restype = c_bool\n\n    CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]\n    CoreFoundation.CFDataCreate.restype = CFDataRef\n\n    CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetLength.restype = CFIndex\n\n    CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetBytePtr.restype = c_void_p\n\n    CoreFoundation.CFArrayCreate.argtypes = [\n        CFAllocatorRef,\n        POINTER(CFTypeRef),\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreate.restype = CFArrayRef\n\n    CoreFoundation.CFArrayCreateMutable.argtypes = [\n        CFAllocatorRef,\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef\n\n    CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]\n    CoreFoundation.CFArrayAppendValue.restype = None\n\n    CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]\n    CoreFoundation.CFArrayGetCount.restype = CFIndex\n\n    CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]\n    CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p\n\n    CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef]\n    CoreFoundation.CFErrorGetCode.restype = CFIndex\n\n    CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef]\n    CoreFoundation.CFErrorCopyDescription.restype = CFStringRef\n\n    CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(  # type: ignore[attr-defined]\n        CoreFoundation, \"kCFAllocatorDefault\"\n    )\n    CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(  # type: ignore[attr-defined]\n        CoreFoundation, \"kCFTypeArrayCallBacks\"\n    )\n\n    CoreFoundation.CFTypeRef = CFTypeRef  # type: ignore[attr-defined]\n    CoreFoundation.CFArrayRef = CFArrayRef  # type: ignore[attr-defined]\n    CoreFoundation.CFStringRef = CFStringRef  # type: ignore[attr-defined]\n    CoreFoundation.CFErrorRef = CFErrorRef  # type: ignore[attr-defined]\n\nexcept AttributeError as e:\n    raise ImportError(f\"Error initializing ctypes: {e}\") from None\n\n# SecTrustEvaluateWithError is macOS 10.14+\nif _is_macos_version_10_14_or_later:\n    try:\n        Security.SecTrustEvaluateWithError.argtypes = [\n            SecTrustRef,\n            POINTER(CFErrorRef),\n        ]\n        Security.SecTrustEvaluateWithError.restype = c_bool\n    except AttributeError as e:\n        raise ImportError(f\"Error initializing ctypes: {e}\") from None\n\n\ndef _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any:\n    \"\"\"\n    Raises an error if the OSStatus value is non-zero.\n    \"\"\"\n    if int(result) == 0:\n        return args\n\n    # Returns a CFString which we need to transform\n    # into a UTF-8 Python string.\n    error_message_cfstring = None\n    try:\n        error_message_cfstring = Security.SecCopyErrorMessageString(result, None)\n\n        # First step is convert the CFString into a C string pointer.\n        # We try the fast no-copy way first.\n        error_message_cfstring_c_void_p = ctypes.cast(\n            error_message_cfstring, ctypes.POINTER(ctypes.c_void_p)\n        )\n        message = CoreFoundation.CFStringGetCStringPtr(\n            error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8\n        )\n\n        # Quoting the Apple dev docs:\n        #\n        # \"A pointer to a C string or NULL if the internal\n        # storage of theString does not allow this to be\n        # returned efficiently.\"\n        #\n        # So we need to get our hands dirty.\n        if message is None:\n            buffer = ctypes.create_string_buffer(1024)\n            result = CoreFoundation.CFStringGetCString(\n                error_message_cfstring_c_void_p,\n                buffer,\n                1024,\n                CFConst.kCFStringEncodingUTF8,\n            )\n            if not result:\n                raise OSError(\"Error copying C string from CFStringRef\")\n            message = buffer.value\n\n    finally:\n        if error_message_cfstring is not None:\n            CoreFoundation.CFRelease(error_message_cfstring)\n\n    # If no message can be found for this status we come\n    # up with a generic one that forwards the status code.\n    if message is None or message == \"\":\n        message = f\"SecureTransport operation returned a non-zero OSStatus: {result}\"\n\n    raise ssl.SSLError(message)\n\n\nSecurity.SecTrustCreateWithCertificates.errcheck = _handle_osstatus  # type: ignore[assignment]\nSecurity.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus  # type: ignore[assignment]\nSecurity.SecTrustSetAnchorCertificatesOnly.errcheck = _handle_osstatus  # type: ignore[assignment]\nSecurity.SecTrustGetTrustResult.errcheck = _handle_osstatus  # type: ignore[assignment]\nSecurity.SecTrustEvaluate.errcheck = _handle_osstatus  # type: ignore[assignment]\n\n\nclass CFConst:\n    \"\"\"CoreFoundation constants\"\"\"\n\n    kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)\n\n    errSecIncompleteCertRevocationCheck = -67635\n    errSecHostNameMismatch = -67602\n    errSecCertificateExpired = -67818\n    errSecNotTrusted = -67843\n\n\ndef _bytes_to_cf_data_ref(value: bytes) -> CFDataRef:  # type: ignore[valid-type]\n    return CoreFoundation.CFDataCreate(  # type: ignore[no-any-return]\n        CoreFoundation.kCFAllocatorDefault, value, len(value)\n    )\n\n\ndef _bytes_to_cf_string(value: bytes) -> CFString:\n    \"\"\"\n    Given a Python binary data, create a CFString.\n    The string must be CFReleased by the caller.\n    \"\"\"\n    c_str = ctypes.c_char_p(value)\n    cf_str = CoreFoundation.CFStringCreateWithCString(\n        CoreFoundation.kCFAllocatorDefault,\n        c_str,\n        CFConst.kCFStringEncodingUTF8,\n    )\n    return cf_str  # type: ignore[no-any-return]\n\n\ndef _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None:  # type: ignore[valid-type]\n    \"\"\"\n    Creates a Unicode string from a CFString object. Used entirely for error\n    reporting.\n    Yes, it annoys me quite a lot that this function is this complex.\n    \"\"\"\n\n    string = CoreFoundation.CFStringGetCStringPtr(\n        cf_string_ref, CFConst.kCFStringEncodingUTF8\n    )\n    if string is None:\n        buffer = ctypes.create_string_buffer(1024)\n        result = CoreFoundation.CFStringGetCString(\n            cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8\n        )\n        if not result:\n            raise OSError(\"Error copying C string from CFStringRef\")\n        string = buffer.value\n    if string is not None:\n        string = string.decode(\"utf-8\")\n    return string  # type: ignore[no-any-return]\n\n\ndef _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef:  # type: ignore[valid-type]\n    \"\"\"Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates.\n    Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray.\n    \"\"\"\n    cf_array = CoreFoundation.CFArrayCreateMutable(\n        CoreFoundation.kCFAllocatorDefault,\n        0,\n        ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n    )\n    if not cf_array:\n        raise MemoryError(\"Unable to allocate memory!\")\n\n    for cert_data in certs:\n        cf_data = None\n        sec_cert_ref = None\n        try:\n            cf_data = _bytes_to_cf_data_ref(cert_data)\n            sec_cert_ref = Security.SecCertificateCreateWithData(\n                CoreFoundation.kCFAllocatorDefault, cf_data\n            )\n            CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref)\n        finally:\n            if cf_data:\n                CoreFoundation.CFRelease(cf_data)\n            if sec_cert_ref:\n                CoreFoundation.CFRelease(sec_cert_ref)\n\n    return cf_array  # type: ignore[no-any-return]\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n    check_hostname = ctx.check_hostname\n    verify_mode = ctx.verify_mode\n    ctx.check_hostname = False\n    _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)\n    try:\n        yield\n    finally:\n        ctx.check_hostname = check_hostname\n        _set_ssl_context_verify_mode(ctx, verify_mode)\n\n\ndef _verify_peercerts_impl(\n    ssl_context: ssl.SSLContext,\n    cert_chain: list[bytes],\n    server_hostname: str | None = None,\n) -> None:\n    certs = None\n    policies = None\n    trust = None\n    try:\n        # Only set a hostname on the policy if we're verifying the hostname\n        # on the leaf certificate.\n        if server_hostname is not None and ssl_context.check_hostname:\n            cf_str_hostname = None\n            try:\n                cf_str_hostname = _bytes_to_cf_string(server_hostname.encode(\"ascii\"))\n                ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)\n            finally:\n                if cf_str_hostname:\n                    CoreFoundation.CFRelease(cf_str_hostname)\n        else:\n            ssl_policy = Security.SecPolicyCreateSSL(True, None)\n\n        policies = ssl_policy\n        if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n            # Add explicit policy requiring positive revocation checks\n            policies = CoreFoundation.CFArrayCreateMutable(\n                CoreFoundation.kCFAllocatorDefault,\n                0,\n                ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n            )\n            CoreFoundation.CFArrayAppendValue(policies, ssl_policy)\n            CoreFoundation.CFRelease(ssl_policy)\n            revocation_policy = Security.SecPolicyCreateRevocation(\n                kSecRevocationUseAnyAvailableMethod\n                | kSecRevocationRequirePositiveResponse\n            )\n            CoreFoundation.CFArrayAppendValue(policies, revocation_policy)\n            CoreFoundation.CFRelease(revocation_policy)\n        elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n            raise NotImplementedError(\"VERIFY_CRL_CHECK_LEAF not implemented for macOS\")\n\n        certs = None\n        try:\n            certs = _der_certs_to_cf_cert_array(cert_chain)\n\n            # Now that we have certificates loaded and a SecPolicy\n            # we can finally create a SecTrust object!\n            trust = Security.SecTrustRef()\n            Security.SecTrustCreateWithCertificates(\n                certs, policies, ctypes.byref(trust)\n            )\n\n        finally:\n            # The certs are now being held by SecTrust so we can\n            # release our handles for the array.\n            if certs:\n                CoreFoundation.CFRelease(certs)\n\n        # If there are additional trust anchors to load we need to transform\n        # the list of DER-encoded certificates into a CFArray.\n        ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(\n            binary_form=True\n        )\n        if ctx_ca_certs_der:\n            ctx_ca_certs = None\n            try:\n                ctx_ca_certs = _der_certs_to_cf_cert_array(ctx_ca_certs_der)\n                Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)\n            finally:\n                if ctx_ca_certs:\n                    CoreFoundation.CFRelease(ctx_ca_certs)\n\n        # We always want system certificates.\n        Security.SecTrustSetAnchorCertificatesOnly(trust, False)\n\n        # macOS 10.13 and earlier don't support SecTrustEvaluateWithError()\n        # so we use SecTrustEvaluate() which means we need to construct error\n        # messages ourselves.\n        if _is_macos_version_10_14_or_later:\n            _verify_peercerts_impl_macos_10_14(ssl_context, trust)\n        else:\n            _verify_peercerts_impl_macos_10_13(ssl_context, trust)\n    finally:\n        if policies:\n            CoreFoundation.CFRelease(policies)\n        if trust:\n            CoreFoundation.CFRelease(trust)\n\n\ndef _verify_peercerts_impl_macos_10_13(\n    ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any\n) -> None:\n    \"\"\"Verify using 'SecTrustEvaluate' API for macOS 10.13 and earlier.\n    macOS 10.14 added the 'SecTrustEvaluateWithError' API.\n    \"\"\"\n    sec_trust_result_type = Security.SecTrustResultType()\n    Security.SecTrustEvaluate(sec_trust_ref, ctypes.byref(sec_trust_result_type))\n\n    try:\n        sec_trust_result_type_as_int = int(sec_trust_result_type.value)\n    except (ValueError, TypeError):\n        sec_trust_result_type_as_int = -1\n\n    # Apple doesn't document these values in their own API docs.\n    # See: https://github.com/xybp888/iOS-SDKs/blob/master/iPhoneOS13.0.sdk/System/Library/Frameworks/Security.framework/Headers/SecTrust.h#L84\n    if (\n        ssl_context.verify_mode == ssl.CERT_REQUIRED\n        and sec_trust_result_type_as_int not in (1, 4)\n    ):\n        # Note that we're not able to ignore only hostname errors\n        # for macOS 10.13 and earlier, so check_hostname=False will\n        # still return an error.\n        sec_trust_result_type_to_message = {\n            0: \"Invalid trust result type\",\n            # 1: \"Trust evaluation succeeded\",\n            2: \"User confirmation required\",\n            3: \"User specified that certificate is not trusted\",\n            # 4: \"Trust result is unspecified\",\n            5: \"Recoverable trust failure occurred\",\n            6: \"Fatal trust failure occurred\",\n            7: \"Other error occurred, certificate may be revoked\",\n        }\n        error_message = sec_trust_result_type_to_message.get(\n            sec_trust_result_type_as_int,\n            f\"Unknown trust result: {sec_trust_result_type_as_int}\",\n        )\n\n        err = ssl.SSLCertVerificationError(error_message)\n        err.verify_message = error_message\n        err.verify_code = sec_trust_result_type_as_int\n        raise err\n\n\ndef _verify_peercerts_impl_macos_10_14(\n    ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any\n) -> None:\n    \"\"\"Verify using 'SecTrustEvaluateWithError' API for macOS 10.14+.\"\"\"\n    cf_error = CoreFoundation.CFErrorRef()\n    sec_trust_eval_result = Security.SecTrustEvaluateWithError(\n        sec_trust_ref, ctypes.byref(cf_error)\n    )\n    # sec_trust_eval_result is a bool (0 or 1)\n    # where 1 means that the certs are trusted.\n    if sec_trust_eval_result == 1:\n        is_trusted = True\n    elif sec_trust_eval_result == 0:\n        is_trusted = False\n    else:\n        raise ssl.SSLError(\n            f\"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}\"\n        )\n\n    cf_error_code = 0\n    if not is_trusted:\n        cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)\n\n        # If the error is a known failure that we're\n        # explicitly okay with from SSLContext configuration\n        # we can set is_trusted accordingly.\n        if ssl_context.verify_mode != ssl.CERT_REQUIRED and (\n            cf_error_code == CFConst.errSecNotTrusted\n            or cf_error_code == CFConst.errSecCertificateExpired\n        ):\n            is_trusted = True\n\n    # If we're still not trusted then we start to\n    # construct and raise the SSLCertVerificationError.\n    if not is_trusted:\n        cf_error_string_ref = None\n        try:\n            cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)\n\n            # Can this ever return 'None' if there's a CFError?\n            cf_error_message = (\n                _cf_string_ref_to_str(cf_error_string_ref)\n                or \"Certificate verification failed\"\n            )\n\n            # TODO: Not sure if we need the SecTrustResultType for anything?\n            # We only care whether or not it's a success or failure for now.\n            sec_trust_result_type = Security.SecTrustResultType()\n            Security.SecTrustGetTrustResult(\n                sec_trust_ref, ctypes.byref(sec_trust_result_type)\n            )\n\n            err = ssl.SSLCertVerificationError(cf_error_message)\n            err.verify_message = cf_error_message\n            err.verify_code = cf_error_code\n            raise err\n        finally:\n            if cf_error_string_ref:\n                CoreFoundation.CFRelease(cf_error_string_ref)\n"
  },
  {
    "path": "src/pip/_vendor/truststore/_openssl.py",
    "content": "import contextlib\nimport os\nimport re\nimport ssl\nimport typing\n\n# candidates based on https://github.com/tiran/certifi-system-store by Christian Heimes\n_CA_FILE_CANDIDATES = [\n    # Alpine, Arch, Fedora 34-42, OpenWRT, RHEL 9-10, BSD\n    \"/etc/ssl/cert.pem\",\n    # Fedora 43+, RHEL 11+\n    \"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem\",\n    # Fedora <= 34, RHEL <= 9, CentOS <= 9\n    \"/etc/pki/tls/cert.pem\",\n    # Debian, Ubuntu (requires ca-certificates)\n    \"/etc/ssl/certs/ca-certificates.crt\",\n    # SUSE\n    \"/etc/ssl/ca-bundle.pem\",\n]\n\n_HASHED_CERT_FILENAME_RE = re.compile(r\"^[0-9a-fA-F]{8}\\.[0-9]$\")\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n    # First, check whether the default locations from OpenSSL\n    # seem like they will give us a usable set of CA certs.\n    # ssl.get_default_verify_paths already takes care of:\n    # - getting cafile from either the SSL_CERT_FILE env var\n    #   or the path configured when OpenSSL was compiled,\n    #   and verifying that that path exists\n    # - getting capath from either the SSL_CERT_DIR env var\n    #   or the path configured when OpenSSL was compiled,\n    #   and verifying that that path exists\n    # In addition we'll check whether capath appears to contain certs.\n    defaults = ssl.get_default_verify_paths()\n    if defaults.cafile or (defaults.capath and _capath_contains_certs(defaults.capath)):\n        ctx.set_default_verify_paths()\n    else:\n        # cafile from OpenSSL doesn't exist\n        # and capath from OpenSSL doesn't contain certs.\n        # Let's search other common locations instead.\n        for cafile in _CA_FILE_CANDIDATES:\n            if os.path.isfile(cafile):\n                ctx.load_verify_locations(cafile=cafile)\n                break\n\n    yield\n\n\ndef _capath_contains_certs(capath: str) -> bool:\n    \"\"\"Check whether capath exists and contains certs in the expected format.\"\"\"\n    if not os.path.isdir(capath):\n        return False\n    for name in os.listdir(capath):\n        if _HASHED_CERT_FILENAME_RE.match(name):\n            return True\n    return False\n\n\ndef _verify_peercerts_impl(\n    ssl_context: ssl.SSLContext,\n    cert_chain: list[bytes],\n    server_hostname: str | None = None,\n) -> None:\n    # This is a no-op because we've enabled SSLContext's built-in\n    # verification via verify_mode=CERT_REQUIRED, and don't need to repeat it.\n    pass\n"
  },
  {
    "path": "src/pip/_vendor/truststore/_ssl_constants.py",
    "content": "import ssl\nimport sys\nimport typing\n\n# Hold on to the original class so we can create it consistently\n# even if we inject our own SSLContext into the ssl module.\n_original_SSLContext = ssl.SSLContext\n_original_super_SSLContext = super(_original_SSLContext, _original_SSLContext)\n\n# CPython is known to be good, but non-CPython implementations\n# may implement SSLContext differently so to be safe we don't\n# subclass the SSLContext.\n\n# This is returned by truststore.SSLContext.__class__()\n_truststore_SSLContext_dunder_class: typing.Optional[type]\n\n# This value is the superclass of truststore.SSLContext.\n_truststore_SSLContext_super_class: type\n\nif sys.implementation.name == \"cpython\":\n    _truststore_SSLContext_super_class = _original_SSLContext\n    _truststore_SSLContext_dunder_class = None\nelse:\n    _truststore_SSLContext_super_class = object\n    _truststore_SSLContext_dunder_class = _original_SSLContext\n\n\ndef _set_ssl_context_verify_mode(\n    ssl_context: ssl.SSLContext, verify_mode: ssl.VerifyMode\n) -> None:\n    _original_super_SSLContext.verify_mode.__set__(ssl_context, verify_mode)  # type: ignore[attr-defined]\n"
  },
  {
    "path": "src/pip/_vendor/truststore/_windows.py",
    "content": "import contextlib\nimport ssl\nimport typing\nfrom ctypes import WinDLL  # type: ignore\nfrom ctypes import WinError  # type: ignore\nfrom ctypes import (\n    POINTER,\n    Structure,\n    c_char_p,\n    c_ulong,\n    c_void_p,\n    c_wchar_p,\n    cast,\n    create_unicode_buffer,\n    pointer,\n    sizeof,\n)\nfrom ctypes.wintypes import (\n    BOOL,\n    DWORD,\n    HANDLE,\n    LONG,\n    LPCSTR,\n    LPCVOID,\n    LPCWSTR,\n    LPFILETIME,\n    LPSTR,\n    LPWSTR,\n)\nfrom typing import TYPE_CHECKING, Any\n\nfrom ._ssl_constants import _set_ssl_context_verify_mode\n\nHCERTCHAINENGINE = HANDLE\nHCERTSTORE = HANDLE\nHCRYPTPROV_LEGACY = HANDLE\n\n\nclass CERT_CONTEXT(Structure):\n    _fields_ = (\n        (\"dwCertEncodingType\", DWORD),\n        (\"pbCertEncoded\", c_void_p),\n        (\"cbCertEncoded\", DWORD),\n        (\"pCertInfo\", c_void_p),\n        (\"hCertStore\", HCERTSTORE),\n    )\n\n\nPCERT_CONTEXT = POINTER(CERT_CONTEXT)\nPCCERT_CONTEXT = POINTER(PCERT_CONTEXT)\n\n\nclass CERT_ENHKEY_USAGE(Structure):\n    _fields_ = (\n        (\"cUsageIdentifier\", DWORD),\n        (\"rgpszUsageIdentifier\", POINTER(LPSTR)),\n    )\n\n\nPCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE)\n\n\nclass CERT_USAGE_MATCH(Structure):\n    _fields_ = (\n        (\"dwType\", DWORD),\n        (\"Usage\", CERT_ENHKEY_USAGE),\n    )\n\n\nclass CERT_CHAIN_PARA(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"RequestedUsage\", CERT_USAGE_MATCH),\n        (\"RequestedIssuancePolicy\", CERT_USAGE_MATCH),\n        (\"dwUrlRetrievalTimeout\", DWORD),\n        (\"fCheckRevocationFreshnessTime\", BOOL),\n        (\"dwRevocationFreshnessTime\", DWORD),\n        (\"pftCacheResync\", LPFILETIME),\n        (\"pStrongSignPara\", c_void_p),\n        (\"dwStrongSignFlags\", DWORD),\n    )\n\n\nif TYPE_CHECKING:\n    PCERT_CHAIN_PARA = pointer[CERT_CHAIN_PARA]  # type: ignore[misc]\nelse:\n    PCERT_CHAIN_PARA = POINTER(CERT_CHAIN_PARA)\n\n\nclass CERT_TRUST_STATUS(Structure):\n    _fields_ = (\n        (\"dwErrorStatus\", DWORD),\n        (\"dwInfoStatus\", DWORD),\n    )\n\n\nclass CERT_CHAIN_ELEMENT(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"pCertContext\", PCERT_CONTEXT),\n        (\"TrustStatus\", CERT_TRUST_STATUS),\n        (\"pRevocationInfo\", c_void_p),\n        (\"pIssuanceUsage\", PCERT_ENHKEY_USAGE),\n        (\"pApplicationUsage\", PCERT_ENHKEY_USAGE),\n        (\"pwszExtendedErrorInfo\", LPCWSTR),\n    )\n\n\nPCERT_CHAIN_ELEMENT = POINTER(CERT_CHAIN_ELEMENT)\n\n\nclass CERT_SIMPLE_CHAIN(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"TrustStatus\", CERT_TRUST_STATUS),\n        (\"cElement\", DWORD),\n        (\"rgpElement\", POINTER(PCERT_CHAIN_ELEMENT)),\n        (\"pTrustListInfo\", c_void_p),\n        (\"fHasRevocationFreshnessTime\", BOOL),\n        (\"dwRevocationFreshnessTime\", DWORD),\n    )\n\n\nPCERT_SIMPLE_CHAIN = POINTER(CERT_SIMPLE_CHAIN)\n\n\nclass CERT_CHAIN_CONTEXT(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"TrustStatus\", CERT_TRUST_STATUS),\n        (\"cChain\", DWORD),\n        (\"rgpChain\", POINTER(PCERT_SIMPLE_CHAIN)),\n        (\"cLowerQualityChainContext\", DWORD),\n        (\"rgpLowerQualityChainContext\", c_void_p),\n        (\"fHasRevocationFreshnessTime\", BOOL),\n        (\"dwRevocationFreshnessTime\", DWORD),\n    )\n\n\nPCERT_CHAIN_CONTEXT = POINTER(CERT_CHAIN_CONTEXT)\nPCCERT_CHAIN_CONTEXT = POINTER(PCERT_CHAIN_CONTEXT)\n\n\nclass SSL_EXTRA_CERT_CHAIN_POLICY_PARA(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"dwAuthType\", DWORD),\n        (\"fdwChecks\", DWORD),\n        (\"pwszServerName\", LPCWSTR),\n    )\n\n\nclass CERT_CHAIN_POLICY_PARA(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"dwFlags\", DWORD),\n        (\"pvExtraPolicyPara\", c_void_p),\n    )\n\n\nPCERT_CHAIN_POLICY_PARA = POINTER(CERT_CHAIN_POLICY_PARA)\n\n\nclass CERT_CHAIN_POLICY_STATUS(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"dwError\", DWORD),\n        (\"lChainIndex\", LONG),\n        (\"lElementIndex\", LONG),\n        (\"pvExtraPolicyStatus\", c_void_p),\n    )\n\n\nPCERT_CHAIN_POLICY_STATUS = POINTER(CERT_CHAIN_POLICY_STATUS)\n\n\nclass CERT_CHAIN_ENGINE_CONFIG(Structure):\n    _fields_ = (\n        (\"cbSize\", DWORD),\n        (\"hRestrictedRoot\", HCERTSTORE),\n        (\"hRestrictedTrust\", HCERTSTORE),\n        (\"hRestrictedOther\", HCERTSTORE),\n        (\"cAdditionalStore\", DWORD),\n        (\"rghAdditionalStore\", c_void_p),\n        (\"dwFlags\", DWORD),\n        (\"dwUrlRetrievalTimeout\", DWORD),\n        (\"MaximumCachedCertificates\", DWORD),\n        (\"CycleDetectionModulus\", DWORD),\n        (\"hExclusiveRoot\", HCERTSTORE),\n        (\"hExclusiveTrustedPeople\", HCERTSTORE),\n        (\"dwExclusiveFlags\", DWORD),\n    )\n\n\nPCERT_CHAIN_ENGINE_CONFIG = POINTER(CERT_CHAIN_ENGINE_CONFIG)\nPHCERTCHAINENGINE = POINTER(HCERTCHAINENGINE)\n\nX509_ASN_ENCODING = 0x00000001\nPKCS_7_ASN_ENCODING = 0x00010000\nCERT_STORE_PROV_MEMORY = b\"Memory\"\nCERT_STORE_ADD_USE_EXISTING = 2\nUSAGE_MATCH_TYPE_OR = 1\nOID_PKIX_KP_SERVER_AUTH = c_char_p(b\"1.3.6.1.5.5.7.3.1\")\nCERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000\nCERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000\nCERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS = 0x00000007\nCERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 0x00000008\nCERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 0x00000010\nCERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 0x00000040\nCERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 0x00000020\nCERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 0x00000080\nCERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS = 0x00000F00\nCERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG = 0x00008000\nCERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG = 0x00004000\nSECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000\nAUTHTYPE_SERVER = 2\nCERT_CHAIN_POLICY_SSL = 4\nFORMAT_MESSAGE_FROM_SYSTEM = 0x00001000\nFORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200\n\n# Flags to set for SSLContext.verify_mode=CERT_NONE\nCERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS = (\n    CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS\n    | CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG\n    | CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG\n    | CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG\n    | CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG\n    | CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG\n    | CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS\n    | CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG\n    | CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG\n)\n\nwincrypt = WinDLL(\"crypt32.dll\")\nkernel32 = WinDLL(\"kernel32.dll\")\n\n\ndef _handle_win_error(result: bool, _: Any, args: Any) -> Any:\n    if not result:\n        # Note, actually raises OSError after calling GetLastError and FormatMessage\n        raise WinError()\n    return args\n\n\nCertCreateCertificateChainEngine = wincrypt.CertCreateCertificateChainEngine\nCertCreateCertificateChainEngine.argtypes = (\n    PCERT_CHAIN_ENGINE_CONFIG,\n    PHCERTCHAINENGINE,\n)\nCertCreateCertificateChainEngine.errcheck = _handle_win_error\n\nCertOpenStore = wincrypt.CertOpenStore\nCertOpenStore.argtypes = (LPCSTR, DWORD, HCRYPTPROV_LEGACY, DWORD, c_void_p)\nCertOpenStore.restype = HCERTSTORE\nCertOpenStore.errcheck = _handle_win_error\n\nCertAddEncodedCertificateToStore = wincrypt.CertAddEncodedCertificateToStore\nCertAddEncodedCertificateToStore.argtypes = (\n    HCERTSTORE,\n    DWORD,\n    c_char_p,\n    DWORD,\n    DWORD,\n    PCCERT_CONTEXT,\n)\nCertAddEncodedCertificateToStore.restype = BOOL\n\nCertCreateCertificateContext = wincrypt.CertCreateCertificateContext\nCertCreateCertificateContext.argtypes = (DWORD, c_char_p, DWORD)\nCertCreateCertificateContext.restype = PCERT_CONTEXT\nCertCreateCertificateContext.errcheck = _handle_win_error\n\nCertGetCertificateChain = wincrypt.CertGetCertificateChain\nCertGetCertificateChain.argtypes = (\n    HCERTCHAINENGINE,\n    PCERT_CONTEXT,\n    LPFILETIME,\n    HCERTSTORE,\n    PCERT_CHAIN_PARA,\n    DWORD,\n    c_void_p,\n    PCCERT_CHAIN_CONTEXT,\n)\nCertGetCertificateChain.restype = BOOL\nCertGetCertificateChain.errcheck = _handle_win_error\n\nCertVerifyCertificateChainPolicy = wincrypt.CertVerifyCertificateChainPolicy\nCertVerifyCertificateChainPolicy.argtypes = (\n    c_ulong,\n    PCERT_CHAIN_CONTEXT,\n    PCERT_CHAIN_POLICY_PARA,\n    PCERT_CHAIN_POLICY_STATUS,\n)\nCertVerifyCertificateChainPolicy.restype = BOOL\n\nCertCloseStore = wincrypt.CertCloseStore\nCertCloseStore.argtypes = (HCERTSTORE, DWORD)\nCertCloseStore.restype = BOOL\nCertCloseStore.errcheck = _handle_win_error\n\nCertFreeCertificateChain = wincrypt.CertFreeCertificateChain\nCertFreeCertificateChain.argtypes = (PCERT_CHAIN_CONTEXT,)\n\nCertFreeCertificateContext = wincrypt.CertFreeCertificateContext\nCertFreeCertificateContext.argtypes = (PCERT_CONTEXT,)\n\nCertFreeCertificateChainEngine = wincrypt.CertFreeCertificateChainEngine\nCertFreeCertificateChainEngine.argtypes = (HCERTCHAINENGINE,)\n\nFormatMessageW = kernel32.FormatMessageW\nFormatMessageW.argtypes = (\n    DWORD,\n    LPCVOID,\n    DWORD,\n    DWORD,\n    LPWSTR,\n    DWORD,\n    c_void_p,\n)\nFormatMessageW.restype = DWORD\n\n\ndef _verify_peercerts_impl(\n    ssl_context: ssl.SSLContext,\n    cert_chain: list[bytes],\n    server_hostname: str | None = None,\n) -> None:\n    \"\"\"Verify the cert_chain from the server using Windows APIs.\"\"\"\n\n    # If the peer didn't send any certificates then\n    # we can't do verification. Raise an error.\n    if not cert_chain:\n        raise ssl.SSLCertVerificationError(\"Peer sent no certificates to verify\")\n\n    pCertContext = None\n    hIntermediateCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)\n    try:\n        # Add intermediate certs to an in-memory cert store\n        for cert_bytes in cert_chain[1:]:\n            CertAddEncodedCertificateToStore(\n                hIntermediateCertStore,\n                X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,\n                cert_bytes,\n                len(cert_bytes),\n                CERT_STORE_ADD_USE_EXISTING,\n                None,\n            )\n\n        # Cert context for leaf cert\n        leaf_cert = cert_chain[0]\n        pCertContext = CertCreateCertificateContext(\n            X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, leaf_cert, len(leaf_cert)\n        )\n\n        # Chain params to match certs for serverAuth extended usage\n        cert_enhkey_usage = CERT_ENHKEY_USAGE()\n        cert_enhkey_usage.cUsageIdentifier = 1\n        cert_enhkey_usage.rgpszUsageIdentifier = (c_char_p * 1)(OID_PKIX_KP_SERVER_AUTH)\n        cert_usage_match = CERT_USAGE_MATCH()\n        cert_usage_match.Usage = cert_enhkey_usage\n        chain_params = CERT_CHAIN_PARA()\n        chain_params.RequestedUsage = cert_usage_match\n        chain_params.cbSize = sizeof(chain_params)\n        pChainPara = pointer(chain_params)\n\n        if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n            chain_flags = CERT_CHAIN_REVOCATION_CHECK_CHAIN\n        elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n            chain_flags = CERT_CHAIN_REVOCATION_CHECK_END_CERT\n        else:\n            chain_flags = 0\n\n        try:\n            # First attempt to verify using the default Windows system trust roots\n            # (default chain engine).\n            _get_and_verify_cert_chain(\n                ssl_context,\n                None,\n                hIntermediateCertStore,\n                pCertContext,\n                pChainPara,\n                server_hostname,\n                chain_flags=chain_flags,\n            )\n        except ssl.SSLCertVerificationError as e:\n            # If that fails but custom CA certs have been added\n            # to the SSLContext using load_verify_locations,\n            # try verifying using a custom chain engine\n            # that trusts the custom CA certs.\n            custom_ca_certs: list[bytes] | None = ssl_context.get_ca_certs(\n                binary_form=True\n            )\n            if custom_ca_certs:\n                try:\n                    _verify_using_custom_ca_certs(\n                        ssl_context,\n                        custom_ca_certs,\n                        hIntermediateCertStore,\n                        pCertContext,\n                        pChainPara,\n                        server_hostname,\n                        chain_flags=chain_flags,\n                    )\n                # Raise the original error, not the new error.\n                except ssl.SSLCertVerificationError:\n                    raise e from None\n            else:\n                raise\n    finally:\n        CertCloseStore(hIntermediateCertStore, 0)\n        if pCertContext:\n            CertFreeCertificateContext(pCertContext)\n\n\ndef _get_and_verify_cert_chain(\n    ssl_context: ssl.SSLContext,\n    hChainEngine: HCERTCHAINENGINE | None,\n    hIntermediateCertStore: HCERTSTORE,\n    pPeerCertContext: c_void_p,\n    pChainPara: PCERT_CHAIN_PARA,  # type: ignore[valid-type]\n    server_hostname: str | None,\n    chain_flags: int,\n) -> None:\n    ppChainContext = None\n    try:\n        # Get cert chain\n        ppChainContext = pointer(PCERT_CHAIN_CONTEXT())\n        CertGetCertificateChain(\n            hChainEngine,  # chain engine\n            pPeerCertContext,  # leaf cert context\n            None,  # current system time\n            hIntermediateCertStore,  # additional in-memory cert store\n            pChainPara,  # chain-building parameters\n            chain_flags,\n            None,  # reserved\n            ppChainContext,  # the resulting chain context\n        )\n        pChainContext = ppChainContext.contents\n\n        # Verify cert chain\n        ssl_extra_cert_chain_policy_para = SSL_EXTRA_CERT_CHAIN_POLICY_PARA()\n        ssl_extra_cert_chain_policy_para.cbSize = sizeof(\n            ssl_extra_cert_chain_policy_para\n        )\n        ssl_extra_cert_chain_policy_para.dwAuthType = AUTHTYPE_SERVER\n        ssl_extra_cert_chain_policy_para.fdwChecks = 0\n        if ssl_context.check_hostname is False:\n            ssl_extra_cert_chain_policy_para.fdwChecks = (\n                SECURITY_FLAG_IGNORE_CERT_CN_INVALID\n            )\n        if server_hostname:\n            ssl_extra_cert_chain_policy_para.pwszServerName = c_wchar_p(server_hostname)\n\n        chain_policy = CERT_CHAIN_POLICY_PARA()\n        chain_policy.pvExtraPolicyPara = cast(\n            pointer(ssl_extra_cert_chain_policy_para), c_void_p\n        )\n        if ssl_context.verify_mode == ssl.CERT_NONE:\n            chain_policy.dwFlags |= CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS\n        chain_policy.cbSize = sizeof(chain_policy)\n\n        pPolicyPara = pointer(chain_policy)\n        policy_status = CERT_CHAIN_POLICY_STATUS()\n        policy_status.cbSize = sizeof(policy_status)\n        pPolicyStatus = pointer(policy_status)\n        CertVerifyCertificateChainPolicy(\n            CERT_CHAIN_POLICY_SSL,\n            pChainContext,\n            pPolicyPara,\n            pPolicyStatus,\n        )\n\n        # Check status\n        error_code = policy_status.dwError\n        if error_code:\n            # Try getting a human readable message for an error code.\n            error_message_buf = create_unicode_buffer(1024)\n            error_message_chars = FormatMessageW(\n                FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n                None,\n                error_code,\n                0,\n                error_message_buf,\n                sizeof(error_message_buf),\n                None,\n            )\n\n            # See if we received a message for the error,\n            # otherwise we use a generic error with the\n            # error code and hope that it's search-able.\n            if error_message_chars <= 0:\n                error_message = f\"Certificate chain policy error {error_code:#x} [{policy_status.lElementIndex}]\"\n            else:\n                error_message = error_message_buf.value.strip()\n\n            err = ssl.SSLCertVerificationError(error_message)\n            err.verify_message = error_message\n            err.verify_code = error_code\n            raise err from None\n    finally:\n        if ppChainContext:\n            CertFreeCertificateChain(ppChainContext.contents)\n\n\ndef _verify_using_custom_ca_certs(\n    ssl_context: ssl.SSLContext,\n    custom_ca_certs: list[bytes],\n    hIntermediateCertStore: HCERTSTORE,\n    pPeerCertContext: c_void_p,\n    pChainPara: PCERT_CHAIN_PARA,  # type: ignore[valid-type]\n    server_hostname: str | None,\n    chain_flags: int,\n) -> None:\n    hChainEngine = None\n    hRootCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)\n    try:\n        # Add custom CA certs to an in-memory cert store\n        for cert_bytes in custom_ca_certs:\n            CertAddEncodedCertificateToStore(\n                hRootCertStore,\n                X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,\n                cert_bytes,\n                len(cert_bytes),\n                CERT_STORE_ADD_USE_EXISTING,\n                None,\n            )\n\n        # Create a custom cert chain engine which exclusively trusts\n        # certs from our hRootCertStore\n        cert_chain_engine_config = CERT_CHAIN_ENGINE_CONFIG()\n        cert_chain_engine_config.cbSize = sizeof(cert_chain_engine_config)\n        cert_chain_engine_config.hExclusiveRoot = hRootCertStore\n        pConfig = pointer(cert_chain_engine_config)\n        phChainEngine = pointer(HCERTCHAINENGINE())\n        CertCreateCertificateChainEngine(\n            pConfig,\n            phChainEngine,\n        )\n        hChainEngine = phChainEngine.contents\n\n        # Get and verify a cert chain using the custom chain engine\n        _get_and_verify_cert_chain(\n            ssl_context,\n            hChainEngine,\n            hIntermediateCertStore,\n            pPeerCertContext,\n            pChainPara,\n            server_hostname,\n            chain_flags,\n        )\n    finally:\n        if hChainEngine:\n            CertFreeCertificateChainEngine(hChainEngine)\n        CertCloseStore(hRootCertStore, 0)\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n    check_hostname = ctx.check_hostname\n    verify_mode = ctx.verify_mode\n    ctx.check_hostname = False\n    _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)\n    try:\n        yield\n    finally:\n        ctx.check_hostname = check_hostname\n        _set_ssl_context_verify_mode(ctx, verify_mode)\n"
  },
  {
    "path": "src/pip/_vendor/truststore/py.typed",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/urllib3/LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2008-2020 Andrey Petrov and contributors (see CONTRIBUTORS.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/__init__.py",
    "content": "\"\"\"\nPython HTTP library with thread-safe connection pooling, file post support, user friendly, and more\n\"\"\"\nfrom __future__ import absolute_import\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\nimport warnings\nfrom logging import NullHandler\n\nfrom . import exceptions\nfrom ._version import __version__\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url\nfrom .filepost import encode_multipart_formdata\nfrom .poolmanager import PoolManager, ProxyManager, proxy_from_url\nfrom .response import HTTPResponse\nfrom .util.request import make_headers\nfrom .util.retry import Retry\nfrom .util.timeout import Timeout\nfrom .util.url import get_host\n\n# === NOTE TO REPACKAGERS AND VENDORS ===\n# Please delete this block, this logic is only\n# for urllib3 being distributed via PyPI.\n# See: https://github.com/urllib3/urllib3/issues/2680\ntry:\n    import urllib3_secure_extra  # type: ignore # noqa: F401\nexcept ImportError:\n    pass\nelse:\n    warnings.warn(\n        \"'urllib3[secure]' extra is deprecated and will be removed \"\n        \"in a future release of urllib3 2.x. Read more in this issue: \"\n        \"https://github.com/urllib3/urllib3/issues/2680\",\n        category=DeprecationWarning,\n        stacklevel=2,\n    )\n\n__author__ = \"Andrey Petrov (andrey.petrov@shazow.net)\"\n__license__ = \"MIT\"\n__version__ = __version__\n\n__all__ = (\n    \"HTTPConnectionPool\",\n    \"HTTPSConnectionPool\",\n    \"PoolManager\",\n    \"ProxyManager\",\n    \"HTTPResponse\",\n    \"Retry\",\n    \"Timeout\",\n    \"add_stderr_logger\",\n    \"connection_from_url\",\n    \"disable_warnings\",\n    \"encode_multipart_formdata\",\n    \"get_host\",\n    \"make_headers\",\n    \"proxy_from_url\",\n)\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n\n\ndef add_stderr_logger(level=logging.DEBUG):\n    \"\"\"\n    Helper for quickly adding a StreamHandler to the logger. Useful for\n    debugging.\n\n    Returns the handler after adding it.\n    \"\"\"\n    # This method needs to be in this __init__.py to get the __name__ correct\n    # even if urllib3 is vendored within another package.\n    logger = logging.getLogger(__name__)\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\"))\n    logger.addHandler(handler)\n    logger.setLevel(level)\n    logger.debug(\"Added a stderr logging handler to logger: %s\", __name__)\n    return handler\n\n\n# ... Clean up.\ndel NullHandler\n\n\n# All warning filters *must* be appended unless you're really certain that they\n# shouldn't be: otherwise, it's very hard for users to use most Python\n# mechanisms to silence them.\n# SecurityWarning's always go off by default.\nwarnings.simplefilter(\"always\", exceptions.SecurityWarning, append=True)\n# SubjectAltNameWarning's should go off once per host\nwarnings.simplefilter(\"default\", exceptions.SubjectAltNameWarning, append=True)\n# InsecurePlatformWarning's don't vary between requests, so we keep it default.\nwarnings.simplefilter(\"default\", exceptions.InsecurePlatformWarning, append=True)\n# SNIMissingWarnings should go off only once.\nwarnings.simplefilter(\"default\", exceptions.SNIMissingWarning, append=True)\n\n\ndef disable_warnings(category=exceptions.HTTPWarning):\n    \"\"\"\n    Helper for quickly disabling all urllib3 warnings.\n    \"\"\"\n    warnings.simplefilter(\"ignore\", category)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/_collections.py",
    "content": "from __future__ import absolute_import\n\ntry:\n    from collections.abc import Mapping, MutableMapping\nexcept ImportError:\n    from collections import Mapping, MutableMapping\ntry:\n    from threading import RLock\nexcept ImportError:  # Platform-specific: No threads available\n\n    class RLock:\n        def __enter__(self):\n            pass\n\n        def __exit__(self, exc_type, exc_value, traceback):\n            pass\n\n\nfrom collections import OrderedDict\n\nfrom .exceptions import InvalidHeader\nfrom .packages import six\nfrom .packages.six import iterkeys, itervalues\n\n__all__ = [\"RecentlyUsedContainer\", \"HTTPHeaderDict\"]\n\n\n_Null = object()\n\n\nclass RecentlyUsedContainer(MutableMapping):\n    \"\"\"\n    Provides a thread-safe dict-like container which maintains up to\n    ``maxsize`` keys while throwing away the least-recently-used keys beyond\n    ``maxsize``.\n\n    :param maxsize:\n        Maximum number of recent elements to retain.\n\n    :param dispose_func:\n        Every time an item is evicted from the container,\n        ``dispose_func(value)`` is called.  Callback which will get called\n    \"\"\"\n\n    ContainerCls = OrderedDict\n\n    def __init__(self, maxsize=10, dispose_func=None):\n        self._maxsize = maxsize\n        self.dispose_func = dispose_func\n\n        self._container = self.ContainerCls()\n        self.lock = RLock()\n\n    def __getitem__(self, key):\n        # Re-insert the item, moving it to the end of the eviction line.\n        with self.lock:\n            item = self._container.pop(key)\n            self._container[key] = item\n            return item\n\n    def __setitem__(self, key, value):\n        evicted_value = _Null\n        with self.lock:\n            # Possibly evict the existing value of 'key'\n            evicted_value = self._container.get(key, _Null)\n            self._container[key] = value\n\n            # If we didn't evict an existing value, we might have to evict the\n            # least recently used item from the beginning of the container.\n            if len(self._container) > self._maxsize:\n                _key, evicted_value = self._container.popitem(last=False)\n\n        if self.dispose_func and evicted_value is not _Null:\n            self.dispose_func(evicted_value)\n\n    def __delitem__(self, key):\n        with self.lock:\n            value = self._container.pop(key)\n\n        if self.dispose_func:\n            self.dispose_func(value)\n\n    def __len__(self):\n        with self.lock:\n            return len(self._container)\n\n    def __iter__(self):\n        raise NotImplementedError(\n            \"Iteration over this class is unlikely to be threadsafe.\"\n        )\n\n    def clear(self):\n        with self.lock:\n            # Copy pointers to all values, then wipe the mapping\n            values = list(itervalues(self._container))\n            self._container.clear()\n\n        if self.dispose_func:\n            for value in values:\n                self.dispose_func(value)\n\n    def keys(self):\n        with self.lock:\n            return list(iterkeys(self._container))\n\n\nclass HTTPHeaderDict(MutableMapping):\n    \"\"\"\n    :param headers:\n        An iterable of field-value pairs. Must not contain multiple field names\n        when compared case-insensitively.\n\n    :param kwargs:\n        Additional field-value pairs to pass in to ``dict.update``.\n\n    A ``dict`` like container for storing HTTP Headers.\n\n    Field names are stored and compared case-insensitively in compliance with\n    RFC 7230. Iteration provides the first case-sensitive key seen for each\n    case-insensitive pair.\n\n    Using ``__setitem__`` syntax overwrites fields that compare equal\n    case-insensitively in order to maintain ``dict``'s api. For fields that\n    compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n    in a loop.\n\n    If multiple fields that are equal case-insensitively are passed to the\n    constructor or ``.update``, the behavior is undefined and some will be\n    lost.\n\n    >>> headers = HTTPHeaderDict()\n    >>> headers.add('Set-Cookie', 'foo=bar')\n    >>> headers.add('set-cookie', 'baz=quxx')\n    >>> headers['content-length'] = '7'\n    >>> headers['SET-cookie']\n    'foo=bar, baz=quxx'\n    >>> headers['Content-Length']\n    '7'\n    \"\"\"\n\n    def __init__(self, headers=None, **kwargs):\n        super(HTTPHeaderDict, self).__init__()\n        self._container = OrderedDict()\n        if headers is not None:\n            if isinstance(headers, HTTPHeaderDict):\n                self._copy_from(headers)\n            else:\n                self.extend(headers)\n        if kwargs:\n            self.extend(kwargs)\n\n    def __setitem__(self, key, val):\n        self._container[key.lower()] = [key, val]\n        return self._container[key.lower()]\n\n    def __getitem__(self, key):\n        val = self._container[key.lower()]\n        return \", \".join(val[1:])\n\n    def __delitem__(self, key):\n        del self._container[key.lower()]\n\n    def __contains__(self, key):\n        return key.lower() in self._container\n\n    def __eq__(self, other):\n        if not isinstance(other, Mapping) and not hasattr(other, \"keys\"):\n            return False\n        if not isinstance(other, type(self)):\n            other = type(self)(other)\n        return dict((k.lower(), v) for k, v in self.itermerged()) == dict(\n            (k.lower(), v) for k, v in other.itermerged()\n        )\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    if six.PY2:  # Python 2\n        iterkeys = MutableMapping.iterkeys\n        itervalues = MutableMapping.itervalues\n\n    __marker = object()\n\n    def __len__(self):\n        return len(self._container)\n\n    def __iter__(self):\n        # Only provide the originally cased names\n        for vals in self._container.values():\n            yield vals[0]\n\n    def pop(self, key, default=__marker):\n        \"\"\"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n        If key is not found, d is returned if given, otherwise KeyError is raised.\n        \"\"\"\n        # Using the MutableMapping function directly fails due to the private marker.\n        # Using ordinary dict.pop would expose the internal structures.\n        # So let's reinvent the wheel.\n        try:\n            value = self[key]\n        except KeyError:\n            if default is self.__marker:\n                raise\n            return default\n        else:\n            del self[key]\n            return value\n\n    def discard(self, key):\n        try:\n            del self[key]\n        except KeyError:\n            pass\n\n    def add(self, key, val):\n        \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n        exists.\n\n        >>> headers = HTTPHeaderDict(foo='bar')\n        >>> headers.add('Foo', 'baz')\n        >>> headers['foo']\n        'bar, baz'\n        \"\"\"\n        key_lower = key.lower()\n        new_vals = [key, val]\n        # Keep the common case aka no item present as fast as possible\n        vals = self._container.setdefault(key_lower, new_vals)\n        if new_vals is not vals:\n            vals.append(val)\n\n    def extend(self, *args, **kwargs):\n        \"\"\"Generic import function for any type of header-like object.\n        Adapted version of MutableMapping.update in order to insert items\n        with self.add instead of self.__setitem__\n        \"\"\"\n        if len(args) > 1:\n            raise TypeError(\n                \"extend() takes at most 1 positional \"\n                \"arguments ({0} given)\".format(len(args))\n            )\n        other = args[0] if len(args) >= 1 else ()\n\n        if isinstance(other, HTTPHeaderDict):\n            for key, val in other.iteritems():\n                self.add(key, val)\n        elif isinstance(other, Mapping):\n            for key in other:\n                self.add(key, other[key])\n        elif hasattr(other, \"keys\"):\n            for key in other.keys():\n                self.add(key, other[key])\n        else:\n            for key, value in other:\n                self.add(key, value)\n\n        for key, value in kwargs.items():\n            self.add(key, value)\n\n    def getlist(self, key, default=__marker):\n        \"\"\"Returns a list of all the values for the named field. Returns an\n        empty list if the key doesn't exist.\"\"\"\n        try:\n            vals = self._container[key.lower()]\n        except KeyError:\n            if default is self.__marker:\n                return []\n            return default\n        else:\n            return vals[1:]\n\n    def _prepare_for_method_change(self):\n        \"\"\"\n        Remove content-specific header fields before changing the request\n        method to GET or HEAD according to RFC 9110, Section 15.4.\n        \"\"\"\n        content_specific_headers = [\n            \"Content-Encoding\",\n            \"Content-Language\",\n            \"Content-Location\",\n            \"Content-Type\",\n            \"Content-Length\",\n            \"Digest\",\n            \"Last-Modified\",\n        ]\n        for header in content_specific_headers:\n            self.discard(header)\n        return self\n\n    # Backwards compatibility for httplib\n    getheaders = getlist\n    getallmatchingheaders = getlist\n    iget = getlist\n\n    # Backwards compatibility for http.cookiejar\n    get_all = getlist\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, dict(self.itermerged()))\n\n    def _copy_from(self, other):\n        for key in other:\n            val = other.getlist(key)\n            if isinstance(val, list):\n                # Don't need to convert tuples\n                val = list(val)\n            self._container[key.lower()] = [key] + val\n\n    def copy(self):\n        clone = type(self)()\n        clone._copy_from(self)\n        return clone\n\n    def iteritems(self):\n        \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n        for key in self:\n            vals = self._container[key.lower()]\n            for val in vals[1:]:\n                yield vals[0], val\n\n    def itermerged(self):\n        \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n        for key in self:\n            val = self._container[key.lower()]\n            yield val[0], \", \".join(val[1:])\n\n    def items(self):\n        return list(self.iteritems())\n\n    @classmethod\n    def from_httplib(cls, message):  # Python 2\n        \"\"\"Read headers from a Python 2 httplib message object.\"\"\"\n        # python2.7 does not expose a proper API for exporting multiheaders\n        # efficiently. This function re-reads raw lines from the message\n        # object and extracts the multiheaders properly.\n        obs_fold_continued_leaders = (\" \", \"\\t\")\n        headers = []\n\n        for line in message.headers:\n            if line.startswith(obs_fold_continued_leaders):\n                if not headers:\n                    # We received a header line that starts with OWS as described\n                    # in RFC-7230 S3.2.4. This indicates a multiline header, but\n                    # there exists no previous header to which we can attach it.\n                    raise InvalidHeader(\n                        \"Header continuation with no previous header: %s\" % line\n                    )\n                else:\n                    key, value = headers[-1]\n                    headers[-1] = (key, value + \" \" + line.strip())\n                    continue\n\n            key, value = line.split(\":\", 1)\n            headers.append((key, value.strip()))\n\n        return cls(headers)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/_version.py",
    "content": "# This file is protected via CODEOWNERS\n__version__ = \"1.26.20\"\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/connection.py",
    "content": "from __future__ import absolute_import\n\nimport datetime\nimport logging\nimport os\nimport re\nimport socket\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom .packages import six\nfrom .packages.six.moves.http_client import HTTPConnection as _HTTPConnection\nfrom .packages.six.moves.http_client import HTTPException  # noqa: F401\nfrom .util.proxy import create_proxy_ssl_context\n\ntry:  # Compiled with SSL?\n    import ssl\n\n    BaseSSLError = ssl.SSLError\nexcept (ImportError, AttributeError):  # Platform-specific: No SSL.\n    ssl = None\n\n    class BaseSSLError(BaseException):\n        pass\n\n\ntry:\n    # Python 3: not a no-op, we're adding this to the namespace so it can be imported.\n    ConnectionError = ConnectionError\nexcept NameError:\n    # Python 2\n    class ConnectionError(Exception):\n        pass\n\n\ntry:  # Python 3:\n    # Not a no-op, we're adding this to the namespace so it can be imported.\n    BrokenPipeError = BrokenPipeError\nexcept NameError:  # Python 2:\n\n    class BrokenPipeError(Exception):\n        pass\n\n\nfrom ._collections import HTTPHeaderDict  # noqa (historical, removed in v2)\nfrom ._version import __version__\nfrom .exceptions import (\n    ConnectTimeoutError,\n    NewConnectionError,\n    SubjectAltNameWarning,\n    SystemTimeWarning,\n)\nfrom .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection\nfrom .util.ssl_ import (\n    assert_fingerprint,\n    create_urllib3_context,\n    is_ipaddress,\n    resolve_cert_reqs,\n    resolve_ssl_version,\n    ssl_wrap_socket,\n)\nfrom .util.ssl_match_hostname import CertificateError, match_hostname\n\nlog = logging.getLogger(__name__)\n\nport_by_scheme = {\"http\": 80, \"https\": 443}\n\n# When it comes time to update this value as a part of regular maintenance\n# (ie test_recent_date is failing) update it to ~6 months before the current date.\nRECENT_DATE = datetime.date(2024, 1, 1)\n\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n\n\nclass HTTPConnection(_HTTPConnection, object):\n    \"\"\"\n    Based on :class:`http.client.HTTPConnection` but provides an extra constructor\n    backwards-compatibility layer between older and newer Pythons.\n\n    Additional keyword parameters are used to configure attributes of the connection.\n    Accepted parameters include:\n\n    - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`\n    - ``source_address``: Set the source address for the current connection.\n    - ``socket_options``: Set specific options on the underlying socket. If not specified, then\n      defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling\n      Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.\n\n      For example, if you wish to enable TCP Keep Alive in addition to the defaults,\n      you might pass:\n\n      .. code-block:: python\n\n         HTTPConnection.default_socket_options + [\n             (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),\n         ]\n\n      Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).\n    \"\"\"\n\n    default_port = port_by_scheme[\"http\"]\n\n    #: Disable Nagle's algorithm by default.\n    #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``\n    default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]\n\n    #: Whether this connection verifies the host's certificate.\n    is_verified = False\n\n    #: Whether this proxy connection (if used) verifies the proxy host's\n    #: certificate.\n    proxy_is_verified = None\n\n    def __init__(self, *args, **kw):\n        if not six.PY2:\n            kw.pop(\"strict\", None)\n\n        # Pre-set source_address.\n        self.source_address = kw.get(\"source_address\")\n\n        #: The socket options provided by the user. If no options are\n        #: provided, we use the default options.\n        self.socket_options = kw.pop(\"socket_options\", self.default_socket_options)\n\n        # Proxy options provided by the user.\n        self.proxy = kw.pop(\"proxy\", None)\n        self.proxy_config = kw.pop(\"proxy_config\", None)\n\n        _HTTPConnection.__init__(self, *args, **kw)\n\n    @property\n    def host(self):\n        \"\"\"\n        Getter method to remove any trailing dots that indicate the hostname is an FQDN.\n\n        In general, SSL certificates don't include the trailing dot indicating a\n        fully-qualified domain name, and thus, they don't validate properly when\n        checked against a domain name that includes the dot. In addition, some\n        servers may not expect to receive the trailing dot when provided.\n\n        However, the hostname with trailing dot is critical to DNS resolution; doing a\n        lookup with the trailing dot will properly only resolve the appropriate FQDN,\n        whereas a lookup without a trailing dot will search the system's search domain\n        list. Thus, it's important to keep the original host around for use only in\n        those cases where it's appropriate (i.e., when doing DNS lookup to establish the\n        actual TCP connection across which we're going to send HTTP requests).\n        \"\"\"\n        return self._dns_host.rstrip(\".\")\n\n    @host.setter\n    def host(self, value):\n        \"\"\"\n        Setter for the `host` property.\n\n        We assume that only urllib3 uses the _dns_host attribute; httplib itself\n        only uses `host`, and it seems reasonable that other libraries follow suit.\n        \"\"\"\n        self._dns_host = value\n\n    def _new_conn(self):\n        \"\"\"Establish a socket connection and set nodelay settings on it.\n\n        :return: New socket connection.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw[\"source_address\"] = self.source_address\n\n        if self.socket_options:\n            extra_kw[\"socket_options\"] = self.socket_options\n\n        try:\n            conn = connection.create_connection(\n                (self._dns_host, self.port), self.timeout, **extra_kw\n            )\n\n        except SocketTimeout:\n            raise ConnectTimeoutError(\n                self,\n                \"Connection to %s timed out. (connect timeout=%s)\"\n                % (self.host, self.timeout),\n            )\n\n        except SocketError as e:\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e\n            )\n\n        return conn\n\n    def _is_using_tunnel(self):\n        # Google App Engine's httplib does not define _tunnel_host\n        return getattr(self, \"_tunnel_host\", None)\n\n    def _prepare_conn(self, conn):\n        self.sock = conn\n        if self._is_using_tunnel():\n            # TODO: Fix tunnel so it doesn't depend on self.sock state.\n            self._tunnel()\n            # Mark this connection as not reusable\n            self.auto_open = 0\n\n    def connect(self):\n        conn = self._new_conn()\n        self._prepare_conn(conn)\n\n    def putrequest(self, method, url, *args, **kwargs):\n        \"\"\" \"\"\"\n        # Empty docstring because the indentation of CPython's implementation\n        # is broken but we don't want this method in our documentation.\n        match = _CONTAINS_CONTROL_CHAR_RE.search(method)\n        if match:\n            raise ValueError(\n                \"Method cannot contain non-token characters %r (found at least %r)\"\n                % (method, match.group())\n            )\n\n        return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)\n\n    def putheader(self, header, *values):\n        \"\"\" \"\"\"\n        if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):\n            _HTTPConnection.putheader(self, header, *values)\n        elif six.ensure_str(header.lower()) not in SKIPPABLE_HEADERS:\n            raise ValueError(\n                \"urllib3.util.SKIP_HEADER only supports '%s'\"\n                % (\"', '\".join(map(str.title, sorted(SKIPPABLE_HEADERS))),)\n            )\n\n    def request(self, method, url, body=None, headers=None):\n        # Update the inner socket's timeout value to send the request.\n        # This only triggers if the connection is re-used.\n        if getattr(self, \"sock\", None) is not None:\n            self.sock.settimeout(self.timeout)\n\n        if headers is None:\n            headers = {}\n        else:\n            # Avoid modifying the headers passed into .request()\n            headers = headers.copy()\n        if \"user-agent\" not in (six.ensure_str(k.lower()) for k in headers):\n            headers[\"User-Agent\"] = _get_default_user_agent()\n        super(HTTPConnection, self).request(method, url, body=body, headers=headers)\n\n    def request_chunked(self, method, url, body=None, headers=None):\n        \"\"\"\n        Alternative to the common request method, which sends the\n        body with chunked encoding and not as one block\n        \"\"\"\n        headers = headers or {}\n        header_keys = set([six.ensure_str(k.lower()) for k in headers])\n        skip_accept_encoding = \"accept-encoding\" in header_keys\n        skip_host = \"host\" in header_keys\n        self.putrequest(\n            method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host\n        )\n        if \"user-agent\" not in header_keys:\n            self.putheader(\"User-Agent\", _get_default_user_agent())\n        for header, value in headers.items():\n            self.putheader(header, value)\n        if \"transfer-encoding\" not in header_keys:\n            self.putheader(\"Transfer-Encoding\", \"chunked\")\n        self.endheaders()\n\n        if body is not None:\n            stringish_types = six.string_types + (bytes,)\n            if isinstance(body, stringish_types):\n                body = (body,)\n            for chunk in body:\n                if not chunk:\n                    continue\n                if not isinstance(chunk, bytes):\n                    chunk = chunk.encode(\"utf8\")\n                len_str = hex(len(chunk))[2:]\n                to_send = bytearray(len_str.encode())\n                to_send += b\"\\r\\n\"\n                to_send += chunk\n                to_send += b\"\\r\\n\"\n                self.send(to_send)\n\n        # After the if clause, to always have a closed body\n        self.send(b\"0\\r\\n\\r\\n\")\n\n\nclass HTTPSConnection(HTTPConnection):\n    \"\"\"\n    Many of the parameters to this constructor are passed to the underlying SSL\n    socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.\n    \"\"\"\n\n    default_port = port_by_scheme[\"https\"]\n\n    cert_reqs = None\n    ca_certs = None\n    ca_cert_dir = None\n    ca_cert_data = None\n    ssl_version = None\n    assert_fingerprint = None\n    tls_in_tls_required = False\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        key_file=None,\n        cert_file=None,\n        key_password=None,\n        strict=None,\n        timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n        ssl_context=None,\n        server_hostname=None,\n        **kw\n    ):\n\n        HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.key_password = key_password\n        self.ssl_context = ssl_context\n        self.server_hostname = server_hostname\n\n        # Required property for Google AppEngine 1.9.0 which otherwise causes\n        # HTTPS requests to go out as HTTP. (See Issue #356)\n        self._protocol = \"https\"\n\n    def set_cert(\n        self,\n        key_file=None,\n        cert_file=None,\n        cert_reqs=None,\n        key_password=None,\n        ca_certs=None,\n        assert_hostname=None,\n        assert_fingerprint=None,\n        ca_cert_dir=None,\n        ca_cert_data=None,\n    ):\n        \"\"\"\n        This method should only be called once, before the connection is used.\n        \"\"\"\n        # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also\n        # have an SSLContext object in which case we'll use its verify_mode.\n        if cert_reqs is None:\n            if self.ssl_context is not None:\n                cert_reqs = self.ssl_context.verify_mode\n            else:\n                cert_reqs = resolve_cert_reqs(None)\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.cert_reqs = cert_reqs\n        self.key_password = key_password\n        self.assert_hostname = assert_hostname\n        self.assert_fingerprint = assert_fingerprint\n        self.ca_certs = ca_certs and os.path.expanduser(ca_certs)\n        self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)\n        self.ca_cert_data = ca_cert_data\n\n    def connect(self):\n        # Add certificate verification\n        self.sock = conn = self._new_conn()\n        hostname = self.host\n        tls_in_tls = False\n\n        if self._is_using_tunnel():\n            if self.tls_in_tls_required:\n                self.sock = conn = self._connect_tls_proxy(hostname, conn)\n                tls_in_tls = True\n\n            # Calls self._set_hostport(), so self.host is\n            # self._tunnel_host below.\n            self._tunnel()\n            # Mark this connection as not reusable\n            self.auto_open = 0\n\n            # Override the host with the one we're requesting data from.\n            hostname = self._tunnel_host\n\n        server_hostname = hostname\n        if self.server_hostname is not None:\n            server_hostname = self.server_hostname\n\n        is_time_off = datetime.date.today() < RECENT_DATE\n        if is_time_off:\n            warnings.warn(\n                (\n                    \"System time is way off (before {0}). This will probably \"\n                    \"lead to SSL verification errors\"\n                ).format(RECENT_DATE),\n                SystemTimeWarning,\n            )\n\n        # Wrap socket using verification with the root certs in\n        # trusted_root_certs\n        default_ssl_context = False\n        if self.ssl_context is None:\n            default_ssl_context = True\n            self.ssl_context = create_urllib3_context(\n                ssl_version=resolve_ssl_version(self.ssl_version),\n                cert_reqs=resolve_cert_reqs(self.cert_reqs),\n            )\n\n        context = self.ssl_context\n        context.verify_mode = resolve_cert_reqs(self.cert_reqs)\n\n        # Try to load OS default certs if none are given.\n        # Works well on Windows (requires Python3.4+)\n        if (\n            not self.ca_certs\n            and not self.ca_cert_dir\n            and not self.ca_cert_data\n            and default_ssl_context\n            and hasattr(context, \"load_default_certs\")\n        ):\n            context.load_default_certs()\n\n        self.sock = ssl_wrap_socket(\n            sock=conn,\n            keyfile=self.key_file,\n            certfile=self.cert_file,\n            key_password=self.key_password,\n            ca_certs=self.ca_certs,\n            ca_cert_dir=self.ca_cert_dir,\n            ca_cert_data=self.ca_cert_data,\n            server_hostname=server_hostname,\n            ssl_context=context,\n            tls_in_tls=tls_in_tls,\n        )\n\n        # If we're using all defaults and the connection\n        # is TLSv1 or TLSv1.1 we throw a DeprecationWarning\n        # for the host.\n        if (\n            default_ssl_context\n            and self.ssl_version is None\n            and hasattr(self.sock, \"version\")\n            and self.sock.version() in {\"TLSv1\", \"TLSv1.1\"}\n        ):  # Defensive:\n            warnings.warn(\n                \"Negotiating TLSv1/TLSv1.1 by default is deprecated \"\n                \"and will be disabled in urllib3 v2.0.0. Connecting to \"\n                \"'%s' with '%s' can be enabled by explicitly opting-in \"\n                \"with 'ssl_version'\" % (self.host, self.sock.version()),\n                DeprecationWarning,\n            )\n\n        if self.assert_fingerprint:\n            assert_fingerprint(\n                self.sock.getpeercert(binary_form=True), self.assert_fingerprint\n            )\n        elif (\n            context.verify_mode != ssl.CERT_NONE\n            and not getattr(context, \"check_hostname\", False)\n            and self.assert_hostname is not False\n        ):\n            # While urllib3 attempts to always turn off hostname matching from\n            # the TLS library, this cannot always be done. So we check whether\n            # the TLS Library still thinks it's matching hostnames.\n            cert = self.sock.getpeercert()\n            if not cert.get(\"subjectAltName\", ()):\n                warnings.warn(\n                    (\n                        \"Certificate for {0} has no `subjectAltName`, falling back to check for a \"\n                        \"`commonName` for now. This feature is being removed by major browsers and \"\n                        \"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 \"\n                        \"for details.)\".format(hostname)\n                    ),\n                    SubjectAltNameWarning,\n                )\n            _match_hostname(cert, self.assert_hostname or server_hostname)\n\n        self.is_verified = (\n            context.verify_mode == ssl.CERT_REQUIRED\n            or self.assert_fingerprint is not None\n        )\n\n    def _connect_tls_proxy(self, hostname, conn):\n        \"\"\"\n        Establish a TLS connection to the proxy using the provided SSL context.\n        \"\"\"\n        proxy_config = self.proxy_config\n        ssl_context = proxy_config.ssl_context\n        if ssl_context:\n            # If the user provided a proxy context, we assume CA and client\n            # certificates have already been set\n            return ssl_wrap_socket(\n                sock=conn,\n                server_hostname=hostname,\n                ssl_context=ssl_context,\n            )\n\n        ssl_context = create_proxy_ssl_context(\n            self.ssl_version,\n            self.cert_reqs,\n            self.ca_certs,\n            self.ca_cert_dir,\n            self.ca_cert_data,\n        )\n\n        # If no cert was provided, use only the default options for server\n        # certificate validation\n        socket = ssl_wrap_socket(\n            sock=conn,\n            ca_certs=self.ca_certs,\n            ca_cert_dir=self.ca_cert_dir,\n            ca_cert_data=self.ca_cert_data,\n            server_hostname=hostname,\n            ssl_context=ssl_context,\n        )\n\n        if ssl_context.verify_mode != ssl.CERT_NONE and not getattr(\n            ssl_context, \"check_hostname\", False\n        ):\n            # While urllib3 attempts to always turn off hostname matching from\n            # the TLS library, this cannot always be done. So we check whether\n            # the TLS Library still thinks it's matching hostnames.\n            cert = socket.getpeercert()\n            if not cert.get(\"subjectAltName\", ()):\n                warnings.warn(\n                    (\n                        \"Certificate for {0} has no `subjectAltName`, falling back to check for a \"\n                        \"`commonName` for now. This feature is being removed by major browsers and \"\n                        \"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 \"\n                        \"for details.)\".format(hostname)\n                    ),\n                    SubjectAltNameWarning,\n                )\n            _match_hostname(cert, hostname)\n\n        self.proxy_is_verified = ssl_context.verify_mode == ssl.CERT_REQUIRED\n        return socket\n\n\ndef _match_hostname(cert, asserted_hostname):\n    # Our upstream implementation of ssl.match_hostname()\n    # only applies this normalization to IP addresses so it doesn't\n    # match DNS SANs so we do the same thing!\n    stripped_hostname = asserted_hostname.strip(\"u[]\")\n    if is_ipaddress(stripped_hostname):\n        asserted_hostname = stripped_hostname\n\n    try:\n        match_hostname(cert, asserted_hostname)\n    except CertificateError as e:\n        log.warning(\n            \"Certificate did not match expected hostname: %s. Certificate: %s\",\n            asserted_hostname,\n            cert,\n        )\n        # Add cert to exception and reraise so client code can inspect\n        # the cert when catching the exception, if they want to\n        e._peer_cert = cert\n        raise\n\n\ndef _get_default_user_agent():\n    return \"python-urllib3/%s\" % __version__\n\n\nclass DummyConnection(object):\n    \"\"\"Used to detect a failed ConnectionCls import.\"\"\"\n\n    pass\n\n\nif not ssl:\n    HTTPSConnection = DummyConnection  # noqa: F811\n\n\nVerifiedHTTPSConnection = HTTPSConnection\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/connectionpool.py",
    "content": "from __future__ import absolute_import\n\nimport errno\nimport logging\nimport re\nimport socket\nimport sys\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom ._collections import HTTPHeaderDict\nfrom .connection import (\n    BaseSSLError,\n    BrokenPipeError,\n    DummyConnection,\n    HTTPConnection,\n    HTTPException,\n    HTTPSConnection,\n    VerifiedHTTPSConnection,\n    port_by_scheme,\n)\nfrom .exceptions import (\n    ClosedPoolError,\n    EmptyPoolError,\n    HeaderParsingError,\n    HostChangedError,\n    InsecureRequestWarning,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ProxyError,\n    ReadTimeoutError,\n    SSLError,\n    TimeoutError,\n)\nfrom .packages import six\nfrom .packages.six.moves import queue\nfrom .request import RequestMethods\nfrom .response import HTTPResponse\nfrom .util.connection import is_connection_dropped\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.queue import LifoQueue\nfrom .util.request import set_file_position\nfrom .util.response import assert_header_parsing\nfrom .util.retry import Retry\nfrom .util.ssl_match_hostname import CertificateError\nfrom .util.timeout import Timeout\nfrom .util.url import Url, _encode_target\nfrom .util.url import _normalize_host as normalize_host\nfrom .util.url import get_host, parse_url\n\ntry:  # Platform-specific: Python 3\n    import weakref\n\n    weakref_finalize = weakref.finalize\nexcept AttributeError:  # Platform-specific: Python 2\n    from .packages.backports.weakref_finalize import weakref_finalize\n\nxrange = six.moves.xrange\n\nlog = logging.getLogger(__name__)\n\n_Default = object()\n\n\n# Pool objects\nclass ConnectionPool(object):\n    \"\"\"\n    Base class for all connection pools, such as\n    :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.\n\n    .. note::\n       ConnectionPool.urlopen() does not normalize or percent-encode target URIs\n       which is useful if your target server doesn't support percent-encoded\n       target URIs.\n    \"\"\"\n\n    scheme = None\n    QueueCls = LifoQueue\n\n    def __init__(self, host, port=None):\n        if not host:\n            raise LocationValueError(\"No host specified.\")\n\n        self.host = _normalize_host(host, scheme=self.scheme)\n        self._proxy_host = host.lower()\n        self.port = port\n\n    def __str__(self):\n        return \"%s(host=%r, port=%r)\" % (type(self).__name__, self.host, self.port)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.close()\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def close(self):\n        \"\"\"\n        Close all pooled connections and disable the pool.\n        \"\"\"\n        pass\n\n\n# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252\n_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}\n\n\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\n    \"\"\"\n    Thread-safe connection pool for one host.\n\n    :param host:\n        Host used for this HTTP Connection (e.g. \"localhost\"), passed into\n        :class:`http.client.HTTPConnection`.\n\n    :param port:\n        Port used for this HTTP Connection (None is equivalent to 80), passed\n        into :class:`http.client.HTTPConnection`.\n\n    :param strict:\n        Causes BadStatusLine to be raised if the status line can't be parsed\n        as a valid HTTP/1.0 or 1.1 status line, passed into\n        :class:`http.client.HTTPConnection`.\n\n        .. note::\n           Only works in Python 2. This parameter is ignored in Python 3.\n\n    :param timeout:\n        Socket timeout in seconds for each individual connection. This can\n        be a float or integer, which sets the timeout for the HTTP request,\n        or an instance of :class:`urllib3.util.Timeout` which gives you more\n        fine-grained control over request timeouts. After the constructor has\n        been parsed, this is always a `urllib3.util.Timeout` object.\n\n    :param maxsize:\n        Number of connections to save that can be reused. More than 1 is useful\n        in multithreaded situations. If ``block`` is set to False, more\n        connections will be created but they will not be saved once they've\n        been used.\n\n    :param block:\n        If set to True, no more than ``maxsize`` connections will be used at\n        a time. When no free connections are available, the call will block\n        until a connection has been released. This is a useful side effect for\n        particular multithreaded situations where one does not want to use more\n        than maxsize connections per host to prevent flooding.\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n\n    :param retries:\n        Retry configuration to use by default with requests in this pool.\n\n    :param _proxy:\n        Parsed proxy URL, should not be used directly, instead, see\n        :class:`urllib3.ProxyManager`\n\n    :param _proxy_headers:\n        A dictionary with proxy headers, should not be used directly,\n        instead, see :class:`urllib3.ProxyManager`\n\n    :param \\\\**conn_kw:\n        Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,\n        :class:`urllib3.connection.HTTPSConnection` instances.\n    \"\"\"\n\n    scheme = \"http\"\n    ConnectionCls = HTTPConnection\n    ResponseCls = HTTPResponse\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        strict=False,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        maxsize=1,\n        block=False,\n        headers=None,\n        retries=None,\n        _proxy=None,\n        _proxy_headers=None,\n        _proxy_config=None,\n        **conn_kw\n    ):\n        ConnectionPool.__init__(self, host, port)\n        RequestMethods.__init__(self, headers)\n\n        self.strict = strict\n\n        if not isinstance(timeout, Timeout):\n            timeout = Timeout.from_float(timeout)\n\n        if retries is None:\n            retries = Retry.DEFAULT\n\n        self.timeout = timeout\n        self.retries = retries\n\n        self.pool = self.QueueCls(maxsize)\n        self.block = block\n\n        self.proxy = _proxy\n        self.proxy_headers = _proxy_headers or {}\n        self.proxy_config = _proxy_config\n\n        # Fill the queue up so that doing get() on it will block properly\n        for _ in xrange(maxsize):\n            self.pool.put(None)\n\n        # These are mostly for testing and debugging purposes.\n        self.num_connections = 0\n        self.num_requests = 0\n        self.conn_kw = conn_kw\n\n        if self.proxy:\n            # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.\n            # We cannot know if the user has added default socket options, so we cannot replace the\n            # list.\n            self.conn_kw.setdefault(\"socket_options\", [])\n\n            self.conn_kw[\"proxy\"] = self.proxy\n            self.conn_kw[\"proxy_config\"] = self.proxy_config\n\n        # Do not pass 'self' as callback to 'finalize'.\n        # Then the 'finalize' would keep an endless living (leak) to self.\n        # By just passing a reference to the pool allows the garbage collector\n        # to free self if nobody else has a reference to it.\n        pool = self.pool\n\n        # Close all the HTTPConnections in the pool before the\n        # HTTPConnectionPool object is garbage collected.\n        weakref_finalize(self, _close_pool_connections, pool)\n\n    def _new_conn(self):\n        \"\"\"\n        Return a fresh :class:`HTTPConnection`.\n        \"\"\"\n        self.num_connections += 1\n        log.debug(\n            \"Starting new HTTP connection (%d): %s:%s\",\n            self.num_connections,\n            self.host,\n            self.port or \"80\",\n        )\n\n        conn = self.ConnectionCls(\n            host=self.host,\n            port=self.port,\n            timeout=self.timeout.connect_timeout,\n            strict=self.strict,\n            **self.conn_kw\n        )\n        return conn\n\n    def _get_conn(self, timeout=None):\n        \"\"\"\n        Get a connection. Will return a pooled connection if one is available.\n\n        If no connections are available and :prop:`.block` is ``False``, then a\n        fresh connection is returned.\n\n        :param timeout:\n            Seconds to wait before giving up and raising\n            :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n            :prop:`.block` is ``True``.\n        \"\"\"\n        conn = None\n        try:\n            conn = self.pool.get(block=self.block, timeout=timeout)\n\n        except AttributeError:  # self.pool is None\n            raise ClosedPoolError(self, \"Pool is closed.\")\n\n        except queue.Empty:\n            if self.block:\n                raise EmptyPoolError(\n                    self,\n                    \"Pool reached maximum size and no more connections are allowed.\",\n                )\n            pass  # Oh well, we'll create a new connection then\n\n        # If this is a persistent connection, check if it got disconnected\n        if conn and is_connection_dropped(conn):\n            log.debug(\"Resetting dropped connection: %s\", self.host)\n            conn.close()\n            if getattr(conn, \"auto_open\", 1) == 0:\n                # This is a proxied connection that has been mutated by\n                # http.client._tunnel() and cannot be reused (since it would\n                # attempt to bypass the proxy)\n                conn = None\n\n        return conn or self._new_conn()\n\n    def _put_conn(self, conn):\n        \"\"\"\n        Put a connection back into the pool.\n\n        :param conn:\n            Connection object for the current host and port as returned by\n            :meth:`._new_conn` or :meth:`._get_conn`.\n\n        If the pool is already full, the connection is closed and discarded\n        because we exceeded maxsize. If connections are discarded frequently,\n        then maxsize should be increased.\n\n        If the pool is closed, then the connection will be closed and discarded.\n        \"\"\"\n        try:\n            self.pool.put(conn, block=False)\n            return  # Everything is dandy, done.\n        except AttributeError:\n            # self.pool is None.\n            pass\n        except queue.Full:\n            # This should never happen if self.block == True\n            log.warning(\n                \"Connection pool is full, discarding connection: %s. Connection pool size: %s\",\n                self.host,\n                self.pool.qsize(),\n            )\n        # Connection never got put back into the pool, close it.\n        if conn:\n            conn.close()\n\n    def _validate_conn(self, conn):\n        \"\"\"\n        Called right before a request is made, after the socket is created.\n        \"\"\"\n        pass\n\n    def _prepare_proxy(self, conn):\n        # Nothing to do for HTTP connections.\n        pass\n\n    def _get_timeout(self, timeout):\n        \"\"\"Helper that always returns a :class:`urllib3.util.Timeout`\"\"\"\n        if timeout is _Default:\n            return self.timeout.clone()\n\n        if isinstance(timeout, Timeout):\n            return timeout.clone()\n        else:\n            # User passed us an int/float. This is for backwards compatibility,\n            # can be removed later\n            return Timeout.from_float(timeout)\n\n    def _raise_timeout(self, err, url, timeout_value):\n        \"\"\"Is the error actually a timeout? Will raise a ReadTimeout or pass\"\"\"\n\n        if isinstance(err, SocketTimeout):\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n        # See the above comment about EAGAIN in Python 3. In Python 2 we have\n        # to specifically catch it and throw the timeout error\n        if hasattr(err, \"errno\") and err.errno in _blocking_errnos:\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n        # Catch possible read timeouts thrown as SSL errors. If not the\n        # case, rethrow the original. We need to do this because of:\n        # http://bugs.python.org/issue10272\n        if \"timed out\" in str(err) or \"did not complete (read)\" in str(\n            err\n        ):  # Python < 2.7.4\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n    def _make_request(\n        self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw\n    ):\n        \"\"\"\n        Perform a request on a given urllib connection object taken from our\n        pool.\n\n        :param conn:\n            a connection from one of our connection pools\n\n        :param timeout:\n            Socket timeout in seconds for the request. This can be a\n            float or integer, which will set the same timeout value for\n            the socket connect and the socket read, or an instance of\n            :class:`urllib3.util.Timeout`, which gives you more fine-grained\n            control over your timeouts.\n        \"\"\"\n        self.num_requests += 1\n\n        timeout_obj = self._get_timeout(timeout)\n        timeout_obj.start_connect()\n        conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout)\n\n        # Trigger any extra validation we need to do.\n        try:\n            self._validate_conn(conn)\n        except (SocketTimeout, BaseSSLError) as e:\n            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.\n            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)\n            raise\n\n        # conn.request() calls http.client.*.request, not the method in\n        # urllib3.request. It also calls makefile (recv) on the socket.\n        try:\n            if chunked:\n                conn.request_chunked(method, url, **httplib_request_kw)\n            else:\n                conn.request(method, url, **httplib_request_kw)\n\n        # We are swallowing BrokenPipeError (errno.EPIPE) since the server is\n        # legitimately able to close the connection after sending a valid response.\n        # With this behaviour, the received response is still readable.\n        except BrokenPipeError:\n            # Python 3\n            pass\n        except IOError as e:\n            # Python 2 and macOS/Linux\n            # EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE/ECONNRESET are needed on macOS\n            # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/\n            if e.errno not in {\n                errno.EPIPE,\n                errno.ESHUTDOWN,\n                errno.EPROTOTYPE,\n                errno.ECONNRESET,\n            }:\n                raise\n\n        # Reset the timeout for the recv() on the socket\n        read_timeout = timeout_obj.read_timeout\n\n        # App Engine doesn't have a sock attr\n        if getattr(conn, \"sock\", None):\n            # In Python 3 socket.py will catch EAGAIN and return None when you\n            # try and read into the file pointer created by http.client, which\n            # instead raises a BadStatusLine exception. Instead of catching\n            # the exception and assuming all BadStatusLine exceptions are read\n            # timeouts, check for a zero timeout before making the request.\n            if read_timeout == 0:\n                raise ReadTimeoutError(\n                    self, url, \"Read timed out. (read timeout=%s)\" % read_timeout\n                )\n            if read_timeout is Timeout.DEFAULT_TIMEOUT:\n                conn.sock.settimeout(socket.getdefaulttimeout())\n            else:  # None or a value\n                conn.sock.settimeout(read_timeout)\n\n        # Receive the response from the server\n        try:\n            try:\n                # Python 2.7, use buffering of HTTP responses\n                httplib_response = conn.getresponse(buffering=True)\n            except TypeError:\n                # Python 3\n                try:\n                    httplib_response = conn.getresponse()\n                except BaseException as e:\n                    # Remove the TypeError from the exception chain in\n                    # Python 3 (including for exceptions like SystemExit).\n                    # Otherwise it looks like a bug in the code.\n                    six.raise_from(e, None)\n        except (SocketTimeout, BaseSSLError, SocketError) as e:\n            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)\n            raise\n\n        # AppEngine doesn't have a version attr.\n        http_version = getattr(conn, \"_http_vsn_str\", \"HTTP/?\")\n        log.debug(\n            '%s://%s:%s \"%s %s %s\" %s %s',\n            self.scheme,\n            self.host,\n            self.port,\n            method,\n            url,\n            http_version,\n            httplib_response.status,\n            httplib_response.length,\n        )\n\n        try:\n            assert_header_parsing(httplib_response.msg)\n        except (HeaderParsingError, TypeError) as hpe:  # Platform-specific: Python 3\n            log.warning(\n                \"Failed to parse headers (url=%s): %s\",\n                self._absolute_url(url),\n                hpe,\n                exc_info=True,\n            )\n\n        return httplib_response\n\n    def _absolute_url(self, path):\n        return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url\n\n    def close(self):\n        \"\"\"\n        Close all pooled connections and disable the pool.\n        \"\"\"\n        if self.pool is None:\n            return\n        # Disable access to the pool\n        old_pool, self.pool = self.pool, None\n\n        # Close all the HTTPConnections in the pool.\n        _close_pool_connections(old_pool)\n\n    def is_same_host(self, url):\n        \"\"\"\n        Check if the given ``url`` is a member of the same host as this\n        connection pool.\n        \"\"\"\n        if url.startswith(\"/\"):\n            return True\n\n        # TODO: Add optional support for socket.gethostbyname checking.\n        scheme, host, port = get_host(url)\n        if host is not None:\n            host = _normalize_host(host, scheme=scheme)\n\n        # Use explicit default port for comparison when none is given\n        if self.port and not port:\n            port = port_by_scheme.get(scheme)\n        elif not self.port and port == port_by_scheme.get(scheme):\n            port = None\n\n        return (scheme, host, port) == (self.scheme, self.host, self.port)\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=None,\n        redirect=True,\n        assert_same_host=True,\n        timeout=_Default,\n        pool_timeout=None,\n        release_conn=None,\n        chunked=False,\n        body_pos=None,\n        **response_kw\n    ):\n        \"\"\"\n        Get a connection from the pool and perform an HTTP request. This is the\n        lowest level call for making a request, so you'll need to specify all\n        the raw details.\n\n        .. note::\n\n           More commonly, it's appropriate to use a convenience method provided\n           by :class:`.RequestMethods`, such as :meth:`request`.\n\n        .. note::\n\n           `release_conn` will only behave as expected if\n           `preload_content=False` because we want to make\n           `preload_content=False` the default behaviour someday soon without\n           breaking backwards compatibility.\n\n        :param method:\n            HTTP request method (such as GET, POST, PUT, etc.)\n\n        :param url:\n            The URL to perform the request on.\n\n        :param body:\n            Data to send in the request body, either :class:`str`, :class:`bytes`,\n            an iterable of :class:`str`/:class:`bytes`, or a file-like object.\n\n        :param headers:\n            Dictionary of custom headers to send, such as User-Agent,\n            If-None-Match, etc. If None, pool headers are used. If provided,\n            these headers completely replace any pool-specific headers.\n\n        :param retries:\n            Configure the number of retries to allow before raising a\n            :class:`~urllib3.exceptions.MaxRetryError` exception.\n\n            Pass ``None`` to retry until you receive a response. Pass a\n            :class:`~urllib3.util.retry.Retry` object for fine-grained control\n            over different types of retries.\n            Pass an integer number to retry connection errors that many times,\n            but no other types of errors. Pass zero to never retry.\n\n            If ``False``, then retries are disabled and any exception is raised\n            immediately. Also, instead of raising a MaxRetryError on redirects,\n            the redirect response will be returned.\n\n        :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.\n\n        :param redirect:\n            If True, automatically handle redirects (status codes 301, 302,\n            303, 307, 308). Each redirect counts as a retry. Disabling retries\n            will disable redirect, too.\n\n        :param assert_same_host:\n            If ``True``, will make sure that the host of the pool requests is\n            consistent else will raise HostChangedError. When ``False``, you can\n            use the pool on an HTTP proxy and request foreign hosts.\n\n        :param timeout:\n            If specified, overrides the default timeout for this one\n            request. It may be a float (in seconds) or an instance of\n            :class:`urllib3.util.Timeout`.\n\n        :param pool_timeout:\n            If set and the pool is set to block=True, then this method will\n            block for ``pool_timeout`` seconds and raise EmptyPoolError if no\n            connection is available within the time period.\n\n        :param release_conn:\n            If False, then the urlopen call will not release the connection\n            back into the pool once a response is received (but will release if\n            you read the entire contents of the response such as when\n            `preload_content=True`). This is useful if you're not preloading\n            the response's content immediately. You will need to call\n            ``r.release_conn()`` on the response ``r`` to return the connection\n            back into the pool. If None, it takes the value of\n            ``response_kw.get('preload_content', True)``.\n\n        :param chunked:\n            If True, urllib3 will send the body using chunked transfer\n            encoding. Otherwise, urllib3 will send the body using the standard\n            content-length form. Defaults to False.\n\n        :param int body_pos:\n            Position to seek to in file-like body in the event of a retry or\n            redirect. Typically this won't need to be set because urllib3 will\n            auto-populate the value when needed.\n\n        :param \\\\**response_kw:\n            Additional parameters are passed to\n            :meth:`urllib3.response.HTTPResponse.from_httplib`\n        \"\"\"\n\n        parsed_url = parse_url(url)\n        destination_scheme = parsed_url.scheme\n\n        if headers is None:\n            headers = self.headers\n\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n        if release_conn is None:\n            release_conn = response_kw.get(\"preload_content\", True)\n\n        # Check host\n        if assert_same_host and not self.is_same_host(url):\n            raise HostChangedError(self, url, retries)\n\n        # Ensure that the URL we're connecting to is properly encoded\n        if url.startswith(\"/\"):\n            url = six.ensure_str(_encode_target(url))\n        else:\n            url = six.ensure_str(parsed_url.url)\n\n        conn = None\n\n        # Track whether `conn` needs to be released before\n        # returning/raising/recursing. Update this variable if necessary, and\n        # leave `release_conn` constant throughout the function. That way, if\n        # the function recurses, the original value of `release_conn` will be\n        # passed down into the recursive call, and its value will be respected.\n        #\n        # See issue #651 [1] for details.\n        #\n        # [1] <https://github.com/urllib3/urllib3/issues/651>\n        release_this_conn = release_conn\n\n        http_tunnel_required = connection_requires_http_tunnel(\n            self.proxy, self.proxy_config, destination_scheme\n        )\n\n        # Merge the proxy headers. Only done when not using HTTP CONNECT. We\n        # have to copy the headers dict so we can safely change it without those\n        # changes being reflected in anyone else's copy.\n        if not http_tunnel_required:\n            headers = headers.copy()\n            headers.update(self.proxy_headers)\n\n        # Must keep the exception bound to a separate variable or else Python 3\n        # complains about UnboundLocalError.\n        err = None\n\n        # Keep track of whether we cleanly exited the except block. This\n        # ensures we do proper cleanup in finally.\n        clean_exit = False\n\n        # Rewind body position, if needed. Record current position\n        # for future rewinds in the event of a redirect/retry.\n        body_pos = set_file_position(body, body_pos)\n\n        try:\n            # Request a connection from the queue.\n            timeout_obj = self._get_timeout(timeout)\n            conn = self._get_conn(timeout=pool_timeout)\n\n            conn.timeout = timeout_obj.connect_timeout\n\n            is_new_proxy_conn = self.proxy is not None and not getattr(\n                conn, \"sock\", None\n            )\n            if is_new_proxy_conn and http_tunnel_required:\n                self._prepare_proxy(conn)\n\n            # Make the request on the httplib connection object.\n            httplib_response = self._make_request(\n                conn,\n                method,\n                url,\n                timeout=timeout_obj,\n                body=body,\n                headers=headers,\n                chunked=chunked,\n            )\n\n            # If we're going to release the connection in ``finally:``, then\n            # the response doesn't need to know about the connection. Otherwise\n            # it will also try to release it and we'll have a double-release\n            # mess.\n            response_conn = conn if not release_conn else None\n\n            # Pass method to Response for length checking\n            response_kw[\"request_method\"] = method\n\n            # Import httplib's response into our own wrapper object\n            response = self.ResponseCls.from_httplib(\n                httplib_response,\n                pool=self,\n                connection=response_conn,\n                retries=retries,\n                **response_kw\n            )\n\n            # Everything went great!\n            clean_exit = True\n\n        except EmptyPoolError:\n            # Didn't get a connection from the pool, no need to clean up\n            clean_exit = True\n            release_this_conn = False\n            raise\n\n        except (\n            TimeoutError,\n            HTTPException,\n            SocketError,\n            ProtocolError,\n            BaseSSLError,\n            SSLError,\n            CertificateError,\n        ) as e:\n            # Discard the connection for these exceptions. It will be\n            # replaced during the next _get_conn() call.\n            clean_exit = False\n\n            def _is_ssl_error_message_from_http_proxy(ssl_error):\n                # We're trying to detect the message 'WRONG_VERSION_NUMBER' but\n                # SSLErrors are kinda all over the place when it comes to the message,\n                # so we try to cover our bases here!\n                message = \" \".join(re.split(\"[^a-z]\", str(ssl_error).lower()))\n                return (\n                    \"wrong version number\" in message\n                    or \"unknown protocol\" in message\n                    or \"record layer failure\" in message\n                )\n\n            # Try to detect a common user error with proxies which is to\n            # set an HTTP proxy to be HTTPS when it should be 'http://'\n            # (ie {'http': 'http://proxy', 'https': 'https://proxy'})\n            # Instead we add a nice error message and point to a URL.\n            if (\n                isinstance(e, BaseSSLError)\n                and self.proxy\n                and _is_ssl_error_message_from_http_proxy(e)\n                and conn.proxy\n                and conn.proxy.scheme == \"https\"\n            ):\n                e = ProxyError(\n                    \"Your proxy appears to only use HTTP and not HTTPS, \"\n                    \"try changing your proxy URL to be HTTP. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#https-proxy-error-http-proxy\",\n                    SSLError(e),\n                )\n            elif isinstance(e, (BaseSSLError, CertificateError)):\n                e = SSLError(e)\n            elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:\n                e = ProxyError(\"Cannot connect to proxy.\", e)\n            elif isinstance(e, (SocketError, HTTPException)):\n                e = ProtocolError(\"Connection aborted.\", e)\n\n            retries = retries.increment(\n                method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]\n            )\n            retries.sleep()\n\n            # Keep track of the error for the retry warning.\n            err = e\n\n        finally:\n            if not clean_exit:\n                # We hit some kind of exception, handled or otherwise. We need\n                # to throw the connection away unless explicitly told not to.\n                # Close the connection, set the variable to None, and make sure\n                # we put the None back in the pool to avoid leaking it.\n                conn = conn and conn.close()\n                release_this_conn = True\n\n            if release_this_conn:\n                # Put the connection back to be reused. If the connection is\n                # expired then it will be None, which will get replaced with a\n                # fresh connection during _get_conn.\n                self._put_conn(conn)\n\n        if not conn:\n            # Try again\n            log.warning(\n                \"Retrying (%r) after connection broken by '%r': %s\", retries, err, url\n            )\n            return self.urlopen(\n                method,\n                url,\n                body,\n                headers,\n                retries,\n                redirect,\n                assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        # Handle redirect?\n        redirect_location = redirect and response.get_redirect_location()\n        if redirect_location:\n            if response.status == 303:\n                # Change the method according to RFC 9110, Section 15.4.4.\n                method = \"GET\"\n                # And lose the body not to transfer anything sensitive.\n                body = None\n                headers = HTTPHeaderDict(headers)._prepare_for_method_change()\n\n            try:\n                retries = retries.increment(method, url, response=response, _pool=self)\n            except MaxRetryError:\n                if retries.raise_on_redirect:\n                    response.drain_conn()\n                    raise\n                return response\n\n            response.drain_conn()\n            retries.sleep_for_retry(response)\n            log.debug(\"Redirecting %s -> %s\", url, redirect_location)\n            return self.urlopen(\n                method,\n                redirect_location,\n                body,\n                headers,\n                retries=retries,\n                redirect=redirect,\n                assert_same_host=assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        # Check if we should retry the HTTP response.\n        has_retry_after = bool(response.headers.get(\"Retry-After\"))\n        if retries.is_retry(method, response.status, has_retry_after):\n            try:\n                retries = retries.increment(method, url, response=response, _pool=self)\n            except MaxRetryError:\n                if retries.raise_on_status:\n                    response.drain_conn()\n                    raise\n                return response\n\n            response.drain_conn()\n            retries.sleep(response)\n            log.debug(\"Retry: %s\", url)\n            return self.urlopen(\n                method,\n                url,\n                body,\n                headers,\n                retries=retries,\n                redirect=redirect,\n                assert_same_host=assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        return response\n\n\nclass HTTPSConnectionPool(HTTPConnectionPool):\n    \"\"\"\n    Same as :class:`.HTTPConnectionPool`, but HTTPS.\n\n    :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,\n    ``assert_hostname`` and ``host`` in this order to verify connections.\n    If ``assert_hostname`` is False, no verification is done.\n\n    The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,\n    ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`\n    is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade\n    the connection socket into an SSL socket.\n    \"\"\"\n\n    scheme = \"https\"\n    ConnectionCls = HTTPSConnection\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        strict=False,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        maxsize=1,\n        block=False,\n        headers=None,\n        retries=None,\n        _proxy=None,\n        _proxy_headers=None,\n        key_file=None,\n        cert_file=None,\n        cert_reqs=None,\n        key_password=None,\n        ca_certs=None,\n        ssl_version=None,\n        assert_hostname=None,\n        assert_fingerprint=None,\n        ca_cert_dir=None,\n        **conn_kw\n    ):\n\n        HTTPConnectionPool.__init__(\n            self,\n            host,\n            port,\n            strict,\n            timeout,\n            maxsize,\n            block,\n            headers,\n            retries,\n            _proxy,\n            _proxy_headers,\n            **conn_kw\n        )\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.cert_reqs = cert_reqs\n        self.key_password = key_password\n        self.ca_certs = ca_certs\n        self.ca_cert_dir = ca_cert_dir\n        self.ssl_version = ssl_version\n        self.assert_hostname = assert_hostname\n        self.assert_fingerprint = assert_fingerprint\n\n    def _prepare_conn(self, conn):\n        \"\"\"\n        Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`\n        and establish the tunnel if proxy is used.\n        \"\"\"\n\n        if isinstance(conn, VerifiedHTTPSConnection):\n            conn.set_cert(\n                key_file=self.key_file,\n                key_password=self.key_password,\n                cert_file=self.cert_file,\n                cert_reqs=self.cert_reqs,\n                ca_certs=self.ca_certs,\n                ca_cert_dir=self.ca_cert_dir,\n                assert_hostname=self.assert_hostname,\n                assert_fingerprint=self.assert_fingerprint,\n            )\n            conn.ssl_version = self.ssl_version\n        return conn\n\n    def _prepare_proxy(self, conn):\n        \"\"\"\n        Establishes a tunnel connection through HTTP CONNECT.\n\n        Tunnel connection is established early because otherwise httplib would\n        improperly set Host: header to proxy's IP:port.\n        \"\"\"\n\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n\n        if self.proxy.scheme == \"https\":\n            conn.tls_in_tls_required = True\n\n        conn.connect()\n\n    def _new_conn(self):\n        \"\"\"\n        Return a fresh :class:`http.client.HTTPSConnection`.\n        \"\"\"\n        self.num_connections += 1\n        log.debug(\n            \"Starting new HTTPS connection (%d): %s:%s\",\n            self.num_connections,\n            self.host,\n            self.port or \"443\",\n        )\n\n        if not self.ConnectionCls or self.ConnectionCls is DummyConnection:\n            raise SSLError(\n                \"Can't connect to HTTPS URL because the SSL module is not available.\"\n            )\n\n        actual_host = self.host\n        actual_port = self.port\n        if self.proxy is not None:\n            actual_host = self.proxy.host\n            actual_port = self.proxy.port\n\n        conn = self.ConnectionCls(\n            host=actual_host,\n            port=actual_port,\n            timeout=self.timeout.connect_timeout,\n            strict=self.strict,\n            cert_file=self.cert_file,\n            key_file=self.key_file,\n            key_password=self.key_password,\n            **self.conn_kw\n        )\n\n        return self._prepare_conn(conn)\n\n    def _validate_conn(self, conn):\n        \"\"\"\n        Called right before a request is made, after the socket is created.\n        \"\"\"\n        super(HTTPSConnectionPool, self)._validate_conn(conn)\n\n        # Force connect early to allow us to validate the connection.\n        if not getattr(conn, \"sock\", None):  # AppEngine might not have  `.sock`\n            conn.connect()\n\n        if not conn.is_verified:\n            warnings.warn(\n                (\n                    \"Unverified HTTPS request is being made to host '%s'. \"\n                    \"Adding certificate verification is strongly advised. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#ssl-warnings\" % conn.host\n                ),\n                InsecureRequestWarning,\n            )\n\n        if getattr(conn, \"proxy_is_verified\", None) is False:\n            warnings.warn(\n                (\n                    \"Unverified HTTPS connection done to an HTTPS proxy. \"\n                    \"Adding certificate verification is strongly advised. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#ssl-warnings\"\n                ),\n                InsecureRequestWarning,\n            )\n\n\ndef connection_from_url(url, **kw):\n    \"\"\"\n    Given a url, return an :class:`.ConnectionPool` instance of its host.\n\n    This is a shortcut for not having to parse out the scheme, host, and port\n    of the url before creating an :class:`.ConnectionPool` instance.\n\n    :param url:\n        Absolute URL string that must include the scheme. Port is optional.\n\n    :param \\\\**kw:\n        Passes additional parameters to the constructor of the appropriate\n        :class:`.ConnectionPool`. Useful for specifying things like\n        timeout, maxsize, headers, etc.\n\n    Example::\n\n        >>> conn = connection_from_url('http://google.com/')\n        >>> r = conn.request('GET', '/')\n    \"\"\"\n    scheme, host, port = get_host(url)\n    port = port or port_by_scheme.get(scheme, 80)\n    if scheme == \"https\":\n        return HTTPSConnectionPool(host, port=port, **kw)\n    else:\n        return HTTPConnectionPool(host, port=port, **kw)\n\n\ndef _normalize_host(host, scheme):\n    \"\"\"\n    Normalize hosts for comparisons and use with sockets.\n    \"\"\"\n\n    host = normalize_host(host, scheme)\n\n    # httplib doesn't like it when we include brackets in IPv6 addresses\n    # Specifically, if we include brackets but also pass the port then\n    # httplib crazily doubles up the square brackets on the Host header.\n    # Instead, we need to make sure we never pass ``None`` as the port.\n    # However, for backward compatibility reasons we can't actually\n    # *assert* that.  See http://bugs.python.org/issue28539\n    if host.startswith(\"[\") and host.endswith(\"]\"):\n        host = host[1:-1]\n    return host\n\n\ndef _close_pool_connections(pool):\n    \"\"\"Drains a queue of connections and closes each one.\"\"\"\n    try:\n        while True:\n            conn = pool.get(block=False)\n            if conn:\n                conn.close()\n    except queue.Empty:\n        pass  # Done.\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/_appengine_environ.py",
    "content": "\"\"\"\nThis module provides means to detect the App Engine environment.\n\"\"\"\n\nimport os\n\n\ndef is_appengine():\n    return is_local_appengine() or is_prod_appengine()\n\n\ndef is_appengine_sandbox():\n    \"\"\"Reports if the app is running in the first generation sandbox.\n\n    The second generation runtimes are technically still in a sandbox, but it\n    is much less restrictive, so generally you shouldn't need to check for it.\n    see https://cloud.google.com/appengine/docs/standard/runtimes\n    \"\"\"\n    return is_appengine() and os.environ[\"APPENGINE_RUNTIME\"] == \"python27\"\n\n\ndef is_local_appengine():\n    return \"APPENGINE_RUNTIME\" in os.environ and os.environ.get(\n        \"SERVER_SOFTWARE\", \"\"\n    ).startswith(\"Development/\")\n\n\ndef is_prod_appengine():\n    return \"APPENGINE_RUNTIME\" in os.environ and os.environ.get(\n        \"SERVER_SOFTWARE\", \"\"\n    ).startswith(\"Google App Engine/\")\n\n\ndef is_prod_appengine_mvms():\n    \"\"\"Deprecated.\"\"\"\n    return False\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/_securetransport/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/_securetransport/bindings.py",
    "content": "\"\"\"\nThis module uses ctypes to bind a whole bunch of functions and constants from\nSecureTransport. The goal here is to provide the low-level API to\nSecureTransport. These are essentially the C-level functions and constants, and\nthey're pretty gross to work with.\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n    Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport platform\nfrom ctypes import (\n    CDLL,\n    CFUNCTYPE,\n    POINTER,\n    c_bool,\n    c_byte,\n    c_char_p,\n    c_int32,\n    c_long,\n    c_size_t,\n    c_uint32,\n    c_ulong,\n    c_void_p,\n)\nfrom ctypes.util import find_library\n\nfrom ...packages.six import raise_from\n\nif platform.system() != \"Darwin\":\n    raise ImportError(\"Only macOS is supported\")\n\nversion = platform.mac_ver()[0]\nversion_info = tuple(map(int, version.split(\".\")))\nif version_info < (10, 8):\n    raise OSError(\n        \"Only OS X 10.8 and newer are supported, not %s.%s\"\n        % (version_info[0], version_info[1])\n    )\n\n\ndef load_cdll(name, macos10_16_path):\n    \"\"\"Loads a CDLL by name, falling back to known path on 10.16+\"\"\"\n    try:\n        # Big Sur is technically 11 but we use 10.16 due to the Big Sur\n        # beta being labeled as 10.16.\n        if version_info >= (10, 16):\n            path = macos10_16_path\n        else:\n            path = find_library(name)\n        if not path:\n            raise OSError  # Caught and reraised as 'ImportError'\n        return CDLL(path, use_errno=True)\n    except OSError:\n        raise_from(ImportError(\"The library %s failed to load\" % name), None)\n\n\nSecurity = load_cdll(\n    \"Security\", \"/System/Library/Frameworks/Security.framework/Security\"\n)\nCoreFoundation = load_cdll(\n    \"CoreFoundation\",\n    \"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation\",\n)\n\n\nBoolean = c_bool\nCFIndex = c_long\nCFStringEncoding = c_uint32\nCFData = c_void_p\nCFString = c_void_p\nCFArray = c_void_p\nCFMutableArray = c_void_p\nCFDictionary = c_void_p\nCFError = c_void_p\nCFType = c_void_p\nCFTypeID = c_ulong\n\nCFTypeRef = POINTER(CFType)\nCFAllocatorRef = c_void_p\n\nOSStatus = c_int32\n\nCFDataRef = POINTER(CFData)\nCFStringRef = POINTER(CFString)\nCFArrayRef = POINTER(CFArray)\nCFMutableArrayRef = POINTER(CFMutableArray)\nCFDictionaryRef = POINTER(CFDictionary)\nCFArrayCallBacks = c_void_p\nCFDictionaryKeyCallBacks = c_void_p\nCFDictionaryValueCallBacks = c_void_p\n\nSecCertificateRef = POINTER(c_void_p)\nSecExternalFormat = c_uint32\nSecExternalItemType = c_uint32\nSecIdentityRef = POINTER(c_void_p)\nSecItemImportExportFlags = c_uint32\nSecItemImportExportKeyParameters = c_void_p\nSecKeychainRef = POINTER(c_void_p)\nSSLProtocol = c_uint32\nSSLCipherSuite = c_uint32\nSSLContextRef = POINTER(c_void_p)\nSecTrustRef = POINTER(c_void_p)\nSSLConnectionRef = c_uint32\nSecTrustResultType = c_uint32\nSecTrustOptionFlags = c_uint32\nSSLProtocolSide = c_uint32\nSSLConnectionType = c_uint32\nSSLSessionOption = c_uint32\n\n\ntry:\n    Security.SecItemImport.argtypes = [\n        CFDataRef,\n        CFStringRef,\n        POINTER(SecExternalFormat),\n        POINTER(SecExternalItemType),\n        SecItemImportExportFlags,\n        POINTER(SecItemImportExportKeyParameters),\n        SecKeychainRef,\n        POINTER(CFArrayRef),\n    ]\n    Security.SecItemImport.restype = OSStatus\n\n    Security.SecCertificateGetTypeID.argtypes = []\n    Security.SecCertificateGetTypeID.restype = CFTypeID\n\n    Security.SecIdentityGetTypeID.argtypes = []\n    Security.SecIdentityGetTypeID.restype = CFTypeID\n\n    Security.SecKeyGetTypeID.argtypes = []\n    Security.SecKeyGetTypeID.restype = CFTypeID\n\n    Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]\n    Security.SecCertificateCreateWithData.restype = SecCertificateRef\n\n    Security.SecCertificateCopyData.argtypes = [SecCertificateRef]\n    Security.SecCertificateCopyData.restype = CFDataRef\n\n    Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n    Security.SecCopyErrorMessageString.restype = CFStringRef\n\n    Security.SecIdentityCreateWithCertificate.argtypes = [\n        CFTypeRef,\n        SecCertificateRef,\n        POINTER(SecIdentityRef),\n    ]\n    Security.SecIdentityCreateWithCertificate.restype = OSStatus\n\n    Security.SecKeychainCreate.argtypes = [\n        c_char_p,\n        c_uint32,\n        c_void_p,\n        Boolean,\n        c_void_p,\n        POINTER(SecKeychainRef),\n    ]\n    Security.SecKeychainCreate.restype = OSStatus\n\n    Security.SecKeychainDelete.argtypes = [SecKeychainRef]\n    Security.SecKeychainDelete.restype = OSStatus\n\n    Security.SecPKCS12Import.argtypes = [\n        CFDataRef,\n        CFDictionaryRef,\n        POINTER(CFArrayRef),\n    ]\n    Security.SecPKCS12Import.restype = OSStatus\n\n    SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))\n    SSLWriteFunc = CFUNCTYPE(\n        OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)\n    )\n\n    Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc]\n    Security.SSLSetIOFuncs.restype = OSStatus\n\n    Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t]\n    Security.SSLSetPeerID.restype = OSStatus\n\n    Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef]\n    Security.SSLSetCertificate.restype = OSStatus\n\n    Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean]\n    Security.SSLSetCertificateAuthorities.restype = OSStatus\n\n    Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef]\n    Security.SSLSetConnection.restype = OSStatus\n\n    Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t]\n    Security.SSLSetPeerDomainName.restype = OSStatus\n\n    Security.SSLHandshake.argtypes = [SSLContextRef]\n    Security.SSLHandshake.restype = OSStatus\n\n    Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n    Security.SSLRead.restype = OSStatus\n\n    Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n    Security.SSLWrite.restype = OSStatus\n\n    Security.SSLClose.argtypes = [SSLContextRef]\n    Security.SSLClose.restype = OSStatus\n\n    Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)]\n    Security.SSLGetNumberSupportedCiphers.restype = OSStatus\n\n    Security.SSLGetSupportedCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        POINTER(c_size_t),\n    ]\n    Security.SSLGetSupportedCiphers.restype = OSStatus\n\n    Security.SSLSetEnabledCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        c_size_t,\n    ]\n    Security.SSLSetEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)]\n    Security.SSLGetNumberEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetEnabledCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        POINTER(c_size_t),\n    ]\n    Security.SSLGetEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)]\n    Security.SSLGetNegotiatedCipher.restype = OSStatus\n\n    Security.SSLGetNegotiatedProtocolVersion.argtypes = [\n        SSLContextRef,\n        POINTER(SSLProtocol),\n    ]\n    Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus\n\n    Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)]\n    Security.SSLCopyPeerTrust.restype = OSStatus\n\n    Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]\n    Security.SecTrustSetAnchorCertificates.restype = OSStatus\n\n    Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean]\n    Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus\n\n    Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)]\n    Security.SecTrustEvaluate.restype = OSStatus\n\n    Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef]\n    Security.SecTrustGetCertificateCount.restype = CFIndex\n\n    Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex]\n    Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef\n\n    Security.SSLCreateContext.argtypes = [\n        CFAllocatorRef,\n        SSLProtocolSide,\n        SSLConnectionType,\n    ]\n    Security.SSLCreateContext.restype = SSLContextRef\n\n    Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean]\n    Security.SSLSetSessionOption.restype = OSStatus\n\n    Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol]\n    Security.SSLSetProtocolVersionMin.restype = OSStatus\n\n    Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol]\n    Security.SSLSetProtocolVersionMax.restype = OSStatus\n\n    try:\n        Security.SSLSetALPNProtocols.argtypes = [SSLContextRef, CFArrayRef]\n        Security.SSLSetALPNProtocols.restype = OSStatus\n    except AttributeError:\n        # Supported only in 10.12+\n        pass\n\n    Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n    Security.SecCopyErrorMessageString.restype = CFStringRef\n\n    Security.SSLReadFunc = SSLReadFunc\n    Security.SSLWriteFunc = SSLWriteFunc\n    Security.SSLContextRef = SSLContextRef\n    Security.SSLProtocol = SSLProtocol\n    Security.SSLCipherSuite = SSLCipherSuite\n    Security.SecIdentityRef = SecIdentityRef\n    Security.SecKeychainRef = SecKeychainRef\n    Security.SecTrustRef = SecTrustRef\n    Security.SecTrustResultType = SecTrustResultType\n    Security.SecExternalFormat = SecExternalFormat\n    Security.OSStatus = OSStatus\n\n    Security.kSecImportExportPassphrase = CFStringRef.in_dll(\n        Security, \"kSecImportExportPassphrase\"\n    )\n    Security.kSecImportItemIdentity = CFStringRef.in_dll(\n        Security, \"kSecImportItemIdentity\"\n    )\n\n    # CoreFoundation time!\n    CoreFoundation.CFRetain.argtypes = [CFTypeRef]\n    CoreFoundation.CFRetain.restype = CFTypeRef\n\n    CoreFoundation.CFRelease.argtypes = [CFTypeRef]\n    CoreFoundation.CFRelease.restype = None\n\n    CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]\n    CoreFoundation.CFGetTypeID.restype = CFTypeID\n\n    CoreFoundation.CFStringCreateWithCString.argtypes = [\n        CFAllocatorRef,\n        c_char_p,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringCreateWithCString.restype = CFStringRef\n\n    CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]\n    CoreFoundation.CFStringGetCStringPtr.restype = c_char_p\n\n    CoreFoundation.CFStringGetCString.argtypes = [\n        CFStringRef,\n        c_char_p,\n        CFIndex,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringGetCString.restype = c_bool\n\n    CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]\n    CoreFoundation.CFDataCreate.restype = CFDataRef\n\n    CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetLength.restype = CFIndex\n\n    CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetBytePtr.restype = c_void_p\n\n    CoreFoundation.CFDictionaryCreate.argtypes = [\n        CFAllocatorRef,\n        POINTER(CFTypeRef),\n        POINTER(CFTypeRef),\n        CFIndex,\n        CFDictionaryKeyCallBacks,\n        CFDictionaryValueCallBacks,\n    ]\n    CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef\n\n    CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef]\n    CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef\n\n    CoreFoundation.CFArrayCreate.argtypes = [\n        CFAllocatorRef,\n        POINTER(CFTypeRef),\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreate.restype = CFArrayRef\n\n    CoreFoundation.CFArrayCreateMutable.argtypes = [\n        CFAllocatorRef,\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef\n\n    CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]\n    CoreFoundation.CFArrayAppendValue.restype = None\n\n    CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]\n    CoreFoundation.CFArrayGetCount.restype = CFIndex\n\n    CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]\n    CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p\n\n    CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(\n        CoreFoundation, \"kCFAllocatorDefault\"\n    )\n    CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeArrayCallBacks\"\n    )\n    CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeDictionaryKeyCallBacks\"\n    )\n    CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeDictionaryValueCallBacks\"\n    )\n\n    CoreFoundation.CFTypeRef = CFTypeRef\n    CoreFoundation.CFArrayRef = CFArrayRef\n    CoreFoundation.CFStringRef = CFStringRef\n    CoreFoundation.CFDictionaryRef = CFDictionaryRef\n\nexcept (AttributeError):\n    raise ImportError(\"Error initializing ctypes\")\n\n\nclass CFConst(object):\n    \"\"\"\n    A class object that acts as essentially a namespace for CoreFoundation\n    constants.\n    \"\"\"\n\n    kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)\n\n\nclass SecurityConst(object):\n    \"\"\"\n    A class object that acts as essentially a namespace for Security constants.\n    \"\"\"\n\n    kSSLSessionOptionBreakOnServerAuth = 0\n\n    kSSLProtocol2 = 1\n    kSSLProtocol3 = 2\n    kTLSProtocol1 = 4\n    kTLSProtocol11 = 7\n    kTLSProtocol12 = 8\n    # SecureTransport does not support TLS 1.3 even if there's a constant for it\n    kTLSProtocol13 = 10\n    kTLSProtocolMaxSupported = 999\n\n    kSSLClientSide = 1\n    kSSLStreamType = 0\n\n    kSecFormatPEMSequence = 10\n\n    kSecTrustResultInvalid = 0\n    kSecTrustResultProceed = 1\n    # This gap is present on purpose: this was kSecTrustResultConfirm, which\n    # is deprecated.\n    kSecTrustResultDeny = 3\n    kSecTrustResultUnspecified = 4\n    kSecTrustResultRecoverableTrustFailure = 5\n    kSecTrustResultFatalTrustFailure = 6\n    kSecTrustResultOtherError = 7\n\n    errSSLProtocol = -9800\n    errSSLWouldBlock = -9803\n    errSSLClosedGraceful = -9805\n    errSSLClosedNoNotify = -9816\n    errSSLClosedAbort = -9806\n\n    errSSLXCertChainInvalid = -9807\n    errSSLCrypto = -9809\n    errSSLInternal = -9810\n    errSSLCertExpired = -9814\n    errSSLCertNotYetValid = -9815\n    errSSLUnknownRootCert = -9812\n    errSSLNoRootCert = -9813\n    errSSLHostNameMismatch = -9843\n    errSSLPeerHandshakeFail = -9824\n    errSSLPeerUserCancelled = -9839\n    errSSLWeakPeerEphemeralDHKey = -9850\n    errSSLServerAuthCompleted = -9841\n    errSSLRecordOverflow = -9847\n\n    errSecVerifyFailed = -67808\n    errSecNoTrustSettings = -25263\n    errSecItemNotFound = -25300\n    errSecInvalidTrustSettings = -25262\n\n    # Cipher suites. We only pick the ones our default cipher string allows.\n    # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values\n    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C\n    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030\n    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B\n    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F\n    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9\n    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8\n    TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F\n    TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E\n    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024\n    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028\n    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A\n    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014\n    TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B\n    TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039\n    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023\n    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027\n    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009\n    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013\n    TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067\n    TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033\n    TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D\n    TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C\n    TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D\n    TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C\n    TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035\n    TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F\n    TLS_AES_128_GCM_SHA256 = 0x1301\n    TLS_AES_256_GCM_SHA384 = 0x1302\n    TLS_AES_128_CCM_8_SHA256 = 0x1305\n    TLS_AES_128_CCM_SHA256 = 0x1304\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/_securetransport/low_level.py",
    "content": "\"\"\"\nLow-level helpers for the SecureTransport bindings.\n\nThese are Python functions that are not directly related to the high-level APIs\nbut are necessary to get them to work. They include a whole bunch of low-level\nCoreFoundation messing about and memory management. The concerns in this module\nare almost entirely about trying to avoid memory leaks and providing\nappropriate and useful assistance to the higher-level code.\n\"\"\"\nimport base64\nimport ctypes\nimport itertools\nimport os\nimport re\nimport ssl\nimport struct\nimport tempfile\n\nfrom .bindings import CFConst, CoreFoundation, Security\n\n# This regular expression is used to grab PEM data out of a PEM bundle.\n_PEM_CERTS_RE = re.compile(\n    b\"-----BEGIN CERTIFICATE-----\\n(.*?)\\n-----END CERTIFICATE-----\", re.DOTALL\n)\n\n\ndef _cf_data_from_bytes(bytestring):\n    \"\"\"\n    Given a bytestring, create a CFData object from it. This CFData object must\n    be CFReleased by the caller.\n    \"\"\"\n    return CoreFoundation.CFDataCreate(\n        CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)\n    )\n\n\ndef _cf_dictionary_from_tuples(tuples):\n    \"\"\"\n    Given a list of Python tuples, create an associated CFDictionary.\n    \"\"\"\n    dictionary_size = len(tuples)\n\n    # We need to get the dictionary keys and values out in the same order.\n    keys = (t[0] for t in tuples)\n    values = (t[1] for t in tuples)\n    cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)\n    cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)\n\n    return CoreFoundation.CFDictionaryCreate(\n        CoreFoundation.kCFAllocatorDefault,\n        cf_keys,\n        cf_values,\n        dictionary_size,\n        CoreFoundation.kCFTypeDictionaryKeyCallBacks,\n        CoreFoundation.kCFTypeDictionaryValueCallBacks,\n    )\n\n\ndef _cfstr(py_bstr):\n    \"\"\"\n    Given a Python binary data, create a CFString.\n    The string must be CFReleased by the caller.\n    \"\"\"\n    c_str = ctypes.c_char_p(py_bstr)\n    cf_str = CoreFoundation.CFStringCreateWithCString(\n        CoreFoundation.kCFAllocatorDefault,\n        c_str,\n        CFConst.kCFStringEncodingUTF8,\n    )\n    return cf_str\n\n\ndef _create_cfstring_array(lst):\n    \"\"\"\n    Given a list of Python binary data, create an associated CFMutableArray.\n    The array must be CFReleased by the caller.\n\n    Raises an ssl.SSLError on failure.\n    \"\"\"\n    cf_arr = None\n    try:\n        cf_arr = CoreFoundation.CFArrayCreateMutable(\n            CoreFoundation.kCFAllocatorDefault,\n            0,\n            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n        )\n        if not cf_arr:\n            raise MemoryError(\"Unable to allocate memory!\")\n        for item in lst:\n            cf_str = _cfstr(item)\n            if not cf_str:\n                raise MemoryError(\"Unable to allocate memory!\")\n            try:\n                CoreFoundation.CFArrayAppendValue(cf_arr, cf_str)\n            finally:\n                CoreFoundation.CFRelease(cf_str)\n    except BaseException as e:\n        if cf_arr:\n            CoreFoundation.CFRelease(cf_arr)\n        raise ssl.SSLError(\"Unable to allocate array: %s\" % (e,))\n    return cf_arr\n\n\ndef _cf_string_to_unicode(value):\n    \"\"\"\n    Creates a Unicode string from a CFString object. Used entirely for error\n    reporting.\n\n    Yes, it annoys me quite a lot that this function is this complex.\n    \"\"\"\n    value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))\n\n    string = CoreFoundation.CFStringGetCStringPtr(\n        value_as_void_p, CFConst.kCFStringEncodingUTF8\n    )\n    if string is None:\n        buffer = ctypes.create_string_buffer(1024)\n        result = CoreFoundation.CFStringGetCString(\n            value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8\n        )\n        if not result:\n            raise OSError(\"Error copying C string from CFStringRef\")\n        string = buffer.value\n    if string is not None:\n        string = string.decode(\"utf-8\")\n    return string\n\n\ndef _assert_no_error(error, exception_class=None):\n    \"\"\"\n    Checks the return code and throws an exception if there is an error to\n    report\n    \"\"\"\n    if error == 0:\n        return\n\n    cf_error_string = Security.SecCopyErrorMessageString(error, None)\n    output = _cf_string_to_unicode(cf_error_string)\n    CoreFoundation.CFRelease(cf_error_string)\n\n    if output is None or output == u\"\":\n        output = u\"OSStatus %s\" % error\n\n    if exception_class is None:\n        exception_class = ssl.SSLError\n\n    raise exception_class(output)\n\n\ndef _cert_array_from_pem(pem_bundle):\n    \"\"\"\n    Given a bundle of certs in PEM format, turns them into a CFArray of certs\n    that can be used to validate a cert chain.\n    \"\"\"\n    # Normalize the PEM bundle's line endings.\n    pem_bundle = pem_bundle.replace(b\"\\r\\n\", b\"\\n\")\n\n    der_certs = [\n        base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle)\n    ]\n    if not der_certs:\n        raise ssl.SSLError(\"No root certificates specified\")\n\n    cert_array = CoreFoundation.CFArrayCreateMutable(\n        CoreFoundation.kCFAllocatorDefault,\n        0,\n        ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n    )\n    if not cert_array:\n        raise ssl.SSLError(\"Unable to allocate memory!\")\n\n    try:\n        for der_bytes in der_certs:\n            certdata = _cf_data_from_bytes(der_bytes)\n            if not certdata:\n                raise ssl.SSLError(\"Unable to allocate memory!\")\n            cert = Security.SecCertificateCreateWithData(\n                CoreFoundation.kCFAllocatorDefault, certdata\n            )\n            CoreFoundation.CFRelease(certdata)\n            if not cert:\n                raise ssl.SSLError(\"Unable to build cert object!\")\n\n            CoreFoundation.CFArrayAppendValue(cert_array, cert)\n            CoreFoundation.CFRelease(cert)\n    except Exception:\n        # We need to free the array before the exception bubbles further.\n        # We only want to do that if an error occurs: otherwise, the caller\n        # should free.\n        CoreFoundation.CFRelease(cert_array)\n        raise\n\n    return cert_array\n\n\ndef _is_cert(item):\n    \"\"\"\n    Returns True if a given CFTypeRef is a certificate.\n    \"\"\"\n    expected = Security.SecCertificateGetTypeID()\n    return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _is_identity(item):\n    \"\"\"\n    Returns True if a given CFTypeRef is an identity.\n    \"\"\"\n    expected = Security.SecIdentityGetTypeID()\n    return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _temporary_keychain():\n    \"\"\"\n    This function creates a temporary Mac keychain that we can use to work with\n    credentials. This keychain uses a one-time password and a temporary file to\n    store the data. We expect to have one keychain per socket. The returned\n    SecKeychainRef must be freed by the caller, including calling\n    SecKeychainDelete.\n\n    Returns a tuple of the SecKeychainRef and the path to the temporary\n    directory that contains it.\n    \"\"\"\n    # Unfortunately, SecKeychainCreate requires a path to a keychain. This\n    # means we cannot use mkstemp to use a generic temporary file. Instead,\n    # we're going to create a temporary directory and a filename to use there.\n    # This filename will be 8 random bytes expanded into base64. We also need\n    # some random bytes to password-protect the keychain we're creating, so we\n    # ask for 40 random bytes.\n    random_bytes = os.urandom(40)\n    filename = base64.b16encode(random_bytes[:8]).decode(\"utf-8\")\n    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8\n    tempdirectory = tempfile.mkdtemp()\n\n    keychain_path = os.path.join(tempdirectory, filename).encode(\"utf-8\")\n\n    # We now want to create the keychain itself.\n    keychain = Security.SecKeychainRef()\n    status = Security.SecKeychainCreate(\n        keychain_path, len(password), password, False, None, ctypes.byref(keychain)\n    )\n    _assert_no_error(status)\n\n    # Having created the keychain, we want to pass it off to the caller.\n    return keychain, tempdirectory\n\n\ndef _load_items_from_file(keychain, path):\n    \"\"\"\n    Given a single file, loads all the trust objects from it into arrays and\n    the keychain.\n    Returns a tuple of lists: the first list is a list of identities, the\n    second a list of certs.\n    \"\"\"\n    certificates = []\n    identities = []\n    result_array = None\n\n    with open(path, \"rb\") as f:\n        raw_filedata = f.read()\n\n    try:\n        filedata = CoreFoundation.CFDataCreate(\n            CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata)\n        )\n        result_array = CoreFoundation.CFArrayRef()\n        result = Security.SecItemImport(\n            filedata,  # cert data\n            None,  # Filename, leaving it out for now\n            None,  # What the type of the file is, we don't care\n            None,  # what's in the file, we don't care\n            0,  # import flags\n            None,  # key params, can include passphrase in the future\n            keychain,  # The keychain to insert into\n            ctypes.byref(result_array),  # Results\n        )\n        _assert_no_error(result)\n\n        # A CFArray is not very useful to us as an intermediary\n        # representation, so we are going to extract the objects we want\n        # and then free the array. We don't need to keep hold of keys: the\n        # keychain already has them!\n        result_count = CoreFoundation.CFArrayGetCount(result_array)\n        for index in range(result_count):\n            item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index)\n            item = ctypes.cast(item, CoreFoundation.CFTypeRef)\n\n            if _is_cert(item):\n                CoreFoundation.CFRetain(item)\n                certificates.append(item)\n            elif _is_identity(item):\n                CoreFoundation.CFRetain(item)\n                identities.append(item)\n    finally:\n        if result_array:\n            CoreFoundation.CFRelease(result_array)\n\n        CoreFoundation.CFRelease(filedata)\n\n    return (identities, certificates)\n\n\ndef _load_client_cert_chain(keychain, *paths):\n    \"\"\"\n    Load certificates and maybe keys from a number of files. Has the end goal\n    of returning a CFArray containing one SecIdentityRef, and then zero or more\n    SecCertificateRef objects, suitable for use as a client certificate trust\n    chain.\n    \"\"\"\n    # Ok, the strategy.\n    #\n    # This relies on knowing that macOS will not give you a SecIdentityRef\n    # unless you have imported a key into a keychain. This is a somewhat\n    # artificial limitation of macOS (for example, it doesn't necessarily\n    # affect iOS), but there is nothing inside Security.framework that lets you\n    # get a SecIdentityRef without having a key in a keychain.\n    #\n    # So the policy here is we take all the files and iterate them in order.\n    # Each one will use SecItemImport to have one or more objects loaded from\n    # it. We will also point at a keychain that macOS can use to work with the\n    # private key.\n    #\n    # Once we have all the objects, we'll check what we actually have. If we\n    # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,\n    # we'll take the first certificate (which we assume to be our leaf) and\n    # ask the keychain to give us a SecIdentityRef with that cert's associated\n    # key.\n    #\n    # We'll then return a CFArray containing the trust chain: one\n    # SecIdentityRef and then zero-or-more SecCertificateRef objects. The\n    # responsibility for freeing this CFArray will be with the caller. This\n    # CFArray must remain alive for the entire connection, so in practice it\n    # will be stored with a single SSLSocket, along with the reference to the\n    # keychain.\n    certificates = []\n    identities = []\n\n    # Filter out bad paths.\n    paths = (path for path in paths if path)\n\n    try:\n        for file_path in paths:\n            new_identities, new_certs = _load_items_from_file(keychain, file_path)\n            identities.extend(new_identities)\n            certificates.extend(new_certs)\n\n        # Ok, we have everything. The question is: do we have an identity? If\n        # not, we want to grab one from the first cert we have.\n        if not identities:\n            new_identity = Security.SecIdentityRef()\n            status = Security.SecIdentityCreateWithCertificate(\n                keychain, certificates[0], ctypes.byref(new_identity)\n            )\n            _assert_no_error(status)\n            identities.append(new_identity)\n\n            # We now want to release the original certificate, as we no longer\n            # need it.\n            CoreFoundation.CFRelease(certificates.pop(0))\n\n        # We now need to build a new CFArray that holds the trust chain.\n        trust_chain = CoreFoundation.CFArrayCreateMutable(\n            CoreFoundation.kCFAllocatorDefault,\n            0,\n            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n        )\n        for item in itertools.chain(identities, certificates):\n            # ArrayAppendValue does a CFRetain on the item. That's fine,\n            # because the finally block will release our other refs to them.\n            CoreFoundation.CFArrayAppendValue(trust_chain, item)\n\n        return trust_chain\n    finally:\n        for obj in itertools.chain(identities, certificates):\n            CoreFoundation.CFRelease(obj)\n\n\nTLS_PROTOCOL_VERSIONS = {\n    \"SSLv2\": (0, 2),\n    \"SSLv3\": (3, 0),\n    \"TLSv1\": (3, 1),\n    \"TLSv1.1\": (3, 2),\n    \"TLSv1.2\": (3, 3),\n}\n\n\ndef _build_tls_unknown_ca_alert(version):\n    \"\"\"\n    Builds a TLS alert record for an unknown CA.\n    \"\"\"\n    ver_maj, ver_min = TLS_PROTOCOL_VERSIONS[version]\n    severity_fatal = 0x02\n    description_unknown_ca = 0x30\n    msg = struct.pack(\">BB\", severity_fatal, description_unknown_ca)\n    msg_len = len(msg)\n    record_type_alert = 0x15\n    record = struct.pack(\">BBBH\", record_type_alert, ver_maj, ver_min, msg_len) + msg\n    return record\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/appengine.py",
    "content": "\"\"\"\nThis module provides a pool manager that uses Google App Engine's\n`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\nExample usage::\n\n    from pip._vendor.urllib3 import PoolManager\n    from pip._vendor.urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox\n\n    if is_appengine_sandbox():\n        # AppEngineManager uses AppEngine's URLFetch API behind the scenes\n        http = AppEngineManager()\n    else:\n        # PoolManager uses a socket-level API behind the scenes\n        http = PoolManager()\n\n    r = http.request('GET', 'https://google.com/')\n\nThere are `limitations <https://cloud.google.com/appengine/docs/python/\\\nurlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be\nthe best choice for your application. There are three options for using\nurllib3 on Google App Engine:\n\n1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is\n   cost-effective in many circumstances as long as your usage is within the\n   limitations.\n2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets.\n   Sockets also have `limitations and restrictions\n   <https://cloud.google.com/appengine/docs/python/sockets/\\\n   #limitations-and-restrictions>`_ and have a lower free quota than URLFetch.\n   To use sockets, be sure to specify the following in your ``app.yaml``::\n\n        env_variables:\n            GAE_USE_SOCKETS_HTTPLIB : 'true'\n\n3. If you are using `App Engine Flexible\n<https://cloud.google.com/appengine/docs/flexible/>`_, you can use the standard\n:class:`PoolManager` without any configuration or special environment variables.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport io\nimport logging\nimport warnings\n\nfrom ..exceptions import (\n    HTTPError,\n    HTTPWarning,\n    MaxRetryError,\n    ProtocolError,\n    SSLError,\n    TimeoutError,\n)\nfrom ..packages.six.moves.urllib.parse import urljoin\nfrom ..request import RequestMethods\nfrom ..response import HTTPResponse\nfrom ..util.retry import Retry\nfrom ..util.timeout import Timeout\nfrom . import _appengine_environ\n\ntry:\n    from google.appengine.api import urlfetch\nexcept ImportError:\n    urlfetch = None\n\n\nlog = logging.getLogger(__name__)\n\n\nclass AppEnginePlatformWarning(HTTPWarning):\n    pass\n\n\nclass AppEnginePlatformError(HTTPError):\n    pass\n\n\nclass AppEngineManager(RequestMethods):\n    \"\"\"\n    Connection manager for Google App Engine sandbox applications.\n\n    This manager uses the URLFetch service directly instead of using the\n    emulated httplib, and is subject to URLFetch limitations as described in\n    the App Engine documentation `here\n    <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\n    Notably it will raise an :class:`AppEnginePlatformError` if:\n        * URLFetch is not available.\n        * If you attempt to use this on App Engine Flexible, as full socket\n          support is available.\n        * If a request size is more than 10 megabytes.\n        * If a response size is more than 32 megabytes.\n        * If you use an unsupported request method such as OPTIONS.\n\n    Beyond those cases, it will raise normal urllib3 errors.\n    \"\"\"\n\n    def __init__(\n        self,\n        headers=None,\n        retries=None,\n        validate_certificate=True,\n        urlfetch_retries=True,\n    ):\n        if not urlfetch:\n            raise AppEnginePlatformError(\n                \"URLFetch is not available in this environment.\"\n            )\n\n        warnings.warn(\n            \"urllib3 is using URLFetch on Google App Engine sandbox instead \"\n            \"of sockets. To use sockets directly instead of URLFetch see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/reference/urllib3.contrib.html.\",\n            AppEnginePlatformWarning,\n        )\n\n        RequestMethods.__init__(self, headers)\n        self.validate_certificate = validate_certificate\n        self.urlfetch_retries = urlfetch_retries\n\n        self.retries = retries or Retry.DEFAULT\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=None,\n        redirect=True,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        **response_kw\n    ):\n\n        retries = self._get_retries(retries, redirect)\n\n        try:\n            follow_redirects = redirect and retries.redirect != 0 and retries.total\n            response = urlfetch.fetch(\n                url,\n                payload=body,\n                method=method,\n                headers=headers or {},\n                allow_truncated=False,\n                follow_redirects=self.urlfetch_retries and follow_redirects,\n                deadline=self._get_absolute_timeout(timeout),\n                validate_certificate=self.validate_certificate,\n            )\n        except urlfetch.DeadlineExceededError as e:\n            raise TimeoutError(self, e)\n\n        except urlfetch.InvalidURLError as e:\n            if \"too large\" in str(e):\n                raise AppEnginePlatformError(\n                    \"URLFetch request too large, URLFetch only \"\n                    \"supports requests up to 10mb in size.\",\n                    e,\n                )\n            raise ProtocolError(e)\n\n        except urlfetch.DownloadError as e:\n            if \"Too many redirects\" in str(e):\n                raise MaxRetryError(self, url, reason=e)\n            raise ProtocolError(e)\n\n        except urlfetch.ResponseTooLargeError as e:\n            raise AppEnginePlatformError(\n                \"URLFetch response too large, URLFetch only supports\"\n                \"responses up to 32mb in size.\",\n                e,\n            )\n\n        except urlfetch.SSLCertificateError as e:\n            raise SSLError(e)\n\n        except urlfetch.InvalidMethodError as e:\n            raise AppEnginePlatformError(\n                \"URLFetch does not support method: %s\" % method, e\n            )\n\n        http_response = self._urlfetch_response_to_http_response(\n            response, retries=retries, **response_kw\n        )\n\n        # Handle redirect?\n        redirect_location = redirect and http_response.get_redirect_location()\n        if redirect_location:\n            # Check for redirect response\n            if self.urlfetch_retries and retries.raise_on_redirect:\n                raise MaxRetryError(self, url, \"too many redirects\")\n            else:\n                if http_response.status == 303:\n                    method = \"GET\"\n\n                try:\n                    retries = retries.increment(\n                        method, url, response=http_response, _pool=self\n                    )\n                except MaxRetryError:\n                    if retries.raise_on_redirect:\n                        raise MaxRetryError(self, url, \"too many redirects\")\n                    return http_response\n\n                retries.sleep_for_retry(http_response)\n                log.debug(\"Redirecting %s -> %s\", url, redirect_location)\n                redirect_url = urljoin(url, redirect_location)\n                return self.urlopen(\n                    method,\n                    redirect_url,\n                    body,\n                    headers,\n                    retries=retries,\n                    redirect=redirect,\n                    timeout=timeout,\n                    **response_kw\n                )\n\n        # Check if we should retry the HTTP response.\n        has_retry_after = bool(http_response.headers.get(\"Retry-After\"))\n        if retries.is_retry(method, http_response.status, has_retry_after):\n            retries = retries.increment(method, url, response=http_response, _pool=self)\n            log.debug(\"Retry: %s\", url)\n            retries.sleep(http_response)\n            return self.urlopen(\n                method,\n                url,\n                body=body,\n                headers=headers,\n                retries=retries,\n                redirect=redirect,\n                timeout=timeout,\n                **response_kw\n            )\n\n        return http_response\n\n    def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):\n\n        if is_prod_appengine():\n            # Production GAE handles deflate encoding automatically, but does\n            # not remove the encoding header.\n            content_encoding = urlfetch_resp.headers.get(\"content-encoding\")\n\n            if content_encoding == \"deflate\":\n                del urlfetch_resp.headers[\"content-encoding\"]\n\n        transfer_encoding = urlfetch_resp.headers.get(\"transfer-encoding\")\n        # We have a full response's content,\n        # so let's make sure we don't report ourselves as chunked data.\n        if transfer_encoding == \"chunked\":\n            encodings = transfer_encoding.split(\",\")\n            encodings.remove(\"chunked\")\n            urlfetch_resp.headers[\"transfer-encoding\"] = \",\".join(encodings)\n\n        original_response = HTTPResponse(\n            # In order for decoding to work, we must present the content as\n            # a file-like object.\n            body=io.BytesIO(urlfetch_resp.content),\n            msg=urlfetch_resp.header_msg,\n            headers=urlfetch_resp.headers,\n            status=urlfetch_resp.status_code,\n            **response_kw\n        )\n\n        return HTTPResponse(\n            body=io.BytesIO(urlfetch_resp.content),\n            headers=urlfetch_resp.headers,\n            status=urlfetch_resp.status_code,\n            original_response=original_response,\n            **response_kw\n        )\n\n    def _get_absolute_timeout(self, timeout):\n        if timeout is Timeout.DEFAULT_TIMEOUT:\n            return None  # Defer to URLFetch's default.\n        if isinstance(timeout, Timeout):\n            if timeout._read is not None or timeout._connect is not None:\n                warnings.warn(\n                    \"URLFetch does not support granular timeout settings, \"\n                    \"reverting to total or default URLFetch timeout.\",\n                    AppEnginePlatformWarning,\n                )\n            return timeout.total\n        return timeout\n\n    def _get_retries(self, retries, redirect):\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n        if retries.connect or retries.read or retries.redirect:\n            warnings.warn(\n                \"URLFetch only supports total retries and does not \"\n                \"recognize connect, read, or redirect retry parameters.\",\n                AppEnginePlatformWarning,\n            )\n\n        return retries\n\n\n# Alias methods from _appengine_environ to maintain public API interface.\n\nis_appengine = _appengine_environ.is_appengine\nis_appengine_sandbox = _appengine_environ.is_appengine_sandbox\nis_local_appengine = _appengine_environ.is_local_appengine\nis_prod_appengine = _appengine_environ.is_prod_appengine\nis_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/ntlmpool.py",
    "content": "\"\"\"\nNTLM authenticating pool, contributed by erikcederstran\n\nIssue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10\n\"\"\"\nfrom __future__ import absolute_import\n\nimport warnings\nfrom logging import getLogger\n\nfrom ntlm import ntlm\n\nfrom .. import HTTPSConnectionPool\nfrom ..packages.six.moves.http_client import HTTPSConnection\n\nwarnings.warn(\n    \"The 'urllib3.contrib.ntlmpool' module is deprecated and will be removed \"\n    \"in urllib3 v2.0 release, urllib3 is not able to support it properly due \"\n    \"to reasons listed in issue: https://github.com/urllib3/urllib3/issues/2282. \"\n    \"If you are a user of this module please comment in the mentioned issue.\",\n    DeprecationWarning,\n)\n\nlog = getLogger(__name__)\n\n\nclass NTLMConnectionPool(HTTPSConnectionPool):\n    \"\"\"\n    Implements an NTLM authentication version of an urllib3 connection pool\n    \"\"\"\n\n    scheme = \"https\"\n\n    def __init__(self, user, pw, authurl, *args, **kwargs):\n        \"\"\"\n        authurl is a random URL on the server that is protected by NTLM.\n        user is the Windows user, probably in the DOMAIN\\\\username format.\n        pw is the password for the user.\n        \"\"\"\n        super(NTLMConnectionPool, self).__init__(*args, **kwargs)\n        self.authurl = authurl\n        self.rawuser = user\n        user_parts = user.split(\"\\\\\", 1)\n        self.domain = user_parts[0].upper()\n        self.user = user_parts[1]\n        self.pw = pw\n\n    def _new_conn(self):\n        # Performs the NTLM handshake that secures the connection. The socket\n        # must be kept open while requests are performed.\n        self.num_connections += 1\n        log.debug(\n            \"Starting NTLM HTTPS connection no. %d: https://%s%s\",\n            self.num_connections,\n            self.host,\n            self.authurl,\n        )\n\n        headers = {\"Connection\": \"Keep-Alive\"}\n        req_header = \"Authorization\"\n        resp_header = \"www-authenticate\"\n\n        conn = HTTPSConnection(host=self.host, port=self.port)\n\n        # Send negotiation message\n        headers[req_header] = \"NTLM %s\" % ntlm.create_NTLM_NEGOTIATE_MESSAGE(\n            self.rawuser\n        )\n        log.debug(\"Request headers: %s\", headers)\n        conn.request(\"GET\", self.authurl, None, headers)\n        res = conn.getresponse()\n        reshdr = dict(res.headers)\n        log.debug(\"Response status: %s %s\", res.status, res.reason)\n        log.debug(\"Response headers: %s\", reshdr)\n        log.debug(\"Response data: %s [...]\", res.read(100))\n\n        # Remove the reference to the socket, so that it can not be closed by\n        # the response object (we want to keep the socket open)\n        res.fp = None\n\n        # Server should respond with a challenge message\n        auth_header_values = reshdr[resp_header].split(\", \")\n        auth_header_value = None\n        for s in auth_header_values:\n            if s[:5] == \"NTLM \":\n                auth_header_value = s[5:]\n        if auth_header_value is None:\n            raise Exception(\n                \"Unexpected %s response header: %s\" % (resp_header, reshdr[resp_header])\n            )\n\n        # Send authentication message\n        ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(\n            auth_header_value\n        )\n        auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(\n            ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags\n        )\n        headers[req_header] = \"NTLM %s\" % auth_msg\n        log.debug(\"Request headers: %s\", headers)\n        conn.request(\"GET\", self.authurl, None, headers)\n        res = conn.getresponse()\n        log.debug(\"Response status: %s %s\", res.status, res.reason)\n        log.debug(\"Response headers: %s\", dict(res.headers))\n        log.debug(\"Response data: %s [...]\", res.read()[:100])\n        if res.status != 200:\n            if res.status == 401:\n                raise Exception(\"Server rejected request: wrong username or password\")\n            raise Exception(\"Wrong server response: %s %s\" % (res.status, res.reason))\n\n        res.fp = None\n        log.debug(\"Connection established\")\n        return conn\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=3,\n        redirect=True,\n        assert_same_host=True,\n    ):\n        if headers is None:\n            headers = {}\n        headers[\"Connection\"] = \"Keep-Alive\"\n        return super(NTLMConnectionPool, self).urlopen(\n            method, url, body, headers, retries, redirect, assert_same_host\n        )\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/pyopenssl.py",
    "content": "\"\"\"\nTLS with SNI_-support for Python 2. Follow these instructions if you would\nlike to verify TLS certificates in Python 2. Note, the default libraries do\n*not* do certificate checking; you need to do additional work to validate\ncertificates yourself.\n\nThis needs the following packages installed:\n\n* `pyOpenSSL`_ (tested with 16.0.0)\n* `cryptography`_ (minimum 1.3.4, from pyopenssl)\n* `idna`_ (minimum 2.0, from cryptography)\n\nHowever, pyopenssl depends on cryptography, which depends on idna, so while we\nuse all three directly here we end up having relatively few packages required.\n\nYou can install them with the following command:\n\n.. code-block:: bash\n\n    $ python -m pip install pyopenssl cryptography idna\n\nTo activate certificate checking, call\n:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code\nbefore you begin making HTTP requests. This can be done in a ``sitecustomize``\nmodule, or at any other time before your application begins using ``urllib3``,\nlike this:\n\n.. code-block:: python\n\n    try:\n        import pip._vendor.urllib3.contrib.pyopenssl as pyopenssl\n        pyopenssl.inject_into_urllib3()\n    except ImportError:\n        pass\n\nNow you can use :mod:`urllib3` as you normally would, and it will support SNI\nwhen the required modules are installed.\n\nActivating this module also has the positive side effect of disabling SSL/TLS\ncompression in Python 2 (see `CRIME attack`_).\n\n.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication\n.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)\n.. _pyopenssl: https://www.pyopenssl.org\n.. _cryptography: https://cryptography.io\n.. _idna: https://github.com/kjd/idna\n\"\"\"\nfrom __future__ import absolute_import\n\nimport OpenSSL.crypto\nimport OpenSSL.SSL\nfrom cryptography import x509\nfrom cryptography.hazmat.backends.openssl import backend as openssl_backend\n\ntry:\n    from cryptography.x509 import UnsupportedExtension\nexcept ImportError:\n    # UnsupportedExtension is gone in cryptography >= 2.1.0\n    class UnsupportedExtension(Exception):\n        pass\n\n\nfrom io import BytesIO\nfrom socket import error as SocketError\nfrom socket import timeout\n\ntry:  # Platform-specific: Python 2\n    from socket import _fileobject\nexcept ImportError:  # Platform-specific: Python 3\n    _fileobject = None\n    from ..packages.backports.makefile import backport_makefile\n\nimport logging\nimport ssl\nimport sys\nimport warnings\n\nfrom .. import util\nfrom ..packages import six\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\n\nwarnings.warn(\n    \"'urllib3.contrib.pyopenssl' module is deprecated and will be removed \"\n    \"in a future release of urllib3 2.x. Read more in this issue: \"\n    \"https://github.com/urllib3/urllib3/issues/2680\",\n    category=DeprecationWarning,\n    stacklevel=2,\n)\n\n__all__ = [\"inject_into_urllib3\", \"extract_from_urllib3\"]\n\n# SNI always works.\nHAS_SNI = True\n\n# Map from urllib3 to PyOpenSSL compatible parameter-values.\n_openssl_versions = {\n    util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD,\n    PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD,\n    ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,\n}\n\nif hasattr(ssl, \"PROTOCOL_SSLv3\") and hasattr(OpenSSL.SSL, \"SSLv3_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD\n\nif hasattr(ssl, \"PROTOCOL_TLSv1_1\") and hasattr(OpenSSL.SSL, \"TLSv1_1_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD\n\nif hasattr(ssl, \"PROTOCOL_TLSv1_2\") and hasattr(OpenSSL.SSL, \"TLSv1_2_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD\n\n\n_stdlib_to_openssl_verify = {\n    ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,\n    ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,\n    ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER\n    + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,\n}\n_openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items())\n\n# OpenSSL will only write 16K at a time\nSSL_WRITE_BLOCKSIZE = 16384\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n\nlog = logging.getLogger(__name__)\n\n\ndef inject_into_urllib3():\n    \"Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.\"\n\n    _validate_dependencies_met()\n\n    util.SSLContext = PyOpenSSLContext\n    util.ssl_.SSLContext = PyOpenSSLContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_PYOPENSSL = True\n    util.ssl_.IS_PYOPENSSL = True\n\n\ndef extract_from_urllib3():\n    \"Undo monkey-patching by :func:`inject_into_urllib3`.\"\n\n    util.SSLContext = orig_util_SSLContext\n    util.ssl_.SSLContext = orig_util_SSLContext\n    util.HAS_SNI = orig_util_HAS_SNI\n    util.ssl_.HAS_SNI = orig_util_HAS_SNI\n    util.IS_PYOPENSSL = False\n    util.ssl_.IS_PYOPENSSL = False\n\n\ndef _validate_dependencies_met():\n    \"\"\"\n    Verifies that PyOpenSSL's package-level dependencies have been met.\n    Throws `ImportError` if they are not met.\n    \"\"\"\n    # Method added in `cryptography==1.1`; not available in older versions\n    from cryptography.x509.extensions import Extensions\n\n    if getattr(Extensions, \"get_extension_for_class\", None) is None:\n        raise ImportError(\n            \"'cryptography' module missing required functionality.  \"\n            \"Try upgrading to v1.3.4 or newer.\"\n        )\n\n    # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509\n    # attribute is only present on those versions.\n    from OpenSSL.crypto import X509\n\n    x509 = X509()\n    if getattr(x509, \"_x509\", None) is None:\n        raise ImportError(\n            \"'pyOpenSSL' module missing required functionality. \"\n            \"Try upgrading to v0.14 or newer.\"\n        )\n\n\ndef _dnsname_to_stdlib(name):\n    \"\"\"\n    Converts a dNSName SubjectAlternativeName field to the form used by the\n    standard library on the given Python version.\n\n    Cryptography produces a dNSName as a unicode string that was idna-decoded\n    from ASCII bytes. We need to idna-encode that string to get it back, and\n    then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n    uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n    If the name cannot be idna-encoded then we return None signalling that\n    the name given should be skipped.\n    \"\"\"\n\n    def idna_encode(name):\n        \"\"\"\n        Borrowed wholesale from the Python Cryptography Project. It turns out\n        that we can't just safely call `idna.encode`: it can explode for\n        wildcard names. This avoids that problem.\n        \"\"\"\n        from pip._vendor import idna\n\n        try:\n            for prefix in [u\"*.\", u\".\"]:\n                if name.startswith(prefix):\n                    name = name[len(prefix) :]\n                    return prefix.encode(\"ascii\") + idna.encode(name)\n            return idna.encode(name)\n        except idna.core.IDNAError:\n            return None\n\n    # Don't send IPv6 addresses through the IDNA encoder.\n    if \":\" in name:\n        return name\n\n    name = idna_encode(name)\n    if name is None:\n        return None\n    elif sys.version_info >= (3, 0):\n        name = name.decode(\"utf-8\")\n    return name\n\n\ndef get_subj_alt_name(peer_cert):\n    \"\"\"\n    Given an PyOpenSSL certificate, provides all the subject alternative names.\n    \"\"\"\n    # Pass the cert to cryptography, which has much better APIs for this.\n    if hasattr(peer_cert, \"to_cryptography\"):\n        cert = peer_cert.to_cryptography()\n    else:\n        der = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, peer_cert)\n        cert = x509.load_der_x509_certificate(der, openssl_backend)\n\n    # We want to find the SAN extension. Ask Cryptography to locate it (it's\n    # faster than looping in Python)\n    try:\n        ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value\n    except x509.ExtensionNotFound:\n        # No such extension, return the empty list.\n        return []\n    except (\n        x509.DuplicateExtension,\n        UnsupportedExtension,\n        x509.UnsupportedGeneralNameType,\n        UnicodeError,\n    ) as e:\n        # A problem has been found with the quality of the certificate. Assume\n        # no SAN field is present.\n        log.warning(\n            \"A problem was encountered with the certificate that prevented \"\n            \"urllib3 from finding the SubjectAlternativeName field. This can \"\n            \"affect certificate validation. The error was %s\",\n            e,\n        )\n        return []\n\n    # We want to return dNSName and iPAddress fields. We need to cast the IPs\n    # back to strings because the match_hostname function wants them as\n    # strings.\n    # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8\n    # decoded. This is pretty frustrating, but that's what the standard library\n    # does with certificates, and so we need to attempt to do the same.\n    # We also want to skip over names which cannot be idna encoded.\n    names = [\n        (\"DNS\", name)\n        for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))\n        if name is not None\n    ]\n    names.extend(\n        (\"IP Address\", str(name)) for name in ext.get_values_for_type(x509.IPAddress)\n    )\n\n    return names\n\n\nclass WrappedSocket(object):\n    \"\"\"API-compatibility wrapper for Python OpenSSL's Connection-class.\n\n    Note: _makefile_refs, _drop() and _reuse() are needed for the garbage\n    collector of pypy.\n    \"\"\"\n\n    def __init__(self, connection, socket, suppress_ragged_eofs=True):\n        self.connection = connection\n        self.socket = socket\n        self.suppress_ragged_eofs = suppress_ragged_eofs\n        self._makefile_refs = 0\n        self._closed = False\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    # Copy-pasted from Python 3.5 source code\n    def _decref_socketios(self):\n        if self._makefile_refs > 0:\n            self._makefile_refs -= 1\n        if self._closed:\n            self.close()\n\n    def recv(self, *args, **kwargs):\n        try:\n            data = self.connection.recv(*args, **kwargs)\n        except OpenSSL.SSL.SysCallError as e:\n            if self.suppress_ragged_eofs and e.args == (-1, \"Unexpected EOF\"):\n                return b\"\"\n            else:\n                raise SocketError(str(e))\n        except OpenSSL.SSL.ZeroReturnError:\n            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n                return b\"\"\n            else:\n                raise\n        except OpenSSL.SSL.WantReadError:\n            if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n                raise timeout(\"The read operation timed out\")\n            else:\n                return self.recv(*args, **kwargs)\n\n        # TLS 1.3 post-handshake authentication\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"read error: %r\" % e)\n        else:\n            return data\n\n    def recv_into(self, *args, **kwargs):\n        try:\n            return self.connection.recv_into(*args, **kwargs)\n        except OpenSSL.SSL.SysCallError as e:\n            if self.suppress_ragged_eofs and e.args == (-1, \"Unexpected EOF\"):\n                return 0\n            else:\n                raise SocketError(str(e))\n        except OpenSSL.SSL.ZeroReturnError:\n            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n                return 0\n            else:\n                raise\n        except OpenSSL.SSL.WantReadError:\n            if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n                raise timeout(\"The read operation timed out\")\n            else:\n                return self.recv_into(*args, **kwargs)\n\n        # TLS 1.3 post-handshake authentication\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"read error: %r\" % e)\n\n    def settimeout(self, timeout):\n        return self.socket.settimeout(timeout)\n\n    def _send_until_done(self, data):\n        while True:\n            try:\n                return self.connection.send(data)\n            except OpenSSL.SSL.WantWriteError:\n                if not util.wait_for_write(self.socket, self.socket.gettimeout()):\n                    raise timeout()\n                continue\n            except OpenSSL.SSL.SysCallError as e:\n                raise SocketError(str(e))\n\n    def sendall(self, data):\n        total_sent = 0\n        while total_sent < len(data):\n            sent = self._send_until_done(\n                data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]\n            )\n            total_sent += sent\n\n    def shutdown(self):\n        # FIXME rethrow compatible exceptions should we ever use this\n        self.connection.shutdown()\n\n    def close(self):\n        if self._makefile_refs < 1:\n            try:\n                self._closed = True\n                return self.connection.close()\n            except OpenSSL.SSL.Error:\n                return\n        else:\n            self._makefile_refs -= 1\n\n    def getpeercert(self, binary_form=False):\n        x509 = self.connection.get_peer_certificate()\n\n        if not x509:\n            return x509\n\n        if binary_form:\n            return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)\n\n        return {\n            \"subject\": (((\"commonName\", x509.get_subject().CN),),),\n            \"subjectAltName\": get_subj_alt_name(x509),\n        }\n\n    def version(self):\n        return self.connection.get_protocol_version_name()\n\n    def _reuse(self):\n        self._makefile_refs += 1\n\n    def _drop(self):\n        if self._makefile_refs < 1:\n            self.close()\n        else:\n            self._makefile_refs -= 1\n\n\nif _fileobject:  # Platform-specific: Python 2\n\n    def makefile(self, mode, bufsize=-1):\n        self._makefile_refs += 1\n        return _fileobject(self, mode, bufsize, close=True)\n\nelse:  # Platform-specific: Python 3\n    makefile = backport_makefile\n\nWrappedSocket.makefile = makefile\n\n\nclass PyOpenSSLContext(object):\n    \"\"\"\n    I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible\n    for translating the interface of the standard library ``SSLContext`` object\n    to calls into PyOpenSSL.\n    \"\"\"\n\n    def __init__(self, protocol):\n        self.protocol = _openssl_versions[protocol]\n        self._ctx = OpenSSL.SSL.Context(self.protocol)\n        self._options = 0\n        self.check_hostname = False\n\n    @property\n    def options(self):\n        return self._options\n\n    @options.setter\n    def options(self, value):\n        self._options = value\n        self._ctx.set_options(value)\n\n    @property\n    def verify_mode(self):\n        return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]\n\n    @verify_mode.setter\n    def verify_mode(self, value):\n        self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)\n\n    def set_default_verify_paths(self):\n        self._ctx.set_default_verify_paths()\n\n    def set_ciphers(self, ciphers):\n        if isinstance(ciphers, six.text_type):\n            ciphers = ciphers.encode(\"utf-8\")\n        self._ctx.set_cipher_list(ciphers)\n\n    def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n        if cafile is not None:\n            cafile = cafile.encode(\"utf-8\")\n        if capath is not None:\n            capath = capath.encode(\"utf-8\")\n        try:\n            self._ctx.load_verify_locations(cafile, capath)\n            if cadata is not None:\n                self._ctx.load_verify_locations(BytesIO(cadata))\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"unable to load trusted certificates: %r\" % e)\n\n    def load_cert_chain(self, certfile, keyfile=None, password=None):\n        self._ctx.use_certificate_chain_file(certfile)\n        if password is not None:\n            if not isinstance(password, six.binary_type):\n                password = password.encode(\"utf-8\")\n            self._ctx.set_passwd_cb(lambda *_: password)\n        self._ctx.use_privatekey_file(keyfile or certfile)\n\n    def set_alpn_protocols(self, protocols):\n        protocols = [six.ensure_binary(p) for p in protocols]\n        return self._ctx.set_alpn_protos(protocols)\n\n    def wrap_socket(\n        self,\n        sock,\n        server_side=False,\n        do_handshake_on_connect=True,\n        suppress_ragged_eofs=True,\n        server_hostname=None,\n    ):\n        cnx = OpenSSL.SSL.Connection(self._ctx, sock)\n\n        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3\n            server_hostname = server_hostname.encode(\"utf-8\")\n\n        if server_hostname is not None:\n            cnx.set_tlsext_host_name(server_hostname)\n\n        cnx.set_connect_state()\n\n        while True:\n            try:\n                cnx.do_handshake()\n            except OpenSSL.SSL.WantReadError:\n                if not util.wait_for_read(sock, sock.gettimeout()):\n                    raise timeout(\"select timed out\")\n                continue\n            except OpenSSL.SSL.Error as e:\n                raise ssl.SSLError(\"bad handshake: %r\" % e)\n            break\n\n        return WrappedSocket(cnx, sock)\n\n\ndef _verify_callback(cnx, x509, err_no, err_depth, return_code):\n    return err_no == 0\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/securetransport.py",
    "content": "\"\"\"\nSecureTranport support for urllib3 via ctypes.\n\nThis makes platform-native TLS available to urllib3 users on macOS without the\nuse of a compiler. This is an important feature because the Python Package\nIndex is moving to become a TLSv1.2-or-higher server, and the default OpenSSL\nthat ships with macOS is not capable of doing TLSv1.2. The only way to resolve\nthis is to give macOS users an alternative solution to the problem, and that\nsolution is to use SecureTransport.\n\nWe use ctypes here because this solution must not require a compiler. That's\nbecause pip is not allowed to require a compiler either.\n\nThis is not intended to be a seriously long-term solution to this problem.\nThe hope is that PEP 543 will eventually solve this issue for us, at which\npoint we can retire this contrib module. But in the short term, we need to\nsolve the impending tire fire that is Python on Mac without this kind of\ncontrib module. So...here we are.\n\nTo use this module, simply import and inject it::\n\n    import pip._vendor.urllib3.contrib.securetransport as securetransport\n    securetransport.inject_into_urllib3()\n\nHappy TLSing!\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n.. code-block::\n\n    Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport contextlib\nimport ctypes\nimport errno\nimport os.path\nimport shutil\nimport socket\nimport ssl\nimport struct\nimport threading\nimport weakref\n\nfrom .. import util\nfrom ..packages import six\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\nfrom ._securetransport.bindings import CoreFoundation, Security, SecurityConst\nfrom ._securetransport.low_level import (\n    _assert_no_error,\n    _build_tls_unknown_ca_alert,\n    _cert_array_from_pem,\n    _create_cfstring_array,\n    _load_client_cert_chain,\n    _temporary_keychain,\n)\n\ntry:  # Platform-specific: Python 2\n    from socket import _fileobject\nexcept ImportError:  # Platform-specific: Python 3\n    _fileobject = None\n    from ..packages.backports.makefile import backport_makefile\n\n__all__ = [\"inject_into_urllib3\", \"extract_from_urllib3\"]\n\n# SNI always works\nHAS_SNI = True\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n# This dictionary is used by the read callback to obtain a handle to the\n# calling wrapped socket. This is a pretty silly approach, but for now it'll\n# do. I feel like I should be able to smuggle a handle to the wrapped socket\n# directly in the SSLConnectionRef, but for now this approach will work I\n# guess.\n#\n# We need to lock around this structure for inserts, but we don't do it for\n# reads/writes in the callbacks. The reasoning here goes as follows:\n#\n#    1. It is not possible to call into the callbacks before the dictionary is\n#       populated, so once in the callback the id must be in the dictionary.\n#    2. The callbacks don't mutate the dictionary, they only read from it, and\n#       so cannot conflict with any of the insertions.\n#\n# This is good: if we had to lock in the callbacks we'd drastically slow down\n# the performance of this code.\n_connection_refs = weakref.WeakValueDictionary()\n_connection_ref_lock = threading.Lock()\n\n# Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over\n# for no better reason than we need *a* limit, and this one is right there.\nSSL_WRITE_BLOCKSIZE = 16384\n\n# This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to\n# individual cipher suites. We need to do this because this is how\n# SecureTransport wants them.\nCIPHER_SUITES = [\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_AES_256_GCM_SHA384,\n    SecurityConst.TLS_AES_128_GCM_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_AES_128_CCM_8_SHA256,\n    SecurityConst.TLS_AES_128_CCM_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,\n]\n\n# Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of\n# TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.\n# TLSv1 to 1.2 are supported on macOS 10.8+\n_protocol_to_min_max = {\n    util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n    PROTOCOL_TLS_CLIENT: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n}\n\nif hasattr(ssl, \"PROTOCOL_SSLv2\"):\n    _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (\n        SecurityConst.kSSLProtocol2,\n        SecurityConst.kSSLProtocol2,\n    )\nif hasattr(ssl, \"PROTOCOL_SSLv3\"):\n    _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (\n        SecurityConst.kSSLProtocol3,\n        SecurityConst.kSSLProtocol3,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (\n        SecurityConst.kTLSProtocol1,\n        SecurityConst.kTLSProtocol1,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1_1\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (\n        SecurityConst.kTLSProtocol11,\n        SecurityConst.kTLSProtocol11,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1_2\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (\n        SecurityConst.kTLSProtocol12,\n        SecurityConst.kTLSProtocol12,\n    )\n\n\ndef inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.SSLContext = SecureTransportContext\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True\n\n\ndef extract_from_urllib3():\n    \"\"\"\n    Undo monkey-patching by :func:`inject_into_urllib3`.\n    \"\"\"\n    util.SSLContext = orig_util_SSLContext\n    util.ssl_.SSLContext = orig_util_SSLContext\n    util.HAS_SNI = orig_util_HAS_SNI\n    util.ssl_.HAS_SNI = orig_util_HAS_SNI\n    util.IS_SECURETRANSPORT = False\n    util.ssl_.IS_SECURETRANSPORT = False\n\n\ndef _read_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    SecureTransport read callback. This is called by ST to request that data\n    be returned from the socket.\n    \"\"\"\n    wrapped_socket = None\n    try:\n        wrapped_socket = _connection_refs.get(connection_id)\n        if wrapped_socket is None:\n            return SecurityConst.errSSLInternal\n        base_socket = wrapped_socket.socket\n\n        requested_length = data_length_pointer[0]\n\n        timeout = wrapped_socket.gettimeout()\n        error = None\n        read_count = 0\n\n        try:\n            while read_count < requested_length:\n                if timeout is None or timeout >= 0:\n                    if not util.wait_for_read(base_socket, timeout):\n                        raise socket.error(errno.EAGAIN, \"timed out\")\n\n                remaining = requested_length - read_count\n                buffer = (ctypes.c_char * remaining).from_address(\n                    data_buffer + read_count\n                )\n                chunk_size = base_socket.recv_into(buffer, remaining)\n                read_count += chunk_size\n                if not chunk_size:\n                    if not read_count:\n                        return SecurityConst.errSSLClosedGraceful\n                    break\n        except (socket.error) as e:\n            error = e.errno\n\n            if error is not None and error != errno.EAGAIN:\n                data_length_pointer[0] = read_count\n                if error == errno.ECONNRESET or error == errno.EPIPE:\n                    return SecurityConst.errSSLClosedAbort\n                raise\n\n        data_length_pointer[0] = read_count\n\n        if read_count != requested_length:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except Exception as e:\n        if wrapped_socket is not None:\n            wrapped_socket._exception = e\n        return SecurityConst.errSSLInternal\n\n\ndef _write_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    SecureTransport write callback. This is called by ST to request that data\n    actually be sent on the network.\n    \"\"\"\n    wrapped_socket = None\n    try:\n        wrapped_socket = _connection_refs.get(connection_id)\n        if wrapped_socket is None:\n            return SecurityConst.errSSLInternal\n        base_socket = wrapped_socket.socket\n\n        bytes_to_write = data_length_pointer[0]\n        data = ctypes.string_at(data_buffer, bytes_to_write)\n\n        timeout = wrapped_socket.gettimeout()\n        error = None\n        sent = 0\n\n        try:\n            while sent < bytes_to_write:\n                if timeout is None or timeout >= 0:\n                    if not util.wait_for_write(base_socket, timeout):\n                        raise socket.error(errno.EAGAIN, \"timed out\")\n                chunk_sent = base_socket.send(data)\n                sent += chunk_sent\n\n                # This has some needless copying here, but I'm not sure there's\n                # much value in optimising this data path.\n                data = data[chunk_sent:]\n        except (socket.error) as e:\n            error = e.errno\n\n            if error is not None and error != errno.EAGAIN:\n                data_length_pointer[0] = sent\n                if error == errno.ECONNRESET or error == errno.EPIPE:\n                    return SecurityConst.errSSLClosedAbort\n                raise\n\n        data_length_pointer[0] = sent\n\n        if sent != bytes_to_write:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except Exception as e:\n        if wrapped_socket is not None:\n            wrapped_socket._exception = e\n        return SecurityConst.errSSLInternal\n\n\n# We need to keep these two objects references alive: if they get GC'd while\n# in use then SecureTransport could attempt to call a function that is in freed\n# memory. That would be...uh...bad. Yeah, that's the word. Bad.\n_read_callback_pointer = Security.SSLReadFunc(_read_callback)\n_write_callback_pointer = Security.SSLWriteFunc(_write_callback)\n\n\nclass WrappedSocket(object):\n    \"\"\"\n    API-compatibility wrapper for Python's OpenSSL wrapped socket object.\n\n    Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage\n    collector of PyPy.\n    \"\"\"\n\n    def __init__(self, socket):\n        self.socket = socket\n        self.context = None\n        self._makefile_refs = 0\n        self._closed = False\n        self._exception = None\n        self._keychain = None\n        self._keychain_dir = None\n        self._client_cert_chain = None\n\n        # We save off the previously-configured timeout and then set it to\n        # zero. This is done because we use select and friends to handle the\n        # timeouts, but if we leave the timeout set on the lower socket then\n        # Python will \"kindly\" call select on that socket again for us. Avoid\n        # that by forcing the timeout to zero.\n        self._timeout = self.socket.gettimeout()\n        self.socket.settimeout(0)\n\n    @contextlib.contextmanager\n    def _raise_on_error(self):\n        \"\"\"\n        A context manager that can be used to wrap calls that do I/O from\n        SecureTransport. If any of the I/O callbacks hit an exception, this\n        context manager will correctly propagate the exception after the fact.\n        This avoids silently swallowing those exceptions.\n\n        It also correctly forces the socket closed.\n        \"\"\"\n        self._exception = None\n\n        # We explicitly don't catch around this yield because in the unlikely\n        # event that an exception was hit in the block we don't want to swallow\n        # it.\n        yield\n        if self._exception is not None:\n            exception, self._exception = self._exception, None\n            self.close()\n            raise exception\n\n    def _set_ciphers(self):\n        \"\"\"\n        Sets up the allowed ciphers. By default this matches the set in\n        util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done\n        custom and doesn't allow changing at this time, mostly because parsing\n        OpenSSL cipher strings is going to be a freaking nightmare.\n        \"\"\"\n        ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)\n        result = Security.SSLSetEnabledCiphers(\n            self.context, ciphers, len(CIPHER_SUITES)\n        )\n        _assert_no_error(result)\n\n    def _set_alpn_protocols(self, protocols):\n        \"\"\"\n        Sets up the ALPN protocols on the context.\n        \"\"\"\n        if not protocols:\n            return\n        protocols_arr = _create_cfstring_array(protocols)\n        try:\n            result = Security.SSLSetALPNProtocols(self.context, protocols_arr)\n            _assert_no_error(result)\n        finally:\n            CoreFoundation.CFRelease(protocols_arr)\n\n    def _custom_validate(self, verify, trust_bundle):\n        \"\"\"\n        Called when we have set custom validation. We do this in two cases:\n        first, when cert validation is entirely disabled; and second, when\n        using a custom trust DB.\n        Raises an SSLError if the connection is not trusted.\n        \"\"\"\n        # If we disabled cert validation, just say: cool.\n        if not verify:\n            return\n\n        successes = (\n            SecurityConst.kSecTrustResultUnspecified,\n            SecurityConst.kSecTrustResultProceed,\n        )\n        try:\n            trust_result = self._evaluate_trust(trust_bundle)\n            if trust_result in successes:\n                return\n            reason = \"error code: %d\" % (trust_result,)\n        except Exception as e:\n            # Do not trust on error\n            reason = \"exception: %r\" % (e,)\n\n        # SecureTransport does not send an alert nor shuts down the connection.\n        rec = _build_tls_unknown_ca_alert(self.version())\n        self.socket.sendall(rec)\n        # close the connection immediately\n        # l_onoff = 1, activate linger\n        # l_linger = 0, linger for 0 seoncds\n        opts = struct.pack(\"ii\", 1, 0)\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts)\n        self.close()\n        raise ssl.SSLError(\"certificate verify failed, %s\" % reason)\n\n    def _evaluate_trust(self, trust_bundle):\n        # We want data in memory, so load it up.\n        if os.path.isfile(trust_bundle):\n            with open(trust_bundle, \"rb\") as f:\n                trust_bundle = f.read()\n\n        cert_array = None\n        trust = Security.SecTrustRef()\n\n        try:\n            # Get a CFArray that contains the certs we want.\n            cert_array = _cert_array_from_pem(trust_bundle)\n\n            # Ok, now the hard part. We want to get the SecTrustRef that ST has\n            # created for this connection, shove our CAs into it, tell ST to\n            # ignore everything else it knows, and then ask if it can build a\n            # chain. This is a buuuunch of code.\n            result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n            _assert_no_error(result)\n            if not trust:\n                raise ssl.SSLError(\"Failed to copy trust reference\")\n\n            result = Security.SecTrustSetAnchorCertificates(trust, cert_array)\n            _assert_no_error(result)\n\n            result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)\n            _assert_no_error(result)\n\n            trust_result = Security.SecTrustResultType()\n            result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result))\n            _assert_no_error(result)\n        finally:\n            if trust:\n                CoreFoundation.CFRelease(trust)\n\n            if cert_array is not None:\n                CoreFoundation.CFRelease(cert_array)\n\n        return trust_result.value\n\n    def handshake(\n        self,\n        server_hostname,\n        verify,\n        trust_bundle,\n        min_version,\n        max_version,\n        client_cert,\n        client_key,\n        client_key_passphrase,\n        alpn_protocols,\n    ):\n        \"\"\"\n        Actually performs the TLS handshake. This is run automatically by\n        wrapped socket, and shouldn't be needed in user code.\n        \"\"\"\n        # First, we do the initial bits of connection setup. We need to create\n        # a context, set its I/O funcs, and set the connection reference.\n        self.context = Security.SSLCreateContext(\n            None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType\n        )\n        result = Security.SSLSetIOFuncs(\n            self.context, _read_callback_pointer, _write_callback_pointer\n        )\n        _assert_no_error(result)\n\n        # Here we need to compute the handle to use. We do this by taking the\n        # id of self modulo 2**31 - 1. If this is already in the dictionary, we\n        # just keep incrementing by one until we find a free space.\n        with _connection_ref_lock:\n            handle = id(self) % 2147483647\n            while handle in _connection_refs:\n                handle = (handle + 1) % 2147483647\n            _connection_refs[handle] = self\n\n        result = Security.SSLSetConnection(self.context, handle)\n        _assert_no_error(result)\n\n        # If we have a server hostname, we should set that too.\n        if server_hostname:\n            if not isinstance(server_hostname, bytes):\n                server_hostname = server_hostname.encode(\"utf-8\")\n\n            result = Security.SSLSetPeerDomainName(\n                self.context, server_hostname, len(server_hostname)\n            )\n            _assert_no_error(result)\n\n        # Setup the ciphers.\n        self._set_ciphers()\n\n        # Setup the ALPN protocols.\n        self._set_alpn_protocols(alpn_protocols)\n\n        # Set the minimum and maximum TLS versions.\n        result = Security.SSLSetProtocolVersionMin(self.context, min_version)\n        _assert_no_error(result)\n\n        result = Security.SSLSetProtocolVersionMax(self.context, max_version)\n        _assert_no_error(result)\n\n        # If there's a trust DB, we need to use it. We do that by telling\n        # SecureTransport to break on server auth. We also do that if we don't\n        # want to validate the certs at all: we just won't actually do any\n        # authing in that case.\n        if not verify or trust_bundle is not None:\n            result = Security.SSLSetSessionOption(\n                self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True\n            )\n            _assert_no_error(result)\n\n        # If there's a client cert, we need to use it.\n        if client_cert:\n            self._keychain, self._keychain_dir = _temporary_keychain()\n            self._client_cert_chain = _load_client_cert_chain(\n                self._keychain, client_cert, client_key\n            )\n            result = Security.SSLSetCertificate(self.context, self._client_cert_chain)\n            _assert_no_error(result)\n\n        while True:\n            with self._raise_on_error():\n                result = Security.SSLHandshake(self.context)\n\n                if result == SecurityConst.errSSLWouldBlock:\n                    raise socket.timeout(\"handshake timed out\")\n                elif result == SecurityConst.errSSLServerAuthCompleted:\n                    self._custom_validate(verify, trust_bundle)\n                    continue\n                else:\n                    _assert_no_error(result)\n                    break\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    # Copy-pasted from Python 3.5 source code\n    def _decref_socketios(self):\n        if self._makefile_refs > 0:\n            self._makefile_refs -= 1\n        if self._closed:\n            self.close()\n\n    def recv(self, bufsiz):\n        buffer = ctypes.create_string_buffer(bufsiz)\n        bytes_read = self.recv_into(buffer, bufsiz)\n        data = buffer[:bytes_read]\n        return data\n\n    def recv_into(self, buffer, nbytes=None):\n        # Read short on EOF.\n        if self._closed:\n            return 0\n\n        if nbytes is None:\n            nbytes = len(buffer)\n\n        buffer = (ctypes.c_char * nbytes).from_buffer(buffer)\n        processed_bytes = ctypes.c_size_t(0)\n\n        with self._raise_on_error():\n            result = Security.SSLRead(\n                self.context, buffer, nbytes, ctypes.byref(processed_bytes)\n            )\n\n        # There are some result codes that we want to treat as \"not always\n        # errors\". Specifically, those are errSSLWouldBlock,\n        # errSSLClosedGraceful, and errSSLClosedNoNotify.\n        if result == SecurityConst.errSSLWouldBlock:\n            # If we didn't process any bytes, then this was just a time out.\n            # However, we can get errSSLWouldBlock in situations when we *did*\n            # read some data, and in those cases we should just read \"short\"\n            # and return.\n            if processed_bytes.value == 0:\n                # Timed out, no data read.\n                raise socket.timeout(\"recv timed out\")\n        elif result in (\n            SecurityConst.errSSLClosedGraceful,\n            SecurityConst.errSSLClosedNoNotify,\n        ):\n            # The remote peer has closed this connection. We should do so as\n            # well. Note that we don't actually return here because in\n            # principle this could actually be fired along with return data.\n            # It's unlikely though.\n            self.close()\n        else:\n            _assert_no_error(result)\n\n        # Ok, we read and probably succeeded. We should return whatever data\n        # was actually read.\n        return processed_bytes.value\n\n    def settimeout(self, timeout):\n        self._timeout = timeout\n\n    def gettimeout(self):\n        return self._timeout\n\n    def send(self, data):\n        processed_bytes = ctypes.c_size_t(0)\n\n        with self._raise_on_error():\n            result = Security.SSLWrite(\n                self.context, data, len(data), ctypes.byref(processed_bytes)\n            )\n\n        if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:\n            # Timed out\n            raise socket.timeout(\"send timed out\")\n        else:\n            _assert_no_error(result)\n\n        # We sent, and probably succeeded. Tell them how much we sent.\n        return processed_bytes.value\n\n    def sendall(self, data):\n        total_sent = 0\n        while total_sent < len(data):\n            sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE])\n            total_sent += sent\n\n    def shutdown(self):\n        with self._raise_on_error():\n            Security.SSLClose(self.context)\n\n    def close(self):\n        # TODO: should I do clean shutdown here? Do I have to?\n        if self._makefile_refs < 1:\n            self._closed = True\n            if self.context:\n                CoreFoundation.CFRelease(self.context)\n                self.context = None\n            if self._client_cert_chain:\n                CoreFoundation.CFRelease(self._client_cert_chain)\n                self._client_cert_chain = None\n            if self._keychain:\n                Security.SecKeychainDelete(self._keychain)\n                CoreFoundation.CFRelease(self._keychain)\n                shutil.rmtree(self._keychain_dir)\n                self._keychain = self._keychain_dir = None\n            return self.socket.close()\n        else:\n            self._makefile_refs -= 1\n\n    def getpeercert(self, binary_form=False):\n        # Urgh, annoying.\n        #\n        # Here's how we do this:\n        #\n        # 1. Call SSLCopyPeerTrust to get hold of the trust object for this\n        #    connection.\n        # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.\n        # 3. To get the CN, call SecCertificateCopyCommonName and process that\n        #    string so that it's of the appropriate type.\n        # 4. To get the SAN, we need to do something a bit more complex:\n        #    a. Call SecCertificateCopyValues to get the data, requesting\n        #       kSecOIDSubjectAltName.\n        #    b. Mess about with this dictionary to try to get the SANs out.\n        #\n        # This is gross. Really gross. It's going to be a few hundred LoC extra\n        # just to repeat something that SecureTransport can *already do*. So my\n        # operating assumption at this time is that what we want to do is\n        # instead to just flag to urllib3 that it shouldn't do its own hostname\n        # validation when using SecureTransport.\n        if not binary_form:\n            raise ValueError(\"SecureTransport only supports dumping binary certs\")\n        trust = Security.SecTrustRef()\n        certdata = None\n        der_bytes = None\n\n        try:\n            # Grab the trust store.\n            result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n            _assert_no_error(result)\n            if not trust:\n                # Probably we haven't done the handshake yet. No biggie.\n                return None\n\n            cert_count = Security.SecTrustGetCertificateCount(trust)\n            if not cert_count:\n                # Also a case that might happen if we haven't handshaked.\n                # Handshook? Handshaken?\n                return None\n\n            leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)\n            assert leaf\n\n            # Ok, now we want the DER bytes.\n            certdata = Security.SecCertificateCopyData(leaf)\n            assert certdata\n\n            data_length = CoreFoundation.CFDataGetLength(certdata)\n            data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)\n            der_bytes = ctypes.string_at(data_buffer, data_length)\n        finally:\n            if certdata:\n                CoreFoundation.CFRelease(certdata)\n            if trust:\n                CoreFoundation.CFRelease(trust)\n\n        return der_bytes\n\n    def version(self):\n        protocol = Security.SSLProtocol()\n        result = Security.SSLGetNegotiatedProtocolVersion(\n            self.context, ctypes.byref(protocol)\n        )\n        _assert_no_error(result)\n        if protocol.value == SecurityConst.kTLSProtocol13:\n            raise ssl.SSLError(\"SecureTransport does not support TLS 1.3\")\n        elif protocol.value == SecurityConst.kTLSProtocol12:\n            return \"TLSv1.2\"\n        elif protocol.value == SecurityConst.kTLSProtocol11:\n            return \"TLSv1.1\"\n        elif protocol.value == SecurityConst.kTLSProtocol1:\n            return \"TLSv1\"\n        elif protocol.value == SecurityConst.kSSLProtocol3:\n            return \"SSLv3\"\n        elif protocol.value == SecurityConst.kSSLProtocol2:\n            return \"SSLv2\"\n        else:\n            raise ssl.SSLError(\"Unknown TLS version: %r\" % protocol)\n\n    def _reuse(self):\n        self._makefile_refs += 1\n\n    def _drop(self):\n        if self._makefile_refs < 1:\n            self.close()\n        else:\n            self._makefile_refs -= 1\n\n\nif _fileobject:  # Platform-specific: Python 2\n\n    def makefile(self, mode, bufsize=-1):\n        self._makefile_refs += 1\n        return _fileobject(self, mode, bufsize, close=True)\n\nelse:  # Platform-specific: Python 3\n\n    def makefile(self, mode=\"r\", buffering=None, *args, **kwargs):\n        # We disable buffering with SecureTransport because it conflicts with\n        # the buffering that ST does internally (see issue #1153 for more).\n        buffering = 0\n        return backport_makefile(self, mode, buffering, *args, **kwargs)\n\n\nWrappedSocket.makefile = makefile\n\n\nclass SecureTransportContext(object):\n    \"\"\"\n    I am a wrapper class for the SecureTransport library, to translate the\n    interface of the standard library ``SSLContext`` object to calls into\n    SecureTransport.\n    \"\"\"\n\n    def __init__(self, protocol):\n        self._min_version, self._max_version = _protocol_to_min_max[protocol]\n        self._options = 0\n        self._verify = False\n        self._trust_bundle = None\n        self._client_cert = None\n        self._client_key = None\n        self._client_key_passphrase = None\n        self._alpn_protocols = None\n\n    @property\n    def check_hostname(self):\n        \"\"\"\n        SecureTransport cannot have its hostname checking disabled. For more,\n        see the comment on getpeercert() in this file.\n        \"\"\"\n        return True\n\n    @check_hostname.setter\n    def check_hostname(self, value):\n        \"\"\"\n        SecureTransport cannot have its hostname checking disabled. For more,\n        see the comment on getpeercert() in this file.\n        \"\"\"\n        pass\n\n    @property\n    def options(self):\n        # TODO: Well, crap.\n        #\n        # So this is the bit of the code that is the most likely to cause us\n        # trouble. Essentially we need to enumerate all of the SSL options that\n        # users might want to use and try to see if we can sensibly translate\n        # them, or whether we should just ignore them.\n        return self._options\n\n    @options.setter\n    def options(self, value):\n        # TODO: Update in line with above.\n        self._options = value\n\n    @property\n    def verify_mode(self):\n        return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE\n\n    @verify_mode.setter\n    def verify_mode(self, value):\n        self._verify = True if value == ssl.CERT_REQUIRED else False\n\n    def set_default_verify_paths(self):\n        # So, this has to do something a bit weird. Specifically, what it does\n        # is nothing.\n        #\n        # This means that, if we had previously had load_verify_locations\n        # called, this does not undo that. We need to do that because it turns\n        # out that the rest of the urllib3 code will attempt to load the\n        # default verify paths if it hasn't been told about any paths, even if\n        # the context itself was sometime earlier. We resolve that by just\n        # ignoring it.\n        pass\n\n    def load_default_certs(self):\n        return self.set_default_verify_paths()\n\n    def set_ciphers(self, ciphers):\n        # For now, we just require the default cipher string.\n        if ciphers != util.ssl_.DEFAULT_CIPHERS:\n            raise ValueError(\"SecureTransport doesn't support custom cipher strings\")\n\n    def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n        # OK, we only really support cadata and cafile.\n        if capath is not None:\n            raise ValueError(\"SecureTransport does not support cert directories\")\n\n        # Raise if cafile does not exist.\n        if cafile is not None:\n            with open(cafile):\n                pass\n\n        self._trust_bundle = cafile or cadata\n\n    def load_cert_chain(self, certfile, keyfile=None, password=None):\n        self._client_cert = certfile\n        self._client_key = keyfile\n        self._client_cert_passphrase = password\n\n    def set_alpn_protocols(self, protocols):\n        \"\"\"\n        Sets the ALPN protocols that will later be set on the context.\n\n        Raises a NotImplementedError if ALPN is not supported.\n        \"\"\"\n        if not hasattr(Security, \"SSLSetALPNProtocols\"):\n            raise NotImplementedError(\n                \"SecureTransport supports ALPN only in macOS 10.12+\"\n            )\n        self._alpn_protocols = [six.ensure_binary(p) for p in protocols]\n\n    def wrap_socket(\n        self,\n        sock,\n        server_side=False,\n        do_handshake_on_connect=True,\n        suppress_ragged_eofs=True,\n        server_hostname=None,\n    ):\n        # So, what do we do here? Firstly, we assert some properties. This is a\n        # stripped down shim, so there is some functionality we don't support.\n        # See PEP 543 for the real deal.\n        assert not server_side\n        assert do_handshake_on_connect\n        assert suppress_ragged_eofs\n\n        # Ok, we're good to go. Now we want to create the wrapped socket object\n        # and store it in the appropriate place.\n        wrapped_socket = WrappedSocket(sock)\n\n        # Now we can handshake\n        wrapped_socket.handshake(\n            server_hostname,\n            self._verify,\n            self._trust_bundle,\n            self._min_version,\n            self._max_version,\n            self._client_cert,\n            self._client_key,\n            self._client_key_passphrase,\n            self._alpn_protocols,\n        )\n        return wrapped_socket\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/contrib/socks.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and\nSOCKS5. To enable its functionality, either install PySocks or install this\nmodule with the ``socks`` extra.\n\nThe SOCKS implementation supports the full range of urllib3 features. It also\nsupports the following SOCKS features:\n\n- SOCKS4A (``proxy_url='socks4a://...``)\n- SOCKS4 (``proxy_url='socks4://...``)\n- SOCKS5 with remote DNS (``proxy_url='socks5h://...``)\n- SOCKS5 with local DNS (``proxy_url='socks5://...``)\n- Usernames and passwords for the SOCKS proxy\n\n.. note::\n   It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in\n   your ``proxy_url`` to ensure that DNS resolution is done from the remote\n   server instead of client-side when connecting to a domain name.\n\nSOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5\nsupports IPv4, IPv6, and domain names.\n\nWhen connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url``\nwill be sent as the ``userid`` section of the SOCKS request:\n\n.. code-block:: python\n\n    proxy_url=\"socks4a://<userid>@proxy-host\"\n\nWhen connecting to a SOCKS5 proxy the ``username`` and ``password`` portion\nof the ``proxy_url`` will be sent as the username/password to authenticate\nwith the proxy:\n\n.. code-block:: python\n\n    proxy_url=\"socks5h://<username>:<password>@proxy-host\"\n\n\"\"\"\nfrom __future__ import absolute_import\n\ntry:\n    import socks\nexcept ImportError:\n    import warnings\n\n    from ..exceptions import DependencyWarning\n\n    warnings.warn(\n        (\n            \"SOCKS support in urllib3 requires the installation of optional \"\n            \"dependencies: specifically, PySocks.  For more information, see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/contrib.html#socks-proxies\"\n        ),\n        DependencyWarning,\n    )\n    raise\n\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom ..connection import HTTPConnection, HTTPSConnection\nfrom ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool\nfrom ..exceptions import ConnectTimeoutError, NewConnectionError\nfrom ..poolmanager import PoolManager\nfrom ..util.url import parse_url\n\ntry:\n    import ssl\nexcept ImportError:\n    ssl = None\n\n\nclass SOCKSConnection(HTTPConnection):\n    \"\"\"\n    A plain-text HTTP connection that connects via a SOCKS proxy.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._socks_options = kwargs.pop(\"_socks_options\")\n        super(SOCKSConnection, self).__init__(*args, **kwargs)\n\n    def _new_conn(self):\n        \"\"\"\n        Establish a new connection via the SOCKS proxy.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw[\"source_address\"] = self.source_address\n\n        if self.socket_options:\n            extra_kw[\"socket_options\"] = self.socket_options\n\n        try:\n            conn = socks.create_connection(\n                (self.host, self.port),\n                proxy_type=self._socks_options[\"socks_version\"],\n                proxy_addr=self._socks_options[\"proxy_host\"],\n                proxy_port=self._socks_options[\"proxy_port\"],\n                proxy_username=self._socks_options[\"username\"],\n                proxy_password=self._socks_options[\"password\"],\n                proxy_rdns=self._socks_options[\"rdns\"],\n                timeout=self.timeout,\n                **extra_kw\n            )\n\n        except SocketTimeout:\n            raise ConnectTimeoutError(\n                self,\n                \"Connection to %s timed out. (connect timeout=%s)\"\n                % (self.host, self.timeout),\n            )\n\n        except socks.ProxyError as e:\n            # This is fragile as hell, but it seems to be the only way to raise\n            # useful errors here.\n            if e.socket_err:\n                error = e.socket_err\n                if isinstance(error, SocketTimeout):\n                    raise ConnectTimeoutError(\n                        self,\n                        \"Connection to %s timed out. (connect timeout=%s)\"\n                        % (self.host, self.timeout),\n                    )\n                else:\n                    raise NewConnectionError(\n                        self, \"Failed to establish a new connection: %s\" % error\n                    )\n            else:\n                raise NewConnectionError(\n                    self, \"Failed to establish a new connection: %s\" % e\n                )\n\n        except SocketError as e:  # Defensive: PySocks should catch all these.\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e\n            )\n\n        return conn\n\n\n# We don't need to duplicate the Verified/Unverified distinction from\n# urllib3/connection.py here because the HTTPSConnection will already have been\n# correctly set to either the Verified or Unverified form by that module. This\n# means the SOCKSHTTPSConnection will automatically be the correct type.\nclass SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):\n    pass\n\n\nclass SOCKSHTTPConnectionPool(HTTPConnectionPool):\n    ConnectionCls = SOCKSConnection\n\n\nclass SOCKSHTTPSConnectionPool(HTTPSConnectionPool):\n    ConnectionCls = SOCKSHTTPSConnection\n\n\nclass SOCKSProxyManager(PoolManager):\n    \"\"\"\n    A version of the urllib3 ProxyManager that routes connections via the\n    defined SOCKS proxy.\n    \"\"\"\n\n    pool_classes_by_scheme = {\n        \"http\": SOCKSHTTPConnectionPool,\n        \"https\": SOCKSHTTPSConnectionPool,\n    }\n\n    def __init__(\n        self,\n        proxy_url,\n        username=None,\n        password=None,\n        num_pools=10,\n        headers=None,\n        **connection_pool_kw\n    ):\n        parsed = parse_url(proxy_url)\n\n        if username is None and password is None and parsed.auth is not None:\n            split = parsed.auth.split(\":\")\n            if len(split) == 2:\n                username, password = split\n        if parsed.scheme == \"socks5\":\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = False\n        elif parsed.scheme == \"socks5h\":\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = True\n        elif parsed.scheme == \"socks4\":\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = False\n        elif parsed.scheme == \"socks4a\":\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = True\n        else:\n            raise ValueError(\"Unable to determine SOCKS version from %s\" % proxy_url)\n\n        self.proxy_url = proxy_url\n\n        socks_options = {\n            \"socks_version\": socks_version,\n            \"proxy_host\": parsed.host,\n            \"proxy_port\": parsed.port,\n            \"username\": username,\n            \"password\": password,\n            \"rdns\": rdns,\n        }\n        connection_pool_kw[\"_socks_options\"] = socks_options\n\n        super(SOCKSProxyManager, self).__init__(\n            num_pools, headers, **connection_pool_kw\n        )\n\n        self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/exceptions.py",
    "content": "from __future__ import absolute_import\n\nfrom .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead\n\n# Base Exceptions\n\n\nclass HTTPError(Exception):\n    \"\"\"Base exception used by this module.\"\"\"\n\n    pass\n\n\nclass HTTPWarning(Warning):\n    \"\"\"Base warning used by this module.\"\"\"\n\n    pass\n\n\nclass PoolError(HTTPError):\n    \"\"\"Base exception for errors caused within a pool.\"\"\"\n\n    def __init__(self, pool, message):\n        self.pool = pool\n        HTTPError.__init__(self, \"%s: %s\" % (pool, message))\n\n    def __reduce__(self):\n        # For pickling purposes.\n        return self.__class__, (None, None)\n\n\nclass RequestError(PoolError):\n    \"\"\"Base exception for PoolErrors that have associated URLs.\"\"\"\n\n    def __init__(self, pool, url, message):\n        self.url = url\n        PoolError.__init__(self, pool, message)\n\n    def __reduce__(self):\n        # For pickling purposes.\n        return self.__class__, (None, self.url, None)\n\n\nclass SSLError(HTTPError):\n    \"\"\"Raised when SSL certificate fails in an HTTPS connection.\"\"\"\n\n    pass\n\n\nclass ProxyError(HTTPError):\n    \"\"\"Raised when the connection to a proxy fails.\"\"\"\n\n    def __init__(self, message, error, *args):\n        super(ProxyError, self).__init__(message, error, *args)\n        self.original_error = error\n\n\nclass DecodeError(HTTPError):\n    \"\"\"Raised when automatic decoding based on Content-Type fails.\"\"\"\n\n    pass\n\n\nclass ProtocolError(HTTPError):\n    \"\"\"Raised when something unexpected happens mid-request/response.\"\"\"\n\n    pass\n\n\n#: Renamed to ProtocolError but aliased for backwards compatibility.\nConnectionError = ProtocolError\n\n\n# Leaf Exceptions\n\n\nclass MaxRetryError(RequestError):\n    \"\"\"Raised when the maximum number of retries is exceeded.\n\n    :param pool: The connection pool\n    :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n    :param string url: The requested Url\n    :param exceptions.Exception reason: The underlying error\n\n    \"\"\"\n\n    def __init__(self, pool, url, reason=None):\n        self.reason = reason\n\n        message = \"Max retries exceeded with url: %s (Caused by %r)\" % (url, reason)\n\n        RequestError.__init__(self, pool, url, message)\n\n\nclass HostChangedError(RequestError):\n    \"\"\"Raised when an existing pool gets a request for a foreign host.\"\"\"\n\n    def __init__(self, pool, url, retries=3):\n        message = \"Tried to open a foreign host with url: %s\" % url\n        RequestError.__init__(self, pool, url, message)\n        self.retries = retries\n\n\nclass TimeoutStateError(HTTPError):\n    \"\"\"Raised when passing an invalid state to a timeout\"\"\"\n\n    pass\n\n\nclass TimeoutError(HTTPError):\n    \"\"\"Raised when a socket timeout error occurs.\n\n    Catching this error will catch both :exc:`ReadTimeoutErrors\n    <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.\n    \"\"\"\n\n    pass\n\n\nclass ReadTimeoutError(TimeoutError, RequestError):\n    \"\"\"Raised when a socket timeout occurs while receiving data from a server\"\"\"\n\n    pass\n\n\n# This timeout error does not have a URL attached and needs to inherit from the\n# base HTTPError\nclass ConnectTimeoutError(TimeoutError):\n    \"\"\"Raised when a socket timeout occurs while connecting to a server\"\"\"\n\n    pass\n\n\nclass NewConnectionError(ConnectTimeoutError, PoolError):\n    \"\"\"Raised when we fail to establish a new connection. Usually ECONNREFUSED.\"\"\"\n\n    pass\n\n\nclass EmptyPoolError(PoolError):\n    \"\"\"Raised when a pool runs out of connections and no more are allowed.\"\"\"\n\n    pass\n\n\nclass ClosedPoolError(PoolError):\n    \"\"\"Raised when a request enters a pool after the pool has been closed.\"\"\"\n\n    pass\n\n\nclass LocationValueError(ValueError, HTTPError):\n    \"\"\"Raised when there is something wrong with a given URL input.\"\"\"\n\n    pass\n\n\nclass LocationParseError(LocationValueError):\n    \"\"\"Raised when get_host or similar fails to parse the URL input.\"\"\"\n\n    def __init__(self, location):\n        message = \"Failed to parse: %s\" % location\n        HTTPError.__init__(self, message)\n\n        self.location = location\n\n\nclass URLSchemeUnknown(LocationValueError):\n    \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n    def __init__(self, scheme):\n        message = \"Not supported URL scheme %s\" % scheme\n        super(URLSchemeUnknown, self).__init__(message)\n\n        self.scheme = scheme\n\n\nclass ResponseError(HTTPError):\n    \"\"\"Used as a container for an error reason supplied in a MaxRetryError.\"\"\"\n\n    GENERIC_ERROR = \"too many error responses\"\n    SPECIFIC_ERROR = \"too many {status_code} error responses\"\n\n\nclass SecurityWarning(HTTPWarning):\n    \"\"\"Warned when performing security reducing actions\"\"\"\n\n    pass\n\n\nclass SubjectAltNameWarning(SecurityWarning):\n    \"\"\"Warned when connecting to a host with a certificate missing a SAN.\"\"\"\n\n    pass\n\n\nclass InsecureRequestWarning(SecurityWarning):\n    \"\"\"Warned when making an unverified HTTPS request.\"\"\"\n\n    pass\n\n\nclass SystemTimeWarning(SecurityWarning):\n    \"\"\"Warned when system time is suspected to be wrong\"\"\"\n\n    pass\n\n\nclass InsecurePlatformWarning(SecurityWarning):\n    \"\"\"Warned when certain TLS/SSL configuration is not available on a platform.\"\"\"\n\n    pass\n\n\nclass SNIMissingWarning(HTTPWarning):\n    \"\"\"Warned when making a HTTPS request without SNI available.\"\"\"\n\n    pass\n\n\nclass DependencyWarning(HTTPWarning):\n    \"\"\"\n    Warned when an attempt is made to import a module with missing optional\n    dependencies.\n    \"\"\"\n\n    pass\n\n\nclass ResponseNotChunked(ProtocolError, ValueError):\n    \"\"\"Response needs to be chunked in order to read it as chunks.\"\"\"\n\n    pass\n\n\nclass BodyNotHttplibCompatible(HTTPError):\n    \"\"\"\n    Body should be :class:`http.client.HTTPResponse` like\n    (have an fp attribute which returns raw chunks) for read_chunked().\n    \"\"\"\n\n    pass\n\n\nclass IncompleteRead(HTTPError, httplib_IncompleteRead):\n    \"\"\"\n    Response length doesn't match expected Content-Length\n\n    Subclass of :class:`http.client.IncompleteRead` to allow int value\n    for ``partial`` to avoid creating large objects on streamed reads.\n    \"\"\"\n\n    def __init__(self, partial, expected):\n        super(IncompleteRead, self).__init__(partial, expected)\n\n    def __repr__(self):\n        return \"IncompleteRead(%i bytes read, %i more expected)\" % (\n            self.partial,\n            self.expected,\n        )\n\n\nclass InvalidChunkLength(HTTPError, httplib_IncompleteRead):\n    \"\"\"Invalid chunk length in a chunked response.\"\"\"\n\n    def __init__(self, response, length):\n        super(InvalidChunkLength, self).__init__(\n            response.tell(), response.length_remaining\n        )\n        self.response = response\n        self.length = length\n\n    def __repr__(self):\n        return \"InvalidChunkLength(got length %r, %i bytes read)\" % (\n            self.length,\n            self.partial,\n        )\n\n\nclass InvalidHeader(HTTPError):\n    \"\"\"The header provided was somehow invalid.\"\"\"\n\n    pass\n\n\nclass ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n    \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n    # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n    def __init__(self, scheme):\n        # 'localhost' is here because our URL parser parses\n        # localhost:8080 -> scheme=localhost, remove if we fix this.\n        if scheme == \"localhost\":\n            scheme = None\n        if scheme is None:\n            message = \"Proxy URL had no scheme, should start with http:// or https://\"\n        else:\n            message = (\n                \"Proxy URL had unsupported scheme %s, should use http:// or https://\"\n                % scheme\n            )\n        super(ProxySchemeUnknown, self).__init__(message)\n\n\nclass ProxySchemeUnsupported(ValueError):\n    \"\"\"Fetching HTTPS resources through HTTPS proxies is unsupported\"\"\"\n\n    pass\n\n\nclass HeaderParsingError(HTTPError):\n    \"\"\"Raised by assert_header_parsing, but we convert it to a log.warning statement.\"\"\"\n\n    def __init__(self, defects, unparsed_data):\n        message = \"%s, unparsed data: %r\" % (defects or \"Unknown\", unparsed_data)\n        super(HeaderParsingError, self).__init__(message)\n\n\nclass UnrewindableBodyError(HTTPError):\n    \"\"\"urllib3 encountered an error when trying to rewind a body\"\"\"\n\n    pass\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/fields.py",
    "content": "from __future__ import absolute_import\n\nimport email.utils\nimport mimetypes\nimport re\n\nfrom .packages import six\n\n\ndef guess_content_type(filename, default=\"application/octet-stream\"):\n    \"\"\"\n    Guess the \"Content-Type\" of a file.\n\n    :param filename:\n        The filename to guess the \"Content-Type\" of using :mod:`mimetypes`.\n    :param default:\n        If no \"Content-Type\" can be guessed, default to `default`.\n    \"\"\"\n    if filename:\n        return mimetypes.guess_type(filename)[0] or default\n    return default\n\n\ndef format_header_param_rfc2231(name, value):\n    \"\"\"\n    Helper function to format and quote a single header parameter using the\n    strategy defined in RFC 2231.\n\n    Particularly useful for header parameters which might contain\n    non-ASCII values, like file names. This follows\n    `RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_.\n\n    :param name:\n        The name of the parameter, a string expected to be ASCII only.\n    :param value:\n        The value of the parameter, provided as ``bytes`` or `str``.\n    :ret:\n        An RFC-2231-formatted unicode string.\n    \"\"\"\n    if isinstance(value, six.binary_type):\n        value = value.decode(\"utf-8\")\n\n    if not any(ch in value for ch in '\"\\\\\\r\\n'):\n        result = u'%s=\"%s\"' % (name, value)\n        try:\n            result.encode(\"ascii\")\n        except (UnicodeEncodeError, UnicodeDecodeError):\n            pass\n        else:\n            return result\n\n    if six.PY2:  # Python 2:\n        value = value.encode(\"utf-8\")\n\n    # encode_rfc2231 accepts an encoded string and returns an ascii-encoded\n    # string in Python 2 but accepts and returns unicode strings in Python 3\n    value = email.utils.encode_rfc2231(value, \"utf-8\")\n    value = \"%s*=%s\" % (name, value)\n\n    if six.PY2:  # Python 2:\n        value = value.decode(\"utf-8\")\n\n    return value\n\n\n_HTML5_REPLACEMENTS = {\n    u\"\\u0022\": u\"%22\",\n    # Replace \"\\\" with \"\\\\\".\n    u\"\\u005C\": u\"\\u005C\\u005C\",\n}\n\n# All control characters from 0x00 to 0x1F *except* 0x1B.\n_HTML5_REPLACEMENTS.update(\n    {\n        six.unichr(cc): u\"%{:02X}\".format(cc)\n        for cc in range(0x00, 0x1F + 1)\n        if cc not in (0x1B,)\n    }\n)\n\n\ndef _replace_multiple(value, needles_and_replacements):\n    def replacer(match):\n        return needles_and_replacements[match.group(0)]\n\n    pattern = re.compile(\n        r\"|\".join([re.escape(needle) for needle in needles_and_replacements.keys()])\n    )\n\n    result = pattern.sub(replacer, value)\n\n    return result\n\n\ndef format_header_param_html5(name, value):\n    \"\"\"\n    Helper function to format and quote a single header parameter using the\n    HTML5 strategy.\n\n    Particularly useful for header parameters which might contain\n    non-ASCII values, like file names. This follows the `HTML5 Working Draft\n    Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.\n\n    .. _HTML5 Working Draft Section 4.10.22.7:\n        https://w3c.github.io/html/sec-forms.html#multipart-form-data\n\n    :param name:\n        The name of the parameter, a string expected to be ASCII only.\n    :param value:\n        The value of the parameter, provided as ``bytes`` or `str``.\n    :ret:\n        A unicode string, stripped of troublesome characters.\n    \"\"\"\n    if isinstance(value, six.binary_type):\n        value = value.decode(\"utf-8\")\n\n    value = _replace_multiple(value, _HTML5_REPLACEMENTS)\n\n    return u'%s=\"%s\"' % (name, value)\n\n\n# For backwards-compatibility.\nformat_header_param = format_header_param_html5\n\n\nclass RequestField(object):\n    \"\"\"\n    A data container for request body parameters.\n\n    :param name:\n        The name of this request field. Must be unicode.\n    :param data:\n        The data/value body.\n    :param filename:\n        An optional filename of the request field. Must be unicode.\n    :param headers:\n        An optional dict-like object of headers to initially use for the field.\n    :param header_formatter:\n        An optional callable that is used to encode and format the headers. By\n        default, this is :func:`format_header_param_html5`.\n    \"\"\"\n\n    def __init__(\n        self,\n        name,\n        data,\n        filename=None,\n        headers=None,\n        header_formatter=format_header_param_html5,\n    ):\n        self._name = name\n        self._filename = filename\n        self.data = data\n        self.headers = {}\n        if headers:\n            self.headers = dict(headers)\n        self.header_formatter = header_formatter\n\n    @classmethod\n    def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5):\n        \"\"\"\n        A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n        Supports constructing :class:`~urllib3.fields.RequestField` from\n        parameter of key/value strings AND key/filetuple. A filetuple is a\n        (filename, data, MIME type) tuple where the MIME type is optional.\n        For example::\n\n            'foo': 'bar',\n            'fakefile': ('foofile.txt', 'contents of foofile'),\n            'realfile': ('barfile.txt', open('realfile').read()),\n            'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n            'nonamefile': 'contents of nonamefile field',\n\n        Field names and filenames must be unicode.\n        \"\"\"\n        if isinstance(value, tuple):\n            if len(value) == 3:\n                filename, data, content_type = value\n            else:\n                filename, data = value\n                content_type = guess_content_type(filename)\n        else:\n            filename = None\n            content_type = None\n            data = value\n\n        request_param = cls(\n            fieldname, data, filename=filename, header_formatter=header_formatter\n        )\n        request_param.make_multipart(content_type=content_type)\n\n        return request_param\n\n    def _render_part(self, name, value):\n        \"\"\"\n        Overridable helper function to format a single header parameter. By\n        default, this calls ``self.header_formatter``.\n\n        :param name:\n            The name of the parameter, a string expected to be ASCII only.\n        :param value:\n            The value of the parameter, provided as a unicode string.\n        \"\"\"\n\n        return self.header_formatter(name, value)\n\n    def _render_parts(self, header_parts):\n        \"\"\"\n        Helper function to format and quote a single header.\n\n        Useful for single headers that are composed of multiple items. E.g.,\n        'Content-Disposition' fields.\n\n        :param header_parts:\n            A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n            as `k1=\"v1\"; k2=\"v2\"; ...`.\n        \"\"\"\n        parts = []\n        iterable = header_parts\n        if isinstance(header_parts, dict):\n            iterable = header_parts.items()\n\n        for name, value in iterable:\n            if value is not None:\n                parts.append(self._render_part(name, value))\n\n        return u\"; \".join(parts)\n\n    def render_headers(self):\n        \"\"\"\n        Renders the headers for this request field.\n        \"\"\"\n        lines = []\n\n        sort_keys = [\"Content-Disposition\", \"Content-Type\", \"Content-Location\"]\n        for sort_key in sort_keys:\n            if self.headers.get(sort_key, False):\n                lines.append(u\"%s: %s\" % (sort_key, self.headers[sort_key]))\n\n        for header_name, header_value in self.headers.items():\n            if header_name not in sort_keys:\n                if header_value:\n                    lines.append(u\"%s: %s\" % (header_name, header_value))\n\n        lines.append(u\"\\r\\n\")\n        return u\"\\r\\n\".join(lines)\n\n    def make_multipart(\n        self, content_disposition=None, content_type=None, content_location=None\n    ):\n        \"\"\"\n        Makes this request field into a multipart request field.\n\n        This method overrides \"Content-Disposition\", \"Content-Type\" and\n        \"Content-Location\" headers to the request parameter.\n\n        :param content_type:\n            The 'Content-Type' of the request body.\n        :param content_location:\n            The 'Content-Location' of the request body.\n\n        \"\"\"\n        self.headers[\"Content-Disposition\"] = content_disposition or u\"form-data\"\n        self.headers[\"Content-Disposition\"] += u\"; \".join(\n            [\n                u\"\",\n                self._render_parts(\n                    ((u\"name\", self._name), (u\"filename\", self._filename))\n                ),\n            ]\n        )\n        self.headers[\"Content-Type\"] = content_type\n        self.headers[\"Content-Location\"] = content_location\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/filepost.py",
    "content": "from __future__ import absolute_import\n\nimport binascii\nimport codecs\nimport os\nfrom io import BytesIO\n\nfrom .fields import RequestField\nfrom .packages import six\nfrom .packages.six import b\n\nwriter = codecs.lookup(\"utf-8\")[3]\n\n\ndef choose_boundary():\n    \"\"\"\n    Our embarrassingly-simple replacement for mimetools.choose_boundary.\n    \"\"\"\n    boundary = binascii.hexlify(os.urandom(16))\n    if not six.PY2:\n        boundary = boundary.decode(\"ascii\")\n    return boundary\n\n\ndef iter_field_objects(fields):\n    \"\"\"\n    Iterate over fields.\n\n    Supports list of (k, v) tuples and dicts, and lists of\n    :class:`~urllib3.fields.RequestField`.\n\n    \"\"\"\n    if isinstance(fields, dict):\n        i = six.iteritems(fields)\n    else:\n        i = iter(fields)\n\n    for field in i:\n        if isinstance(field, RequestField):\n            yield field\n        else:\n            yield RequestField.from_tuples(*field)\n\n\ndef iter_fields(fields):\n    \"\"\"\n    .. deprecated:: 1.6\n\n    Iterate over fields.\n\n    The addition of :class:`~urllib3.fields.RequestField` makes this function\n    obsolete. Instead, use :func:`iter_field_objects`, which returns\n    :class:`~urllib3.fields.RequestField` objects.\n\n    Supports list of (k, v) tuples and dicts.\n    \"\"\"\n    if isinstance(fields, dict):\n        return ((k, v) for k, v in six.iteritems(fields))\n\n    return ((k, v) for k, v in fields)\n\n\ndef encode_multipart_formdata(fields, boundary=None):\n    \"\"\"\n    Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n    :param fields:\n        Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n\n    :param boundary:\n        If not specified, then a random boundary will be generated using\n        :func:`urllib3.filepost.choose_boundary`.\n    \"\"\"\n    body = BytesIO()\n    if boundary is None:\n        boundary = choose_boundary()\n\n    for field in iter_field_objects(fields):\n        body.write(b(\"--%s\\r\\n\" % (boundary)))\n\n        writer(body).write(field.render_headers())\n        data = field.data\n\n        if isinstance(data, int):\n            data = str(data)  # Backwards compatibility\n\n        if isinstance(data, six.text_type):\n            writer(body).write(data)\n        else:\n            body.write(data)\n\n        body.write(b\"\\r\\n\")\n\n    body.write(b(\"--%s--\\r\\n\" % (boundary)))\n\n    content_type = str(\"multipart/form-data; boundary=%s\" % boundary)\n\n    return body.getvalue(), content_type\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/packages/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/urllib3/packages/backports/__init__.py",
    "content": ""
  },
  {
    "path": "src/pip/_vendor/urllib3/packages/backports/makefile.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nbackports.makefile\n~~~~~~~~~~~~~~~~~~\n\nBackports the Python 3 ``socket.makefile`` method for use with anything that\nwants to create a \"fake\" socket object.\n\"\"\"\nimport io\nfrom socket import SocketIO\n\n\ndef backport_makefile(\n    self, mode=\"r\", buffering=None, encoding=None, errors=None, newline=None\n):\n    \"\"\"\n    Backport of ``socket.makefile`` from Python 3.5.\n    \"\"\"\n    if not set(mode) <= {\"r\", \"w\", \"b\"}:\n        raise ValueError(\"invalid mode %r (only r, w, b allowed)\" % (mode,))\n    writing = \"w\" in mode\n    reading = \"r\" in mode or not writing\n    assert reading or writing\n    binary = \"b\" in mode\n    rawmode = \"\"\n    if reading:\n        rawmode += \"r\"\n    if writing:\n        rawmode += \"w\"\n    raw = SocketIO(self, rawmode)\n    self._makefile_refs += 1\n    if buffering is None:\n        buffering = -1\n    if buffering < 0:\n        buffering = io.DEFAULT_BUFFER_SIZE\n    if buffering == 0:\n        if not binary:\n            raise ValueError(\"unbuffered streams must be binary\")\n        return raw\n    if reading and writing:\n        buffer = io.BufferedRWPair(raw, raw, buffering)\n    elif reading:\n        buffer = io.BufferedReader(raw, buffering)\n    else:\n        assert writing\n        buffer = io.BufferedWriter(raw, buffering)\n    if binary:\n        return buffer\n    text = io.TextIOWrapper(buffer, encoding, errors, newline)\n    text.mode = mode\n    return text\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/packages/backports/weakref_finalize.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nbackports.weakref_finalize\n~~~~~~~~~~~~~~~~~~\n\nBackports the Python 3 ``weakref.finalize`` method.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport itertools\nimport sys\nfrom weakref import ref\n\n__all__ = [\"weakref_finalize\"]\n\n\nclass weakref_finalize(object):\n    \"\"\"Class for finalization of weakrefable objects\n    finalize(obj, func, *args, **kwargs) returns a callable finalizer\n    object which will be called when obj is garbage collected. The\n    first time the finalizer is called it evaluates func(*arg, **kwargs)\n    and returns the result. After this the finalizer is dead, and\n    calling it just returns None.\n    When the program exits any remaining finalizers for which the\n    atexit attribute is true will be run in reverse order of creation.\n    By default atexit is true.\n    \"\"\"\n\n    # Finalizer objects don't have any state of their own.  They are\n    # just used as keys to lookup _Info objects in the registry.  This\n    # ensures that they cannot be part of a ref-cycle.\n\n    __slots__ = ()\n    _registry = {}\n    _shutdown = False\n    _index_iter = itertools.count()\n    _dirty = False\n    _registered_with_atexit = False\n\n    class _Info(object):\n        __slots__ = (\"weakref\", \"func\", \"args\", \"kwargs\", \"atexit\", \"index\")\n\n    def __init__(self, obj, func, *args, **kwargs):\n        if not self._registered_with_atexit:\n            # We may register the exit function more than once because\n            # of a thread race, but that is harmless\n            import atexit\n\n            atexit.register(self._exitfunc)\n            weakref_finalize._registered_with_atexit = True\n        info = self._Info()\n        info.weakref = ref(obj, self)\n        info.func = func\n        info.args = args\n        info.kwargs = kwargs or None\n        info.atexit = True\n        info.index = next(self._index_iter)\n        self._registry[self] = info\n        weakref_finalize._dirty = True\n\n    def __call__(self, _=None):\n        \"\"\"If alive then mark as dead and return func(*args, **kwargs);\n        otherwise return None\"\"\"\n        info = self._registry.pop(self, None)\n        if info and not self._shutdown:\n            return info.func(*info.args, **(info.kwargs or {}))\n\n    def detach(self):\n        \"\"\"If alive then mark as dead and return (obj, func, args, kwargs);\n        otherwise return None\"\"\"\n        info = self._registry.get(self)\n        obj = info and info.weakref()\n        if obj is not None and self._registry.pop(self, None):\n            return (obj, info.func, info.args, info.kwargs or {})\n\n    def peek(self):\n        \"\"\"If alive then return (obj, func, args, kwargs);\n        otherwise return None\"\"\"\n        info = self._registry.get(self)\n        obj = info and info.weakref()\n        if obj is not None:\n            return (obj, info.func, info.args, info.kwargs or {})\n\n    @property\n    def alive(self):\n        \"\"\"Whether finalizer is alive\"\"\"\n        return self in self._registry\n\n    @property\n    def atexit(self):\n        \"\"\"Whether finalizer should be called at exit\"\"\"\n        info = self._registry.get(self)\n        return bool(info) and info.atexit\n\n    @atexit.setter\n    def atexit(self, value):\n        info = self._registry.get(self)\n        if info:\n            info.atexit = bool(value)\n\n    def __repr__(self):\n        info = self._registry.get(self)\n        obj = info and info.weakref()\n        if obj is None:\n            return \"<%s object at %#x; dead>\" % (type(self).__name__, id(self))\n        else:\n            return \"<%s object at %#x; for %r at %#x>\" % (\n                type(self).__name__,\n                id(self),\n                type(obj).__name__,\n                id(obj),\n            )\n\n    @classmethod\n    def _select_for_exit(cls):\n        # Return live finalizers marked for exit, oldest first\n        L = [(f, i) for (f, i) in cls._registry.items() if i.atexit]\n        L.sort(key=lambda item: item[1].index)\n        return [f for (f, i) in L]\n\n    @classmethod\n    def _exitfunc(cls):\n        # At shutdown invoke finalizers for which atexit is true.\n        # This is called once all other non-daemonic threads have been\n        # joined.\n        reenable_gc = False\n        try:\n            if cls._registry:\n                import gc\n\n                if gc.isenabled():\n                    reenable_gc = True\n                    gc.disable()\n                pending = None\n                while True:\n                    if pending is None or weakref_finalize._dirty:\n                        pending = cls._select_for_exit()\n                        weakref_finalize._dirty = False\n                    if not pending:\n                        break\n                    f = pending.pop()\n                    try:\n                        # gc is disabled, so (assuming no daemonic\n                        # threads) the following is the only line in\n                        # this function which might trigger creation\n                        # of a new finalizer\n                        f()\n                    except Exception:\n                        sys.excepthook(*sys.exc_info())\n                    assert f not in cls._registry\n        finally:\n            # prevent any more finalizers from executing during shutdown\n            weakref_finalize._shutdown = True\n            if reenable_gc:\n                gc.enable()\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/packages/six.py",
    "content": "# Copyright (c) 2010-2020 Benjamin Peterson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"Utilities for writing code that runs on Python 2 and 3\"\"\"\n\nfrom __future__ import absolute_import\n\nimport functools\nimport itertools\nimport operator\nimport sys\nimport types\n\n__author__ = \"Benjamin Peterson <benjamin@python.org>\"\n__version__ = \"1.16.0\"\n\n\n# Useful for very coarse version differentiation.\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n\nif PY3:\n    string_types = (str,)\n    integer_types = (int,)\n    class_types = (type,)\n    text_type = str\n    binary_type = bytes\n\n    MAXSIZE = sys.maxsize\nelse:\n    string_types = (basestring,)\n    integer_types = (int, long)\n    class_types = (type, types.ClassType)\n    text_type = unicode\n    binary_type = str\n\n    if sys.platform.startswith(\"java\"):\n        # Jython always uses 32 bits.\n        MAXSIZE = int((1 << 31) - 1)\n    else:\n        # It's possible to have sizeof(long) != sizeof(Py_ssize_t).\n        class X(object):\n            def __len__(self):\n                return 1 << 31\n\n        try:\n            len(X())\n        except OverflowError:\n            # 32-bit\n            MAXSIZE = int((1 << 31) - 1)\n        else:\n            # 64-bit\n            MAXSIZE = int((1 << 63) - 1)\n        del X\n\nif PY34:\n    from importlib.util import spec_from_loader\nelse:\n    spec_from_loader = None\n\n\ndef _add_doc(func, doc):\n    \"\"\"Add documentation to a function.\"\"\"\n    func.__doc__ = doc\n\n\ndef _import_module(name):\n    \"\"\"Import module, returning the module after the last dot.\"\"\"\n    __import__(name)\n    return sys.modules[name]\n\n\nclass _LazyDescr(object):\n    def __init__(self, name):\n        self.name = name\n\n    def __get__(self, obj, tp):\n        result = self._resolve()\n        setattr(obj, self.name, result)  # Invokes __set__.\n        try:\n            # This is a bit ugly, but it avoids running this again by\n            # removing this descriptor.\n            delattr(obj.__class__, self.name)\n        except AttributeError:\n            pass\n        return result\n\n\nclass MovedModule(_LazyDescr):\n    def __init__(self, name, old, new=None):\n        super(MovedModule, self).__init__(name)\n        if PY3:\n            if new is None:\n                new = name\n            self.mod = new\n        else:\n            self.mod = old\n\n    def _resolve(self):\n        return _import_module(self.mod)\n\n    def __getattr__(self, attr):\n        _module = self._resolve()\n        value = getattr(_module, attr)\n        setattr(self, attr, value)\n        return value\n\n\nclass _LazyModule(types.ModuleType):\n    def __init__(self, name):\n        super(_LazyModule, self).__init__(name)\n        self.__doc__ = self.__class__.__doc__\n\n    def __dir__(self):\n        attrs = [\"__doc__\", \"__name__\"]\n        attrs += [attr.name for attr in self._moved_attributes]\n        return attrs\n\n    # Subclasses should override this\n    _moved_attributes = []\n\n\nclass MovedAttribute(_LazyDescr):\n    def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n        super(MovedAttribute, self).__init__(name)\n        if PY3:\n            if new_mod is None:\n                new_mod = name\n            self.mod = new_mod\n            if new_attr is None:\n                if old_attr is None:\n                    new_attr = name\n                else:\n                    new_attr = old_attr\n            self.attr = new_attr\n        else:\n            self.mod = old_mod\n            if old_attr is None:\n                old_attr = name\n            self.attr = old_attr\n\n    def _resolve(self):\n        module = _import_module(self.mod)\n        return getattr(module, self.attr)\n\n\nclass _SixMetaPathImporter(object):\n\n    \"\"\"\n    A meta path importer to import six.moves and its submodules.\n\n    This class implements a PEP302 finder and loader. It should be compatible\n    with Python 2.5 and all existing versions of Python3\n    \"\"\"\n\n    def __init__(self, six_module_name):\n        self.name = six_module_name\n        self.known_modules = {}\n\n    def _add_module(self, mod, *fullnames):\n        for fullname in fullnames:\n            self.known_modules[self.name + \".\" + fullname] = mod\n\n    def _get_module(self, fullname):\n        return self.known_modules[self.name + \".\" + fullname]\n\n    def find_module(self, fullname, path=None):\n        if fullname in self.known_modules:\n            return self\n        return None\n\n    def find_spec(self, fullname, path, target=None):\n        if fullname in self.known_modules:\n            return spec_from_loader(fullname, self)\n        return None\n\n    def __get_module(self, fullname):\n        try:\n            return self.known_modules[fullname]\n        except KeyError:\n            raise ImportError(\"This loader does not know module \" + fullname)\n\n    def load_module(self, fullname):\n        try:\n            # in case of a reload\n            return sys.modules[fullname]\n        except KeyError:\n            pass\n        mod = self.__get_module(fullname)\n        if isinstance(mod, MovedModule):\n            mod = mod._resolve()\n        else:\n            mod.__loader__ = self\n        sys.modules[fullname] = mod\n        return mod\n\n    def is_package(self, fullname):\n        \"\"\"\n        Return true, if the named module is a package.\n\n        We need this method to get correct spec objects with\n        Python 3.4 (see PEP451)\n        \"\"\"\n        return hasattr(self.__get_module(fullname), \"__path__\")\n\n    def get_code(self, fullname):\n        \"\"\"Return None\n\n        Required, if is_package is implemented\"\"\"\n        self.__get_module(fullname)  # eventually raises ImportError\n        return None\n\n    get_source = get_code  # same as get_code\n\n    def create_module(self, spec):\n        return self.load_module(spec.name)\n\n    def exec_module(self, module):\n        pass\n\n\n_importer = _SixMetaPathImporter(__name__)\n\n\nclass _MovedItems(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects\"\"\"\n\n    __path__ = []  # mark as package\n\n\n_moved_attributes = [\n    MovedAttribute(\"cStringIO\", \"cStringIO\", \"io\", \"StringIO\"),\n    MovedAttribute(\"filter\", \"itertools\", \"builtins\", \"ifilter\", \"filter\"),\n    MovedAttribute(\n        \"filterfalse\", \"itertools\", \"itertools\", \"ifilterfalse\", \"filterfalse\"\n    ),\n    MovedAttribute(\"input\", \"__builtin__\", \"builtins\", \"raw_input\", \"input\"),\n    MovedAttribute(\"intern\", \"__builtin__\", \"sys\"),\n    MovedAttribute(\"map\", \"itertools\", \"builtins\", \"imap\", \"map\"),\n    MovedAttribute(\"getcwd\", \"os\", \"os\", \"getcwdu\", \"getcwd\"),\n    MovedAttribute(\"getcwdb\", \"os\", \"os\", \"getcwd\", \"getcwdb\"),\n    MovedAttribute(\"getoutput\", \"commands\", \"subprocess\"),\n    MovedAttribute(\"range\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\n        \"reload_module\", \"__builtin__\", \"importlib\" if PY34 else \"imp\", \"reload\"\n    ),\n    MovedAttribute(\"reduce\", \"__builtin__\", \"functools\"),\n    MovedAttribute(\"shlex_quote\", \"pipes\", \"shlex\", \"quote\"),\n    MovedAttribute(\"StringIO\", \"StringIO\", \"io\"),\n    MovedAttribute(\"UserDict\", \"UserDict\", \"collections\"),\n    MovedAttribute(\"UserList\", \"UserList\", \"collections\"),\n    MovedAttribute(\"UserString\", \"UserString\", \"collections\"),\n    MovedAttribute(\"xrange\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\"zip\", \"itertools\", \"builtins\", \"izip\", \"zip\"),\n    MovedAttribute(\n        \"zip_longest\", \"itertools\", \"itertools\", \"izip_longest\", \"zip_longest\"\n    ),\n    MovedModule(\"builtins\", \"__builtin__\"),\n    MovedModule(\"configparser\", \"ConfigParser\"),\n    MovedModule(\n        \"collections_abc\",\n        \"collections\",\n        \"collections.abc\" if sys.version_info >= (3, 3) else \"collections\",\n    ),\n    MovedModule(\"copyreg\", \"copy_reg\"),\n    MovedModule(\"dbm_gnu\", \"gdbm\", \"dbm.gnu\"),\n    MovedModule(\"dbm_ndbm\", \"dbm\", \"dbm.ndbm\"),\n    MovedModule(\n        \"_dummy_thread\",\n        \"dummy_thread\",\n        \"_dummy_thread\" if sys.version_info < (3, 9) else \"_thread\",\n    ),\n    MovedModule(\"http_cookiejar\", \"cookielib\", \"http.cookiejar\"),\n    MovedModule(\"http_cookies\", \"Cookie\", \"http.cookies\"),\n    MovedModule(\"html_entities\", \"htmlentitydefs\", \"html.entities\"),\n    MovedModule(\"html_parser\", \"HTMLParser\", \"html.parser\"),\n    MovedModule(\"http_client\", \"httplib\", \"http.client\"),\n    MovedModule(\"email_mime_base\", \"email.MIMEBase\", \"email.mime.base\"),\n    MovedModule(\"email_mime_image\", \"email.MIMEImage\", \"email.mime.image\"),\n    MovedModule(\"email_mime_multipart\", \"email.MIMEMultipart\", \"email.mime.multipart\"),\n    MovedModule(\n        \"email_mime_nonmultipart\", \"email.MIMENonMultipart\", \"email.mime.nonmultipart\"\n    ),\n    MovedModule(\"email_mime_text\", \"email.MIMEText\", \"email.mime.text\"),\n    MovedModule(\"BaseHTTPServer\", \"BaseHTTPServer\", \"http.server\"),\n    MovedModule(\"CGIHTTPServer\", \"CGIHTTPServer\", \"http.server\"),\n    MovedModule(\"SimpleHTTPServer\", \"SimpleHTTPServer\", \"http.server\"),\n    MovedModule(\"cPickle\", \"cPickle\", \"pickle\"),\n    MovedModule(\"queue\", \"Queue\"),\n    MovedModule(\"reprlib\", \"repr\"),\n    MovedModule(\"socketserver\", \"SocketServer\"),\n    MovedModule(\"_thread\", \"thread\", \"_thread\"),\n    MovedModule(\"tkinter\", \"Tkinter\"),\n    MovedModule(\"tkinter_dialog\", \"Dialog\", \"tkinter.dialog\"),\n    MovedModule(\"tkinter_filedialog\", \"FileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_scrolledtext\", \"ScrolledText\", \"tkinter.scrolledtext\"),\n    MovedModule(\"tkinter_simpledialog\", \"SimpleDialog\", \"tkinter.simpledialog\"),\n    MovedModule(\"tkinter_tix\", \"Tix\", \"tkinter.tix\"),\n    MovedModule(\"tkinter_ttk\", \"ttk\", \"tkinter.ttk\"),\n    MovedModule(\"tkinter_constants\", \"Tkconstants\", \"tkinter.constants\"),\n    MovedModule(\"tkinter_dnd\", \"Tkdnd\", \"tkinter.dnd\"),\n    MovedModule(\"tkinter_colorchooser\", \"tkColorChooser\", \"tkinter.colorchooser\"),\n    MovedModule(\"tkinter_commondialog\", \"tkCommonDialog\", \"tkinter.commondialog\"),\n    MovedModule(\"tkinter_tkfiledialog\", \"tkFileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_font\", \"tkFont\", \"tkinter.font\"),\n    MovedModule(\"tkinter_messagebox\", \"tkMessageBox\", \"tkinter.messagebox\"),\n    MovedModule(\"tkinter_tksimpledialog\", \"tkSimpleDialog\", \"tkinter.simpledialog\"),\n    MovedModule(\"urllib_parse\", __name__ + \".moves.urllib_parse\", \"urllib.parse\"),\n    MovedModule(\"urllib_error\", __name__ + \".moves.urllib_error\", \"urllib.error\"),\n    MovedModule(\"urllib\", __name__ + \".moves.urllib\", __name__ + \".moves.urllib\"),\n    MovedModule(\"urllib_robotparser\", \"robotparser\", \"urllib.robotparser\"),\n    MovedModule(\"xmlrpc_client\", \"xmlrpclib\", \"xmlrpc.client\"),\n    MovedModule(\"xmlrpc_server\", \"SimpleXMLRPCServer\", \"xmlrpc.server\"),\n]\n# Add windows specific modules.\nif sys.platform == \"win32\":\n    _moved_attributes += [\n        MovedModule(\"winreg\", \"_winreg\"),\n    ]\n\nfor attr in _moved_attributes:\n    setattr(_MovedItems, attr.name, attr)\n    if isinstance(attr, MovedModule):\n        _importer._add_module(attr, \"moves.\" + attr.name)\ndel attr\n\n_MovedItems._moved_attributes = _moved_attributes\n\nmoves = _MovedItems(__name__ + \".moves\")\n_importer._add_module(moves, \"moves\")\n\n\nclass Module_six_moves_urllib_parse(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_parse\"\"\"\n\n\n_urllib_parse_moved_attributes = [\n    MovedAttribute(\"ParseResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"SplitResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qs\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qsl\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urldefrag\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urljoin\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"quote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"quote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\n        \"unquote_to_bytes\", \"urllib\", \"urllib.parse\", \"unquote\", \"unquote_to_bytes\"\n    ),\n    MovedAttribute(\"urlencode\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitquery\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splittag\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splituser\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitvalue\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"uses_fragment\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_netloc\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_params\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_query\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_relative\", \"urlparse\", \"urllib.parse\"),\n]\nfor attr in _urllib_parse_moved_attributes:\n    setattr(Module_six_moves_urllib_parse, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_parse(__name__ + \".moves.urllib_parse\"),\n    \"moves.urllib_parse\",\n    \"moves.urllib.parse\",\n)\n\n\nclass Module_six_moves_urllib_error(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_error\"\"\"\n\n\n_urllib_error_moved_attributes = [\n    MovedAttribute(\"URLError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"HTTPError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"ContentTooShortError\", \"urllib\", \"urllib.error\"),\n]\nfor attr in _urllib_error_moved_attributes:\n    setattr(Module_six_moves_urllib_error, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_error(__name__ + \".moves.urllib.error\"),\n    \"moves.urllib_error\",\n    \"moves.urllib.error\",\n)\n\n\nclass Module_six_moves_urllib_request(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_request\"\"\"\n\n\n_urllib_request_moved_attributes = [\n    MovedAttribute(\"urlopen\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"install_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"build_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"pathname2url\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"url2pathname\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"getproxies\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"Request\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"OpenerDirector\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDefaultErrorHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPRedirectHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPCookieProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"BaseHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgr\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgrWithDefaultRealm\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPSHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FileHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"CacheFTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"UnknownHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPErrorProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"urlretrieve\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"urlcleanup\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"URLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"FancyURLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"proxy_bypass\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"parse_http_list\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"parse_keqv_list\", \"urllib2\", \"urllib.request\"),\n]\nfor attr in _urllib_request_moved_attributes:\n    setattr(Module_six_moves_urllib_request, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_request(__name__ + \".moves.urllib.request\"),\n    \"moves.urllib_request\",\n    \"moves.urllib.request\",\n)\n\n\nclass Module_six_moves_urllib_response(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_response\"\"\"\n\n\n_urllib_response_moved_attributes = [\n    MovedAttribute(\"addbase\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addclosehook\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfo\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfourl\", \"urllib\", \"urllib.response\"),\n]\nfor attr in _urllib_response_moved_attributes:\n    setattr(Module_six_moves_urllib_response, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_response(__name__ + \".moves.urllib.response\"),\n    \"moves.urllib_response\",\n    \"moves.urllib.response\",\n)\n\n\nclass Module_six_moves_urllib_robotparser(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_robotparser\"\"\"\n\n\n_urllib_robotparser_moved_attributes = [\n    MovedAttribute(\"RobotFileParser\", \"robotparser\", \"urllib.robotparser\"),\n]\nfor attr in _urllib_robotparser_moved_attributes:\n    setattr(Module_six_moves_urllib_robotparser, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_robotparser._moved_attributes = (\n    _urllib_robotparser_moved_attributes\n)\n\n_importer._add_module(\n    Module_six_moves_urllib_robotparser(__name__ + \".moves.urllib.robotparser\"),\n    \"moves.urllib_robotparser\",\n    \"moves.urllib.robotparser\",\n)\n\n\nclass Module_six_moves_urllib(types.ModuleType):\n\n    \"\"\"Create a six.moves.urllib namespace that resembles the Python 3 namespace\"\"\"\n\n    __path__ = []  # mark as package\n    parse = _importer._get_module(\"moves.urllib_parse\")\n    error = _importer._get_module(\"moves.urllib_error\")\n    request = _importer._get_module(\"moves.urllib_request\")\n    response = _importer._get_module(\"moves.urllib_response\")\n    robotparser = _importer._get_module(\"moves.urllib_robotparser\")\n\n    def __dir__(self):\n        return [\"parse\", \"error\", \"request\", \"response\", \"robotparser\"]\n\n\n_importer._add_module(\n    Module_six_moves_urllib(__name__ + \".moves.urllib\"), \"moves.urllib\"\n)\n\n\ndef add_move(move):\n    \"\"\"Add an item to six.moves.\"\"\"\n    setattr(_MovedItems, move.name, move)\n\n\ndef remove_move(name):\n    \"\"\"Remove item from six.moves.\"\"\"\n    try:\n        delattr(_MovedItems, name)\n    except AttributeError:\n        try:\n            del moves.__dict__[name]\n        except KeyError:\n            raise AttributeError(\"no such move, %r\" % (name,))\n\n\nif PY3:\n    _meth_func = \"__func__\"\n    _meth_self = \"__self__\"\n\n    _func_closure = \"__closure__\"\n    _func_code = \"__code__\"\n    _func_defaults = \"__defaults__\"\n    _func_globals = \"__globals__\"\nelse:\n    _meth_func = \"im_func\"\n    _meth_self = \"im_self\"\n\n    _func_closure = \"func_closure\"\n    _func_code = \"func_code\"\n    _func_defaults = \"func_defaults\"\n    _func_globals = \"func_globals\"\n\n\ntry:\n    advance_iterator = next\nexcept NameError:\n\n    def advance_iterator(it):\n        return it.next()\n\n\nnext = advance_iterator\n\n\ntry:\n    callable = callable\nexcept NameError:\n\n    def callable(obj):\n        return any(\"__call__\" in klass.__dict__ for klass in type(obj).__mro__)\n\n\nif PY3:\n\n    def get_unbound_function(unbound):\n        return unbound\n\n    create_bound_method = types.MethodType\n\n    def create_unbound_method(func, cls):\n        return func\n\n    Iterator = object\nelse:\n\n    def get_unbound_function(unbound):\n        return unbound.im_func\n\n    def create_bound_method(func, obj):\n        return types.MethodType(func, obj, obj.__class__)\n\n    def create_unbound_method(func, cls):\n        return types.MethodType(func, None, cls)\n\n    class Iterator(object):\n        def next(self):\n            return type(self).__next__(self)\n\n    callable = callable\n_add_doc(\n    get_unbound_function, \"\"\"Get the function out of a possibly unbound function\"\"\"\n)\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)\nget_function_defaults = operator.attrgetter(_func_defaults)\nget_function_globals = operator.attrgetter(_func_globals)\n\n\nif PY3:\n\n    def iterkeys(d, **kw):\n        return iter(d.keys(**kw))\n\n    def itervalues(d, **kw):\n        return iter(d.values(**kw))\n\n    def iteritems(d, **kw):\n        return iter(d.items(**kw))\n\n    def iterlists(d, **kw):\n        return iter(d.lists(**kw))\n\n    viewkeys = operator.methodcaller(\"keys\")\n\n    viewvalues = operator.methodcaller(\"values\")\n\n    viewitems = operator.methodcaller(\"items\")\nelse:\n\n    def iterkeys(d, **kw):\n        return d.iterkeys(**kw)\n\n    def itervalues(d, **kw):\n        return d.itervalues(**kw)\n\n    def iteritems(d, **kw):\n        return d.iteritems(**kw)\n\n    def iterlists(d, **kw):\n        return d.iterlists(**kw)\n\n    viewkeys = operator.methodcaller(\"viewkeys\")\n\n    viewvalues = operator.methodcaller(\"viewvalues\")\n\n    viewitems = operator.methodcaller(\"viewitems\")\n\n_add_doc(iterkeys, \"Return an iterator over the keys of a dictionary.\")\n_add_doc(itervalues, \"Return an iterator over the values of a dictionary.\")\n_add_doc(iteritems, \"Return an iterator over the (key, value) pairs of a dictionary.\")\n_add_doc(\n    iterlists, \"Return an iterator over the (key, [values]) pairs of a dictionary.\"\n)\n\n\nif PY3:\n\n    def b(s):\n        return s.encode(\"latin-1\")\n\n    def u(s):\n        return s\n\n    unichr = chr\n    import struct\n\n    int2byte = struct.Struct(\">B\").pack\n    del struct\n    byte2int = operator.itemgetter(0)\n    indexbytes = operator.getitem\n    iterbytes = iter\n    import io\n\n    StringIO = io.StringIO\n    BytesIO = io.BytesIO\n    del io\n    _assertCountEqual = \"assertCountEqual\"\n    if sys.version_info[1] <= 1:\n        _assertRaisesRegex = \"assertRaisesRegexp\"\n        _assertRegex = \"assertRegexpMatches\"\n        _assertNotRegex = \"assertNotRegexpMatches\"\n    else:\n        _assertRaisesRegex = \"assertRaisesRegex\"\n        _assertRegex = \"assertRegex\"\n        _assertNotRegex = \"assertNotRegex\"\nelse:\n\n    def b(s):\n        return s\n\n    # Workaround for standalone backslash\n\n    def u(s):\n        return unicode(s.replace(r\"\\\\\", r\"\\\\\\\\\"), \"unicode_escape\")\n\n    unichr = unichr\n    int2byte = chr\n\n    def byte2int(bs):\n        return ord(bs[0])\n\n    def indexbytes(buf, i):\n        return ord(buf[i])\n\n    iterbytes = functools.partial(itertools.imap, ord)\n    import StringIO\n\n    StringIO = BytesIO = StringIO.StringIO\n    _assertCountEqual = \"assertItemsEqual\"\n    _assertRaisesRegex = \"assertRaisesRegexp\"\n    _assertRegex = \"assertRegexpMatches\"\n    _assertNotRegex = \"assertNotRegexpMatches\"\n_add_doc(b, \"\"\"Byte literal\"\"\")\n_add_doc(u, \"\"\"Text literal\"\"\")\n\n\ndef assertCountEqual(self, *args, **kwargs):\n    return getattr(self, _assertCountEqual)(*args, **kwargs)\n\n\ndef assertRaisesRegex(self, *args, **kwargs):\n    return getattr(self, _assertRaisesRegex)(*args, **kwargs)\n\n\ndef assertRegex(self, *args, **kwargs):\n    return getattr(self, _assertRegex)(*args, **kwargs)\n\n\ndef assertNotRegex(self, *args, **kwargs):\n    return getattr(self, _assertNotRegex)(*args, **kwargs)\n\n\nif PY3:\n    exec_ = getattr(moves.builtins, \"exec\")\n\n    def reraise(tp, value, tb=None):\n        try:\n            if value is None:\n                value = tp()\n            if value.__traceback__ is not tb:\n                raise value.with_traceback(tb)\n            raise value\n        finally:\n            value = None\n            tb = None\n\nelse:\n\n    def exec_(_code_, _globs_=None, _locs_=None):\n        \"\"\"Execute code in a namespace.\"\"\"\n        if _globs_ is None:\n            frame = sys._getframe(1)\n            _globs_ = frame.f_globals\n            if _locs_ is None:\n                _locs_ = frame.f_locals\n            del frame\n        elif _locs_ is None:\n            _locs_ = _globs_\n        exec (\"\"\"exec _code_ in _globs_, _locs_\"\"\")\n\n    exec_(\n        \"\"\"def reraise(tp, value, tb=None):\n    try:\n        raise tp, value, tb\n    finally:\n        tb = None\n\"\"\"\n    )\n\n\nif sys.version_info[:2] > (3,):\n    exec_(\n        \"\"\"def raise_from(value, from_value):\n    try:\n        raise value from from_value\n    finally:\n        value = None\n\"\"\"\n    )\nelse:\n\n    def raise_from(value, from_value):\n        raise value\n\n\nprint_ = getattr(moves.builtins, \"print\", None)\nif print_ is None:\n\n    def print_(*args, **kwargs):\n        \"\"\"The new-style print function for Python 2.4 and 2.5.\"\"\"\n        fp = kwargs.pop(\"file\", sys.stdout)\n        if fp is None:\n            return\n\n        def write(data):\n            if not isinstance(data, basestring):\n                data = str(data)\n            # If the file has an encoding, encode unicode with it.\n            if (\n                isinstance(fp, file)\n                and isinstance(data, unicode)\n                and fp.encoding is not None\n            ):\n                errors = getattr(fp, \"errors\", None)\n                if errors is None:\n                    errors = \"strict\"\n                data = data.encode(fp.encoding, errors)\n            fp.write(data)\n\n        want_unicode = False\n        sep = kwargs.pop(\"sep\", None)\n        if sep is not None:\n            if isinstance(sep, unicode):\n                want_unicode = True\n            elif not isinstance(sep, str):\n                raise TypeError(\"sep must be None or a string\")\n        end = kwargs.pop(\"end\", None)\n        if end is not None:\n            if isinstance(end, unicode):\n                want_unicode = True\n            elif not isinstance(end, str):\n                raise TypeError(\"end must be None or a string\")\n        if kwargs:\n            raise TypeError(\"invalid keyword arguments to print()\")\n        if not want_unicode:\n            for arg in args:\n                if isinstance(arg, unicode):\n                    want_unicode = True\n                    break\n        if want_unicode:\n            newline = unicode(\"\\n\")\n            space = unicode(\" \")\n        else:\n            newline = \"\\n\"\n            space = \" \"\n        if sep is None:\n            sep = space\n        if end is None:\n            end = newline\n        for i, arg in enumerate(args):\n            if i:\n                write(sep)\n            write(arg)\n        write(end)\n\n\nif sys.version_info[:2] < (3, 3):\n    _print = print_\n\n    def print_(*args, **kwargs):\n        fp = kwargs.get(\"file\", sys.stdout)\n        flush = kwargs.pop(\"flush\", False)\n        _print(*args, **kwargs)\n        if flush and fp is not None:\n            fp.flush()\n\n\n_add_doc(reraise, \"\"\"Reraise an exception.\"\"\")\n\nif sys.version_info[0:2] < (3, 4):\n    # This does exactly the same what the :func:`py3:functools.update_wrapper`\n    # function does on Python versions after 3.2. It sets the ``__wrapped__``\n    # attribute on ``wrapper`` object and it doesn't raise an error if any of\n    # the attributes mentioned in ``assigned`` and ``updated`` are missing on\n    # ``wrapped`` object.\n    def _update_wrapper(\n        wrapper,\n        wrapped,\n        assigned=functools.WRAPPER_ASSIGNMENTS,\n        updated=functools.WRAPPER_UPDATES,\n    ):\n        for attr in assigned:\n            try:\n                value = getattr(wrapped, attr)\n            except AttributeError:\n                continue\n            else:\n                setattr(wrapper, attr, value)\n        for attr in updated:\n            getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n        wrapper.__wrapped__ = wrapped\n        return wrapper\n\n    _update_wrapper.__doc__ = functools.update_wrapper.__doc__\n\n    def wraps(\n        wrapped,\n        assigned=functools.WRAPPER_ASSIGNMENTS,\n        updated=functools.WRAPPER_UPDATES,\n    ):\n        return functools.partial(\n            _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated\n        )\n\n    wraps.__doc__ = functools.wraps.__doc__\n\nelse:\n    wraps = functools.wraps\n\n\ndef with_metaclass(meta, *bases):\n    \"\"\"Create a base class with a metaclass.\"\"\"\n    # This requires a bit of explanation: the basic idea is to make a dummy\n    # metaclass for one level of class instantiation that replaces itself with\n    # the actual metaclass.\n    class metaclass(type):\n        def __new__(cls, name, this_bases, d):\n            if sys.version_info[:2] >= (3, 7):\n                # This version introduced PEP 560 that requires a bit\n                # of extra care (we mimic what is done by __build_class__).\n                resolved_bases = types.resolve_bases(bases)\n                if resolved_bases is not bases:\n                    d[\"__orig_bases__\"] = bases\n            else:\n                resolved_bases = bases\n            return meta(name, resolved_bases, d)\n\n        @classmethod\n        def __prepare__(cls, name, this_bases):\n            return meta.__prepare__(name, bases)\n\n    return type.__new__(metaclass, \"temporary_class\", (), {})\n\n\ndef add_metaclass(metaclass):\n    \"\"\"Class decorator for creating a class with a metaclass.\"\"\"\n\n    def wrapper(cls):\n        orig_vars = cls.__dict__.copy()\n        slots = orig_vars.get(\"__slots__\")\n        if slots is not None:\n            if isinstance(slots, str):\n                slots = [slots]\n            for slots_var in slots:\n                orig_vars.pop(slots_var)\n        orig_vars.pop(\"__dict__\", None)\n        orig_vars.pop(\"__weakref__\", None)\n        if hasattr(cls, \"__qualname__\"):\n            orig_vars[\"__qualname__\"] = cls.__qualname__\n        return metaclass(cls.__name__, cls.__bases__, orig_vars)\n\n    return wrapper\n\n\ndef ensure_binary(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce **s** to six.binary_type.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> encoded to `bytes`\n      - `bytes` -> `bytes`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s\n    if isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef ensure_str(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce *s* to `str`.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    # Optimization: Fast return for the common case.\n    if type(s) is str:\n        return s\n    if PY2 and isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    elif PY3 and isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif not isinstance(s, (text_type, binary_type)):\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n    return s\n\n\ndef ensure_text(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce *s* to six.text_type.\n\n    For Python 2:\n      - `unicode` -> `unicode`\n      - `str` -> `unicode`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif isinstance(s, text_type):\n        return s\n    else:\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef python_2_unicode_compatible(klass):\n    \"\"\"\n    A class decorator that defines __unicode__ and __str__ methods under Python 2.\n    Under Python 3 it does nothing.\n\n    To support Python 2 and 3 with a single code base, define a __str__ method\n    returning text and apply this decorator to the class.\n    \"\"\"\n    if PY2:\n        if \"__str__\" not in klass.__dict__:\n            raise ValueError(\n                \"@python_2_unicode_compatible cannot be applied \"\n                \"to %s because it doesn't define __str__().\" % klass.__name__\n            )\n        klass.__unicode__ = klass.__str__\n        klass.__str__ = lambda self: self.__unicode__().encode(\"utf-8\")\n    return klass\n\n\n# Complete the moves implementation.\n# This code is at the end of this module to speed up module loading.\n# Turn this module into a package.\n__path__ = []  # required for PEP 302 and PEP 451\n__package__ = __name__  # see PEP 366 @ReservedAssignment\nif globals().get(\"__spec__\") is not None:\n    __spec__.submodule_search_locations = []  # PEP 451 @UndefinedVariable\n# Remove other six meta path importers, since they cause problems. This can\n# happen if six is removed from sys.modules and then reloaded. (Setuptools does\n# this for some reason.)\nif sys.meta_path:\n    for i, importer in enumerate(sys.meta_path):\n        # Here's some real nastiness: Another \"instance\" of the six module might\n        # be floating around. Therefore, we can't use isinstance() to check for\n        # the six meta path importer, since the other six instance will have\n        # inserted an importer with different class.\n        if (\n            type(importer).__name__ == \"_SixMetaPathImporter\"\n            and importer.name == __name__\n        ):\n            del sys.meta_path[i]\n            break\n    del i, importer\n# Finally, add the importer to the meta path import hook.\nsys.meta_path.append(_importer)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/poolmanager.py",
    "content": "from __future__ import absolute_import\n\nimport collections\nimport functools\nimport logging\n\nfrom ._collections import HTTPHeaderDict, RecentlyUsedContainer\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme\nfrom .exceptions import (\n    LocationValueError,\n    MaxRetryError,\n    ProxySchemeUnknown,\n    ProxySchemeUnsupported,\n    URLSchemeUnknown,\n)\nfrom .packages import six\nfrom .packages.six.moves.urllib.parse import urljoin\nfrom .request import RequestMethods\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.retry import Retry\nfrom .util.url import parse_url\n\n__all__ = [\"PoolManager\", \"ProxyManager\", \"proxy_from_url\"]\n\n\nlog = logging.getLogger(__name__)\n\nSSL_KEYWORDS = (\n    \"key_file\",\n    \"cert_file\",\n    \"cert_reqs\",\n    \"ca_certs\",\n    \"ssl_version\",\n    \"ca_cert_dir\",\n    \"ssl_context\",\n    \"key_password\",\n    \"server_hostname\",\n)\n\n# All known keyword arguments that could be provided to the pool manager, its\n# pools, or the underlying connections. This is used to construct a pool key.\n_key_fields = (\n    \"key_scheme\",  # str\n    \"key_host\",  # str\n    \"key_port\",  # int\n    \"key_timeout\",  # int or float or Timeout\n    \"key_retries\",  # int or Retry\n    \"key_strict\",  # bool\n    \"key_block\",  # bool\n    \"key_source_address\",  # str\n    \"key_key_file\",  # str\n    \"key_key_password\",  # str\n    \"key_cert_file\",  # str\n    \"key_cert_reqs\",  # str\n    \"key_ca_certs\",  # str\n    \"key_ssl_version\",  # str\n    \"key_ca_cert_dir\",  # str\n    \"key_ssl_context\",  # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext\n    \"key_maxsize\",  # int\n    \"key_headers\",  # dict\n    \"key__proxy\",  # parsed proxy url\n    \"key__proxy_headers\",  # dict\n    \"key__proxy_config\",  # class\n    \"key_socket_options\",  # list of (level (int), optname (int), value (int or str)) tuples\n    \"key__socks_options\",  # dict\n    \"key_assert_hostname\",  # bool or string\n    \"key_assert_fingerprint\",  # str\n    \"key_server_hostname\",  # str\n)\n\n#: The namedtuple class used to construct keys for the connection pool.\n#: All custom key schemes should include the fields in this key at a minimum.\nPoolKey = collections.namedtuple(\"PoolKey\", _key_fields)\n\n_proxy_config_fields = (\"ssl_context\", \"use_forwarding_for_https\")\nProxyConfig = collections.namedtuple(\"ProxyConfig\", _proxy_config_fields)\n\n\ndef _default_key_normalizer(key_class, request_context):\n    \"\"\"\n    Create a pool key out of a request context dictionary.\n\n    According to RFC 3986, both the scheme and host are case-insensitive.\n    Therefore, this function normalizes both before constructing the pool\n    key for an HTTPS request. If you wish to change this behaviour, provide\n    alternate callables to ``key_fn_by_scheme``.\n\n    :param key_class:\n        The class to use when constructing the key. This should be a namedtuple\n        with the ``scheme`` and ``host`` keys at a minimum.\n    :type  key_class: namedtuple\n    :param request_context:\n        A dictionary-like object that contain the context for a request.\n    :type  request_context: dict\n\n    :return: A namedtuple that can be used as a connection pool key.\n    :rtype:  PoolKey\n    \"\"\"\n    # Since we mutate the dictionary, make a copy first\n    context = request_context.copy()\n    context[\"scheme\"] = context[\"scheme\"].lower()\n    context[\"host\"] = context[\"host\"].lower()\n\n    # These are both dictionaries and need to be transformed into frozensets\n    for key in (\"headers\", \"_proxy_headers\", \"_socks_options\"):\n        if key in context and context[key] is not None:\n            context[key] = frozenset(context[key].items())\n\n    # The socket_options key may be a list and needs to be transformed into a\n    # tuple.\n    socket_opts = context.get(\"socket_options\")\n    if socket_opts is not None:\n        context[\"socket_options\"] = tuple(socket_opts)\n\n    # Map the kwargs to the names in the namedtuple - this is necessary since\n    # namedtuples can't have fields starting with '_'.\n    for key in list(context.keys()):\n        context[\"key_\" + key] = context.pop(key)\n\n    # Default to ``None`` for keys missing from the context\n    for field in key_class._fields:\n        if field not in context:\n            context[field] = None\n\n    return key_class(**context)\n\n\n#: A dictionary that maps a scheme to a callable that creates a pool key.\n#: This can be used to alter the way pool keys are constructed, if desired.\n#: Each PoolManager makes a copy of this dictionary so they can be configured\n#: globally here, or individually on the instance.\nkey_fn_by_scheme = {\n    \"http\": functools.partial(_default_key_normalizer, PoolKey),\n    \"https\": functools.partial(_default_key_normalizer, PoolKey),\n}\n\npool_classes_by_scheme = {\"http\": HTTPConnectionPool, \"https\": HTTPSConnectionPool}\n\n\nclass PoolManager(RequestMethods):\n    \"\"\"\n    Allows for arbitrary requests while transparently keeping track of\n    necessary connection pools for you.\n\n    :param num_pools:\n        Number of connection pools to cache before discarding the least\n        recently used pool.\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n\n    :param \\\\**connection_pool_kw:\n        Additional parameters are used to create fresh\n        :class:`urllib3.connectionpool.ConnectionPool` instances.\n\n    Example::\n\n        >>> manager = PoolManager(num_pools=2)\n        >>> r = manager.request('GET', 'http://google.com/')\n        >>> r = manager.request('GET', 'http://google.com/mail')\n        >>> r = manager.request('GET', 'http://yahoo.com/')\n        >>> len(manager.pools)\n        2\n\n    \"\"\"\n\n    proxy = None\n    proxy_config = None\n\n    def __init__(self, num_pools=10, headers=None, **connection_pool_kw):\n        RequestMethods.__init__(self, headers)\n        self.connection_pool_kw = connection_pool_kw\n        self.pools = RecentlyUsedContainer(num_pools)\n\n        # Locally set the pool classes and keys so other PoolManagers can\n        # override them.\n        self.pool_classes_by_scheme = pool_classes_by_scheme\n        self.key_fn_by_scheme = key_fn_by_scheme.copy()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.clear()\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def _new_pool(self, scheme, host, port, request_context=None):\n        \"\"\"\n        Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and\n        any additional pool keyword arguments.\n\n        If ``request_context`` is provided, it is provided as keyword arguments\n        to the pool class used. This method is used to actually create the\n        connection pools handed out by :meth:`connection_from_url` and\n        companion methods. It is intended to be overridden for customization.\n        \"\"\"\n        pool_cls = self.pool_classes_by_scheme[scheme]\n        if request_context is None:\n            request_context = self.connection_pool_kw.copy()\n\n        # Although the context has everything necessary to create the pool,\n        # this function has historically only used the scheme, host, and port\n        # in the positional args. When an API change is acceptable these can\n        # be removed.\n        for key in (\"scheme\", \"host\", \"port\"):\n            request_context.pop(key, None)\n\n        if scheme == \"http\":\n            for kw in SSL_KEYWORDS:\n                request_context.pop(kw, None)\n\n        return pool_cls(host, port, **request_context)\n\n    def clear(self):\n        \"\"\"\n        Empty our store of pools and direct them all to close.\n\n        This will not affect in-flight connections, but they will not be\n        re-used after completion.\n        \"\"\"\n        self.pools.clear()\n\n    def connection_from_host(self, host, port=None, scheme=\"http\", pool_kwargs=None):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.\n\n        If ``port`` isn't given, it will be derived from the ``scheme`` using\n        ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is\n        provided, it is merged with the instance's ``connection_pool_kw``\n        variable and used to create the new connection pool, if one is\n        needed.\n        \"\"\"\n\n        if not host:\n            raise LocationValueError(\"No host specified.\")\n\n        request_context = self._merge_pool_kwargs(pool_kwargs)\n        request_context[\"scheme\"] = scheme or \"http\"\n        if not port:\n            port = port_by_scheme.get(request_context[\"scheme\"].lower(), 80)\n        request_context[\"port\"] = port\n        request_context[\"host\"] = host\n\n        return self.connection_from_context(request_context)\n\n    def connection_from_context(self, request_context):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.\n\n        ``request_context`` must at least contain the ``scheme`` key and its\n        value must be a key in ``key_fn_by_scheme`` instance variable.\n        \"\"\"\n        scheme = request_context[\"scheme\"].lower()\n        pool_key_constructor = self.key_fn_by_scheme.get(scheme)\n        if not pool_key_constructor:\n            raise URLSchemeUnknown(scheme)\n        pool_key = pool_key_constructor(request_context)\n\n        return self.connection_from_pool_key(pool_key, request_context=request_context)\n\n    def connection_from_pool_key(self, pool_key, request_context=None):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.\n\n        ``pool_key`` should be a namedtuple that only contains immutable\n        objects. At a minimum it must have the ``scheme``, ``host``, and\n        ``port`` fields.\n        \"\"\"\n        with self.pools.lock:\n            # If the scheme, host, or port doesn't match existing open\n            # connections, open a new ConnectionPool.\n            pool = self.pools.get(pool_key)\n            if pool:\n                return pool\n\n            # Make a fresh ConnectionPool of the desired type\n            scheme = request_context[\"scheme\"]\n            host = request_context[\"host\"]\n            port = request_context[\"port\"]\n            pool = self._new_pool(scheme, host, port, request_context=request_context)\n            self.pools[pool_key] = pool\n\n        return pool\n\n    def connection_from_url(self, url, pool_kwargs=None):\n        \"\"\"\n        Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n        If ``pool_kwargs`` is not provided and a new pool needs to be\n        constructed, ``self.connection_pool_kw`` is used to initialize\n        the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n        is provided, it is used instead. Note that if a new pool does not\n        need to be created for the request, the provided ``pool_kwargs`` are\n        not used.\n        \"\"\"\n        u = parse_url(url)\n        return self.connection_from_host(\n            u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n        )\n\n    def _merge_pool_kwargs(self, override):\n        \"\"\"\n        Merge a dictionary of override values for self.connection_pool_kw.\n\n        This does not modify self.connection_pool_kw and returns a new dict.\n        Any keys in the override dictionary with a value of ``None`` are\n        removed from the merged dictionary.\n        \"\"\"\n        base_pool_kwargs = self.connection_pool_kw.copy()\n        if override:\n            for key, value in override.items():\n                if value is None:\n                    try:\n                        del base_pool_kwargs[key]\n                    except KeyError:\n                        pass\n                else:\n                    base_pool_kwargs[key] = value\n        return base_pool_kwargs\n\n    def _proxy_requires_url_absolute_form(self, parsed_url):\n        \"\"\"\n        Indicates if the proxy requires the complete destination URL in the\n        request.  Normally this is only needed when not using an HTTP CONNECT\n        tunnel.\n        \"\"\"\n        if self.proxy is None:\n            return False\n\n        return not connection_requires_http_tunnel(\n            self.proxy, self.proxy_config, parsed_url.scheme\n        )\n\n    def _validate_proxy_scheme_url_selection(self, url_scheme):\n        \"\"\"\n        Validates that were not attempting to do TLS in TLS connections on\n        Python2 or with unsupported SSL implementations.\n        \"\"\"\n        if self.proxy is None or url_scheme != \"https\":\n            return\n\n        if self.proxy.scheme != \"https\":\n            return\n\n        if six.PY2 and not self.proxy_config.use_forwarding_for_https:\n            raise ProxySchemeUnsupported(\n                \"Contacting HTTPS destinations through HTTPS proxies \"\n                \"'via CONNECT tunnels' is not supported in Python 2\"\n            )\n\n    def urlopen(self, method, url, redirect=True, **kw):\n        \"\"\"\n        Same as :meth:`urllib3.HTTPConnectionPool.urlopen`\n        with custom cross-host redirect logic and only sends the request-uri\n        portion of the ``url``.\n\n        The given ``url`` parameter must be absolute, such that an appropriate\n        :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.\n        \"\"\"\n        u = parse_url(url)\n        self._validate_proxy_scheme_url_selection(u.scheme)\n\n        conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)\n\n        kw[\"assert_same_host\"] = False\n        kw[\"redirect\"] = False\n\n        if \"headers\" not in kw:\n            kw[\"headers\"] = self.headers.copy()\n\n        if self._proxy_requires_url_absolute_form(u):\n            response = conn.urlopen(method, url, **kw)\n        else:\n            response = conn.urlopen(method, u.request_uri, **kw)\n\n        redirect_location = redirect and response.get_redirect_location()\n        if not redirect_location:\n            return response\n\n        # Support relative URLs for redirecting.\n        redirect_location = urljoin(url, redirect_location)\n\n        if response.status == 303:\n            # Change the method according to RFC 9110, Section 15.4.4.\n            method = \"GET\"\n            # And lose the body not to transfer anything sensitive.\n            kw[\"body\"] = None\n            kw[\"headers\"] = HTTPHeaderDict(kw[\"headers\"])._prepare_for_method_change()\n\n        retries = kw.get(\"retries\")\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect)\n\n        # Strip headers marked as unsafe to forward to the redirected location.\n        # Check remove_headers_on_redirect to avoid a potential network call within\n        # conn.is_same_host() which may use socket.gethostbyname() in the future.\n        if retries.remove_headers_on_redirect and not conn.is_same_host(\n            redirect_location\n        ):\n            headers = list(six.iterkeys(kw[\"headers\"]))\n            for header in headers:\n                if header.lower() in retries.remove_headers_on_redirect:\n                    kw[\"headers\"].pop(header, None)\n\n        try:\n            retries = retries.increment(method, url, response=response, _pool=conn)\n        except MaxRetryError:\n            if retries.raise_on_redirect:\n                response.drain_conn()\n                raise\n            return response\n\n        kw[\"retries\"] = retries\n        kw[\"redirect\"] = redirect\n\n        log.info(\"Redirecting %s -> %s\", url, redirect_location)\n\n        response.drain_conn()\n        return self.urlopen(method, redirect_location, **kw)\n\n\nclass ProxyManager(PoolManager):\n    \"\"\"\n    Behaves just like :class:`PoolManager`, but sends all requests through\n    the defined proxy, using the CONNECT method for HTTPS URLs.\n\n    :param proxy_url:\n        The URL of the proxy to be used.\n\n    :param proxy_headers:\n        A dictionary containing headers that will be sent to the proxy. In case\n        of HTTP they are being sent with each request, while in the\n        HTTPS/CONNECT case they are sent only once. Could be used for proxy\n        authentication.\n\n    :param proxy_ssl_context:\n        The proxy SSL context is used to establish the TLS connection to the\n        proxy when using HTTPS proxies.\n\n    :param use_forwarding_for_https:\n        (Defaults to False) If set to True will forward requests to the HTTPS\n        proxy to be made on behalf of the client instead of creating a TLS\n        tunnel via the CONNECT method. **Enabling this flag means that request\n        and response headers and content will be visible from the HTTPS proxy**\n        whereas tunneling keeps request and response headers and content\n        private.  IP address, target hostname, SNI, and port are always visible\n        to an HTTPS proxy even when this flag is disabled.\n\n    Example:\n        >>> proxy = urllib3.ProxyManager('http://localhost:3128/')\n        >>> r1 = proxy.request('GET', 'http://google.com/')\n        >>> r2 = proxy.request('GET', 'http://httpbin.org/')\n        >>> len(proxy.pools)\n        1\n        >>> r3 = proxy.request('GET', 'https://httpbin.org/')\n        >>> r4 = proxy.request('GET', 'https://twitter.com/')\n        >>> len(proxy.pools)\n        3\n\n    \"\"\"\n\n    def __init__(\n        self,\n        proxy_url,\n        num_pools=10,\n        headers=None,\n        proxy_headers=None,\n        proxy_ssl_context=None,\n        use_forwarding_for_https=False,\n        **connection_pool_kw\n    ):\n\n        if isinstance(proxy_url, HTTPConnectionPool):\n            proxy_url = \"%s://%s:%i\" % (\n                proxy_url.scheme,\n                proxy_url.host,\n                proxy_url.port,\n            )\n        proxy = parse_url(proxy_url)\n\n        if proxy.scheme not in (\"http\", \"https\"):\n            raise ProxySchemeUnknown(proxy.scheme)\n\n        if not proxy.port:\n            port = port_by_scheme.get(proxy.scheme, 80)\n            proxy = proxy._replace(port=port)\n\n        self.proxy = proxy\n        self.proxy_headers = proxy_headers or {}\n        self.proxy_ssl_context = proxy_ssl_context\n        self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https)\n\n        connection_pool_kw[\"_proxy\"] = self.proxy\n        connection_pool_kw[\"_proxy_headers\"] = self.proxy_headers\n        connection_pool_kw[\"_proxy_config\"] = self.proxy_config\n\n        super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw)\n\n    def connection_from_host(self, host, port=None, scheme=\"http\", pool_kwargs=None):\n        if scheme == \"https\":\n            return super(ProxyManager, self).connection_from_host(\n                host, port, scheme, pool_kwargs=pool_kwargs\n            )\n\n        return super(ProxyManager, self).connection_from_host(\n            self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs\n        )\n\n    def _set_proxy_headers(self, url, headers=None):\n        \"\"\"\n        Sets headers needed by proxies: specifically, the Accept and Host\n        headers. Only sets headers not provided by the user.\n        \"\"\"\n        headers_ = {\"Accept\": \"*/*\"}\n\n        netloc = parse_url(url).netloc\n        if netloc:\n            headers_[\"Host\"] = netloc\n\n        if headers:\n            headers_.update(headers)\n        return headers_\n\n    def urlopen(self, method, url, redirect=True, **kw):\n        \"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.\"\n        u = parse_url(url)\n        if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):\n            # For connections using HTTP CONNECT, httplib sets the necessary\n            # headers on the CONNECT to the proxy. If we're not using CONNECT,\n            # we'll definitely need to set 'Host' at the very least.\n            headers = kw.get(\"headers\", self.headers)\n            kw[\"headers\"] = self._set_proxy_headers(url, headers)\n\n        return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)\n\n\ndef proxy_from_url(url, **kw):\n    return ProxyManager(proxy_url=url, **kw)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/request.py",
    "content": "from __future__ import absolute_import\n\nimport sys\n\nfrom .filepost import encode_multipart_formdata\nfrom .packages import six\nfrom .packages.six.moves.urllib.parse import urlencode\n\n__all__ = [\"RequestMethods\"]\n\n\nclass RequestMethods(object):\n    \"\"\"\n    Convenience mixin for classes who implement a :meth:`urlopen` method, such\n    as :class:`urllib3.HTTPConnectionPool` and\n    :class:`urllib3.PoolManager`.\n\n    Provides behavior for making common types of HTTP request methods and\n    decides which type of request field encoding to use.\n\n    Specifically,\n\n    :meth:`.request_encode_url` is for sending requests whose fields are\n    encoded in the URL (such as GET, HEAD, DELETE).\n\n    :meth:`.request_encode_body` is for sending requests whose fields are\n    encoded in the *body* of the request using multipart or www-form-urlencoded\n    (such as for POST, PUT, PATCH).\n\n    :meth:`.request` is for making any kind of request, it will look up the\n    appropriate encoding format and use one of the above two methods to make\n    the request.\n\n    Initializer parameters:\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n    \"\"\"\n\n    _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n    def __init__(self, headers=None):\n        self.headers = headers or {}\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        encode_multipart=True,\n        multipart_boundary=None,\n        **kw\n    ):  # Abstract\n        raise NotImplementedError(\n            \"Classes extending RequestMethods must implement \"\n            \"their own ``urlopen`` method.\"\n        )\n\n    def request(self, method, url, fields=None, headers=None, **urlopen_kw):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the appropriate encoding of\n        ``fields`` based on the ``method`` used.\n\n        This is a convenience method that requires the least amount of manual\n        effort. It can be used in most situations, while still having the\n        option to drop down to more specific methods when necessary, such as\n        :meth:`request_encode_url`, :meth:`request_encode_body`,\n        or even the lowest level :meth:`urlopen`.\n        \"\"\"\n        method = method.upper()\n\n        urlopen_kw[\"request_url\"] = url\n\n        if method in self._encode_url_methods:\n            return self.request_encode_url(\n                method, url, fields=fields, headers=headers, **urlopen_kw\n            )\n        else:\n            return self.request_encode_body(\n                method, url, fields=fields, headers=headers, **urlopen_kw\n            )\n\n    def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the ``fields`` encoded in\n        the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n        \"\"\"\n        if headers is None:\n            headers = self.headers\n\n        extra_kw = {\"headers\": headers}\n        extra_kw.update(urlopen_kw)\n\n        if fields:\n            url += \"?\" + urlencode(fields)\n\n        return self.urlopen(method, url, **extra_kw)\n\n    def request_encode_body(\n        self,\n        method,\n        url,\n        fields=None,\n        headers=None,\n        encode_multipart=True,\n        multipart_boundary=None,\n        **urlopen_kw\n    ):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the ``fields`` encoded in\n        the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n        When ``encode_multipart=True`` (default), then\n        :func:`urllib3.encode_multipart_formdata` is used to encode\n        the payload with the appropriate content type. Otherwise\n        :func:`urllib.parse.urlencode` is used with the\n        'application/x-www-form-urlencoded' content type.\n\n        Multipart encoding must be used when posting files, and it's reasonably\n        safe to use it in other times too. However, it may break request\n        signing, such as with OAuth.\n\n        Supports an optional ``fields`` parameter of key/value strings AND\n        key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n        the MIME type is optional. For example::\n\n            fields = {\n                'foo': 'bar',\n                'fakefile': ('foofile.txt', 'contents of foofile'),\n                'realfile': ('barfile.txt', open('realfile').read()),\n                'typedfile': ('bazfile.bin', open('bazfile').read(),\n                              'image/jpeg'),\n                'nonamefile': 'contents of nonamefile field',\n            }\n\n        When uploading a file, providing a filename (the first parameter of the\n        tuple) is optional but recommended to best mimic behavior of browsers.\n\n        Note that if ``headers`` are supplied, the 'Content-Type' header will\n        be overwritten because it depends on the dynamic random boundary string\n        which is used to compose the body of the request. The random boundary\n        string can be explicitly set with the ``multipart_boundary`` parameter.\n        \"\"\"\n        if headers is None:\n            headers = self.headers\n\n        extra_kw = {\"headers\": {}}\n\n        if fields:\n            if \"body\" in urlopen_kw:\n                raise TypeError(\n                    \"request got values for both 'fields' and 'body', can only specify one.\"\n                )\n\n            if encode_multipart:\n                body, content_type = encode_multipart_formdata(\n                    fields, boundary=multipart_boundary\n                )\n            else:\n                body, content_type = (\n                    urlencode(fields),\n                    \"application/x-www-form-urlencoded\",\n                )\n\n            extra_kw[\"body\"] = body\n            extra_kw[\"headers\"] = {\"Content-Type\": content_type}\n\n        extra_kw[\"headers\"].update(headers)\n        extra_kw.update(urlopen_kw)\n\n        return self.urlopen(method, url, **extra_kw)\n\n\nif not six.PY2:\n\n    class RequestModule(sys.modules[__name__].__class__):\n        def __call__(self, *args, **kwargs):\n            \"\"\"\n            If user tries to call this module directly urllib3 v2.x style raise an error to the user\n            suggesting they may need urllib3 v2\n            \"\"\"\n            raise TypeError(\n                \"'module' object is not callable\\n\"\n                \"urllib3.request() method is not supported in this release, \"\n                \"upgrade to urllib3 v2 to use it\\n\"\n                \"see https://urllib3.readthedocs.io/en/stable/v2-migration-guide.html\"\n            )\n\n    sys.modules[__name__].__class__ = RequestModule\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/response.py",
    "content": "from __future__ import absolute_import\n\nimport io\nimport logging\nimport sys\nimport warnings\nimport zlib\nfrom contextlib import contextmanager\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nbrotli = None\n\nfrom . import util\nfrom ._collections import HTTPHeaderDict\nfrom .connection import BaseSSLError, HTTPException\nfrom .exceptions import (\n    BodyNotHttplibCompatible,\n    DecodeError,\n    HTTPError,\n    IncompleteRead,\n    InvalidChunkLength,\n    InvalidHeader,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseNotChunked,\n    SSLError,\n)\nfrom .packages import six\nfrom .util.response import is_fp_closed, is_response_to_head\n\nlog = logging.getLogger(__name__)\n\n\nclass DeflateDecoder(object):\n    def __init__(self):\n        self._first_try = True\n        self._data = b\"\"\n        self._obj = zlib.decompressobj()\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        if not data:\n            return data\n\n        if not self._first_try:\n            return self._obj.decompress(data)\n\n        self._data += data\n        try:\n            decompressed = self._obj.decompress(data)\n            if decompressed:\n                self._first_try = False\n                self._data = None\n            return decompressed\n        except zlib.error:\n            self._first_try = False\n            self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n            try:\n                return self.decompress(self._data)\n            finally:\n                self._data = None\n\n\nclass GzipDecoderState(object):\n\n    FIRST_MEMBER = 0\n    OTHER_MEMBERS = 1\n    SWALLOW_DATA = 2\n\n\nclass GzipDecoder(object):\n    def __init__(self):\n        self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n        self._state = GzipDecoderState.FIRST_MEMBER\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        ret = bytearray()\n        if self._state == GzipDecoderState.SWALLOW_DATA or not data:\n            return bytes(ret)\n        while True:\n            try:\n                ret += self._obj.decompress(data)\n            except zlib.error:\n                previous_state = self._state\n                # Ignore data after the first error\n                self._state = GzipDecoderState.SWALLOW_DATA\n                if previous_state == GzipDecoderState.OTHER_MEMBERS:\n                    # Allow trailing garbage acceptable in other gzip clients\n                    return bytes(ret)\n                raise\n            data = self._obj.unused_data\n            if not data:\n                return bytes(ret)\n            self._state = GzipDecoderState.OTHER_MEMBERS\n            self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n\nif brotli is not None:\n\n    class BrotliDecoder(object):\n        # Supports both 'brotlipy' and 'Brotli' packages\n        # since they share an import name. The top branches\n        # are for 'brotlipy' and bottom branches for 'Brotli'\n        def __init__(self):\n            self._obj = brotli.Decompressor()\n            if hasattr(self._obj, \"decompress\"):\n                self.decompress = self._obj.decompress\n            else:\n                self.decompress = self._obj.process\n\n        def flush(self):\n            if hasattr(self._obj, \"flush\"):\n                return self._obj.flush()\n            return b\"\"\n\n\nclass MultiDecoder(object):\n    \"\"\"\n    From RFC7231:\n        If one or more encodings have been applied to a representation, the\n        sender that applied the encodings MUST generate a Content-Encoding\n        header field that lists the content codings in the order in which\n        they were applied.\n    \"\"\"\n\n    def __init__(self, modes):\n        self._decoders = [_get_decoder(m.strip()) for m in modes.split(\",\")]\n\n    def flush(self):\n        return self._decoders[0].flush()\n\n    def decompress(self, data):\n        for d in reversed(self._decoders):\n            data = d.decompress(data)\n        return data\n\n\ndef _get_decoder(mode):\n    if \",\" in mode:\n        return MultiDecoder(mode)\n\n    if mode == \"gzip\":\n        return GzipDecoder()\n\n    if brotli is not None and mode == \"br\":\n        return BrotliDecoder()\n\n    return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n    \"\"\"\n    HTTP Response container.\n\n    Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is\n    loaded and decoded on-demand when the ``data`` property is accessed.  This\n    class is also compatible with the Python standard library's :mod:`io`\n    module, and can hence be treated as a readable object in the context of that\n    framework.\n\n    Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:\n\n    :param preload_content:\n        If True, the response's body will be preloaded during construction.\n\n    :param decode_content:\n        If True, will attempt to decode the body based on the\n        'content-encoding' header.\n\n    :param original_response:\n        When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`\n        object, it's convenient to include the original for debug purposes. It's\n        otherwise unused.\n\n    :param retries:\n        The retries contains the last :class:`~urllib3.util.retry.Retry` that\n        was used during the request.\n\n    :param enforce_content_length:\n        Enforce content length checking. Body returned by server must match\n        value of Content-Length header, if present. Otherwise, raise error.\n    \"\"\"\n\n    CONTENT_DECODERS = [\"gzip\", \"deflate\"]\n    if brotli is not None:\n        CONTENT_DECODERS += [\"br\"]\n    REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n    def __init__(\n        self,\n        body=\"\",\n        headers=None,\n        status=0,\n        version=0,\n        reason=None,\n        strict=0,\n        preload_content=True,\n        decode_content=True,\n        original_response=None,\n        pool=None,\n        connection=None,\n        msg=None,\n        retries=None,\n        enforce_content_length=False,\n        request_method=None,\n        request_url=None,\n        auto_close=True,\n    ):\n\n        if isinstance(headers, HTTPHeaderDict):\n            self.headers = headers\n        else:\n            self.headers = HTTPHeaderDict(headers)\n        self.status = status\n        self.version = version\n        self.reason = reason\n        self.strict = strict\n        self.decode_content = decode_content\n        self.retries = retries\n        self.enforce_content_length = enforce_content_length\n        self.auto_close = auto_close\n\n        self._decoder = None\n        self._body = None\n        self._fp = None\n        self._original_response = original_response\n        self._fp_bytes_read = 0\n        self.msg = msg\n        self._request_url = request_url\n\n        if body and isinstance(body, (six.string_types, bytes)):\n            self._body = body\n\n        self._pool = pool\n        self._connection = connection\n\n        if hasattr(body, \"read\"):\n            self._fp = body\n\n        # Are we using the chunked-style of transfer encoding?\n        self.chunked = False\n        self.chunk_left = None\n        tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n        # Don't incur the penalty of creating a list and then discarding it\n        encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n        if \"chunked\" in encodings:\n            self.chunked = True\n\n        # Determine length of response\n        self.length_remaining = self._init_length(request_method)\n\n        # If requested, preload the body.\n        if preload_content and not self._body:\n            self._body = self.read(decode_content=decode_content)\n\n    def get_redirect_location(self):\n        \"\"\"\n        Should we redirect and where to?\n\n        :returns: Truthy redirect location string if we got a redirect status\n            code and valid location. ``None`` if redirect status and no\n            location. ``False`` if not a redirect status code.\n        \"\"\"\n        if self.status in self.REDIRECT_STATUSES:\n            return self.headers.get(\"location\")\n\n        return False\n\n    def release_conn(self):\n        if not self._pool or not self._connection:\n            return\n\n        self._pool._put_conn(self._connection)\n        self._connection = None\n\n    def drain_conn(self):\n        \"\"\"\n        Read and discard any remaining HTTP response data in the response connection.\n\n        Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.\n        \"\"\"\n        try:\n            self.read()\n        except (HTTPError, SocketError, BaseSSLError, HTTPException):\n            pass\n\n    @property\n    def data(self):\n        # For backwards-compat with earlier urllib3 0.4 and earlier.\n        if self._body:\n            return self._body\n\n        if self._fp:\n            return self.read(cache_content=True)\n\n    @property\n    def connection(self):\n        return self._connection\n\n    def isclosed(self):\n        return is_fp_closed(self._fp)\n\n    def tell(self):\n        \"\"\"\n        Obtain the number of bytes pulled over the wire so far. May differ from\n        the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``\n        if bytes are encoded on the wire (e.g, compressed).\n        \"\"\"\n        return self._fp_bytes_read\n\n    def _init_length(self, request_method):\n        \"\"\"\n        Set initial length value for Response content if available.\n        \"\"\"\n        length = self.headers.get(\"content-length\")\n\n        if length is not None:\n            if self.chunked:\n                # This Response will fail with an IncompleteRead if it can't be\n                # received as chunked. This method falls back to attempt reading\n                # the response before raising an exception.\n                log.warning(\n                    \"Received response with both Content-Length and \"\n                    \"Transfer-Encoding set. This is expressly forbidden \"\n                    \"by RFC 7230 sec 3.3.2. Ignoring Content-Length and \"\n                    \"attempting to process response as Transfer-Encoding: \"\n                    \"chunked.\"\n                )\n                return None\n\n            try:\n                # RFC 7230 section 3.3.2 specifies multiple content lengths can\n                # be sent in a single Content-Length header\n                # (e.g. Content-Length: 42, 42). This line ensures the values\n                # are all valid ints and that as long as the `set` length is 1,\n                # all values are the same. Otherwise, the header is invalid.\n                lengths = set([int(val) for val in length.split(\",\")])\n                if len(lengths) > 1:\n                    raise InvalidHeader(\n                        \"Content-Length contained multiple \"\n                        \"unmatching values (%s)\" % length\n                    )\n                length = lengths.pop()\n            except ValueError:\n                length = None\n            else:\n                if length < 0:\n                    length = None\n\n        # Convert status to int for comparison\n        # In some cases, httplib returns a status of \"_UNKNOWN\"\n        try:\n            status = int(self.status)\n        except ValueError:\n            status = 0\n\n        # Check for responses that shouldn't include a body\n        if status in (204, 304) or 100 <= status < 200 or request_method == \"HEAD\":\n            length = 0\n\n        return length\n\n    def _init_decoder(self):\n        \"\"\"\n        Set-up the _decoder attribute if necessary.\n        \"\"\"\n        # Note: content-encoding value should be case-insensitive, per RFC 7230\n        # Section 3.2\n        content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n        if self._decoder is None:\n            if content_encoding in self.CONTENT_DECODERS:\n                self._decoder = _get_decoder(content_encoding)\n            elif \",\" in content_encoding:\n                encodings = [\n                    e.strip()\n                    for e in content_encoding.split(\",\")\n                    if e.strip() in self.CONTENT_DECODERS\n                ]\n                if len(encodings):\n                    self._decoder = _get_decoder(content_encoding)\n\n    DECODER_ERROR_CLASSES = (IOError, zlib.error)\n    if brotli is not None:\n        DECODER_ERROR_CLASSES += (brotli.error,)\n\n    def _decode(self, data, decode_content, flush_decoder):\n        \"\"\"\n        Decode the data passed in and potentially flush the decoder.\n        \"\"\"\n        if not decode_content:\n            return data\n\n        try:\n            if self._decoder:\n                data = self._decoder.decompress(data)\n        except self.DECODER_ERROR_CLASSES as e:\n            content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n            raise DecodeError(\n                \"Received response with content-encoding: %s, but \"\n                \"failed to decode it.\" % content_encoding,\n                e,\n            )\n        if flush_decoder:\n            data += self._flush_decoder()\n\n        return data\n\n    def _flush_decoder(self):\n        \"\"\"\n        Flushes the decoder. Should only be called if the decoder is actually\n        being used.\n        \"\"\"\n        if self._decoder:\n            buf = self._decoder.decompress(b\"\")\n            return buf + self._decoder.flush()\n\n        return b\"\"\n\n    @contextmanager\n    def _error_catcher(self):\n        \"\"\"\n        Catch low-level python exceptions, instead re-raising urllib3\n        variants, so that low-level exceptions are not leaked in the\n        high-level api.\n\n        On exit, release the connection back to the pool.\n        \"\"\"\n        clean_exit = False\n\n        try:\n            try:\n                yield\n\n            except SocketTimeout:\n                # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n                # there is yet no clean way to get at it from this context.\n                raise ReadTimeoutError(self._pool, None, \"Read timed out.\")\n\n            except BaseSSLError as e:\n                # FIXME: Is there a better way to differentiate between SSLErrors?\n                if \"read operation timed out\" not in str(e):\n                    # SSL errors related to framing/MAC get wrapped and reraised here\n                    raise SSLError(e)\n\n                raise ReadTimeoutError(self._pool, None, \"Read timed out.\")\n\n            except (HTTPException, SocketError) as e:\n                # This includes IncompleteRead.\n                raise ProtocolError(\"Connection broken: %r\" % e, e)\n\n            # If no exception is thrown, we should avoid cleaning up\n            # unnecessarily.\n            clean_exit = True\n        finally:\n            # If we didn't terminate cleanly, we need to throw away our\n            # connection.\n            if not clean_exit:\n                # The response may not be closed but we're not going to use it\n                # anymore so close it now to ensure that the connection is\n                # released back to the pool.\n                if self._original_response:\n                    self._original_response.close()\n\n                # Closing the response may not actually be sufficient to close\n                # everything, so if we have a hold of the connection close that\n                # too.\n                if self._connection:\n                    self._connection.close()\n\n            # If we hold the original response but it's closed now, we should\n            # return the connection back to the pool.\n            if self._original_response and self._original_response.isclosed():\n                self.release_conn()\n\n    def _fp_read(self, amt):\n        \"\"\"\n        Read a response with the thought that reading the number of bytes\n        larger than can fit in a 32-bit int at a time via SSL in some\n        known cases leads to an overflow error that has to be prevented\n        if `amt` or `self.length_remaining` indicate that a problem may\n        happen.\n\n        The known cases:\n          * 3.8 <= CPython < 3.9.7 because of a bug\n            https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.\n          * urllib3 injected with pyOpenSSL-backed SSL-support.\n          * CPython < 3.10 only when `amt` does not fit 32-bit int.\n        \"\"\"\n        assert self._fp\n        c_int_max = 2 ** 31 - 1\n        if (\n            (\n                (amt and amt > c_int_max)\n                or (self.length_remaining and self.length_remaining > c_int_max)\n            )\n            and not util.IS_SECURETRANSPORT\n            and (util.IS_PYOPENSSL or sys.version_info < (3, 10))\n        ):\n            buffer = io.BytesIO()\n            # Besides `max_chunk_amt` being a maximum chunk size, it\n            # affects memory overhead of reading a response by this\n            # method in CPython.\n            # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum\n            # chunk size that does not lead to an overflow error, but\n            # 256 MiB is a compromise.\n            max_chunk_amt = 2 ** 28\n            while amt is None or amt != 0:\n                if amt is not None:\n                    chunk_amt = min(amt, max_chunk_amt)\n                    amt -= chunk_amt\n                else:\n                    chunk_amt = max_chunk_amt\n                data = self._fp.read(chunk_amt)\n                if not data:\n                    break\n                buffer.write(data)\n                del data  # to reduce peak memory usage by `max_chunk_amt`.\n            return buffer.getvalue()\n        else:\n            # StringIO doesn't like amt=None\n            return self._fp.read(amt) if amt is not None else self._fp.read()\n\n    def read(self, amt=None, decode_content=None, cache_content=False):\n        \"\"\"\n        Similar to :meth:`http.client.HTTPResponse.read`, but with two additional\n        parameters: ``decode_content`` and ``cache_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n\n        :param cache_content:\n            If True, will save the returned data such that the same result is\n            returned despite of the state of the underlying file object. This\n            is useful if you want the ``.data`` property to continue working\n            after having ``.read()`` the file object. (Overridden if ``amt`` is\n            set.)\n        \"\"\"\n        self._init_decoder()\n        if decode_content is None:\n            decode_content = self.decode_content\n\n        if self._fp is None:\n            return\n\n        flush_decoder = False\n        fp_closed = getattr(self._fp, \"closed\", False)\n\n        with self._error_catcher():\n            data = self._fp_read(amt) if not fp_closed else b\"\"\n            if amt is None:\n                flush_decoder = True\n            else:\n                cache_content = False\n                if (\n                    amt != 0 and not data\n                ):  # Platform-specific: Buggy versions of Python.\n                    # Close the connection when no data is returned\n                    #\n                    # This is redundant to what httplib/http.client _should_\n                    # already do.  However, versions of python released before\n                    # December 15, 2012 (http://bugs.python.org/issue16298) do\n                    # not properly close the connection in all cases. There is\n                    # no harm in redundantly calling close.\n                    self._fp.close()\n                    flush_decoder = True\n                    if self.enforce_content_length and self.length_remaining not in (\n                        0,\n                        None,\n                    ):\n                        # This is an edge case that httplib failed to cover due\n                        # to concerns of backward compatibility. We're\n                        # addressing it here to make sure IncompleteRead is\n                        # raised during streaming, so all calls with incorrect\n                        # Content-Length are caught.\n                        raise IncompleteRead(self._fp_bytes_read, self.length_remaining)\n\n        if data:\n            self._fp_bytes_read += len(data)\n            if self.length_remaining is not None:\n                self.length_remaining -= len(data)\n\n            data = self._decode(data, decode_content, flush_decoder)\n\n            if cache_content:\n                self._body = data\n\n        return data\n\n    def stream(self, amt=2 ** 16, decode_content=None):\n        \"\"\"\n        A generator wrapper for the read() method. A call will block until\n        ``amt`` bytes have been read from the connection or until the\n        connection is closed.\n\n        :param amt:\n            How much of the content to read. The generator will return up to\n            much data per iteration, but may return less. This is particularly\n            likely when using compressed data. However, the empty string will\n            never be returned.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        if self.chunked and self.supports_chunked_reads():\n            for line in self.read_chunked(amt, decode_content=decode_content):\n                yield line\n        else:\n            while not is_fp_closed(self._fp):\n                data = self.read(amt=amt, decode_content=decode_content)\n\n                if data:\n                    yield data\n\n    @classmethod\n    def from_httplib(ResponseCls, r, **response_kw):\n        \"\"\"\n        Given an :class:`http.client.HTTPResponse` instance ``r``, return a\n        corresponding :class:`urllib3.response.HTTPResponse` object.\n\n        Remaining parameters are passed to the HTTPResponse constructor, along\n        with ``original_response=r``.\n        \"\"\"\n        headers = r.msg\n\n        if not isinstance(headers, HTTPHeaderDict):\n            if six.PY2:\n                # Python 2.7\n                headers = HTTPHeaderDict.from_httplib(headers)\n            else:\n                headers = HTTPHeaderDict(headers.items())\n\n        # HTTPResponse objects in Python 3 don't have a .strict attribute\n        strict = getattr(r, \"strict\", 0)\n        resp = ResponseCls(\n            body=r,\n            headers=headers,\n            status=r.status,\n            version=r.version,\n            reason=r.reason,\n            strict=strict,\n            original_response=r,\n            **response_kw\n        )\n        return resp\n\n    # Backwards-compatibility methods for http.client.HTTPResponse\n    def getheaders(self):\n        warnings.warn(\n            \"HTTPResponse.getheaders() is deprecated and will be removed \"\n            \"in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.\",\n            category=DeprecationWarning,\n            stacklevel=2,\n        )\n        return self.headers\n\n    def getheader(self, name, default=None):\n        warnings.warn(\n            \"HTTPResponse.getheader() is deprecated and will be removed \"\n            \"in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).\",\n            category=DeprecationWarning,\n            stacklevel=2,\n        )\n        return self.headers.get(name, default)\n\n    # Backwards compatibility for http.cookiejar\n    def info(self):\n        return self.headers\n\n    # Overrides from io.IOBase\n    def close(self):\n        if not self.closed:\n            self._fp.close()\n\n        if self._connection:\n            self._connection.close()\n\n        if not self.auto_close:\n            io.IOBase.close(self)\n\n    @property\n    def closed(self):\n        if not self.auto_close:\n            return io.IOBase.closed.__get__(self)\n        elif self._fp is None:\n            return True\n        elif hasattr(self._fp, \"isclosed\"):\n            return self._fp.isclosed()\n        elif hasattr(self._fp, \"closed\"):\n            return self._fp.closed\n        else:\n            return True\n\n    def fileno(self):\n        if self._fp is None:\n            raise IOError(\"HTTPResponse has no file to get a fileno from\")\n        elif hasattr(self._fp, \"fileno\"):\n            return self._fp.fileno()\n        else:\n            raise IOError(\n                \"The file-like object this HTTPResponse is wrapped \"\n                \"around has no file descriptor\"\n            )\n\n    def flush(self):\n        if (\n            self._fp is not None\n            and hasattr(self._fp, \"flush\")\n            and not getattr(self._fp, \"closed\", False)\n        ):\n            return self._fp.flush()\n\n    def readable(self):\n        # This method is required for `io` module compatibility.\n        return True\n\n    def readinto(self, b):\n        # This method is required for `io` module compatibility.\n        temp = self.read(len(b))\n        if len(temp) == 0:\n            return 0\n        else:\n            b[: len(temp)] = temp\n            return len(temp)\n\n    def supports_chunked_reads(self):\n        \"\"\"\n        Checks if the underlying file-like object looks like a\n        :class:`http.client.HTTPResponse` object. We do this by testing for\n        the fp attribute. If it is present we assume it returns raw chunks as\n        processed by read_chunked().\n        \"\"\"\n        return hasattr(self._fp, \"fp\")\n\n    def _update_chunk_length(self):\n        # First, we'll figure out length of a chunk and then\n        # we'll try to read it from socket.\n        if self.chunk_left is not None:\n            return\n        line = self._fp.fp.readline()\n        line = line.split(b\";\", 1)[0]\n        try:\n            self.chunk_left = int(line, 16)\n        except ValueError:\n            # Invalid chunked protocol response, abort.\n            self.close()\n            raise InvalidChunkLength(self, line)\n\n    def _handle_chunk(self, amt):\n        returned_chunk = None\n        if amt is None:\n            chunk = self._fp._safe_read(self.chunk_left)\n            returned_chunk = chunk\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n        elif amt < self.chunk_left:\n            value = self._fp._safe_read(amt)\n            self.chunk_left = self.chunk_left - amt\n            returned_chunk = value\n        elif amt == self.chunk_left:\n            value = self._fp._safe_read(amt)\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n            returned_chunk = value\n        else:  # amt > self.chunk_left\n            returned_chunk = self._fp._safe_read(self.chunk_left)\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n        return returned_chunk\n\n    def read_chunked(self, amt=None, decode_content=None):\n        \"\"\"\n        Similar to :meth:`HTTPResponse.read`, but with an additional\n        parameter: ``decode_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        self._init_decoder()\n        # FIXME: Rewrite this method and make it a class with a better structured logic.\n        if not self.chunked:\n            raise ResponseNotChunked(\n                \"Response is not chunked. \"\n                \"Header 'transfer-encoding: chunked' is missing.\"\n            )\n        if not self.supports_chunked_reads():\n            raise BodyNotHttplibCompatible(\n                \"Body should be http.client.HTTPResponse like. \"\n                \"It should have have an fp attribute which returns raw chunks.\"\n            )\n\n        with self._error_catcher():\n            # Don't bother reading the body of a HEAD request.\n            if self._original_response and is_response_to_head(self._original_response):\n                self._original_response.close()\n                return\n\n            # If a response is already read and closed\n            # then return immediately.\n            if self._fp.fp is None:\n                return\n\n            while True:\n                self._update_chunk_length()\n                if self.chunk_left == 0:\n                    break\n                chunk = self._handle_chunk(amt)\n                decoded = self._decode(\n                    chunk, decode_content=decode_content, flush_decoder=False\n                )\n                if decoded:\n                    yield decoded\n\n            if decode_content:\n                # On CPython and PyPy, we should never need to flush the\n                # decoder. However, on Jython we *might* need to, so\n                # lets defensively do it anyway.\n                decoded = self._flush_decoder()\n                if decoded:  # Platform-specific: Jython.\n                    yield decoded\n\n            # Chunk content ends with \\r\\n: discard it.\n            while True:\n                line = self._fp.fp.readline()\n                if not line:\n                    # Some sites may not end with '\\r\\n'.\n                    break\n                if line == b\"\\r\\n\":\n                    break\n\n            # We read everything; close the \"file\".\n            if self._original_response:\n                self._original_response.close()\n\n    def geturl(self):\n        \"\"\"\n        Returns the URL that was the source of this response.\n        If the request that generated this response redirected, this method\n        will return the final redirect location.\n        \"\"\"\n        if self.retries is not None and len(self.retries.history):\n            return self.retries.history[-1].redirect_location\n        else:\n            return self._request_url\n\n    def __iter__(self):\n        buffer = []\n        for chunk in self.stream(decode_content=True):\n            if b\"\\n\" in chunk:\n                chunk = chunk.split(b\"\\n\")\n                yield b\"\".join(buffer) + chunk[0] + b\"\\n\"\n                for x in chunk[1:-1]:\n                    yield x + b\"\\n\"\n                if chunk[-1]:\n                    buffer = [chunk[-1]]\n                else:\n                    buffer = []\n            else:\n                buffer.append(chunk)\n        if buffer:\n            yield b\"\".join(buffer)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/__init__.py",
    "content": "from __future__ import absolute_import\n\n# For backwards compatibility, provide imports that used to be here.\nfrom .connection import is_connection_dropped\nfrom .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers\nfrom .response import is_fp_closed\nfrom .retry import Retry\nfrom .ssl_ import (\n    ALPN_PROTOCOLS,\n    HAS_SNI,\n    IS_PYOPENSSL,\n    IS_SECURETRANSPORT,\n    PROTOCOL_TLS,\n    SSLContext,\n    assert_fingerprint,\n    resolve_cert_reqs,\n    resolve_ssl_version,\n    ssl_wrap_socket,\n)\nfrom .timeout import Timeout, current_time\nfrom .url import Url, get_host, parse_url, split_first\nfrom .wait import wait_for_read, wait_for_write\n\n__all__ = (\n    \"HAS_SNI\",\n    \"IS_PYOPENSSL\",\n    \"IS_SECURETRANSPORT\",\n    \"SSLContext\",\n    \"PROTOCOL_TLS\",\n    \"ALPN_PROTOCOLS\",\n    \"Retry\",\n    \"Timeout\",\n    \"Url\",\n    \"assert_fingerprint\",\n    \"current_time\",\n    \"is_connection_dropped\",\n    \"is_fp_closed\",\n    \"get_host\",\n    \"parse_url\",\n    \"make_headers\",\n    \"resolve_cert_reqs\",\n    \"resolve_ssl_version\",\n    \"split_first\",\n    \"ssl_wrap_socket\",\n    \"wait_for_read\",\n    \"wait_for_write\",\n    \"SKIP_HEADER\",\n    \"SKIPPABLE_HEADERS\",\n)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/connection.py",
    "content": "from __future__ import absolute_import\n\nimport socket\n\nfrom ..contrib import _appengine_environ\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\nfrom .wait import NoWayToWaitForSocketError, wait_for_read\n\n\ndef is_connection_dropped(conn):  # Platform-specific\n    \"\"\"\n    Returns True if the connection is dropped and should be closed.\n\n    :param conn:\n        :class:`http.client.HTTPConnection` object.\n\n    Note: For platforms like AppEngine, this will always return ``False`` to\n    let the platform handle connection recycling transparently for us.\n    \"\"\"\n    sock = getattr(conn, \"sock\", False)\n    if sock is False:  # Platform-specific: AppEngine\n        return False\n    if sock is None:  # Connection already closed (such as by httplib).\n        return True\n    try:\n        # Returns True if readable, which here means it's been dropped\n        return wait_for_read(sock, timeout=0.0)\n    except NoWayToWaitForSocketError:  # Platform-specific: AppEngine\n        return False\n\n\n# This function is copied from socket.py in the Python 2.7 standard\n# library test suite. Added to its signature is only `socket_options`.\n# One additional modification is that we avoid binding to IPv6 servers\n# discovered in DNS if the system doesn't have IPv6 functionality.\ndef create_connection(\n    address,\n    timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n    source_address=None,\n    socket_options=None,\n):\n    \"\"\"Connect to *address* and return the socket object.\n\n    Convenience function.  Connect to *address* (a 2-tuple ``(host,\n    port)``) and return the socket object.  Passing the optional\n    *timeout* parameter will set the timeout on the socket instance\n    before attempting to connect.  If no *timeout* is supplied, the\n    global default timeout setting returned by :func:`socket.getdefaulttimeout`\n    is used.  If *source_address* is set it must be a tuple of (host, port)\n    for the socket to bind as a source address before making the connection.\n    An host of '' or port 0 tells the OS to use the default.\n    \"\"\"\n\n    host, port = address\n    if host.startswith(\"[\"):\n        host = host.strip(\"[]\")\n    err = None\n\n    # Using the value from allowed_gai_family() in the context of getaddrinfo lets\n    # us select whether to work with IPv4 DNS records, IPv6 records, or both.\n    # The original create_connection function always returns all records.\n    family = allowed_gai_family()\n\n    try:\n        host.encode(\"idna\")\n    except UnicodeError:\n        return six.raise_from(\n            LocationParseError(u\"'%s', label empty or too long\" % host), None\n        )\n\n    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):\n        af, socktype, proto, canonname, sa = res\n        sock = None\n        try:\n            sock = socket.socket(af, socktype, proto)\n\n            # If provided, set socket level options before connecting.\n            _set_socket_options(sock, socket_options)\n\n            if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:\n                sock.settimeout(timeout)\n            if source_address:\n                sock.bind(source_address)\n            sock.connect(sa)\n            return sock\n\n        except socket.error as e:\n            err = e\n            if sock is not None:\n                sock.close()\n                sock = None\n\n    if err is not None:\n        raise err\n\n    raise socket.error(\"getaddrinfo returns an empty list\")\n\n\ndef _set_socket_options(sock, options):\n    if options is None:\n        return\n\n    for opt in options:\n        sock.setsockopt(*opt)\n\n\ndef allowed_gai_family():\n    \"\"\"This function is designed to work in the context of\n    getaddrinfo, where family=socket.AF_UNSPEC is the default and\n    will perform a DNS search for both IPv6 and IPv4 records.\"\"\"\n\n    family = socket.AF_INET\n    if HAS_IPV6:\n        family = socket.AF_UNSPEC\n    return family\n\n\ndef _has_ipv6(host):\n    \"\"\"Returns True if the system can bind an IPv6 address.\"\"\"\n    sock = None\n    has_ipv6 = False\n\n    # App Engine doesn't support IPV6 sockets and actually has a quota on the\n    # number of sockets that can be used, so just early out here instead of\n    # creating a socket needlessly.\n    # See https://github.com/urllib3/urllib3/issues/1446\n    if _appengine_environ.is_appengine_sandbox():\n        return False\n\n    if socket.has_ipv6:\n        # has_ipv6 returns true if cPython was compiled with IPv6 support.\n        # It does not tell us if the system has IPv6 support enabled. To\n        # determine that we must bind to an IPv6 address.\n        # https://github.com/urllib3/urllib3/pull/611\n        # https://bugs.python.org/issue658327\n        try:\n            sock = socket.socket(socket.AF_INET6)\n            sock.bind((host, 0))\n            has_ipv6 = True\n        except Exception:\n            pass\n\n    if sock:\n        sock.close()\n    return has_ipv6\n\n\nHAS_IPV6 = _has_ipv6(\"::1\")\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/proxy.py",
    "content": "from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version\n\n\ndef connection_requires_http_tunnel(\n    proxy_url=None, proxy_config=None, destination_scheme=None\n):\n    \"\"\"\n    Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n    :param URL proxy_url:\n        URL of the proxy.\n    :param ProxyConfig proxy_config:\n        Proxy configuration from poolmanager.py\n    :param str destination_scheme:\n        The scheme of the destination. (i.e https, http, etc)\n    \"\"\"\n    # If we're not using a proxy, no way to use a tunnel.\n    if proxy_url is None:\n        return False\n\n    # HTTP destinations never require tunneling, we always forward.\n    if destination_scheme == \"http\":\n        return False\n\n    # Support for forwarding with HTTPS proxies and HTTPS destinations.\n    if (\n        proxy_url.scheme == \"https\"\n        and proxy_config\n        and proxy_config.use_forwarding_for_https\n    ):\n        return False\n\n    # Otherwise always use a tunnel.\n    return True\n\n\ndef create_proxy_ssl_context(\n    ssl_version, cert_reqs, ca_certs=None, ca_cert_dir=None, ca_cert_data=None\n):\n    \"\"\"\n    Generates a default proxy ssl context if one hasn't been provided by the\n    user.\n    \"\"\"\n    ssl_context = create_urllib3_context(\n        ssl_version=resolve_ssl_version(ssl_version),\n        cert_reqs=resolve_cert_reqs(cert_reqs),\n    )\n\n    if (\n        not ca_certs\n        and not ca_cert_dir\n        and not ca_cert_data\n        and hasattr(ssl_context, \"load_default_certs\")\n    ):\n        ssl_context.load_default_certs()\n\n    return ssl_context\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/queue.py",
    "content": "import collections\n\nfrom ..packages import six\nfrom ..packages.six.moves import queue\n\nif six.PY2:\n    # Queue is imported for side effects on MS Windows. See issue #229.\n    import Queue as _unused_module_Queue  # noqa: F401\n\n\nclass LifoQueue(queue.Queue):\n    def _init(self, _):\n        self.queue = collections.deque()\n\n    def _qsize(self, len=len):\n        return len(self.queue)\n\n    def _put(self, item):\n        self.queue.append(item)\n\n    def _get(self):\n        return self.queue.pop()\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/request.py",
    "content": "from __future__ import absolute_import\n\nfrom base64 import b64encode\n\nfrom ..exceptions import UnrewindableBodyError\nfrom ..packages.six import b, integer_types\n\n# Pass as a value within ``headers`` to skip\n# emitting some HTTP headers that are added automatically.\n# The only headers that are supported are ``Accept-Encoding``,\n# ``Host``, and ``User-Agent``.\nSKIP_HEADER = \"@@@SKIP_HEADER@@@\"\nSKIPPABLE_HEADERS = frozenset([\"accept-encoding\", \"host\", \"user-agent\"])\n\nACCEPT_ENCODING = \"gzip,deflate\"\n\n_FAILEDTELL = object()\n\n\ndef make_headers(\n    keep_alive=None,\n    accept_encoding=None,\n    user_agent=None,\n    basic_auth=None,\n    proxy_basic_auth=None,\n    disable_cache=None,\n):\n    \"\"\"\n    Shortcuts for generating request headers.\n\n    :param keep_alive:\n        If ``True``, adds 'connection: keep-alive' header.\n\n    :param accept_encoding:\n        Can be a boolean, list, or string.\n        ``True`` translates to 'gzip,deflate'.\n        List will get joined by comma.\n        String will be used as provided.\n\n    :param user_agent:\n        String representing the user-agent you want, such as\n        \"python-urllib3/0.6\"\n\n    :param basic_auth:\n        Colon-separated username:password string for 'authorization: basic ...'\n        auth header.\n\n    :param proxy_basic_auth:\n        Colon-separated username:password string for 'proxy-authorization: basic ...'\n        auth header.\n\n    :param disable_cache:\n        If ``True``, adds 'cache-control: no-cache' header.\n\n    Example::\n\n        >>> make_headers(keep_alive=True, user_agent=\"Batman/1.0\")\n        {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}\n        >>> make_headers(accept_encoding=True)\n        {'accept-encoding': 'gzip,deflate'}\n    \"\"\"\n    headers = {}\n    if accept_encoding:\n        if isinstance(accept_encoding, str):\n            pass\n        elif isinstance(accept_encoding, list):\n            accept_encoding = \",\".join(accept_encoding)\n        else:\n            accept_encoding = ACCEPT_ENCODING\n        headers[\"accept-encoding\"] = accept_encoding\n\n    if user_agent:\n        headers[\"user-agent\"] = user_agent\n\n    if keep_alive:\n        headers[\"connection\"] = \"keep-alive\"\n\n    if basic_auth:\n        headers[\"authorization\"] = \"Basic \" + b64encode(b(basic_auth)).decode(\"utf-8\")\n\n    if proxy_basic_auth:\n        headers[\"proxy-authorization\"] = \"Basic \" + b64encode(\n            b(proxy_basic_auth)\n        ).decode(\"utf-8\")\n\n    if disable_cache:\n        headers[\"cache-control\"] = \"no-cache\"\n\n    return headers\n\n\ndef set_file_position(body, pos):\n    \"\"\"\n    If a position is provided, move file to that point.\n    Otherwise, we'll attempt to record a position for future use.\n    \"\"\"\n    if pos is not None:\n        rewind_body(body, pos)\n    elif getattr(body, \"tell\", None) is not None:\n        try:\n            pos = body.tell()\n        except (IOError, OSError):\n            # This differentiates from None, allowing us to catch\n            # a failed `tell()` later when trying to rewind the body.\n            pos = _FAILEDTELL\n\n    return pos\n\n\ndef rewind_body(body, body_pos):\n    \"\"\"\n    Attempt to rewind body to a certain position.\n    Primarily used for request redirects and retries.\n\n    :param body:\n        File-like object that supports seek.\n\n    :param int pos:\n        Position to seek to in file.\n    \"\"\"\n    body_seek = getattr(body, \"seek\", None)\n    if body_seek is not None and isinstance(body_pos, integer_types):\n        try:\n            body_seek(body_pos)\n        except (IOError, OSError):\n            raise UnrewindableBodyError(\n                \"An error occurred when rewinding request body for redirect/retry.\"\n            )\n    elif body_pos is _FAILEDTELL:\n        raise UnrewindableBodyError(\n            \"Unable to record file position for rewinding \"\n            \"request body during a redirect/retry.\"\n        )\n    else:\n        raise ValueError(\n            \"body_pos must be of type integer, instead it was %s.\" % type(body_pos)\n        )\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/response.py",
    "content": "from __future__ import absolute_import\n\nfrom email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect\n\nfrom ..exceptions import HeaderParsingError\nfrom ..packages.six.moves import http_client as httplib\n\n\ndef is_fp_closed(obj):\n    \"\"\"\n    Checks whether a given file-like object is closed.\n\n    :param obj:\n        The file-like object to check.\n    \"\"\"\n\n    try:\n        # Check `isclosed()` first, in case Python3 doesn't set `closed`.\n        # GH Issue #928\n        return obj.isclosed()\n    except AttributeError:\n        pass\n\n    try:\n        # Check via the official file-like-object way.\n        return obj.closed\n    except AttributeError:\n        pass\n\n    try:\n        # Check if the object is a container for another file-like object that\n        # gets released on exhaustion (e.g. HTTPResponse).\n        return obj.fp is None\n    except AttributeError:\n        pass\n\n    raise ValueError(\"Unable to determine whether fp is closed.\")\n\n\ndef assert_header_parsing(headers):\n    \"\"\"\n    Asserts whether all headers have been successfully parsed.\n    Extracts encountered errors from the result of parsing headers.\n\n    Only works on Python 3.\n\n    :param http.client.HTTPMessage headers: Headers to verify.\n\n    :raises urllib3.exceptions.HeaderParsingError:\n        If parsing errors are found.\n    \"\"\"\n\n    # This will fail silently if we pass in the wrong kind of parameter.\n    # To make debugging easier add an explicit check.\n    if not isinstance(headers, httplib.HTTPMessage):\n        raise TypeError(\"expected httplib.Message, got {0}.\".format(type(headers)))\n\n    defects = getattr(headers, \"defects\", None)\n    get_payload = getattr(headers, \"get_payload\", None)\n\n    unparsed_data = None\n    if get_payload:\n        # get_payload is actually email.message.Message.get_payload;\n        # we're only interested in the result if it's not a multipart message\n        if not headers.is_multipart():\n            payload = get_payload()\n\n            if isinstance(payload, (bytes, str)):\n                unparsed_data = payload\n    if defects:\n        # httplib is assuming a response body is available\n        # when parsing headers even when httplib only sends\n        # header data to parse_headers() This results in\n        # defects on multipart responses in particular.\n        # See: https://github.com/urllib3/urllib3/issues/800\n\n        # So we ignore the following defects:\n        # - StartBoundaryNotFoundDefect:\n        #     The claimed start boundary was never found.\n        # - MultipartInvariantViolationDefect:\n        #     A message claimed to be a multipart but no subparts were found.\n        defects = [\n            defect\n            for defect in defects\n            if not isinstance(\n                defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)\n            )\n        ]\n\n    if defects or unparsed_data:\n        raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)\n\n\ndef is_response_to_head(response):\n    \"\"\"\n    Checks whether the request of a response has been a HEAD-request.\n    Handles the quirks of AppEngine.\n\n    :param http.client.HTTPResponse response:\n        Response to check if the originating request\n        used 'HEAD' as a method.\n    \"\"\"\n    # FIXME: Can we do this somehow without accessing private httplib _method?\n    method = response._method\n    if isinstance(method, int):  # Platform-specific: Appengine\n        return method == 3\n    return method.upper() == \"HEAD\"\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/retry.py",
    "content": "from __future__ import absolute_import\n\nimport email\nimport logging\nimport re\nimport time\nimport warnings\nfrom collections import namedtuple\nfrom itertools import takewhile\n\nfrom ..exceptions import (\n    ConnectTimeoutError,\n    InvalidHeader,\n    MaxRetryError,\n    ProtocolError,\n    ProxyError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom ..packages import six\n\nlog = logging.getLogger(__name__)\n\n\n# Data structure for representing the metadata of requests that result in a retry.\nRequestHistory = namedtuple(\n    \"RequestHistory\", [\"method\", \"url\", \"error\", \"status\", \"redirect_location\"]\n)\n\n\n# TODO: In v2 we can remove this sentinel and metaclass with deprecated options.\n_Default = object()\n\n\nclass _RetryMeta(type):\n    @property\n    def DEFAULT_METHOD_WHITELIST(cls):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_ALLOWED_METHODS\n\n    @DEFAULT_METHOD_WHITELIST.setter\n    def DEFAULT_METHOD_WHITELIST(cls, value):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_ALLOWED_METHODS = value\n\n    @property\n    def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n    @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter\n    def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value\n\n    @property\n    def BACKOFF_MAX(cls):\n        warnings.warn(\n            \"Using 'Retry.BACKOFF_MAX' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_BACKOFF_MAX\n\n    @BACKOFF_MAX.setter\n    def BACKOFF_MAX(cls, value):\n        warnings.warn(\n            \"Using 'Retry.BACKOFF_MAX' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_BACKOFF_MAX = value\n\n\n@six.add_metaclass(_RetryMeta)\nclass Retry(object):\n    \"\"\"Retry configuration.\n\n    Each retry attempt will create a new Retry object with updated values, so\n    they can be safely reused.\n\n    Retries can be defined as a default for a pool::\n\n        retries = Retry(connect=5, read=2, redirect=5)\n        http = PoolManager(retries=retries)\n        response = http.request('GET', 'http://example.com/')\n\n    Or per-request (which overrides the default for the pool)::\n\n        response = http.request('GET', 'http://example.com/', retries=Retry(10))\n\n    Retries can be disabled by passing ``False``::\n\n        response = http.request('GET', 'http://example.com/', retries=False)\n\n    Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n    retries are disabled, in which case the causing exception will be raised.\n\n    :param int total:\n        Total number of retries to allow. Takes precedence over other counts.\n\n        Set to ``None`` to remove this constraint and fall back on other\n        counts.\n\n        Set to ``0`` to fail on the first retry.\n\n        Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n    :param int connect:\n        How many connection-related errors to retry on.\n\n        These are errors raised before the request is sent to the remote server,\n        which we assume has not triggered the server to process the request.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int read:\n        How many times to retry on read errors.\n\n        These errors are raised after the request was sent to the server, so the\n        request may have side-effects.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int redirect:\n        How many redirects to perform. Limit this to avoid infinite redirect\n        loops.\n\n        A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n        308.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n        Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n    :param int status:\n        How many times to retry on bad status codes.\n\n        These are retries made on responses, where status code matches\n        ``status_forcelist``.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int other:\n        How many times to retry on other errors.\n\n        Other errors are errors that are not connect, read, redirect or status errors.\n        These errors might be raised after the request was sent to the server, so the\n        request might have side-effects.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n        If ``total`` is not set, it's a good idea to set this to 0 to account\n        for unexpected edge cases and avoid infinite retry loops.\n\n    :param iterable allowed_methods:\n        Set of uppercased HTTP method verbs that we should retry on.\n\n        By default, we only retry on methods which are considered to be\n        idempotent (multiple requests with the same parameters end with the\n        same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n        Set to a ``False`` value to retry on any verb.\n\n        .. warning::\n\n            Previously this parameter was named ``method_whitelist``, that\n            usage is deprecated in v1.26.0 and will be removed in v2.0.\n\n    :param iterable status_forcelist:\n        A set of integer HTTP status codes that we should force a retry on.\n        A retry is initiated if the request method is in ``allowed_methods``\n        and the response status code is in ``status_forcelist``.\n\n        By default, this is disabled with ``None``.\n\n    :param float backoff_factor:\n        A backoff factor to apply between attempts after the second try\n        (most errors are resolved immediately by a second try without a\n        delay). urllib3 will sleep for::\n\n            {backoff factor} * (2 ** ({number of total retries} - 1))\n\n        seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep\n        for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer\n        than :attr:`Retry.DEFAULT_BACKOFF_MAX`.\n\n        By default, backoff is disabled (set to 0).\n\n    :param bool raise_on_redirect: Whether, if the number of redirects is\n        exhausted, to raise a MaxRetryError, or to return a response with a\n        response code in the 3xx range.\n\n    :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n        whether we should raise an exception, or return a response,\n        if status falls in ``status_forcelist`` range and retries have\n        been exhausted.\n\n    :param tuple history: The history of the request encountered during\n        each call to :meth:`~Retry.increment`. The list is in the order\n        the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n    :param bool respect_retry_after_header:\n        Whether to respect Retry-After header on status codes defined as\n        :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n    :param iterable remove_headers_on_redirect:\n        Sequence of headers to remove from the request when a response\n        indicating a redirect is returned before firing off the redirected\n        request.\n    \"\"\"\n\n    #: Default methods to be used for ``allowed_methods``\n    DEFAULT_ALLOWED_METHODS = frozenset(\n        [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n    )\n\n    #: Default status codes to be used for ``status_forcelist``\n    RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n    #: Default headers to be used for ``remove_headers_on_redirect``\n    DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(\n        [\"Cookie\", \"Authorization\", \"Proxy-Authorization\"]\n    )\n\n    #: Maximum backoff time.\n    DEFAULT_BACKOFF_MAX = 120\n\n    def __init__(\n        self,\n        total=10,\n        connect=None,\n        read=None,\n        redirect=None,\n        status=None,\n        other=None,\n        allowed_methods=_Default,\n        status_forcelist=None,\n        backoff_factor=0,\n        raise_on_redirect=True,\n        raise_on_status=True,\n        history=None,\n        respect_retry_after_header=True,\n        remove_headers_on_redirect=_Default,\n        # TODO: Deprecated, remove in v2.0\n        method_whitelist=_Default,\n    ):\n\n        if method_whitelist is not _Default:\n            if allowed_methods is not _Default:\n                raise ValueError(\n                    \"Using both 'allowed_methods' and \"\n                    \"'method_whitelist' together is not allowed. \"\n                    \"Instead only use 'allowed_methods'\"\n                )\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n            allowed_methods = method_whitelist\n        if allowed_methods is _Default:\n            allowed_methods = self.DEFAULT_ALLOWED_METHODS\n        if remove_headers_on_redirect is _Default:\n            remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n        self.total = total\n        self.connect = connect\n        self.read = read\n        self.status = status\n        self.other = other\n\n        if redirect is False or total is False:\n            redirect = 0\n            raise_on_redirect = False\n\n        self.redirect = redirect\n        self.status_forcelist = status_forcelist or set()\n        self.allowed_methods = allowed_methods\n        self.backoff_factor = backoff_factor\n        self.raise_on_redirect = raise_on_redirect\n        self.raise_on_status = raise_on_status\n        self.history = history or tuple()\n        self.respect_retry_after_header = respect_retry_after_header\n        self.remove_headers_on_redirect = frozenset(\n            [h.lower() for h in remove_headers_on_redirect]\n        )\n\n    def new(self, **kw):\n        params = dict(\n            total=self.total,\n            connect=self.connect,\n            read=self.read,\n            redirect=self.redirect,\n            status=self.status,\n            other=self.other,\n            status_forcelist=self.status_forcelist,\n            backoff_factor=self.backoff_factor,\n            raise_on_redirect=self.raise_on_redirect,\n            raise_on_status=self.raise_on_status,\n            history=self.history,\n            remove_headers_on_redirect=self.remove_headers_on_redirect,\n            respect_retry_after_header=self.respect_retry_after_header,\n        )\n\n        # TODO: If already given in **kw we use what's given to us\n        # If not given we need to figure out what to pass. We decide\n        # based on whether our class has the 'method_whitelist' property\n        # and if so we pass the deprecated 'method_whitelist' otherwise\n        # we use 'allowed_methods'. Remove in v2.0\n        if \"method_whitelist\" not in kw and \"allowed_methods\" not in kw:\n            if \"method_whitelist\" in self.__dict__:\n                warnings.warn(\n                    \"Using 'method_whitelist' with Retry is deprecated and \"\n                    \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                    DeprecationWarning,\n                )\n                params[\"method_whitelist\"] = self.allowed_methods\n            else:\n                params[\"allowed_methods\"] = self.allowed_methods\n\n        params.update(kw)\n        return type(self)(**params)\n\n    @classmethod\n    def from_int(cls, retries, redirect=True, default=None):\n        \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n        if retries is None:\n            retries = default if default is not None else cls.DEFAULT\n\n        if isinstance(retries, Retry):\n            return retries\n\n        redirect = bool(redirect) and None\n        new_retries = cls(retries, redirect=redirect)\n        log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n        return new_retries\n\n    def get_backoff_time(self):\n        \"\"\"Formula for computing the current backoff\n\n        :rtype: float\n        \"\"\"\n        # We want to consider only the last consecutive errors sequence (Ignore redirects).\n        consecutive_errors_len = len(\n            list(\n                takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n            )\n        )\n        if consecutive_errors_len <= 1:\n            return 0\n\n        backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n        return min(self.DEFAULT_BACKOFF_MAX, backoff_value)\n\n    def parse_retry_after(self, retry_after):\n        # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n        if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n            seconds = int(retry_after)\n        else:\n            retry_date_tuple = email.utils.parsedate_tz(retry_after)\n            if retry_date_tuple is None:\n                raise InvalidHeader(\"Invalid Retry-After header: %s\" % retry_after)\n            if retry_date_tuple[9] is None:  # Python 2\n                # Assume UTC if no timezone was specified\n                # On Python2.7, parsedate_tz returns None for a timezone offset\n                # instead of 0 if no timezone is given, where mktime_tz treats\n                # a None timezone offset as local time.\n                retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]\n\n            retry_date = email.utils.mktime_tz(retry_date_tuple)\n            seconds = retry_date - time.time()\n\n        if seconds < 0:\n            seconds = 0\n\n        return seconds\n\n    def get_retry_after(self, response):\n        \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n        retry_after = response.headers.get(\"Retry-After\")\n\n        if retry_after is None:\n            return None\n\n        return self.parse_retry_after(retry_after)\n\n    def sleep_for_retry(self, response=None):\n        retry_after = self.get_retry_after(response)\n        if retry_after:\n            time.sleep(retry_after)\n            return True\n\n        return False\n\n    def _sleep_backoff(self):\n        backoff = self.get_backoff_time()\n        if backoff <= 0:\n            return\n        time.sleep(backoff)\n\n    def sleep(self, response=None):\n        \"\"\"Sleep between retry attempts.\n\n        This method will respect a server's ``Retry-After`` response header\n        and sleep the duration of the time requested. If that is not present, it\n        will use an exponential backoff. By default, the backoff factor is 0 and\n        this method will return immediately.\n        \"\"\"\n\n        if self.respect_retry_after_header and response:\n            slept = self.sleep_for_retry(response)\n            if slept:\n                return\n\n        self._sleep_backoff()\n\n    def _is_connection_error(self, err):\n        \"\"\"Errors when we're fairly sure that the server did not receive the\n        request, so it should be safe to retry.\n        \"\"\"\n        if isinstance(err, ProxyError):\n            err = err.original_error\n        return isinstance(err, ConnectTimeoutError)\n\n    def _is_read_error(self, err):\n        \"\"\"Errors that occur after the request has been started, so we should\n        assume that the server began processing it.\n        \"\"\"\n        return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n    def _is_method_retryable(self, method):\n        \"\"\"Checks if a given HTTP method should be retried upon, depending if\n        it is included in the allowed_methods\n        \"\"\"\n        # TODO: For now favor if the Retry implementation sets its own method_whitelist\n        # property outside of our constructor to avoid breaking custom implementations.\n        if \"method_whitelist\" in self.__dict__:\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n            )\n            allowed_methods = self.method_whitelist\n        else:\n            allowed_methods = self.allowed_methods\n\n        if allowed_methods and method.upper() not in allowed_methods:\n            return False\n        return True\n\n    def is_retry(self, method, status_code, has_retry_after=False):\n        \"\"\"Is this method/status code retryable? (Based on allowlists and control\n        variables such as the number of total retries to allow, whether to\n        respect the Retry-After header, whether this header is present, and\n        whether the returned status code is on the list of status codes to\n        be retried upon on the presence of the aforementioned header)\n        \"\"\"\n        if not self._is_method_retryable(method):\n            return False\n\n        if self.status_forcelist and status_code in self.status_forcelist:\n            return True\n\n        return (\n            self.total\n            and self.respect_retry_after_header\n            and has_retry_after\n            and (status_code in self.RETRY_AFTER_STATUS_CODES)\n        )\n\n    def is_exhausted(self):\n        \"\"\"Are we out of retries?\"\"\"\n        retry_counts = (\n            self.total,\n            self.connect,\n            self.read,\n            self.redirect,\n            self.status,\n            self.other,\n        )\n        retry_counts = list(filter(None, retry_counts))\n        if not retry_counts:\n            return False\n\n        return min(retry_counts) < 0\n\n    def increment(\n        self,\n        method=None,\n        url=None,\n        response=None,\n        error=None,\n        _pool=None,\n        _stacktrace=None,\n    ):\n        \"\"\"Return a new Retry object with incremented retry counters.\n\n        :param response: A response object, or None, if the server did not\n            return a response.\n        :type response: :class:`~urllib3.response.HTTPResponse`\n        :param Exception error: An error encountered during the request, or\n            None if the response was received successfully.\n\n        :return: A new ``Retry`` object.\n        \"\"\"\n        if self.total is False and error:\n            # Disabled, indicate to re-raise the error.\n            raise six.reraise(type(error), error, _stacktrace)\n\n        total = self.total\n        if total is not None:\n            total -= 1\n\n        connect = self.connect\n        read = self.read\n        redirect = self.redirect\n        status_count = self.status\n        other = self.other\n        cause = \"unknown\"\n        status = None\n        redirect_location = None\n\n        if error and self._is_connection_error(error):\n            # Connect retry?\n            if connect is False:\n                raise six.reraise(type(error), error, _stacktrace)\n            elif connect is not None:\n                connect -= 1\n\n        elif error and self._is_read_error(error):\n            # Read retry?\n            if read is False or not self._is_method_retryable(method):\n                raise six.reraise(type(error), error, _stacktrace)\n            elif read is not None:\n                read -= 1\n\n        elif error:\n            # Other retry?\n            if other is not None:\n                other -= 1\n\n        elif response and response.get_redirect_location():\n            # Redirect retry?\n            if redirect is not None:\n                redirect -= 1\n            cause = \"too many redirects\"\n            redirect_location = response.get_redirect_location()\n            status = response.status\n\n        else:\n            # Incrementing because of a server error like a 500 in\n            # status_forcelist and the given method is in the allowed_methods\n            cause = ResponseError.GENERIC_ERROR\n            if response and response.status:\n                if status_count is not None:\n                    status_count -= 1\n                cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n                status = response.status\n\n        history = self.history + (\n            RequestHistory(method, url, error, status, redirect_location),\n        )\n\n        new_retry = self.new(\n            total=total,\n            connect=connect,\n            read=read,\n            redirect=redirect,\n            status=status_count,\n            other=other,\n            history=history,\n        )\n\n        if new_retry.is_exhausted():\n            raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n        log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n        return new_retry\n\n    def __repr__(self):\n        return (\n            \"{cls.__name__}(total={self.total}, connect={self.connect}, \"\n            \"read={self.read}, redirect={self.redirect}, status={self.status})\"\n        ).format(cls=type(self), self=self)\n\n    def __getattr__(self, item):\n        if item == \"method_whitelist\":\n            # TODO: Remove this deprecated alias in v2.0\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n            )\n            return self.allowed_methods\n        try:\n            return getattr(super(Retry, self), item)\n        except AttributeError:\n            return getattr(Retry, item)\n\n\n# For backwards compatibility (equivalent to pre-v1.9):\nRetry.DEFAULT = Retry(3)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/ssl_.py",
    "content": "from __future__ import absolute_import\n\nimport hashlib\nimport hmac\nimport os\nimport sys\nimport warnings\nfrom binascii import hexlify, unhexlify\n\nfrom ..exceptions import (\n    InsecurePlatformWarning,\n    ProxySchemeUnsupported,\n    SNIMissingWarning,\n    SSLError,\n)\nfrom ..packages import six\nfrom .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE\n\nSSLContext = None\nSSLTransport = None\nHAS_SNI = False\nIS_PYOPENSSL = False\nIS_SECURETRANSPORT = False\nALPN_PROTOCOLS = [\"http/1.1\"]\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {\n    length: getattr(hashlib, algorithm, None)\n    for length, algorithm in ((32, \"md5\"), (40, \"sha1\"), (64, \"sha256\"))\n}\n\n\ndef _const_compare_digest_backport(a, b):\n    \"\"\"\n    Compare two digests of equal length in constant time.\n\n    The digests must be of type str/bytes.\n    Returns True if the digests match, and False otherwise.\n    \"\"\"\n    result = abs(len(a) - len(b))\n    for left, right in zip(bytearray(a), bytearray(b)):\n        result |= left ^ right\n    return result == 0\n\n\n_const_compare_digest = getattr(hmac, \"compare_digest\", _const_compare_digest_backport)\n\ntry:  # Test for SSL features\n    import ssl\n    from ssl import CERT_REQUIRED, wrap_socket\nexcept ImportError:\n    pass\n\ntry:\n    from ssl import HAS_SNI  # Has SNI?\nexcept ImportError:\n    pass\n\ntry:\n    from .ssltransport import SSLTransport\nexcept ImportError:\n    pass\n\n\ntry:  # Platform-specific: Python 3.6\n    from ssl import PROTOCOL_TLS\n\n    PROTOCOL_SSLv23 = PROTOCOL_TLS\nexcept ImportError:\n    try:\n        from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS\n\n        PROTOCOL_SSLv23 = PROTOCOL_TLS\n    except ImportError:\n        PROTOCOL_SSLv23 = PROTOCOL_TLS = 2\n\ntry:\n    from ssl import PROTOCOL_TLS_CLIENT\nexcept ImportError:\n    PROTOCOL_TLS_CLIENT = PROTOCOL_TLS\n\n\ntry:\n    from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3\nexcept ImportError:\n    OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000\n    OP_NO_COMPRESSION = 0x20000\n\n\ntry:  # OP_NO_TICKET was added in Python 3.6\n    from ssl import OP_NO_TICKET\nexcept ImportError:\n    OP_NO_TICKET = 0x4000\n\n\n# A secure default.\n# Sources for more information on TLS ciphers:\n#\n# - https://wiki.mozilla.org/Security/Server_Side_TLS\n# - https://www.ssllabs.com/projects/best-practices/index.html\n# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/\n#\n# The general intent is:\n# - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),\n# - prefer ECDHE over DHE for better performance,\n# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and\n#   security,\n# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,\n# - disable NULL authentication, MD5 MACs, DSS, and other\n#   insecure ciphers for security reasons.\n# - NOTE: TLS 1.3 cipher suites are managed through a different interface\n#   not exposed by CPython (yet!) and are enabled by default if they're available.\nDEFAULT_CIPHERS = \":\".join(\n    [\n        \"ECDHE+AESGCM\",\n        \"ECDHE+CHACHA20\",\n        \"DHE+AESGCM\",\n        \"DHE+CHACHA20\",\n        \"ECDH+AESGCM\",\n        \"DH+AESGCM\",\n        \"ECDH+AES\",\n        \"DH+AES\",\n        \"RSA+AESGCM\",\n        \"RSA+AES\",\n        \"!aNULL\",\n        \"!eNULL\",\n        \"!MD5\",\n        \"!DSS\",\n    ]\n)\n\ntry:\n    from ssl import SSLContext  # Modern SSL?\nexcept ImportError:\n\n    class SSLContext(object):  # Platform-specific: Python 2\n        def __init__(self, protocol_version):\n            self.protocol = protocol_version\n            # Use default values from a real SSLContext\n            self.check_hostname = False\n            self.verify_mode = ssl.CERT_NONE\n            self.ca_certs = None\n            self.options = 0\n            self.certfile = None\n            self.keyfile = None\n            self.ciphers = None\n\n        def load_cert_chain(self, certfile, keyfile):\n            self.certfile = certfile\n            self.keyfile = keyfile\n\n        def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n            self.ca_certs = cafile\n\n            if capath is not None:\n                raise SSLError(\"CA directories not supported in older Pythons\")\n\n            if cadata is not None:\n                raise SSLError(\"CA data not supported in older Pythons\")\n\n        def set_ciphers(self, cipher_suite):\n            self.ciphers = cipher_suite\n\n        def wrap_socket(self, socket, server_hostname=None, server_side=False):\n            warnings.warn(\n                \"A true SSLContext object is not available. This prevents \"\n                \"urllib3 from configuring SSL appropriately and may cause \"\n                \"certain SSL connections to fail. You can upgrade to a newer \"\n                \"version of Python to solve this. For more information, see \"\n                \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                \"#ssl-warnings\",\n                InsecurePlatformWarning,\n            )\n            kwargs = {\n                \"keyfile\": self.keyfile,\n                \"certfile\": self.certfile,\n                \"ca_certs\": self.ca_certs,\n                \"cert_reqs\": self.verify_mode,\n                \"ssl_version\": self.protocol,\n                \"server_side\": server_side,\n            }\n            return wrap_socket(socket, ciphers=self.ciphers, **kwargs)\n\n\ndef assert_fingerprint(cert, fingerprint):\n    \"\"\"\n    Checks if given fingerprint matches the supplied certificate.\n\n    :param cert:\n        Certificate as bytes object.\n    :param fingerprint:\n        Fingerprint as string of hexdigits, can be interspersed by colons.\n    \"\"\"\n\n    fingerprint = fingerprint.replace(\":\", \"\").lower()\n    digest_length = len(fingerprint)\n    if digest_length not in HASHFUNC_MAP:\n        raise SSLError(\"Fingerprint of invalid length: {0}\".format(fingerprint))\n    hashfunc = HASHFUNC_MAP.get(digest_length)\n    if hashfunc is None:\n        raise SSLError(\n            \"Hash function implementation unavailable for fingerprint length: {0}\".format(\n                digest_length\n            )\n        )\n\n    # We need encode() here for py32; works on py2 and p33.\n    fingerprint_bytes = unhexlify(fingerprint.encode())\n\n    cert_digest = hashfunc(cert).digest()\n\n    if not _const_compare_digest(cert_digest, fingerprint_bytes):\n        raise SSLError(\n            'Fingerprints did not match. Expected \"{0}\", got \"{1}\".'.format(\n                fingerprint, hexlify(cert_digest)\n            )\n        )\n\n\ndef resolve_cert_reqs(candidate):\n    \"\"\"\n    Resolves the argument to a numeric constant, which can be passed to\n    the wrap_socket function/method from the ssl module.\n    Defaults to :data:`ssl.CERT_REQUIRED`.\n    If given a string it is assumed to be the name of the constant in the\n    :mod:`ssl` module or its abbreviation.\n    (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n    If it's neither `None` nor a string we assume it is already the numeric\n    constant which can directly be passed to wrap_socket.\n    \"\"\"\n    if candidate is None:\n        return CERT_REQUIRED\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, \"CERT_\" + candidate)\n        return res\n\n    return candidate\n\n\ndef resolve_ssl_version(candidate):\n    \"\"\"\n    like resolve_cert_reqs\n    \"\"\"\n    if candidate is None:\n        return PROTOCOL_TLS\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, \"PROTOCOL_\" + candidate)\n        return res\n\n    return candidate\n\n\ndef create_urllib3_context(\n    ssl_version=None, cert_reqs=None, options=None, ciphers=None\n):\n    \"\"\"All arguments have the same meaning as ``ssl_wrap_socket``.\n\n    By default, this function does a lot of the same work that\n    ``ssl.create_default_context`` does on Python 3.4+. It:\n\n    - Disables SSLv2, SSLv3, and compression\n    - Sets a restricted set of server ciphers\n\n    If you wish to enable SSLv3, you can do::\n\n        from pip._vendor.urllib3.util import ssl_\n        context = ssl_.create_urllib3_context()\n        context.options &= ~ssl_.OP_NO_SSLv3\n\n    You can do the same to enable compression (substituting ``COMPRESSION``\n    for ``SSLv3`` in the last line above).\n\n    :param ssl_version:\n        The desired protocol version to use. This will default to\n        PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n        the server and your installation of OpenSSL support.\n    :param cert_reqs:\n        Whether to require the certificate verification. This defaults to\n        ``ssl.CERT_REQUIRED``.\n    :param options:\n        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.\n    :param ciphers:\n        Which cipher suites to allow the server to select.\n    :returns:\n        Constructed SSLContext object with specified options\n    :rtype: SSLContext\n    \"\"\"\n    # PROTOCOL_TLS is deprecated in Python 3.10\n    if not ssl_version or ssl_version == PROTOCOL_TLS:\n        ssl_version = PROTOCOL_TLS_CLIENT\n\n    context = SSLContext(ssl_version)\n\n    context.set_ciphers(ciphers or DEFAULT_CIPHERS)\n\n    # Setting the default here, as we may have no ssl module on import\n    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n    if options is None:\n        options = 0\n        # SSLv2 is easily broken and is considered harmful and dangerous\n        options |= OP_NO_SSLv2\n        # SSLv3 has several problems and is now dangerous\n        options |= OP_NO_SSLv3\n        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n        # (issue #309)\n        options |= OP_NO_COMPRESSION\n        # TLSv1.2 only. Unless set explicitly, do not request tickets.\n        # This may save some bandwidth on wire, and although the ticket is encrypted,\n        # there is a risk associated with it being on wire,\n        # if the server is not rotating its ticketing keys properly.\n        options |= OP_NO_TICKET\n\n    context.options |= options\n\n    # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is\n    # necessary for conditional client cert authentication with TLS 1.3.\n    # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older\n    # versions of Python.  We only enable on Python 3.7.4+ or if certificate\n    # verification is enabled to work around Python issue #37428\n    # See: https://bugs.python.org/issue37428\n    if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(\n        context, \"post_handshake_auth\", None\n    ) is not None:\n        context.post_handshake_auth = True\n\n    def disable_check_hostname():\n        if (\n            getattr(context, \"check_hostname\", None) is not None\n        ):  # Platform-specific: Python 3.2\n            # We do our own verification, including fingerprints and alternative\n            # hostnames. So disable it here\n            context.check_hostname = False\n\n    # The order of the below lines setting verify_mode and check_hostname\n    # matter due to safe-guards SSLContext has to prevent an SSLContext with\n    # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more\n    # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used\n    # or not so we don't know the initial state of the freshly created SSLContext.\n    if cert_reqs == ssl.CERT_REQUIRED:\n        context.verify_mode = cert_reqs\n        disable_check_hostname()\n    else:\n        disable_check_hostname()\n        context.verify_mode = cert_reqs\n\n    # Enable logging of TLS session keys via defacto standard environment variable\n    # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.\n    if hasattr(context, \"keylog_filename\"):\n        sslkeylogfile = os.environ.get(\"SSLKEYLOGFILE\")\n        if sslkeylogfile:\n            context.keylog_filename = sslkeylogfile\n\n    return context\n\n\ndef ssl_wrap_socket(\n    sock,\n    keyfile=None,\n    certfile=None,\n    cert_reqs=None,\n    ca_certs=None,\n    server_hostname=None,\n    ssl_version=None,\n    ciphers=None,\n    ssl_context=None,\n    ca_cert_dir=None,\n    key_password=None,\n    ca_cert_data=None,\n    tls_in_tls=False,\n):\n    \"\"\"\n    All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n    the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n    :param server_hostname:\n        When SNI is supported, the expected hostname of the certificate\n    :param ssl_context:\n        A pre-made :class:`SSLContext` object. If none is provided, one will\n        be created using :func:`create_urllib3_context`.\n    :param ciphers:\n        A string of ciphers we wish the client to support.\n    :param ca_cert_dir:\n        A directory containing CA certificates in multiple separate files, as\n        supported by OpenSSL's -CApath flag or the capath argument to\n        SSLContext.load_verify_locations().\n    :param key_password:\n        Optional password if the keyfile is encrypted.\n    :param ca_cert_data:\n        Optional string containing CA certificates in PEM format suitable for\n        passing as the cadata parameter to SSLContext.load_verify_locations()\n    :param tls_in_tls:\n        Use SSLTransport to wrap the existing socket.\n    \"\"\"\n    context = ssl_context\n    if context is None:\n        # Note: This branch of code and all the variables in it are no longer\n        # used by urllib3 itself. We should consider deprecating and removing\n        # this code.\n        context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)\n\n    if ca_certs or ca_cert_dir or ca_cert_data:\n        try:\n            context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)\n        except (IOError, OSError) as e:\n            raise SSLError(e)\n\n    elif ssl_context is None and hasattr(context, \"load_default_certs\"):\n        # try to load OS default certs; works well on Windows (require Python3.4+)\n        context.load_default_certs()\n\n    # Attempt to detect if we get the goofy behavior of the\n    # keyfile being encrypted and OpenSSL asking for the\n    # passphrase via the terminal and instead error out.\n    if keyfile and key_password is None and _is_key_file_encrypted(keyfile):\n        raise SSLError(\"Client private key is encrypted, password is required\")\n\n    if certfile:\n        if key_password is None:\n            context.load_cert_chain(certfile, keyfile)\n        else:\n            context.load_cert_chain(certfile, keyfile, key_password)\n\n    try:\n        if hasattr(context, \"set_alpn_protocols\"):\n            context.set_alpn_protocols(ALPN_PROTOCOLS)\n    except NotImplementedError:  # Defensive: in CI, we always have set_alpn_protocols\n        pass\n\n    # If we detect server_hostname is an IP address then the SNI\n    # extension should not be used according to RFC3546 Section 3.1\n    use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)\n    # SecureTransport uses server_hostname in certificate verification.\n    send_sni = (use_sni_hostname and HAS_SNI) or (\n        IS_SECURETRANSPORT and server_hostname\n    )\n    # Do not warn the user if server_hostname is an invalid SNI hostname.\n    if not HAS_SNI and use_sni_hostname:\n        warnings.warn(\n            \"An HTTPS request has been made, but the SNI (Server Name \"\n            \"Indication) extension to TLS is not available on this platform. \"\n            \"This may cause the server to present an incorrect TLS \"\n            \"certificate, which can cause validation failures. You can upgrade to \"\n            \"a newer version of Python to solve this. For more information, see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n            \"#ssl-warnings\",\n            SNIMissingWarning,\n        )\n\n    if send_sni:\n        ssl_sock = _ssl_wrap_socket_impl(\n            sock, context, tls_in_tls, server_hostname=server_hostname\n        )\n    else:\n        ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)\n    return ssl_sock\n\n\ndef is_ipaddress(hostname):\n    \"\"\"Detects whether the hostname given is an IPv4 or IPv6 address.\n    Also detects IPv6 addresses with Zone IDs.\n\n    :param str hostname: Hostname to examine.\n    :return: True if the hostname is an IP address, False otherwise.\n    \"\"\"\n    if not six.PY2 and isinstance(hostname, bytes):\n        # IDN A-label bytes are ASCII compatible.\n        hostname = hostname.decode(\"ascii\")\n    return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))\n\n\ndef _is_key_file_encrypted(key_file):\n    \"\"\"Detects if a key file is encrypted or not.\"\"\"\n    with open(key_file, \"r\") as f:\n        for line in f:\n            # Look for Proc-Type: 4,ENCRYPTED\n            if \"ENCRYPTED\" in line:\n                return True\n\n    return False\n\n\ndef _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):\n    if tls_in_tls:\n        if not SSLTransport:\n            # Import error, ssl is not available.\n            raise ProxySchemeUnsupported(\n                \"TLS in TLS requires support for the 'ssl' module\"\n            )\n\n        SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)\n        return SSLTransport(sock, ssl_context, server_hostname)\n\n    if server_hostname:\n        return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n    else:\n        return ssl_context.wrap_socket(sock)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/ssl_match_hostname.py",
    "content": "\"\"\"The match_hostname() function from Python 3.3.3, essential when using SSL.\"\"\"\n\n# Note: This file is under the PSF license as the code comes from the python\n# stdlib.   http://docs.python.org/3/license.html\n\nimport re\nimport sys\n\n# ipaddress has been backported to 2.6+ in pypi.  If it is installed on the\n# system, use it to handle IPAddress ServerAltnames (this was added in\n# python-3.5) otherwise only do DNS matching.  This allows\n# util.ssl_match_hostname to continue to be used in Python 2.7.\ntry:\n    import ipaddress\nexcept ImportError:\n    ipaddress = None\n\n__version__ = \"3.5.0.1\"\n\n\nclass CertificateError(ValueError):\n    pass\n\n\ndef _dnsname_match(dn, hostname, max_wildcards=1):\n    \"\"\"Matching according to RFC 6125, section 6.4.3\n\n    http://tools.ietf.org/html/rfc6125#section-6.4.3\n    \"\"\"\n    pats = []\n    if not dn:\n        return False\n\n    # Ported from python3-syntax:\n    # leftmost, *remainder = dn.split(r'.')\n    parts = dn.split(r\".\")\n    leftmost = parts[0]\n    remainder = parts[1:]\n\n    wildcards = leftmost.count(\"*\")\n    if wildcards > max_wildcards:\n        # Issue #17980: avoid denials of service by refusing more\n        # than one wildcard per fragment.  A survey of established\n        # policy among SSL implementations showed it to be a\n        # reasonable choice.\n        raise CertificateError(\n            \"too many wildcards in certificate DNS name: \" + repr(dn)\n        )\n\n    # speed up common case w/o wildcards\n    if not wildcards:\n        return dn.lower() == hostname.lower()\n\n    # RFC 6125, section 6.4.3, subitem 1.\n    # The client SHOULD NOT attempt to match a presented identifier in which\n    # the wildcard character comprises a label other than the left-most label.\n    if leftmost == \"*\":\n        # When '*' is a fragment by itself, it matches a non-empty dotless\n        # fragment.\n        pats.append(\"[^.]+\")\n    elif leftmost.startswith(\"xn--\") or hostname.startswith(\"xn--\"):\n        # RFC 6125, section 6.4.3, subitem 3.\n        # The client SHOULD NOT attempt to match a presented identifier\n        # where the wildcard character is embedded within an A-label or\n        # U-label of an internationalized domain name.\n        pats.append(re.escape(leftmost))\n    else:\n        # Otherwise, '*' matches any dotless string, e.g. www*\n        pats.append(re.escape(leftmost).replace(r\"\\*\", \"[^.]*\"))\n\n    # add the remaining fragments, ignore any wildcards\n    for frag in remainder:\n        pats.append(re.escape(frag))\n\n    pat = re.compile(r\"\\A\" + r\"\\.\".join(pats) + r\"\\Z\", re.IGNORECASE)\n    return pat.match(hostname)\n\n\ndef _to_unicode(obj):\n    if isinstance(obj, str) and sys.version_info < (3,):\n        # ignored flake8 # F821 to support python 2.7 function\n        obj = unicode(obj, encoding=\"ascii\", errors=\"strict\")  # noqa: F821\n    return obj\n\n\ndef _ipaddress_match(ipname, host_ip):\n    \"\"\"Exact matching of IP addresses.\n\n    RFC 6125 explicitly doesn't define an algorithm for this\n    (section 1.7.2 - \"Out of Scope\").\n    \"\"\"\n    # OpenSSL may add a trailing newline to a subjectAltName's IP address\n    # Divergence from upstream: ipaddress can't handle byte str\n    ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())\n    return ip == host_ip\n\n\ndef match_hostname(cert, hostname):\n    \"\"\"Verify that *cert* (in decoded format as returned by\n    SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125\n    rules are followed, but IP addresses are not accepted for *hostname*.\n\n    CertificateError is raised on failure. On success, the function\n    returns nothing.\n    \"\"\"\n    if not cert:\n        raise ValueError(\n            \"empty or no certificate, match_hostname needs a \"\n            \"SSL socket or SSL context with either \"\n            \"CERT_OPTIONAL or CERT_REQUIRED\"\n        )\n    try:\n        # Divergence from upstream: ipaddress can't handle byte str\n        host_ip = ipaddress.ip_address(_to_unicode(hostname))\n    except (UnicodeError, ValueError):\n        # ValueError: Not an IP address (common case)\n        # UnicodeError: Divergence from upstream: Have to deal with ipaddress not taking\n        # byte strings.  addresses should be all ascii, so we consider it not\n        # an ipaddress in this case\n        host_ip = None\n    except AttributeError:\n        # Divergence from upstream: Make ipaddress library optional\n        if ipaddress is None:\n            host_ip = None\n        else:  # Defensive\n            raise\n    dnsnames = []\n    san = cert.get(\"subjectAltName\", ())\n    for key, value in san:\n        if key == \"DNS\":\n            if host_ip is None and _dnsname_match(value, hostname):\n                return\n            dnsnames.append(value)\n        elif key == \"IP Address\":\n            if host_ip is not None and _ipaddress_match(value, host_ip):\n                return\n            dnsnames.append(value)\n    if not dnsnames:\n        # The subject is only checked when there is no dNSName entry\n        # in subjectAltName\n        for sub in cert.get(\"subject\", ()):\n            for key, value in sub:\n                # XXX according to RFC 2818, the most specific Common Name\n                # must be used.\n                if key == \"commonName\":\n                    if _dnsname_match(value, hostname):\n                        return\n                    dnsnames.append(value)\n    if len(dnsnames) > 1:\n        raise CertificateError(\n            \"hostname %r \"\n            \"doesn't match either of %s\" % (hostname, \", \".join(map(repr, dnsnames)))\n        )\n    elif len(dnsnames) == 1:\n        raise CertificateError(\"hostname %r doesn't match %r\" % (hostname, dnsnames[0]))\n    else:\n        raise CertificateError(\n            \"no appropriate commonName or subjectAltName fields were found\"\n        )\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/ssltransport.py",
    "content": "import io\nimport socket\nimport ssl\n\nfrom ..exceptions import ProxySchemeUnsupported\nfrom ..packages import six\n\nSSL_BLOCKSIZE = 16384\n\n\nclass SSLTransport:\n    \"\"\"\n    The SSLTransport wraps an existing socket and establishes an SSL connection.\n\n    Contrary to Python's implementation of SSLSocket, it allows you to chain\n    multiple TLS connections together. It's particularly useful if you need to\n    implement TLS within TLS.\n\n    The class supports most of the socket API operations.\n    \"\"\"\n\n    @staticmethod\n    def _validate_ssl_context_for_tls_in_tls(ssl_context):\n        \"\"\"\n        Raises a ProxySchemeUnsupported if the provided ssl_context can't be used\n        for TLS in TLS.\n\n        The only requirement is that the ssl_context provides the 'wrap_bio'\n        methods.\n        \"\"\"\n\n        if not hasattr(ssl_context, \"wrap_bio\"):\n            if six.PY2:\n                raise ProxySchemeUnsupported(\n                    \"TLS in TLS requires SSLContext.wrap_bio() which isn't \"\n                    \"supported on Python 2\"\n                )\n            else:\n                raise ProxySchemeUnsupported(\n                    \"TLS in TLS requires SSLContext.wrap_bio() which isn't \"\n                    \"available on non-native SSLContext\"\n                )\n\n    def __init__(\n        self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True\n    ):\n        \"\"\"\n        Create an SSLTransport around socket using the provided ssl_context.\n        \"\"\"\n        self.incoming = ssl.MemoryBIO()\n        self.outgoing = ssl.MemoryBIO()\n\n        self.suppress_ragged_eofs = suppress_ragged_eofs\n        self.socket = socket\n\n        self.sslobj = ssl_context.wrap_bio(\n            self.incoming, self.outgoing, server_hostname=server_hostname\n        )\n\n        # Perform initial handshake.\n        self._ssl_io_loop(self.sslobj.do_handshake)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *_):\n        self.close()\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    def read(self, len=1024, buffer=None):\n        return self._wrap_ssl_read(len, buffer)\n\n    def recv(self, len=1024, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to recv\")\n        return self._wrap_ssl_read(len)\n\n    def recv_into(self, buffer, nbytes=None, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to recv_into\")\n        if buffer and (nbytes is None):\n            nbytes = len(buffer)\n        elif nbytes is None:\n            nbytes = 1024\n        return self.read(nbytes, buffer)\n\n    def sendall(self, data, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to sendall\")\n        count = 0\n        with memoryview(data) as view, view.cast(\"B\") as byte_view:\n            amount = len(byte_view)\n            while count < amount:\n                v = self.send(byte_view[count:])\n                count += v\n\n    def send(self, data, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to send\")\n        response = self._ssl_io_loop(self.sslobj.write, data)\n        return response\n\n    def makefile(\n        self, mode=\"r\", buffering=None, encoding=None, errors=None, newline=None\n    ):\n        \"\"\"\n        Python's httpclient uses makefile and buffered io when reading HTTP\n        messages and we need to support it.\n\n        This is unfortunately a copy and paste of socket.py makefile with small\n        changes to point to the socket directly.\n        \"\"\"\n        if not set(mode) <= {\"r\", \"w\", \"b\"}:\n            raise ValueError(\"invalid mode %r (only r, w, b allowed)\" % (mode,))\n\n        writing = \"w\" in mode\n        reading = \"r\" in mode or not writing\n        assert reading or writing\n        binary = \"b\" in mode\n        rawmode = \"\"\n        if reading:\n            rawmode += \"r\"\n        if writing:\n            rawmode += \"w\"\n        raw = socket.SocketIO(self, rawmode)\n        self.socket._io_refs += 1\n        if buffering is None:\n            buffering = -1\n        if buffering < 0:\n            buffering = io.DEFAULT_BUFFER_SIZE\n        if buffering == 0:\n            if not binary:\n                raise ValueError(\"unbuffered streams must be binary\")\n            return raw\n        if reading and writing:\n            buffer = io.BufferedRWPair(raw, raw, buffering)\n        elif reading:\n            buffer = io.BufferedReader(raw, buffering)\n        else:\n            assert writing\n            buffer = io.BufferedWriter(raw, buffering)\n        if binary:\n            return buffer\n        text = io.TextIOWrapper(buffer, encoding, errors, newline)\n        text.mode = mode\n        return text\n\n    def unwrap(self):\n        self._ssl_io_loop(self.sslobj.unwrap)\n\n    def close(self):\n        self.socket.close()\n\n    def getpeercert(self, binary_form=False):\n        return self.sslobj.getpeercert(binary_form)\n\n    def version(self):\n        return self.sslobj.version()\n\n    def cipher(self):\n        return self.sslobj.cipher()\n\n    def selected_alpn_protocol(self):\n        return self.sslobj.selected_alpn_protocol()\n\n    def selected_npn_protocol(self):\n        return self.sslobj.selected_npn_protocol()\n\n    def shared_ciphers(self):\n        return self.sslobj.shared_ciphers()\n\n    def compression(self):\n        return self.sslobj.compression()\n\n    def settimeout(self, value):\n        self.socket.settimeout(value)\n\n    def gettimeout(self):\n        return self.socket.gettimeout()\n\n    def _decref_socketios(self):\n        self.socket._decref_socketios()\n\n    def _wrap_ssl_read(self, len, buffer=None):\n        try:\n            return self._ssl_io_loop(self.sslobj.read, len, buffer)\n        except ssl.SSLError as e:\n            if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:\n                return 0  # eof, return 0.\n            else:\n                raise\n\n    def _ssl_io_loop(self, func, *args):\n        \"\"\"Performs an I/O loop between incoming/outgoing and the socket.\"\"\"\n        should_loop = True\n        ret = None\n\n        while should_loop:\n            errno = None\n            try:\n                ret = func(*args)\n            except ssl.SSLError as e:\n                if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):\n                    # WANT_READ, and WANT_WRITE are expected, others are not.\n                    raise e\n                errno = e.errno\n\n            buf = self.outgoing.read()\n            self.socket.sendall(buf)\n\n            if errno is None:\n                should_loop = False\n            elif errno == ssl.SSL_ERROR_WANT_READ:\n                buf = self.socket.recv(SSL_BLOCKSIZE)\n                if buf:\n                    self.incoming.write(buf)\n                else:\n                    self.incoming.write_eof()\n        return ret\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/timeout.py",
    "content": "from __future__ import absolute_import\n\nimport time\n\n# The default socket timeout, used by httplib to indicate that no timeout was; specified by the user\nfrom socket import _GLOBAL_DEFAULT_TIMEOUT, getdefaulttimeout\n\nfrom ..exceptions import TimeoutStateError\n\n# A sentinel value to indicate that no timeout was specified by the user in\n# urllib3\n_Default = object()\n\n\n# Use time.monotonic if available.\ncurrent_time = getattr(time, \"monotonic\", time.time)\n\n\nclass Timeout(object):\n    \"\"\"Timeout configuration.\n\n    Timeouts can be defined as a default for a pool:\n\n    .. code-block:: python\n\n       timeout = Timeout(connect=2.0, read=7.0)\n       http = PoolManager(timeout=timeout)\n       response = http.request('GET', 'http://example.com/')\n\n    Or per-request (which overrides the default for the pool):\n\n    .. code-block:: python\n\n       response = http.request('GET', 'http://example.com/', timeout=Timeout(10))\n\n    Timeouts can be disabled by setting all the parameters to ``None``:\n\n    .. code-block:: python\n\n       no_timeout = Timeout(connect=None, read=None)\n       response = http.request('GET', 'http://example.com/, timeout=no_timeout)\n\n\n    :param total:\n        This combines the connect and read timeouts into one; the read timeout\n        will be set to the time leftover from the connect attempt. In the\n        event that both a connect timeout and a total are specified, or a read\n        timeout and a total are specified, the shorter timeout will be applied.\n\n        Defaults to None.\n\n    :type total: int, float, or None\n\n    :param connect:\n        The maximum amount of time (in seconds) to wait for a connection\n        attempt to a server to succeed. Omitting the parameter will default the\n        connect timeout to the system default, probably `the global default\n        timeout in socket.py\n        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n        None will set an infinite timeout for connection attempts.\n\n    :type connect: int, float, or None\n\n    :param read:\n        The maximum amount of time (in seconds) to wait between consecutive\n        read operations for a response from the server. Omitting the parameter\n        will default the read timeout to the system default, probably `the\n        global default timeout in socket.py\n        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n        None will set an infinite timeout.\n\n    :type read: int, float, or None\n\n    .. note::\n\n        Many factors can affect the total amount of time for urllib3 to return\n        an HTTP response.\n\n        For example, Python's DNS resolver does not obey the timeout specified\n        on the socket. Other factors that can affect total request time include\n        high CPU load, high swap, the program running at a low priority level,\n        or other behaviors.\n\n        In addition, the read and total timeouts only measure the time between\n        read operations on the socket connecting the client and the server,\n        not the total amount of time for the request to return a complete\n        response. For most requests, the timeout is raised because the server\n        has not sent the first byte in the specified time. This is not always\n        the case; if a server streams one byte every fifteen seconds, a timeout\n        of 20 seconds will not trigger, even though the request will take\n        several minutes to complete.\n\n        If your goal is to cut off any request after a set amount of wall clock\n        time, consider having a second \"watcher\" thread to cut off a slow\n        request.\n    \"\"\"\n\n    #: A sentinel object representing the default timeout value\n    DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT\n\n    def __init__(self, total=None, connect=_Default, read=_Default):\n        self._connect = self._validate_timeout(connect, \"connect\")\n        self._read = self._validate_timeout(read, \"read\")\n        self.total = self._validate_timeout(total, \"total\")\n        self._start_connect = None\n\n    def __repr__(self):\n        return \"%s(connect=%r, read=%r, total=%r)\" % (\n            type(self).__name__,\n            self._connect,\n            self._read,\n            self.total,\n        )\n\n    # __str__ provided for backwards compatibility\n    __str__ = __repr__\n\n    @classmethod\n    def resolve_default_timeout(cls, timeout):\n        return getdefaulttimeout() if timeout is cls.DEFAULT_TIMEOUT else timeout\n\n    @classmethod\n    def _validate_timeout(cls, value, name):\n        \"\"\"Check that a timeout attribute is valid.\n\n        :param value: The timeout value to validate\n        :param name: The name of the timeout attribute to validate. This is\n            used to specify in error messages.\n        :return: The validated and casted version of the given value.\n        :raises ValueError: If it is a numeric value less than or equal to\n            zero, or the type is not an integer, float, or None.\n        \"\"\"\n        if value is _Default:\n            return cls.DEFAULT_TIMEOUT\n\n        if value is None or value is cls.DEFAULT_TIMEOUT:\n            return value\n\n        if isinstance(value, bool):\n            raise ValueError(\n                \"Timeout cannot be a boolean value. It must \"\n                \"be an int, float or None.\"\n            )\n        try:\n            float(value)\n        except (TypeError, ValueError):\n            raise ValueError(\n                \"Timeout value %s was %s, but it must be an \"\n                \"int, float or None.\" % (name, value)\n            )\n\n        try:\n            if value <= 0:\n                raise ValueError(\n                    \"Attempted to set %s timeout to %s, but the \"\n                    \"timeout cannot be set to a value less \"\n                    \"than or equal to 0.\" % (name, value)\n                )\n        except TypeError:\n            # Python 3\n            raise ValueError(\n                \"Timeout value %s was %s, but it must be an \"\n                \"int, float or None.\" % (name, value)\n            )\n\n        return value\n\n    @classmethod\n    def from_float(cls, timeout):\n        \"\"\"Create a new Timeout from a legacy timeout value.\n\n        The timeout value used by httplib.py sets the same timeout on the\n        connect(), and recv() socket requests. This creates a :class:`Timeout`\n        object that sets the individual timeouts to the ``timeout`` value\n        passed to this function.\n\n        :param timeout: The legacy timeout value.\n        :type timeout: integer, float, sentinel default object, or None\n        :return: Timeout object\n        :rtype: :class:`Timeout`\n        \"\"\"\n        return Timeout(read=timeout, connect=timeout)\n\n    def clone(self):\n        \"\"\"Create a copy of the timeout object\n\n        Timeout properties are stored per-pool but each request needs a fresh\n        Timeout object to ensure each one has its own start/stop configured.\n\n        :return: a copy of the timeout object\n        :rtype: :class:`Timeout`\n        \"\"\"\n        # We can't use copy.deepcopy because that will also create a new object\n        # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n        # detect the user default.\n        return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n    def start_connect(self):\n        \"\"\"Start the timeout clock, used during a connect() attempt\n\n        :raises urllib3.exceptions.TimeoutStateError: if you attempt\n            to start a timer that has been started already.\n        \"\"\"\n        if self._start_connect is not None:\n            raise TimeoutStateError(\"Timeout timer has already been started.\")\n        self._start_connect = current_time()\n        return self._start_connect\n\n    def get_connect_duration(self):\n        \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n        :return: Elapsed time in seconds.\n        :rtype: float\n        :raises urllib3.exceptions.TimeoutStateError: if you attempt\n            to get duration for a timer that hasn't been started.\n        \"\"\"\n        if self._start_connect is None:\n            raise TimeoutStateError(\n                \"Can't get connect duration for timer that has not started.\"\n            )\n        return current_time() - self._start_connect\n\n    @property\n    def connect_timeout(self):\n        \"\"\"Get the value to use when setting a connection timeout.\n\n        This will be a positive float or integer, the value None\n        (never timeout), or the default system timeout.\n\n        :return: Connect timeout.\n        :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n        \"\"\"\n        if self.total is None:\n            return self._connect\n\n        if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:\n            return self.total\n\n        return min(self._connect, self.total)\n\n    @property\n    def read_timeout(self):\n        \"\"\"Get the value for the read timeout.\n\n        This assumes some time has elapsed in the connection timeout and\n        computes the read timeout appropriately.\n\n        If self.total is set, the read timeout is dependent on the amount of\n        time taken by the connect timeout. If the connection time has not been\n        established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n        raised.\n\n        :return: Value to use for the read timeout.\n        :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n        :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n            has not yet been called on this object.\n        \"\"\"\n        if (\n            self.total is not None\n            and self.total is not self.DEFAULT_TIMEOUT\n            and self._read is not None\n            and self._read is not self.DEFAULT_TIMEOUT\n        ):\n            # In case the connect timeout has not yet been established.\n            if self._start_connect is None:\n                return self._read\n            return max(0, min(self.total - self.get_connect_duration(), self._read))\n        elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:\n            return max(0, self.total - self.get_connect_duration())\n        else:\n            return self._read\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/url.py",
    "content": "from __future__ import absolute_import\n\nimport re\nfrom collections import namedtuple\n\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\n\nurl_attrs = [\"scheme\", \"auth\", \"host\", \"port\", \"path\", \"query\", \"fragment\"]\n\n# We only want to normalize urls with an HTTP(S) scheme.\n# urllib3 infers URLs without a scheme (None) to be http.\nNORMALIZABLE_SCHEMES = (\"http\", \"https\", None)\n\n# Almost all of these patterns were derived from the\n# 'rfc3986' module: https://github.com/python-hyper/rfc3986\nPERCENT_RE = re.compile(r\"%[a-fA-F0-9]{2}\")\nSCHEME_RE = re.compile(r\"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)\")\nURI_RE = re.compile(\n    r\"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?\"\n    r\"(?://([^\\\\/?#]*))?\"\n    r\"([^?#]*)\"\n    r\"(?:\\?([^#]*))?\"\n    r\"(?:#(.*))?$\",\n    re.UNICODE | re.DOTALL,\n)\n\nIPV4_PAT = r\"(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\"\nHEX_PAT = \"[0-9A-Fa-f]{1,4}\"\nLS32_PAT = \"(?:{hex}:{hex}|{ipv4})\".format(hex=HEX_PAT, ipv4=IPV4_PAT)\n_subs = {\"hex\": HEX_PAT, \"ls32\": LS32_PAT}\n_variations = [\n    #                            6( h16 \":\" ) ls32\n    \"(?:%(hex)s:){6}%(ls32)s\",\n    #                       \"::\" 5( h16 \":\" ) ls32\n    \"::(?:%(hex)s:){5}%(ls32)s\",\n    # [               h16 ] \"::\" 4( h16 \":\" ) ls32\n    \"(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s\",\n    # [ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n    \"(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s\",\n    # [ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n    \"(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s\",\n    # [ *3( h16 \":\" ) h16 ] \"::\"    h16 \":\"   ls32\n    \"(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s\",\n    # [ *4( h16 \":\" ) h16 ] \"::\"              ls32\n    \"(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s\",\n    # [ *5( h16 \":\" ) h16 ] \"::\"              h16\n    \"(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s\",\n    # [ *6( h16 \":\" ) h16 ] \"::\"\n    \"(?:(?:%(hex)s:){0,6}%(hex)s)?::\",\n]\n\nUNRESERVED_PAT = r\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\\-~\"\nIPV6_PAT = \"(?:\" + \"|\".join([x % _subs for x in _variations]) + \")\"\nZONE_ID_PAT = \"(?:%25|%)(?:[\" + UNRESERVED_PAT + \"]|%[a-fA-F0-9]{2})+\"\nIPV6_ADDRZ_PAT = r\"\\[\" + IPV6_PAT + r\"(?:\" + ZONE_ID_PAT + r\")?\\]\"\nREG_NAME_PAT = r\"(?:[^\\[\\]%:/?#]|%[a-fA-F0-9]{2})*\"\nTARGET_RE = re.compile(r\"^(/[^?#]*)(?:\\?([^#]*))?(?:#.*)?$\")\n\nIPV4_RE = re.compile(\"^\" + IPV4_PAT + \"$\")\nIPV6_RE = re.compile(\"^\" + IPV6_PAT + \"$\")\nIPV6_ADDRZ_RE = re.compile(\"^\" + IPV6_ADDRZ_PAT + \"$\")\nBRACELESS_IPV6_ADDRZ_RE = re.compile(\"^\" + IPV6_ADDRZ_PAT[2:-2] + \"$\")\nZONE_ID_RE = re.compile(\"(\" + ZONE_ID_PAT + r\")\\]$\")\n\n_HOST_PORT_PAT = (\"^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$\") % (\n    REG_NAME_PAT,\n    IPV4_PAT,\n    IPV6_ADDRZ_PAT,\n)\n_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)\n\nUNRESERVED_CHARS = set(\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~\"\n)\nSUB_DELIM_CHARS = set(\"!$&'()*+,;=\")\nUSERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {\":\"}\nPATH_CHARS = USERINFO_CHARS | {\"@\", \"/\"}\nQUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {\"?\"}\n\n\nclass Url(namedtuple(\"Url\", url_attrs)):\n    \"\"\"\n    Data structure for representing an HTTP URL. Used as a return value for\n    :func:`parse_url`. Both the scheme and host are normalized as they are\n    both case-insensitive according to RFC 3986.\n    \"\"\"\n\n    __slots__ = ()\n\n    def __new__(\n        cls,\n        scheme=None,\n        auth=None,\n        host=None,\n        port=None,\n        path=None,\n        query=None,\n        fragment=None,\n    ):\n        if path and not path.startswith(\"/\"):\n            path = \"/\" + path\n        if scheme is not None:\n            scheme = scheme.lower()\n        return super(Url, cls).__new__(\n            cls, scheme, auth, host, port, path, query, fragment\n        )\n\n    @property\n    def hostname(self):\n        \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n        return self.host\n\n    @property\n    def request_uri(self):\n        \"\"\"Absolute path including the query string.\"\"\"\n        uri = self.path or \"/\"\n\n        if self.query is not None:\n            uri += \"?\" + self.query\n\n        return uri\n\n    @property\n    def netloc(self):\n        \"\"\"Network location including host and port\"\"\"\n        if self.port:\n            return \"%s:%d\" % (self.host, self.port)\n        return self.host\n\n    @property\n    def url(self):\n        \"\"\"\n        Convert self into a url\n\n        This function should more or less round-trip with :func:`.parse_url`. The\n        returned url may not be exactly the same as the url inputted to\n        :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n        with a blank port will have : removed).\n\n        Example: ::\n\n            >>> U = parse_url('http://google.com/mail/')\n            >>> U.url\n            'http://google.com/mail/'\n            >>> Url('http', 'username:password', 'host.com', 80,\n            ... '/path', 'query', 'fragment').url\n            'http://username:password@host.com:80/path?query#fragment'\n        \"\"\"\n        scheme, auth, host, port, path, query, fragment = self\n        url = u\"\"\n\n        # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n        if scheme is not None:\n            url += scheme + u\"://\"\n        if auth is not None:\n            url += auth + u\"@\"\n        if host is not None:\n            url += host\n        if port is not None:\n            url += u\":\" + str(port)\n        if path is not None:\n            url += path\n        if query is not None:\n            url += u\"?\" + query\n        if fragment is not None:\n            url += u\"#\" + fragment\n\n        return url\n\n    def __str__(self):\n        return self.url\n\n\ndef split_first(s, delims):\n    \"\"\"\n    .. deprecated:: 1.25\n\n    Given a string and an iterable of delimiters, split on the first found\n    delimiter. Return two split parts and the matched delimiter.\n\n    If not found, then the first part is the full input string.\n\n    Example::\n\n        >>> split_first('foo/bar?baz', '?/=')\n        ('foo', 'bar?baz', '/')\n        >>> split_first('foo/bar?baz', '123')\n        ('foo/bar?baz', '', None)\n\n    Scales linearly with number of delims. Not ideal for large number of delims.\n    \"\"\"\n    min_idx = None\n    min_delim = None\n    for d in delims:\n        idx = s.find(d)\n        if idx < 0:\n            continue\n\n        if min_idx is None or idx < min_idx:\n            min_idx = idx\n            min_delim = d\n\n    if min_idx is None or min_idx < 0:\n        return s, \"\", None\n\n    return s[:min_idx], s[min_idx + 1 :], min_delim\n\n\ndef _encode_invalid_chars(component, allowed_chars, encoding=\"utf-8\"):\n    \"\"\"Percent-encodes a URI component without reapplying\n    onto an already percent-encoded component.\n    \"\"\"\n    if component is None:\n        return component\n\n    component = six.ensure_text(component)\n\n    # Normalize existing percent-encoded bytes.\n    # Try to see if the component we're encoding is already percent-encoded\n    # so we can skip all '%' characters but still encode all others.\n    component, percent_encodings = PERCENT_RE.subn(\n        lambda match: match.group(0).upper(), component\n    )\n\n    uri_bytes = component.encode(\"utf-8\", \"surrogatepass\")\n    is_percent_encoded = percent_encodings == uri_bytes.count(b\"%\")\n    encoded_component = bytearray()\n\n    for i in range(0, len(uri_bytes)):\n        # Will return a single character bytestring on both Python 2 & 3\n        byte = uri_bytes[i : i + 1]\n        byte_ord = ord(byte)\n        if (is_percent_encoded and byte == b\"%\") or (\n            byte_ord < 128 and byte.decode() in allowed_chars\n        ):\n            encoded_component += byte\n            continue\n        encoded_component.extend(b\"%\" + (hex(byte_ord)[2:].encode().zfill(2).upper()))\n\n    return encoded_component.decode(encoding)\n\n\ndef _remove_path_dot_segments(path):\n    # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code\n    segments = path.split(\"/\")  # Turn the path into a list of segments\n    output = []  # Initialize the variable to use to store output\n\n    for segment in segments:\n        # '.' is the current directory, so ignore it, it is superfluous\n        if segment == \".\":\n            continue\n        # Anything other than '..', should be appended to the output\n        elif segment != \"..\":\n            output.append(segment)\n        # In this case segment == '..', if we can, we should pop the last\n        # element\n        elif output:\n            output.pop()\n\n    # If the path starts with '/' and the output is empty or the first string\n    # is non-empty\n    if path.startswith(\"/\") and (not output or output[0]):\n        output.insert(0, \"\")\n\n    # If the path starts with '/.' or '/..' ensure we add one more empty\n    # string to add a trailing '/'\n    if path.endswith((\"/.\", \"/..\")):\n        output.append(\"\")\n\n    return \"/\".join(output)\n\n\ndef _normalize_host(host, scheme):\n    if host:\n        if isinstance(host, six.binary_type):\n            host = six.ensure_str(host)\n\n        if scheme in NORMALIZABLE_SCHEMES:\n            is_ipv6 = IPV6_ADDRZ_RE.match(host)\n            if is_ipv6:\n                # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as\n                # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID\n                # separator as necessary to return a valid RFC 4007 scoped IP.\n                match = ZONE_ID_RE.search(host)\n                if match:\n                    start, end = match.span(1)\n                    zone_id = host[start:end]\n\n                    if zone_id.startswith(\"%25\") and zone_id != \"%25\":\n                        zone_id = zone_id[3:]\n                    else:\n                        zone_id = zone_id[1:]\n                    zone_id = \"%\" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS)\n                    return host[:start].lower() + zone_id + host[end:]\n                else:\n                    return host.lower()\n            elif not IPV4_RE.match(host):\n                return six.ensure_str(\n                    b\".\".join([_idna_encode(label) for label in host.split(\".\")])\n                )\n    return host\n\n\ndef _idna_encode(name):\n    if name and any(ord(x) >= 128 for x in name):\n        try:\n            from pip._vendor import idna\n        except ImportError:\n            six.raise_from(\n                LocationParseError(\"Unable to parse URL without the 'idna' module\"),\n                None,\n            )\n        try:\n            return idna.encode(name.lower(), strict=True, std3_rules=True)\n        except idna.IDNAError:\n            six.raise_from(\n                LocationParseError(u\"Name '%s' is not a valid IDNA label\" % name), None\n            )\n    return name.lower().encode(\"ascii\")\n\n\ndef _encode_target(target):\n    \"\"\"Percent-encodes a request target so that there are no invalid characters\"\"\"\n    path, query = TARGET_RE.match(target).groups()\n    target = _encode_invalid_chars(path, PATH_CHARS)\n    query = _encode_invalid_chars(query, QUERY_CHARS)\n    if query is not None:\n        target += \"?\" + query\n    return target\n\n\ndef parse_url(url):\n    \"\"\"\n    Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n    performed to parse incomplete urls. Fields not provided will be None.\n    This parser is RFC 3986 and RFC 6874 compliant.\n\n    The parser logic and helper functions are based heavily on\n    work done in the ``rfc3986`` module.\n\n    :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n    Partly backwards-compatible with :mod:`urlparse`.\n\n    Example::\n\n        >>> parse_url('http://google.com/mail/')\n        Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n        >>> parse_url('google.com:80')\n        Url(scheme=None, host='google.com', port=80, path=None, ...)\n        >>> parse_url('/foo?bar')\n        Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n    \"\"\"\n    if not url:\n        # Empty\n        return Url()\n\n    source_url = url\n    if not SCHEME_RE.search(url):\n        url = \"//\" + url\n\n    try:\n        scheme, authority, path, query, fragment = URI_RE.match(url).groups()\n        normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES\n\n        if scheme:\n            scheme = scheme.lower()\n\n        if authority:\n            auth, _, host_port = authority.rpartition(\"@\")\n            auth = auth or None\n            host, port = _HOST_PORT_RE.match(host_port).groups()\n            if auth and normalize_uri:\n                auth = _encode_invalid_chars(auth, USERINFO_CHARS)\n            if port == \"\":\n                port = None\n        else:\n            auth, host, port = None, None, None\n\n        if port is not None:\n            port = int(port)\n            if not (0 <= port <= 65535):\n                raise LocationParseError(url)\n\n        host = _normalize_host(host, scheme)\n\n        if normalize_uri and path:\n            path = _remove_path_dot_segments(path)\n            path = _encode_invalid_chars(path, PATH_CHARS)\n        if normalize_uri and query:\n            query = _encode_invalid_chars(query, QUERY_CHARS)\n        if normalize_uri and fragment:\n            fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)\n\n    except (ValueError, AttributeError):\n        return six.raise_from(LocationParseError(source_url), None)\n\n    # For the sake of backwards compatibility we put empty\n    # string values for path if there are any defined values\n    # beyond the path in the URL.\n    # TODO: Remove this when we break backwards compatibility.\n    if not path:\n        if query is not None or fragment is not None:\n            path = \"\"\n        else:\n            path = None\n\n    # Ensure that each part of the URL is a `str` for\n    # backwards compatibility.\n    if isinstance(url, six.text_type):\n        ensure_func = six.ensure_text\n    else:\n        ensure_func = six.ensure_str\n\n    def ensure_type(x):\n        return x if x is None else ensure_func(x)\n\n    return Url(\n        scheme=ensure_type(scheme),\n        auth=ensure_type(auth),\n        host=ensure_type(host),\n        port=port,\n        path=ensure_type(path),\n        query=ensure_type(query),\n        fragment=ensure_type(fragment),\n    )\n\n\ndef get_host(url):\n    \"\"\"\n    Deprecated. Use :func:`parse_url` instead.\n    \"\"\"\n    p = parse_url(url)\n    return p.scheme or \"http\", p.hostname, p.port\n"
  },
  {
    "path": "src/pip/_vendor/urllib3/util/wait.py",
    "content": "import errno\nimport select\nimport sys\nfrom functools import partial\n\ntry:\n    from time import monotonic\nexcept ImportError:\n    from time import time as monotonic\n\n__all__ = [\"NoWayToWaitForSocketError\", \"wait_for_read\", \"wait_for_write\"]\n\n\nclass NoWayToWaitForSocketError(Exception):\n    pass\n\n\n# How should we wait on sockets?\n#\n# There are two types of APIs you can use for waiting on sockets: the fancy\n# modern stateful APIs like epoll/kqueue, and the older stateless APIs like\n# select/poll. The stateful APIs are more efficient when you have a lots of\n# sockets to keep track of, because you can set them up once and then use them\n# lots of times. But we only ever want to wait on a single socket at a time\n# and don't want to keep track of state, so the stateless APIs are actually\n# more efficient. So we want to use select() or poll().\n#\n# Now, how do we choose between select() and poll()? On traditional Unixes,\n# select() has a strange calling convention that makes it slow, or fail\n# altogether, for high-numbered file descriptors. The point of poll() is to fix\n# that, so on Unixes, we prefer poll().\n#\n# On Windows, there is no poll() (or at least Python doesn't provide a wrapper\n# for it), but that's OK, because on Windows, select() doesn't have this\n# strange calling convention; plain select() works fine.\n#\n# So: on Windows we use select(), and everywhere else we use poll(). We also\n# fall back to select() in case poll() is somehow broken or missing.\n\nif sys.version_info >= (3, 5):\n    # Modern Python, that retries syscalls by default\n    def _retry_on_intr(fn, timeout):\n        return fn(timeout)\n\nelse:\n    # Old and broken Pythons.\n    def _retry_on_intr(fn, timeout):\n        if timeout is None:\n            deadline = float(\"inf\")\n        else:\n            deadline = monotonic() + timeout\n\n        while True:\n            try:\n                return fn(timeout)\n            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7\n            except (OSError, select.error) as e:\n                # 'e.args[0]' incantation works for both OSError and select.error\n                if e.args[0] != errno.EINTR:\n                    raise\n                else:\n                    timeout = deadline - monotonic()\n                    if timeout < 0:\n                        timeout = 0\n                    if timeout == float(\"inf\"):\n                        timeout = None\n                    continue\n\n\ndef select_wait_for_socket(sock, read=False, write=False, timeout=None):\n    if not read and not write:\n        raise RuntimeError(\"must specify at least one of read=True, write=True\")\n    rcheck = []\n    wcheck = []\n    if read:\n        rcheck.append(sock)\n    if write:\n        wcheck.append(sock)\n    # When doing a non-blocking connect, most systems signal success by\n    # marking the socket writable. Windows, though, signals success by marked\n    # it as \"exceptional\". We paper over the difference by checking the write\n    # sockets for both conditions. (The stdlib selectors module does the same\n    # thing.)\n    fn = partial(select.select, rcheck, wcheck, wcheck)\n    rready, wready, xready = _retry_on_intr(fn, timeout)\n    return bool(rready or wready or xready)\n\n\ndef poll_wait_for_socket(sock, read=False, write=False, timeout=None):\n    if not read and not write:\n        raise RuntimeError(\"must specify at least one of read=True, write=True\")\n    mask = 0\n    if read:\n        mask |= select.POLLIN\n    if write:\n        mask |= select.POLLOUT\n    poll_obj = select.poll()\n    poll_obj.register(sock, mask)\n\n    # For some reason, poll() takes timeout in milliseconds\n    def do_poll(t):\n        if t is not None:\n            t *= 1000\n        return poll_obj.poll(t)\n\n    return bool(_retry_on_intr(do_poll, timeout))\n\n\ndef null_wait_for_socket(*args, **kwargs):\n    raise NoWayToWaitForSocketError(\"no select-equivalent available\")\n\n\ndef _have_working_poll():\n    # Apparently some systems have a select.poll that fails as soon as you try\n    # to use it, either due to strange configuration or broken monkeypatching\n    # from libraries like eventlet/greenlet.\n    try:\n        poll_obj = select.poll()\n        _retry_on_intr(poll_obj.poll, 0)\n    except (AttributeError, OSError):\n        return False\n    else:\n        return True\n\n\ndef wait_for_socket(*args, **kwargs):\n    # We delay choosing which implementation to use until the first time we're\n    # called. We could do it at import time, but then we might make the wrong\n    # decision if someone goes wild with monkeypatching select.poll after\n    # we're imported.\n    global wait_for_socket\n    if _have_working_poll():\n        wait_for_socket = poll_wait_for_socket\n    elif hasattr(select, \"select\"):\n        wait_for_socket = select_wait_for_socket\n    else:  # Platform-specific: Appengine.\n        wait_for_socket = null_wait_for_socket\n    return wait_for_socket(*args, **kwargs)\n\n\ndef wait_for_read(sock, timeout=None):\n    \"\"\"Waits for reading to be available on a given socket.\n    Returns True if the socket is readable, or False if the timeout expired.\n    \"\"\"\n    return wait_for_socket(sock, read=True, timeout=timeout)\n\n\ndef wait_for_write(sock, timeout=None):\n    \"\"\"Waits for writing to be available on a given socket.\n    Returns True if the socket is readable, or False if the timeout expired.\n    \"\"\"\n    return wait_for_socket(sock, write=True, timeout=timeout)\n"
  },
  {
    "path": "src/pip/_vendor/urllib3.pyi",
    "content": "from urllib3 import *"
  },
  {
    "path": "src/pip/_vendor/vendor.txt",
    "content": "CacheControl==0.14.4\ndistlib==0.4.0\ndistro==1.9.0\nmsgpack==1.1.2\npackaging==26.0\nplatformdirs==4.5.1\npyproject-hooks==1.2.0\nrequests==2.32.5\n    certifi==2026.1.4\n    idna==3.11\n    urllib3==1.26.20\nrich==14.2.0\n    pygments==2.19.2\nresolvelib==1.2.1\nsetuptools==70.3.0\ntomli==2.3.0\ntomli-w==1.2.0\ntruststore==0.10.4\ndependency-groups==1.3.1\n"
  },
  {
    "path": "src/pip/py.typed",
    "content": "pip is a command line program. While it is implemented in Python, and so is\navailable for import, you must not use pip's internal APIs in this way. Typing\ninformation is provided as a convenience only and is not a guarantee. Expect\nunannounced changes to the API and types in releases.\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/conftest.py",
    "content": "from __future__ import annotations\n\nimport compileall\nimport contextlib\nimport fnmatch\nimport http.server\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport threading\nfrom collections.abc import Iterable, Iterator\nfrom contextlib import AbstractContextManager\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom textwrap import dedent\nfrom typing import TYPE_CHECKING, Any, AnyStr, Callable, ClassVar\nfrom unittest.mock import patch\nfrom zipfile import ZipFile\n\nimport pytest\n\n# Config will be available from the public API in pytest >= 7.0.0:\n# https://github.com/pytest-dev/pytest/commit/88d84a57916b592b070f4201dc84f0286d1f9fef\nfrom _pytest.config import Config\n\n# Parser will be available from the public API in pytest >= 7.0.0:\n# https://github.com/pytest-dev/pytest/commit/538b5c24999e9ebb4fab43faabc8bcc28737bcdf\nfrom _pytest.config.argparsing import Parser\nfrom installer import install\nfrom installer.destinations import SchemeDictionaryDestination\nfrom installer.sources import WheelFile\n\nfrom pip import __file__ as pip_location\nfrom pip._internal.locations import _USE_SYSCONFIG\nfrom pip._internal.utils.temp_dir import global_tempdir_manager\n\nfrom tests.lib import (\n    DATA_DIR,\n    SRC_DIR,\n    CertFactory,\n    InMemoryPip,\n    PipTestEnvironment,\n    ScriptFactory,\n    TestData,\n)\nfrom tests.lib.server import MockServer, make_mock_server, patch_getfqdn\nfrom tests.lib.venv import VirtualEnvironment, VirtualEnvironmentType\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addoption(\n        \"--keep-tmpdir\",\n        action=\"store_true\",\n        default=False,\n        help=\"keep temporary test directories\",\n    )\n    parser.addoption(\n        \"--resolver\",\n        action=\"store\",\n        default=\"resolvelib\",\n        choices=[\"resolvelib\", \"legacy\"],\n        help=\"use given resolver in tests\",\n    )\n    parser.addoption(\n        \"--use-venv\",\n        action=\"store_true\",\n        default=False,\n        help=\"use venv for virtual environment creation\",\n    )\n    parser.addoption(\n        \"--run-search\",\n        action=\"store_true\",\n        default=False,\n        help=\"run 'pip search' tests\",\n    )\n    parser.addoption(\n        \"--proxy\",\n        action=\"store\",\n        default=None,\n        help=\"use given proxy in session network tests\",\n    )\n    parser.addoption(\n        \"--use-zipapp\",\n        action=\"store_true\",\n        default=False,\n        help=\"use a zipapp when running pip in tests\",\n    )\n\n\ndef pytest_collection_modifyitems(config: Config, items: list[pytest.Function]) -> None:\n    for item in items:\n        if not hasattr(item, \"module\"):  # e.g.: DoctestTextfile\n            continue\n\n        if item.get_closest_marker(\"search\") and not config.getoption(\"--run-search\"):\n            item.add_marker(pytest.mark.skip(\"pip search test skipped\"))\n\n        # Exempt tests known to use the network from pytest-subket.\n        if item.get_closest_marker(\"network\") is not None:\n            item.add_marker(pytest.mark.enable_socket)\n\n        if \"CI\" in os.environ:\n            # Mark network tests as flaky\n            if item.get_closest_marker(\"network\") is not None:\n                item.add_marker(pytest.mark.flaky(reruns=3, reruns_delay=2))\n\n        if (\n            item.get_closest_marker(\"incompatible_with_venv\")\n            and sys.prefix != sys.base_prefix\n        ):\n            item.add_marker(pytest.mark.skip(\"Incompatible with venv\"))\n\n        if item.get_closest_marker(\"incompatible_with_sysconfig\") and _USE_SYSCONFIG:\n            item.add_marker(pytest.mark.skip(\"Incompatible with sysconfig\"))\n\n        module_file = item.module.__file__\n        module_path = os.path.relpath(\n            module_file, os.path.commonprefix([__file__, module_file])\n        )\n\n        module_root_dir = module_path.split(os.pathsep)[0]\n        if module_root_dir.startswith((\"functional\", \"integration\", \"lib\")):\n            item.add_marker(pytest.mark.integration)\n        elif module_root_dir.startswith(\"unit\"):\n            item.add_marker(pytest.mark.unit)\n\n            # We don't want to allow using the script resource if this is a\n            # unit test, as unit tests should not need all that heavy lifting\n            if \"script\" in item.fixturenames:\n                raise RuntimeError(\n                    \"Cannot use the ``script`` funcarg in a unit test: \"\n                    f\"(filename = {module_path}, item = {item})\"\n                )\n        else:\n            raise RuntimeError(f\"Unknown test type (filename = {module_path})\")\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef resolver_variant(request: pytest.FixtureRequest) -> Iterator[str]:\n    \"\"\"Set environment variable to make pip default to the correct resolver.\"\"\"\n    resolver = request.config.getoption(\"--resolver\")\n\n    # Handle the environment variables for this test.\n    features = set(os.environ.get(\"PIP_USE_FEATURE\", \"\").split())\n    deprecated_features = set(os.environ.get(\"PIP_USE_DEPRECATED\", \"\").split())\n\n    if resolver == \"legacy\":\n        deprecated_features.add(\"legacy-resolver\")\n    else:\n        deprecated_features.discard(\"legacy-resolver\")\n\n    env = {\n        \"PIP_USE_FEATURE\": \" \".join(features),\n        \"PIP_USE_DEPRECATED\": \" \".join(deprecated_features),\n    }\n    with patch.dict(os.environ, env):\n        yield resolver\n\n\n@pytest.fixture(scope=\"session\")\ndef tmp_path_factory(\n    request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory\n) -> Iterator[pytest.TempPathFactory]:\n    \"\"\"Modified `tmpdir_factory` session fixture\n    that will automatically cleanup after itself.\n    \"\"\"\n    yield tmp_path_factory\n    if not request.config.getoption(\"--keep-tmpdir\"):\n        shutil.rmtree(\n            tmp_path_factory.getbasetemp(),\n            ignore_errors=True,\n        )\n\n\n@pytest.fixture(scope=\"session\")\ndef tmpdir_factory(tmp_path_factory: pytest.TempPathFactory) -> pytest.TempPathFactory:\n    \"\"\"Override Pytest's ``tmpdir_factory`` with our pathlib implementation.\n\n    This prevents misuse of this fixture.\n    \"\"\"\n    return tmp_path_factory\n\n\n@pytest.fixture\ndef tmp_path(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[Path]:\n    \"\"\"\n    Return a temporary directory path object which is unique to each test\n    function invocation, created as a sub directory of the base temporary\n    directory. The returned object is a ``Path`` object.\n\n    This uses the built-in tmp_path fixture from pytest itself, but deletes the\n    temporary directories at the end of each test case.\n    \"\"\"\n    assert tmp_path.is_dir()\n    yield tmp_path\n    # Clear out the temporary directory after the test has finished using it.\n    # This should prevent us from needing a multiple gigabyte temporary\n    # directory while running the tests.\n    if not request.config.getoption(\"--keep-tmpdir\"):\n        shutil.rmtree(tmp_path, ignore_errors=True)\n\n\n@pytest.fixture\ndef tmpdir(tmp_path: Path) -> Path:\n    \"\"\"Override Pytest's ``tmpdir`` with our pathlib implementation.\n\n    This prevents misuse of this fixture.\n    \"\"\"\n    return tmp_path\n\n\n@pytest.fixture(autouse=True)\ndef isolate(tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:\n    \"\"\"\n    Isolate our tests so that things like global configuration files and the\n    like do not affect our test results.\n\n    We use an autouse function scoped fixture because we want to ensure that\n    every test has it's own isolated home directory.\n    \"\"\"\n\n    # TODO: Figure out how to isolate from *system* level configuration files\n    #       as well as user level configuration files.\n\n    # Create a directory to use as our home location.\n    home_dir = os.path.join(str(tmpdir), \"home\")\n    os.makedirs(home_dir)\n\n    # Create a directory to use as a fake root\n    fake_root = os.path.join(str(tmpdir), \"fake-root\")\n    os.makedirs(fake_root)\n\n    if sys.platform == \"win32\":\n        # Note: this will only take effect in subprocesses...\n        home_drive, home_path = os.path.splitdrive(home_dir)\n        monkeypatch.setenv(\"USERPROFILE\", home_dir)\n        monkeypatch.setenv(\"HOMEDRIVE\", home_drive)\n        monkeypatch.setenv(\"HOMEPATH\", home_path)\n        for env_var, sub_path in (\n            (\"APPDATA\", \"AppData/Roaming\"),\n            (\"LOCALAPPDATA\", \"AppData/Local\"),\n        ):\n            path = os.path.join(home_dir, *sub_path.split(\"/\"))\n            monkeypatch.setenv(env_var, path)\n            os.makedirs(path)\n    else:\n        # Set our home directory to our temporary directory, this should force\n        # all of our relative configuration files to be read from here instead\n        # of the user's actual $HOME directory.\n        monkeypatch.setenv(\"HOME\", home_dir)\n        # Isolate ourselves from XDG directories\n        monkeypatch.setenv(\n            \"XDG_DATA_HOME\",\n            os.path.join(\n                home_dir,\n                \".local\",\n                \"share\",\n            ),\n        )\n        monkeypatch.setenv(\n            \"XDG_CONFIG_HOME\",\n            os.path.join(\n                home_dir,\n                \".config\",\n            ),\n        )\n        monkeypatch.setenv(\"XDG_CACHE_HOME\", os.path.join(home_dir, \".cache\"))\n        monkeypatch.setenv(\n            \"XDG_RUNTIME_DIR\",\n            os.path.join(\n                home_dir,\n                \".runtime\",\n            ),\n        )\n        monkeypatch.setenv(\n            \"XDG_DATA_DIRS\",\n            os.pathsep.join(\n                [\n                    os.path.join(fake_root, \"usr\", \"local\", \"share\"),\n                    os.path.join(fake_root, \"usr\", \"share\"),\n                ]\n            ),\n        )\n        monkeypatch.setenv(\n            \"XDG_CONFIG_DIRS\",\n            os.path.join(\n                fake_root,\n                \"etc\",\n                \"xdg\",\n            ),\n        )\n\n    # Configure git, because without an author name/email git will complain\n    # and cause test failures.\n    monkeypatch.setenv(\"GIT_CONFIG_NOSYSTEM\", \"1\")\n    monkeypatch.setenv(\"GIT_AUTHOR_NAME\", \"pip\")\n    monkeypatch.setenv(\"GIT_AUTHOR_EMAIL\", \"distutils-sig@python.org\")\n\n    # We want to disable the version check from running in the tests\n    monkeypatch.setenv(\"PIP_DISABLE_PIP_VERSION_CHECK\", \"true\")\n\n    # Make sure tests don't share a requirements tracker.\n    monkeypatch.delenv(\"PIP_BUILD_TRACKER\", False)\n\n    # Make sure color control variables don't affect internal output.\n    monkeypatch.delenv(\"FORCE_COLOR\", False)\n    monkeypatch.delenv(\"NO_COLOR\", False)\n\n    # FIXME: Windows...\n    os.makedirs(os.path.join(home_dir, \".config\", \"git\"))\n    with open(os.path.join(home_dir, \".config\", \"git\", \"config\"), \"wb\") as fp:\n        fp.write(b\"[user]\\n\\tname = pip\\n\\temail = distutils-sig@python.org\\n\")\n\n\n@pytest.fixture(autouse=True)\ndef scoped_global_tempdir_manager(request: pytest.FixtureRequest) -> Iterator[None]:\n    \"\"\"Make unit tests with globally-managed tempdirs easier\n\n    Each test function gets its own individual scope for globally-managed\n    temporary directories in the application.\n    \"\"\"\n    if \"no_auto_tempdir_manager\" in request.keywords:\n        ctx: Callable[[], AbstractContextManager[None]] = contextlib.nullcontext\n    else:\n        ctx = global_tempdir_manager\n\n    with ctx():\n        yield\n\n\n@pytest.fixture(scope=\"session\")\ndef pip_src(tmpdir_factory: pytest.TempPathFactory) -> Path:\n    def not_code_files_and_folders(path: str, names: list[str]) -> Iterable[str]:\n        # In the root directory...\n        if os.path.samefile(path, SRC_DIR):\n            # ignore all folders except \"src\"\n            folders = {\n                name for name in names if os.path.isdir(os.path.join(path, name))\n            }\n            to_ignore = folders - {\"src\"}\n            # and ignore \".git\" if present (which may be a file if in a linked\n            # worktree).\n            if \".git\" in names:\n                to_ignore.add(\".git\")\n            return to_ignore\n\n        # Ignore all compiled files and egg-info.\n        ignored = set()\n        for pattern in (\"__pycache__\", \"*.pyc\", \"pip.egg-info\"):\n            ignored.update(fnmatch.filter(names, pattern))\n        return ignored\n\n    pip_src = tmpdir_factory.mktemp(\"pip_src\").joinpath(\"pip_src\")\n    # Copy over our source tree so that each use is self contained\n    shutil.copytree(\n        SRC_DIR,\n        pip_src.resolve(),\n        ignore=not_code_files_and_folders,\n    )\n    return pip_src\n\n\n@pytest.fixture(scope=\"session\")\ndef pip_editable_parts(\n    pip_src: Path, tmpdir_factory: pytest.TempPathFactory\n) -> tuple[Path, ...]:\n    pip_editable = tmpdir_factory.mktemp(\"pip\") / \"pip\"\n    shutil.copytree(pip_src, pip_editable, symlinks=True)\n    # noxfile.py is Python 3 only\n    assert compileall.compile_dir(\n        pip_editable,\n        quiet=1,\n        rx=re.compile(\"noxfile.py$\"),\n    )\n    pip_self_install_path = tmpdir_factory.mktemp(\"pip_self_install\")\n    subprocess.check_call(\n        [\n            sys.executable,\n            \"-m\",\n            \"pip\",\n            \"install\",\n            \"--no-build-isolation\",\n            \"--target\",\n            pip_self_install_path,\n            \"-e\",\n            pip_editable,\n        ]\n    )\n    pth = next(pip_self_install_path.glob(\"*pip*.pth\"))\n    dist_info = next(pip_self_install_path.glob(\"*.dist-info\"))\n    return (pth, dist_info)\n\n\ndef _common_wheel_editable_install(\n    tmpdir_factory: pytest.TempPathFactory, common_wheels: Path, package: str\n) -> Path:\n    wheel_candidates = list(common_wheels.glob(f\"{package}-*.whl\"))\n    assert len(wheel_candidates) == 1, (\n        f\"Missing wheels in {common_wheels}, expected 1 got '{wheel_candidates}'.\"\n        \" Are you running the tests via nox? See https://pip.pypa.io/en/latest/development/getting-started/#running-tests\"\n    )\n    install_dir = tmpdir_factory.mktemp(package) / \"install\"\n    lib_install_dir = install_dir / \"lib\"\n    bin_install_dir = install_dir / \"bin\"\n    with WheelFile.open(wheel_candidates[0]) as source:\n        install(\n            source,\n            SchemeDictionaryDestination(\n                {\n                    \"purelib\": os.fspath(lib_install_dir),\n                    \"platlib\": os.fspath(lib_install_dir),\n                    \"scripts\": os.fspath(bin_install_dir),\n                },\n                interpreter=sys.executable,\n                script_kind=\"posix\",\n                bytecode_optimization_levels=[0],\n            ),\n            additional_metadata={},\n        )\n    # The scripts are not necessary for our use cases, and they would be installed with\n    # the wrong interpreter, so remove them.\n    # TODO consider a refactoring by adding a install_from_wheel(path) method\n    # to the virtualenv fixture.\n    if bin_install_dir.exists():\n        shutil.rmtree(bin_install_dir)\n    return lib_install_dir\n\n\n@pytest.fixture(scope=\"session\")\ndef setuptools_install(\n    tmpdir_factory: pytest.TempPathFactory, common_wheels: Path\n) -> Path:\n    return _common_wheel_editable_install(tmpdir_factory, common_wheels, \"setuptools\")\n\n\n@pytest.fixture(scope=\"session\")\ndef coverage_install(\n    tmpdir_factory: pytest.TempPathFactory, common_wheels: Path\n) -> Path:\n    return _common_wheel_editable_install(tmpdir_factory, common_wheels, \"coverage\")\n\n\n@pytest.fixture(scope=\"session\")\ndef socket_install(tmpdir_factory: pytest.TempPathFactory, common_wheels: Path) -> Path:\n    lib_dir = _common_wheel_editable_install(\n        tmpdir_factory, common_wheels, \"pytest_subket\"\n    )\n    # pytest-subket is only included so it can intercept and block unexpected\n    # network requests. It should NOT be visible to the pip under test.\n    dist_info = next(lib_dir.glob(\"*.dist-info\"))\n    shutil.rmtree(dist_info)\n    return lib_dir\n\n\ndef install_pth_link(\n    venv: VirtualEnvironment, project_name: str, lib_dir: Path\n) -> None:\n    venv.site.joinpath(f\"_pip_testsuite_{project_name}.pth\").write_text(\n        str(lib_dir.resolve()), encoding=\"utf-8\"\n    )\n\n\n@pytest.fixture(scope=\"session\")\ndef virtualenv_template(\n    request: pytest.FixtureRequest,\n    tmpdir_factory: pytest.TempPathFactory,\n    pip_src: Path,\n    pip_editable_parts: tuple[Path, ...],\n    setuptools_install: Path,\n    coverage_install: Path,\n    socket_install: Path,\n) -> VirtualEnvironment:\n    venv_type: VirtualEnvironmentType\n    if request.config.getoption(\"--use-venv\"):\n        venv_type = \"venv\"\n    else:\n        venv_type = \"virtualenv\"\n\n    # Create the virtual environment\n    tmpdir = tmpdir_factory.mktemp(\"virtualenv\")\n    venv = VirtualEnvironment(tmpdir.joinpath(\"venv_orig\"), venv_type=venv_type)\n\n    # Install setuptools, pytest-subket, and pip.\n    install_pth_link(venv, \"setuptools\", setuptools_install)\n    install_pth_link(venv, \"pytest_subket\", socket_install)\n    # Also copy pytest-subket's .pth file so it can intercept socket calls.\n    with open(venv.site / \"pytest_socket.pth\", \"w\") as f:\n        f.write(socket_install.joinpath(\"pytest_socket.pth\").read_text())\n\n    pth, dist_info = pip_editable_parts\n\n    shutil.copy(pth, venv.site)\n    shutil.copytree(\n        dist_info, venv.site / dist_info.name, dirs_exist_ok=True, symlinks=True\n    )\n    # Create placeholder ``easy-install.pth``, as several tests depend on its\n    # existence.  TODO: Ensure ``tests.lib.TestPipResult.files_updated`` correctly\n    # detects changed files.\n    venv.site.joinpath(\"easy-install.pth\").touch()\n\n    if request.config.getoption(\"--cov\"):\n        # Install coverage and pth file for executing it in any spawned processes\n        # in this virtual environment.\n        install_pth_link(venv, \"coverage\", coverage_install)\n        # zz prefix ensures the file is after easy-install.pth.\n        with open(venv.site / \"zz-coverage-helper.pth\", \"a\") as f:\n            f.write(\"import coverage; coverage.process_startup()\")\n\n    # Drop (non-relocatable) launchers.\n    for exe in os.listdir(venv.bin):\n        if not exe.startswith((\"python\", \"libpy\")):  # Don't remove libpypy-c.so...\n            (venv.bin / exe).unlink()\n\n    # Rename original virtualenv directory to make sure\n    # it's not reused by mistake from one of the copies.\n    venv_template = tmpdir / \"venv_template\"\n    venv.move(venv_template)\n    return venv\n\n\n@pytest.fixture(scope=\"session\")\ndef virtualenv_factory(\n    virtualenv_template: VirtualEnvironment,\n) -> Callable[[Path], VirtualEnvironment]:\n    def factory(tmpdir: Path) -> VirtualEnvironment:\n        return VirtualEnvironment(tmpdir, virtualenv_template)\n\n    return factory\n\n\n@pytest.fixture\ndef virtualenv(\n    virtualenv_factory: Callable[[Path], VirtualEnvironment], tmpdir: Path\n) -> VirtualEnvironment:\n    \"\"\"\n    Return a virtual environment which is unique to each test function\n    invocation created inside of a sub directory of the test function's\n    temporary directory. The returned object is a\n    ``tests.lib.venv.VirtualEnvironment`` object.\n    \"\"\"\n    return virtualenv_factory(tmpdir.joinpath(\"workspace\", \"venv\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef script_factory(\n    virtualenv_factory: Callable[[Path], VirtualEnvironment],\n    deprecated_python: bool,\n    zipapp: str | None,\n) -> ScriptFactory:\n    def factory(\n        tmpdir: Path,\n        virtualenv: VirtualEnvironment | None = None,\n        environ: dict[AnyStr, AnyStr] | None = None,\n    ) -> PipTestEnvironment:\n        kwargs = {}\n        if environ:\n            kwargs[\"environ\"] = environ\n        if virtualenv is None:\n            virtualenv = virtualenv_factory(tmpdir.joinpath(\"venv\"))\n        return PipTestEnvironment(\n            # The base location for our test environment\n            tmpdir,\n            # Tell the Test Environment where our virtualenv is located\n            virtualenv=virtualenv,\n            # Do not ignore hidden files, they need to be checked as well\n            ignore_hidden=False,\n            # We are starting with an already empty directory\n            start_clear=False,\n            # We want to ensure no temporary files are left behind, so the\n            # PipTestEnvironment needs to capture and assert against temp\n            capture_temp=True,\n            assert_no_temp=True,\n            # Deprecated python versions produce an extra deprecation warning\n            pip_expect_warning=deprecated_python,\n            # Tell the Test Environment if we want to run pip via a zipapp\n            zipapp=zipapp,\n            **kwargs,\n        )\n\n    return factory\n\n\nZIPAPP_MAIN = \"\"\"\\\n#!/usr/bin/env python\n\nimport os\nimport runpy\nimport sys\n\nlib = os.path.join(os.path.dirname(__file__), \"lib\")\nsys.path.insert(0, lib)\n\nrunpy.run_module(\"pip\", run_name=\"__main__\")\n\"\"\"\n\n\ndef make_zipapp_from_pip(zipapp_name: Path) -> None:\n    pip_dir = Path(pip_location).parent\n    with zipapp_name.open(\"wb\") as zipapp_file:\n        zipapp_file.write(b\"#!/usr/bin/env python\\n\")\n        with ZipFile(zipapp_file, \"w\") as zipapp:\n            for pip_file in pip_dir.rglob(\"*\"):\n                if pip_file.suffix == \".pyc\":\n                    continue\n                if pip_file.name == \"__pycache__\":\n                    continue\n                rel_name = pip_file.relative_to(pip_dir.parent)\n                zipapp.write(pip_file, arcname=f\"lib/{rel_name}\")\n            zipapp.writestr(\"__main__.py\", ZIPAPP_MAIN)\n\n\n@pytest.fixture(scope=\"session\")\ndef zipapp(\n    request: pytest.FixtureRequest, tmpdir_factory: pytest.TempPathFactory\n) -> str | None:\n    \"\"\"\n    If the user requested for pip to be run from a zipapp, build that zipapp\n    and return its location. If the user didn't request a zipapp, return None.\n\n    This fixture is session scoped, so the zipapp will only be created once.\n    \"\"\"\n    if not request.config.getoption(\"--use-zipapp\"):\n        return None\n\n    temp_location = tmpdir_factory.mktemp(\"zipapp\")\n    pyz_file = temp_location / \"pip.pyz\"\n    make_zipapp_from_pip(pyz_file)\n    return str(pyz_file)\n\n\n@pytest.fixture\ndef script(\n    request: pytest.FixtureRequest,\n    tmpdir: Path,\n    virtualenv: VirtualEnvironment,\n    script_factory: ScriptFactory,\n) -> PipTestEnvironment:\n    \"\"\"\n    Return a PipTestEnvironment which is unique to each test function and\n    will execute all commands inside of the unique virtual environment for this\n    test function. The returned object is a\n    ``tests.lib.PipTestEnvironment``.\n    \"\"\"\n    return script_factory(tmpdir.joinpath(\"workspace\"), virtualenv)\n\n\n@pytest.fixture(scope=\"session\")\ndef common_wheels() -> Path:\n    \"\"\"Provide a directory with latest setuptools and wheel wheels\"\"\"\n    return DATA_DIR.joinpath(\"common_wheels\")\n\n\n@pytest.fixture(scope=\"session\")\ndef shared_data(tmpdir_factory: pytest.TempPathFactory) -> TestData:\n    return TestData.copy(tmpdir_factory.mktemp(\"data\"))\n\n\n@pytest.fixture\ndef data(tmpdir: Path) -> TestData:\n    return TestData.copy(tmpdir.joinpath(\"data\"))\n\n\n@pytest.fixture\ndef in_memory_pip() -> InMemoryPip:\n    return InMemoryPip()\n\n\n@pytest.fixture(scope=\"session\")\ndef deprecated_python() -> bool:\n    \"\"\"Used to indicate whether pip deprecated this Python version\"\"\"\n    return sys.version_info[:2] in []\n\n\n@pytest.fixture(scope=\"session\")\ndef cert_factory(tmpdir_factory: pytest.TempPathFactory) -> CertFactory:\n    # Delay the import requiring cryptography in order to make it possible\n    # to deselect relevant tests on systems where cryptography cannot\n    # be installed.\n    from tests.lib.certs import make_tls_cert, serialize_cert, serialize_key\n\n    def factory() -> str:\n        \"\"\"Returns path to cert/key file.\"\"\"\n        output_path = tmpdir_factory.mktemp(\"certs\") / \"cert.pem\"\n        # Must be Text on PY2.\n        cert, key = make_tls_cert(\"localhost\")\n        with open(str(output_path), \"wb\") as f:\n            f.write(serialize_cert(cert))\n            f.write(serialize_key(key))\n\n        return str(output_path)\n\n    return factory\n\n\n@pytest.fixture\ndef mock_server() -> Iterator[MockServer]:\n    server = make_mock_server()\n    test_server = MockServer(server)\n    with test_server.context:\n        yield test_server\n\n\n@pytest.fixture\ndef proxy(request: pytest.FixtureRequest) -> str:\n    return request.config.getoption(\"proxy\")\n\n\n@pytest.fixture\ndef enable_user_site(virtualenv: VirtualEnvironment) -> None:\n    virtualenv.user_site_packages = True\n\n\nclass MetadataKind(Enum):\n    \"\"\"All the types of values we might be provided for the data-dist-info-metadata\n    attribute from PEP 658.\"\"\"\n\n    # Valid: will read metadata from the dist instead.\n    No = \"none\"\n    # Valid: will read the .metadata file, but won't check its hash.\n    Unhashed = \"unhashed\"\n    # Valid: will read the .metadata file and check its hash matches.\n    Sha256 = \"sha256\"\n    # Invalid: will error out after checking the hash.\n    WrongHash = \"wrong-hash\"\n    # Invalid: will error out after failing to fetch the .metadata file.\n    NoFile = \"no-file\"\n\n\n@dataclass(frozen=True)\nclass FakePackage:\n    \"\"\"Mock package structure used to generate a PyPI repository.\n\n    FakePackage name and version should correspond to sdists (.tar.gz files) in our test\n    data.\"\"\"\n\n    name: str\n    version: str\n    filename: str\n    metadata: MetadataKind\n    # This will override any dependencies specified in the actual dist's METADATA.\n    requires_dist: tuple[str, ...] = ()\n    # This will override the Name specified in the actual dist's METADATA.\n    metadata_name: str | None = None\n\n    def metadata_filename(self) -> str:\n        \"\"\"This is specified by PEP 658.\"\"\"\n        return f\"{self.filename}.metadata\"\n\n    def generate_additional_tag(self) -> str:\n        \"\"\"This gets injected into the <a> tag in the generated PyPI index page for this\n        package.\"\"\"\n        if self.metadata == MetadataKind.No:\n            return \"\"\n        if self.metadata in [MetadataKind.Unhashed, MetadataKind.NoFile]:\n            return 'data-dist-info-metadata=\"true\"'\n        if self.metadata == MetadataKind.WrongHash:\n            return 'data-dist-info-metadata=\"sha256=WRONG-HASH\"'\n        assert self.metadata == MetadataKind.Sha256\n        checksum = sha256(self.generate_metadata()).hexdigest()\n        return f'data-dist-info-metadata=\"sha256={checksum}\"'\n\n    def requires_str(self) -> str:\n        if not self.requires_dist:\n            return \"\"\n        joined = \" and \".join(self.requires_dist)\n        return f\"Requires-Dist: {joined}\"\n\n    def generate_metadata(self) -> bytes:\n        \"\"\"This is written to `self.metadata_filename()` and will override the actual\n        dist's METADATA, unless `self.metadata == MetadataKind.NoFile`.\"\"\"\n        return dedent(\n            f\"\"\"\\\n        Metadata-Version: 2.1\n        Name: {self.metadata_name or self.name}\n        Version: {self.version}\n        {self.requires_str()}\n        \"\"\"\n        ).encode(\"utf-8\")\n\n\n@pytest.fixture(scope=\"session\")\ndef fake_packages() -> dict[str, list[FakePackage]]:\n    \"\"\"The package database we generate for testing PEP 658 support.\"\"\"\n    return {\n        \"simple\": [\n            FakePackage(\"simple\", \"1.0\", \"simple-1.0.tar.gz\", MetadataKind.Sha256),\n            FakePackage(\"simple\", \"2.0\", \"simple-2.0.tar.gz\", MetadataKind.No),\n            # This will raise a hashing error.\n            FakePackage(\"simple\", \"3.0\", \"simple-3.0.tar.gz\", MetadataKind.WrongHash),\n        ],\n        \"simple2\": [\n            # Override the dependencies here in order to force pip to download\n            # simple-1.0.tar.gz as well.\n            FakePackage(\n                \"simple2\",\n                \"1.0\",\n                \"simple2-1.0.tar.gz\",\n                MetadataKind.Unhashed,\n                (\"simple==1.0\",),\n            ),\n            # This will raise an error when pip attempts to fetch the metadata file.\n            FakePackage(\"simple2\", \"2.0\", \"simple2-2.0.tar.gz\", MetadataKind.NoFile),\n            # This has a METADATA file with a mismatched name.\n            FakePackage(\n                \"simple2\",\n                \"3.0\",\n                \"simple2-3.0.tar.gz\",\n                MetadataKind.Sha256,\n                metadata_name=\"not-simple2\",\n            ),\n        ],\n        \"colander\": [\n            # Ensure we can read the dependencies from a metadata file within a wheel\n            # *without* PEP 658 metadata.\n            FakePackage(\n                \"colander\",\n                \"0.9.9\",\n                \"colander-0.9.9-py2.py3-none-any.whl\",\n                MetadataKind.No,\n            ),\n        ],\n        \"compilewheel\": [\n            # Ensure we can override the dependencies of a wheel file by injecting PEP\n            # 658 metadata.\n            FakePackage(\n                \"compilewheel\",\n                \"1.0\",\n                \"compilewheel-1.0-py2.py3-none-any.whl\",\n                MetadataKind.Unhashed,\n                (\"simple==1.0\",),\n            ),\n        ],\n        \"has-script\": [\n            # Ensure we check PEP 658 metadata hashing errors for wheel files.\n            FakePackage(\n                \"has-script\",\n                \"1.0\",\n                \"has.script-1.0-py2.py3-none-any.whl\",\n                MetadataKind.WrongHash,\n            ),\n        ],\n        \"translationstring\": [\n            FakePackage(\n                \"translationstring\",\n                \"1.1\",\n                \"translationstring-1.1.tar.gz\",\n                MetadataKind.No,\n            ),\n        ],\n        \"priority\": [\n            # Ensure we check for a missing metadata file for wheels.\n            FakePackage(\n                \"priority\",\n                \"1.0\",\n                \"priority-1.0-py2.py3-none-any.whl\",\n                MetadataKind.NoFile,\n            ),\n        ],\n        \"requires-simple-extra\": [\n            # Metadata name is not canonicalized.\n            FakePackage(\n                \"requires-simple-extra\",\n                \"0.1\",\n                \"requires_simple_extra-0.1-py2.py3-none-any.whl\",\n                MetadataKind.Sha256,\n                metadata_name=\"Requires_Simple.Extra\",\n            ),\n        ],\n    }\n\n\n@pytest.fixture(scope=\"session\")\ndef html_index_for_packages(\n    shared_data: TestData,\n    fake_packages: dict[str, list[FakePackage]],\n    tmpdir_factory: pytest.TempPathFactory,\n) -> Path:\n    \"\"\"Generate a PyPI HTML package index within a local directory pointing to\n    synthetic test data.\"\"\"\n    html_dir = tmpdir_factory.mktemp(\"fake_index_html_content\")\n\n    # (1) Generate the content for a PyPI index.html.\n    pkg_links = \"\\n\".join(\n        f'    <a href=\"{pkg}/index.html\">{pkg}</a>' for pkg in fake_packages.keys()\n    )\n    # Output won't be nicely indented because dedent() acts after f-string\n    # arg insertion.\n    index_html = dedent(\n        f\"\"\"\\\n        <!DOCTYPE html>\n        <html>\n          <head>\n            <meta name=\"pypi:repository-version\" content=\"1.0\">\n            <title>Simple index</title>\n          </head>\n          <body>\n          {pkg_links}\n          </body>\n        </html>\"\"\"\n    )\n    # (2) Generate the index.html in a new subdirectory of the temp directory.\n    (html_dir / \"index.html\").write_text(index_html)\n\n    # (3) Generate subdirectories for individual packages, each with their own\n    # index.html.\n    for pkg, links in fake_packages.items():\n        pkg_subdir = html_dir / pkg\n        pkg_subdir.mkdir()\n\n        download_links: list[str] = []\n        for package_link in links:\n            # (3.1) Generate the <a> tag which pip can crawl pointing to this\n            # specific package version.\n            download_links.append(\n                f'    <a href=\"{package_link.filename}\" {package_link.generate_additional_tag()}>{package_link.filename}</a><br/>'  # noqa: E501\n            )\n            # (3.2) Copy over the corresponding file in `shared_data.packages`.\n            shutil.copy(\n                shared_data.packages / package_link.filename,\n                pkg_subdir / package_link.filename,\n            )\n            # (3.3) Write a metadata file, if applicable.\n            if package_link.metadata != MetadataKind.NoFile:\n                with open(pkg_subdir / package_link.metadata_filename(), \"wb\") as f:\n                    f.write(package_link.generate_metadata())\n\n        # (3.4) After collating all the download links and copying over the files,\n        # write an index.html with the generated download links for each\n        # copied file for this specific package name.\n        download_links_str = \"\\n\".join(download_links)\n        pkg_index_content = dedent(\n            f\"\"\"\\\n            <!DOCTYPE html>\n            <html>\n              <head>\n                <meta name=\"pypi:repository-version\" content=\"1.0\">\n                <title>Links for {pkg}</title>\n              </head>\n              <body>\n                <h1>Links for {pkg}</h1>\n                {download_links_str}\n              </body>\n            </html>\"\"\"\n        )\n        with open(pkg_subdir / \"index.html\", \"w\") as f:\n            f.write(pkg_index_content)\n\n    return html_dir\n\n\nclass OneTimeDownloadHandler(http.server.SimpleHTTPRequestHandler):\n    \"\"\"Serve files from the current directory, but error if a file is downloaded more\n    than once.\"\"\"\n\n    _seen_paths: ClassVar[set[str]] = set()\n\n    def do_GET(self) -> None:\n        if self.path in self._seen_paths:\n            self.send_error(\n                http.HTTPStatus.NOT_FOUND,\n                f\"File {self.path} not available more than once!\",\n            )\n            return\n        super().do_GET()\n        if not (self.path.endswith(\"/\") or self.path.endswith(\".metadata\")):\n            self._seen_paths.add(self.path)\n\n\n@pytest.fixture\ndef html_index_with_onetime_server(\n    html_index_for_packages: Path,\n) -> Iterator[http.server.ThreadingHTTPServer]:\n    \"\"\"Serve files from a generated pypi index, erroring if a file is downloaded more\n    than once.\n\n    Provide `-i http://localhost:8000` to pip invocations to point them at this server.\n    \"\"\"\n\n    class InDirectoryServer(http.server.ThreadingHTTPServer):\n        def finish_request(self: Self, request: Any, client_address: Any) -> None:\n            self.RequestHandlerClass(\n                request,\n                client_address,\n                self,\n                directory=str(html_index_for_packages),  # type: ignore[call-arg]\n            )\n\n    class Handler(OneTimeDownloadHandler):\n        _seen_paths: ClassVar[set[str]] = set()\n\n    with patch_getfqdn(), InDirectoryServer((\"\", 8000), Handler) as httpd:\n        server_thread = threading.Thread(target=httpd.serve_forever)\n        server_thread.start()\n\n        try:\n            yield httpd\n        finally:\n            httpd.shutdown()\n            server_thread.join()\n"
  },
  {
    "path": "tests/data/completion_paths/README.txt",
    "content": ""
  },
  {
    "path": "tests/data/completion_paths/REPLAY/video.mpeg",
    "content": ""
  },
  {
    "path": "tests/data/completion_paths/requirements.txt",
    "content": ""
  },
  {
    "path": "tests/data/indexes/README.txt",
    "content": "\nDetails on Test Indexes\n=======================\n\nempty_with_pkg\n--------------\nempty index, but there's a package in the dir\n\nin dex\n------\nfor testing url quoting with indexes\n\nsimple\n------\ncontains index page for \"simple\" pkg\n"
  },
  {
    "path": "tests/data/indexes/datarequire/fakepackage/index.html",
    "content": "<!DOCTYPE html>\n<html><head><title>Links for fakepackage</title><meta name=\"api-version\" value=\"2\" /></head><body><h1>Links for fakepackage</h1>\n    <a data-requires-python=''                href=\"/fakepackage-1.0.0.tar.gz#md5=00000000000000000000000000000000\" rel=\"internal\">fakepackage-1.0.0.tar.gz</a><br/>\n    <a data-requires-python='&lt;2.7'         href=\"/fakepackage-2.6.0.tar.gz#md5=00000000000000000000000000000000\" rel=\"internal\">fakepackage-2.6.0.tar.gz</a><br/>\n    <a data-requires-python='&gt;=2.7,&lt;3'  href=\"/fakepackage-2.7.0.tar.gz#md5=00000000000000000000000000000000\" rel=\"internal\">fakepackage-2.7.0.tar.gz</a><br/>\n    <a data-requires-python='&gt;=3.3'        href=\"/fakepackage-3.3.0.tar.gz#md5=00000000000000000000000000000000\" rel=\"internal\">fakepackage-3.3.0.tar.gz</a><br/>\n    <a data-requires-python='&gt;&lt;X.y.z'   href=\"/fakepackage-9.9.9.tar.gz#md5=00000000000000000000000000000000\" rel=\"internal\">fakepackage-9.9.9.tar.gz</a><br/>\n</body></html>\n"
  },
  {
    "path": "tests/data/indexes/dev/bar/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"bar-1.0.tar.gz\">bar-1.0.tar.gz</a>\n    <a href=\"bar-2.0.dev1.tar.gz\">bar-2.0.dev1.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/empty_with_pkg/index.html",
    "content": ""
  },
  {
    "path": "tests/data/indexes/in dex/README.txt",
    "content": "This directory has the odd space in its name in order to test urlquoting and\ndequoting of file:// scheme index URLs.\n"
  },
  {
    "path": "tests/data/indexes/in dex/simple/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"../../../packages/simple-1.0.tar.gz#md5=4bdf78ebb7911f215c1972cf71b378f0\">simple-1.0.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/invalid-version/invalid-version/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"../../../packages/invalid_version-2010i-py3-none-any.whl\">invalid_version-2010i-py3-none-any.whl</a>\n    <a href=\"../../../packages/invalid_version-1.0-py3-none-any.whl\">invalid_version-1.0-py3-none-any.whl</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/pre/bar/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"bar-1.0.tar.gz\">bar-1.0.tar.gz</a>\n    <a href=\"bar-2.0b1.tar.gz\">bar-1.0b1.tar.gz</a>\n    <a href=\"bar-2.0.dev1.tar.gz\">bar-2.0.dev1.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/require-invalid-version/invalid-version/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"../../../packages/invalid_version-2010i-py3-none-any.whl\">invalid_version-2010i-py3-none-any.whl</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/require-invalid-version/require-invalid-version/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"../../../packages/require_invalid_version-0.1-py3-none-any.whl\">require_invalid_version-0.1-py3-none-any.whl</a>\n    <a href=\"../../../packages/require_invalid_version-1.0-py3-none-any.whl\">require_invalid_version-1.0-py3-none-any.whl</a>\n    <a href=\"../../../packages/require_invalid_version-1.0.tar.gz\">require_invalid_version-1.0.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/simple/simple/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a href=\"../../../packages/simple-1.0.tar.gz#md5=4bdf78ebb7911f215c1972cf71b378f0\">simple-1.0.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/yanked/simple/index.html",
    "content": "<!doctype html>\n<html>\n  <body>\n    <a href=\"../../../packages/simple-1.0.tar.gz\">simple-1.0.tar.gz</a>\n    <a href=\"../../../packages/simple-2.0.tar.gz\">simple-2.0.tar.gz</a>\n    <a data-yanked=\"test reason message\" href=\"../../../packages/simple-3.0.tar.gz\">simple-3.0.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/indexes/yanked_all/simple/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <body>\n    <a data-yanked=\"test reason message\" href=\"../../../packages/simple-1.0.tar.gz\">simple-1.0.tar.gz</a>\n    <a data-yanked=\"test reason message\" href=\"../../../packages/simple-2.0.tar.gz\">simple-2.0.tar.gz</a>\n    <a data-yanked=\"test reason message\" href=\"../../../packages/simple-3.0.tar.gz\">simple-3.0.tar.gz</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/data/packages/BrokenEmitsUTF8/broken.py",
    "content": ""
  },
  {
    "path": "tests/data/packages/BrokenEmitsUTF8/setup.py",
    "content": "import sys\nfrom distutils.core import setup\n\n\nclass FakeError(Exception):\n    pass\n\n\nif sys.argv[1] in (\"install\", \"bdist_wheel\"):\n    if hasattr(sys.stdout, \"buffer\"):\n        sys.stdout.buffer.write(\n            \"\\nThis package prints out UTF-8 stuff like:\\n\".encode()\n        )\n        sys.stdout.buffer.write(\"* return type of ‘main’ is not ‘int’\\n\".encode())\n        sys.stdout.buffer.write(\n            \"* Björk Guðmundsdóttir [ˈpjœr̥k ˈkvʏðmʏntsˌtoʊhtɪr]\".encode()\n        )\n    else:\n        pass\n        sys.stdout.write(\"\\nThis package prints out UTF-8 stuff like:\\n\")\n        sys.stdout.write(\n            \"* return type of \\xe2\\x80\\x98main\\xe2\\x80\\x99 is not \\xe2\\x80\\x98int\\xe2\\x80\\x99\\n\"\n        )\n        sys.stdout.write(\n            \"* Bj\\xc3\\xb6rk Gu\\xc3\\xb0mundsd\\xc3\\xb3ttir [\\xcb\\x88pj\\xc5\\x93r\\xcc\\xa5k \\xcb\\x88kv\\xca\\x8f\\xc3\\xb0m\\xca\\x8fnts\\xcb\\x8cto\\xca\\x8aht\\xc9\\xaar]\\n\"\n        )\n\n    raise FakeError(\"this package designed to fail on install\")\n\nsetup(\n    name=\"broken\",\n    version=\"0.2\",\n    py_modules=[\"broken\"],\n)\n"
  },
  {
    "path": "tests/data/packages/FSPkg/fspkg/__init__.py",
    "content": "#\n"
  },
  {
    "path": "tests/data/packages/FSPkg/setup.py",
    "content": "from setuptools import find_packages, setup\n\nversion = \"0.1dev\"\n\nsetup(\n    name=\"FSPkg\",\n    version=version,\n    description=\"File system test package\",\n    long_description=\"\"\"\\\nFile system test package\"\"\",\n    classifiers=[],  # Get strings from https://pypi.org/pypi?%3Aaction=list_classifiers\n    keywords=\"pip tests\",\n    author=\"pip\",\n    author_email=\"pip@openplans.org\",\n    url=\"http://pip.openplans.org\",\n    license=\"\",\n    packages=find_packages(exclude=[\"ez_setup\", \"examples\", \"tests\"]),\n    include_package_data=True,\n    zip_safe=False,\n    install_requires=[\n        # -*- Extra requirements: -*-\n    ],\n    entry_points=\"\"\"\n      # -*- Entry points: -*-\n      \"\"\",\n)\n"
  },
  {
    "path": "tests/data/packages/HackedEggInfo/setup.py",
    "content": "from setuptools import setup\nfrom setuptools.command import egg_info as orig_egg_info\n\n\nclass egg_info(orig_egg_info.egg_info):\n    def run(self):\n        orig_egg_info.egg_info.run(self)\n\n\nsetup(\n    name=\"hackedegginfo\",\n    version=\"0.0.0\",\n    cmdclass={\"egg_info\": egg_info},\n    zip_safe=False,\n)\n"
  },
  {
    "path": "tests/data/packages/LineEndings/setup.py",
    "content": "from distutils.core import setup\n\nsetup()\n"
  },
  {
    "path": "tests/data/packages/LocalEnvironMarker/.gitignore",
    "content": "/LocalEnvironMarker.egg-info\n"
  },
  {
    "path": "tests/data/packages/LocalEnvironMarker/localenvironmarker/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/packages/LocalEnvironMarker/setup.py",
    "content": "import os\n\nfrom setuptools import find_packages, setup\n\n\ndef path_to_url(path):\n    \"\"\"\n    Convert a path to URI. The path will be made absolute and\n    will not have quoted path parts.\n    \"\"\"\n    path = os.path.normpath(os.path.abspath(path))\n    drive, path = os.path.splitdrive(path)\n    filepath = path.split(os.path.sep)\n    url = \"/\".join(filepath)\n    if drive:\n        return \"file:///\" + drive + url\n    return \"file://\" + url\n\n\nsetup(\n    name=\"LocalEnvironMarker\",\n    version=\"0.0.1\",\n    packages=find_packages(),\n    extras_require={\n        \":python_version == '2.7'\": [\"simple\"],\n    },\n)\n"
  },
  {
    "path": "tests/data/packages/LocalExtras/.gitignore",
    "content": "/LocalExtras.egg-info\n"
  },
  {
    "path": "tests/data/packages/LocalExtras/localextras/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/packages/LocalExtras/setup.py",
    "content": "import os\n\nfrom setuptools import find_packages, setup\n\n\ndef path_to_url(path):\n    \"\"\"\n    Convert a path to URI. The path will be made absolute and\n    will not have quoted path parts.\n    \"\"\"\n    path = os.path.normpath(os.path.abspath(path))\n    drive, path = os.path.splitdrive(path)\n    filepath = path.split(os.path.sep)\n    url = \"/\".join(filepath)\n    if drive:\n        return \"file:///\" + drive + url\n    return \"file://\" + url\n\n\nsetup(\n    name=\"LocalExtras\",\n    version=\"0.0.1\",\n    packages=find_packages(),\n    extras_require={\"bar\": [\"simple\"], \"baz\": [\"singlemodule\"]},\n)\n"
  },
  {
    "path": "tests/data/packages/LocalExtras-0.0.2/.gitignore",
    "content": "/LocalExtras-0.0.2.egg-info\n"
  },
  {
    "path": "tests/data/packages/LocalExtras-0.0.2/localextras/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/packages/LocalExtras-0.0.2/setup.py",
    "content": "import os\n\nfrom setuptools import find_packages, setup\n\n\ndef path_to_url(path):\n    \"\"\"\n    Convert a path to URI. The path will be made absolute and\n    will not have quoted path parts.\n    \"\"\"\n    path = os.path.normpath(os.path.abspath(path))\n    drive, path = os.path.splitdrive(path)\n    filepath = path.split(os.path.sep)\n    url = \"/\".join(filepath)\n    if drive:\n        return \"file:///\" + drive + url\n    return \"file://\" + url\n\n\nsetup(\n    name=\"LocalExtras\",\n    version=\"0.0.2\",\n    packages=find_packages(),\n    install_requires=[\"simple==1.0\"],\n    extras_require={\"bar\": [\"simple==2.0\"], \"baz\": [\"singlemodule\"]},\n)\n"
  },
  {
    "path": "tests/data/packages/README.txt",
    "content": "\nDetails on Test Packages\n========================\n\nbroken-0.1.tar.gz\n-----------------\nThis package exists for testing uninstall-rollback.\n\nbroken-0.2+broken.tar.gz\n------------------------\nVersion 0.2+broken has a setup.py crafted to fail on install (and only on\ninstall). If any earlier step would fail (i.e. egg-info-generation), the\nalready-installed version would never be uninstalled, so uninstall-rollback\nwould not come into play.\n\nbrokenegginfo-0.1.tar.gz\n------------------------\ncrafted to fail on egg_info\n\nBrokenEmitsUTF8\n---------------\nfor generating unicode error in py3.x\n\nduplicate-1.0.tar.gz\n--------------------\nfor testing finding dupes across multiple find-links\n\nFSPkg\n-----\nfor installing from the file system\n\ngmpy-1.15.tar.gz\n----------------\nhash testing (although this pkg isn't needed explicitly)\n\ngmpy2-2.0.tar.gz\n----------------\nfor testing finder logic when name *contains* the name of the package specified\n\nHackedEggInfo\n-------------\nhas its own egg_info class\n\nLineEndings\n-----------\ncontains DOS line endings\n\nLocalExtras\n-----------\nhas an extra in a local file:// dependency link\n\nparent/child-0.1.tar.gz\n-----------------------\nThe parent-0.1.tar.gz and child-0.1.tar.gz packages are used by\ntest_uninstall:test_uninstall_overlapping_package.\n\npkgwithmpkg-1.0.tar.gz; pkgwithmpkg-1.0-py2.7-macosx10.7.mpkg.zip\n-----------------------------------------------------------------\nused for osx test case (tests.test_finder:test_no_mpkg)\n\npriority-*\n----------\nused for testing wheel priority over sdists\n\nTopoRequires[1234][-0.0.1.tar.gz]\n--------------------------------\n\nThese are used for testing topological handling of requirements: we have\nTopoRequires, which is install-required by TopoRequires2 and TopoRequires3\nand finally TopoRequires4 which install-requires both TopoRequires2 and 3\nand also install-Requires TopoRequires.\nThis creates a diamond where no matter which way we walk without topological\nawareness we'll end up attempting to install TopoRequires after one of\nTopoRequires2, TopoRequires3 or TopoRequires4. (prefix iteration works as its\ntopological, suffix iteration likewise, infix breaks).\n\nsimple[2]-[123].0.tar.gz\n------------------------\ncontains \"simple[2]\" package; good for basic testing and version logic.\n\nwheelbroken-0.1.tar.gz\n----------------------\nfails for \"setup.py bdist_wheel\"\n\nUpper-[12].0.tar.gz and requiresuppper-1.0.tar.gz\n--------------------------------------------------\n'requiresupper' requires 'upper'\nused for testing case mismatch case for url requirements\n\nmeta-1.0-py2.py3-none-any.whl\n--------------------------------------------------\nIs an empty package which install_requires the simple and simple2 packages.\n\nrequires_simple_extra-0.1-py2.py3-none-any.whl\n----------------------------------------------\nrequires_simple_extra[extra] requires simple==1.0\n\nrequires_wheelbroken_upper\n--------------------------\nRequires wheelbroken and upper - used for testing implicit wheel building\nduring install.\n\nrequire_simple-1.0.tar.gz\n------------------------\ncontains \"require_simple\" package which requires simple>=2.0 - used for testing\nif dependencies are handled correctly.\n\ninvalid_version-2010i-py3-none-any.whl\n--------------------------------------\nThe invalid-version package with a legacy version.\n\ninvalid_version-1.0-py3-none-any.whl\n------------------------------------\nA valid variant of the invalid-version package. Used, for instance, to test that the\nversion with invalid metadata is ignored in favor of this one.\n\nrequire_invalid_version-0.1-py3-none-any.whl\n--------------------------------------------\nA valid variant of the require-invalid-version package.\n\nrequire_invalid_version-1.0-py3-none-any.whl\n--------------------------------------------\nThis package has an invalid version specifier in its requirements.\n\nrequire_invalid_version-1.0.tar.gz\n----------------------------------\nThis package has an invalid version specifier in its requirements.\n"
  },
  {
    "path": "tests/data/packages/SetupPyLatin1/setup.py",
    "content": "# -*- coding: latin-1 -*-\n\nfrom distutils.core import setup\n\nsetup(\n    name=\"SetupPyUTF8\",\n    author=\"Sal Ibarra Corretg\",\n)\n"
  },
  {
    "path": "tests/data/packages/SetupPyUTF8/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"SetupPyUTF8\",\n    author=\"Saúl Ibarra Corretgé\",\n)\n"
  },
  {
    "path": "tests/data/packages/corruptwheel-1.0-py2.py3-none-any.whl",
    "content": "This is a corrupt wheel which _clearly_ is not a zip file.\n"
  },
  {
    "path": "tests/data/packages/invalid.whl",
    "content": ""
  },
  {
    "path": "tests/data/packages/pep517_setup_and_pyproject/pyproject.toml",
    "content": "[build-system]\nrequires = [ \"setuptools\" ]\nbuild-backend = \"setuptools.build_meta\"\n"
  },
  {
    "path": "tests/data/packages/pep517_setup_and_pyproject/setup.cfg",
    "content": "[metadata]\nname = pep517-setup-and-pyproject\nversion = 1.0\n"
  },
  {
    "path": "tests/data/packages/pep517_setup_and_pyproject/setup.py",
    "content": "from setuptools import setup\n\nsetup()\n"
  },
  {
    "path": "tests/data/packages/pep517_wrapper_buildsys/mybuildsys.py",
    "content": "import os\n\nfrom setuptools.build_meta import build_sdist\nfrom setuptools.build_meta import build_wheel as setuptools_build_wheel\nfrom setuptools.build_meta import (\n    get_requires_for_build_sdist,\n    get_requires_for_build_wheel,\n    prepare_metadata_for_build_wheel,\n)\n\n\ndef build_wheel(*a, **kw):\n    if os.environ.get(\"PIP_TEST_FAIL_BUILD_WHEEL\"):\n        raise RuntimeError(\"Failing build_wheel, as requested.\")\n\n    # Create the marker file to record that the hook was called\n    with open(os.environ[\"PIP_TEST_MARKER_FILE\"], \"wb\"):\n        pass\n\n    return setuptools_build_wheel(*a, **kw)\n"
  },
  {
    "path": "tests/data/packages/pep517_wrapper_buildsys/pyproject.toml",
    "content": "[build-system]\nrequires = [ \"setuptools\" ]\nbuild-backend = \"mybuildsys\"  # setuptools.build_meta\nbackend-path = [\".\"]\n"
  },
  {
    "path": "tests/data/packages/pep517_wrapper_buildsys/setup.cfg",
    "content": "[metadata]\nname = pep517-wrapper-buildsys\nversion = 1.0\n"
  },
  {
    "path": "tests/data/packages/pep517_wrapper_buildsys/setup.py",
    "content": "from setuptools import setup\n\nsetup()\n"
  },
  {
    "path": "tests/data/packages/priority-1.0-py2.py3-none-any.whl",
    "content": ""
  },
  {
    "path": "tests/data/packages/requiresPaste/pyproject.toml",
    "content": "[build-system]\nrequires = ['flit_core >=2,<4']\nbuild-backend = 'flit_core.buildapi'\n\n[tool.flit.metadata]\nmodule = 'requiresPaste'\nauthor = 'A. Random Developer'\nauthor-email = 'author@example.com'\nrequires = ['Paste==3.4.2']\n"
  },
  {
    "path": "tests/data/packages/requiresPaste/requiresPaste.py",
    "content": "\"\"\"Module requiring Paste to test dependencies download of pip wheel.\"\"\"\n\n__version__ = \"3.1.4\"\n"
  },
  {
    "path": "tests/data/packages/requires_wheelbroken_upper/requires_wheelbroken_upper/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/packages/requires_wheelbroken_upper/setup.py",
    "content": "import setuptools\n\nsetuptools.setup(\n    name=\"requires_wheelbroken_upper\",\n    version=\"0\",\n    install_requires=[\"wheelbroken\", \"upper\"],\n)\n"
  },
  {
    "path": "tests/data/packages/symlinks/doc/intro",
    "content": ""
  },
  {
    "path": "tests/data/packages/symlinks/setup.cfg",
    "content": "[egg_info]\ntag_build = dev\n"
  },
  {
    "path": "tests/data/packages/symlinks/setup.py",
    "content": "from setuptools import setup\n\nversion = \"0.1\"\n\nsetup(\n    name=\"symlinks\",\n    version=version,\n    packages=[\"symlinks\"],\n)\n"
  },
  {
    "path": "tests/data/packages/symlinks/symlinks/__init__.py",
    "content": "#\n"
  },
  {
    "path": "tests/data/packages3/dinner/index.html",
    "content": "<!DOCTYPE html>\n<html><head><title>PyPI Mirror</title></head>\n<body>\n  <h1>PyPI Mirror</h1>\n  <h2>For testing --index-url with a file:// url for the index</h2>\n  <a href='Dinner-1.0.tar.gz'>Dinner-1.0.tar.gz</a><br />\n  <a href='Dinner-2.0.tar.gz'>Dinner-2.0.tar.gz</a><br />\n</body>\n</html>\n"
  },
  {
    "path": "tests/data/packages3/index.html",
    "content": "<!DOCTYPE html>\n<html><head><title>PyPI Mirror</title></head>\n<body>\n  <h1>PyPI Mirror</h1>\n  <h2>For testing --index-url with a file:// url for the index</h2>\n  <a href='requiredinner'>requiredinner</a><br />\n  <a href='Dinner'>Dinner</a><br />\n</body>\n</html>\n"
  },
  {
    "path": "tests/data/packages3/requiredinner/index.html",
    "content": "<!DOCTYPE html>\n<html><head><title>PyPI Mirror</title></head>\n<body>\n  <h1>PyPI Mirror</h1>\n  <h2>For testing --index-url with a file:// url for the index</h2>\n  <a href='requiredinner-1.0.tar.gz'>requiredinner=1.0.tar.gz</a><br />\n</body>\n</html>\n"
  },
  {
    "path": "tests/data/reqfiles/README.txt",
    "content": "supported_options.txt\n---------------------\n\nContains --no-use-wheel.\n\nsupported_options2.txt\n----------------------\n\nContains --no-binary and --only-binary options.\n"
  },
  {
    "path": "tests/data/reqfiles/supported_options2.txt",
    "content": "# default is no constraints\n# We're not testing the format control logic here, just that the options are\n# accepted\n--no-binary fred\n--only-binary wilma\n"
  },
  {
    "path": "tests/data/src/TopoRequires/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"TopoRequires\",\n    version=\"0.0.1\",\n    packages=[\"toporequires\"],\n)\n"
  },
  {
    "path": "tests/data/src/TopoRequires/toporequires/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/TopoRequires2/setup.cfg.pending",
    "content": "[metadata]\nname = TopoRequires2\ninstall-requires =\n  TopoRequires\n"
  },
  {
    "path": "tests/data/src/TopoRequires2/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"TopoRequires2\",\n    version=\"0.0.1\",\n    packages=[\"toporequires2\"],\n    install_requires=[\"TopoRequires\"],\n)\n"
  },
  {
    "path": "tests/data/src/TopoRequires2/toporequires2/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/TopoRequires3/setup.cfg.pending",
    "content": "[metadata]\nname = TopoRequires3\ninstall-requires =\n  TopoRequires\n"
  },
  {
    "path": "tests/data/src/TopoRequires3/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"TopoRequires3\",\n    version=\"0.0.1\",\n    packages=[\"toporequires3\"],\n    install_requires=[\"TopoRequires\"],\n)\n"
  },
  {
    "path": "tests/data/src/TopoRequires3/toporequires3/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/TopoRequires4/setup.cfg.pending",
    "content": "[metadata]\nname = TopoRequires4\ninstall-requires =\n  TopoRequires2\n  TopoRequires\n  TopoRequires3\n"
  },
  {
    "path": "tests/data/src/TopoRequires4/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"TopoRequires4\",\n    version=\"0.0.1\",\n    packages=[\"toporequires4\"],\n    install_requires=[\"TopoRequires2\", \"TopoRequires\", \"TopoRequires3\"],\n)\n"
  },
  {
    "path": "tests/data/src/TopoRequires4/toporequires4/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/chattymodule/backend.py",
    "content": "import os\nimport sys\n\nfrom setuptools import build_meta\nfrom setuptools.build_meta import *\n\n\ndef prepare_metadata_for_build_wheel(metadata_directory, config_settings=None):\n    if config_settings and \"fail\" in config_settings:\n        print(\"I DIE, I DIE in prepare_metadata_for_build_wheel\")\n        sys.exit(1)\n    print(\"HELLO FROM CHATTYMODULE prepare_metadata_for_build_wheel\")\n    return build_meta.prepare_metadata_for_build_wheel(\n        metadata_directory, config_settings\n    )\n\n\ndef build_wheel(wheel_directory, config_settings=None, metadata_directory=None):\n    if config_settings and \"fail\" in config_settings:\n        print(\"I DIE, I DIE in build_wheel\")\n        sys.exit(1)\n    print(\"HELLO FROM CHATTYMODULE build_wheel\")\n    return build_meta.build_wheel(wheel_directory, config_settings, metadata_directory)\n"
  },
  {
    "path": "tests/data/src/chattymodule/chattymodule.py",
    "content": "def main():\n    \"\"\"Entry point for the application script\"\"\"\n    print(\"Call your main application code here\")\n"
  },
  {
    "path": "tests/data/src/chattymodule/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"backend\"\nbackend-path = [\".\"]\n\n[project]\nname = \"chattymodule\"\nversion = \"0.0.1\"\n\n[tool.setuptools]\npy-modules = [\"chattymodule\"]\n"
  },
  {
    "path": "tests/data/src/compilewheel/setup.cfg",
    "content": "[bdist_wheel]\n# This flag says that the code is written to work on both Python 2 and Python\n# 3. If at all possible, it is good practice to do this. If you cannot, you\n# will need to generate wheels for each Python version that you support.\nuniversal=1\n"
  },
  {
    "path": "tests/data/src/compilewheel/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\nsetup(name=\"compilewheel\", version=\"1.0\", packages=find_packages())\n"
  },
  {
    "path": "tests/data/src/compilewheel/simple/__init__.py",
    "content": "def spam(gen):\n    yield from gen\n"
  },
  {
    "path": "tests/data/src/extension/extension.c",
    "content": ""
  },
  {
    "path": "tests/data/src/extension/setup.py",
    "content": "from setuptools import Extension, setup\n\nmodule = Extension(\"extension\", sources=[\"extension.c\"])\nsetup(name=\"extension\", version=\"0.0.1\", ext_modules=[module])\n"
  },
  {
    "path": "tests/data/src/pep517_pyproject_only/pyproject.toml",
    "content": "[build-system]\nrequires = [\"foo\"]\nbuild-backend = \"foo\"\n"
  },
  {
    "path": "tests/data/src/pep517_setup_and_pyproject/pyproject.toml",
    "content": "[build-system]\nrequires = [\"foo\"]\nbuild-backend = \"foo\"\n"
  },
  {
    "path": "tests/data/src/pep517_setup_and_pyproject/setup.py",
    "content": "from setuptools import setup\n\nsetup(name=\"dummy\", version=\"0.1\")\n"
  },
  {
    "path": "tests/data/src/pep517_setup_cfg_only/setup.cfg",
    "content": "[metadata]\nname = \"dummy\"\nversion = \"0.1\"\n"
  },
  {
    "path": "tests/data/src/pep517_setup_only/setup.py",
    "content": "from setuptools import setup\n\nsetup(name=\"dummy\", version=\"0.1\")\n"
  },
  {
    "path": "tests/data/src/pep518-3.0/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518-3.0/pep518.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518-3.0/pyproject.toml",
    "content": "[build-system]\nrequires=[\"simplewheel==2.0\", \"setuptools\"]\n"
  },
  {
    "path": "tests/data/src/pep518-3.0/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518-3.0/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nimport simplewheel  # ensure dependency is installed\n\nsetup(\n    name=\"pep518\",\n    version=\"3.0\",\n    py_modules=[\"pep518\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_conflicting_requires/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_conflicting_requires/pep518.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518_conflicting_requires/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools==1.0\"]\n"
  },
  {
    "path": "tests/data/src/pep518_conflicting_requires/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nsetup(\n    name=\"pep518_conflicting_requires\",\n    version=\"1.0.0\",\n    py_modules=[\"pep518\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_forkbomb-235/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_forkbomb-235/pep518_forkbomb.py",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_forkbomb-235/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"pep518_forkbomb\"]\n"
  },
  {
    "path": "tests/data/src/pep518_forkbomb-235/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_forkbomb-235/setup.py",
    "content": "from setuptools import setup\n\nsetup(name=\"pep518_forkbomb\", version=\"235\", py_modules=[\"pep518_forkbomb\"])\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_build_system/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_build_system/pep518.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_build_system/pyproject.toml",
    "content": "[build-system]\n# This table is intentionally empty.\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_build_system/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nsetup(\n    name=\"pep518_invalid_build_system\",\n    version=\"1.0.0\",\n    py_modules=[\"pep518\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_requires/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_requires/pep518.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_requires/pyproject.toml",
    "content": "[build-system]\nrequires = [1, 2, 3]  # not a list of strings\n"
  },
  {
    "path": "tests/data/src/pep518_invalid_requires/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nsetup(\n    name=\"pep518_invalid_requires\",\n    version=\"1.0.0\",\n    py_modules=[\"pep518\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_missing_requires/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_missing_requires/pep518.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518_missing_requires/pyproject.toml",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_missing_requires/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nsetup(\n    name=\"pep518_missing_requires\",\n    version=\"1.0.0\",\n    py_modules=[\"pep518\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_first-234/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_first-234/pep518_twin_forkbombs_first.py",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_first-234/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"pep518_twin_forkbombs_second\"]\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_first-234/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_first-234/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"pep518_twin_forkbombs_first\",\n    version=\"234\",\n    py_modules=[\"pep518_twin_forkbombs_first\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_second-238/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_second-238/pep518_twin_forkbombs_second.py",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_second-238/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"pep518_twin_forkbombs_first\"]\n"
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_second-238/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_twin_forkbombs_second-238/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"pep518_twin_forkbombs_second\",\n    version=\"238\",\n    py_modules=[\"pep518_twin_forkbombs_second\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_with_extra_and_markers-1.0/MANIFEST.in",
    "content": "include pyproject.toml\n"
  },
  {
    "path": "tests/data/src/pep518_with_extra_and_markers-1.0/pep518_with_extra_and_markers.py",
    "content": "# dummy\n"
  },
  {
    "path": "tests/data/src/pep518_with_extra_and_markers-1.0/pyproject.toml",
    "content": "[build-system]\nrequires = [\n    \"requires_simple_extra[extra]\",\n    \"simplewheel==1.0; python_version < '3'\",\n    \"simplewheel==2.0; python_version >= '3'\",\n    \"setuptools\",\n]\n"
  },
  {
    "path": "tests/data/src/pep518_with_extra_and_markers-1.0/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_with_extra_and_markers-1.0/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\n# ensure dependencies are installed\nimport simple\nimport simplewheel\n\nassert simplewheel.__version__ == \"2.0\"\n\nsetup(\n    name=\"pep518_with_extra_and_markers\",\n    version=\"1.0\",\n    py_modules=[\"pep518_with_extra_and_markers\"],\n)\n"
  },
  {
    "path": "tests/data/src/pep518_with_namespace_package-1.0/pep518_with_namespace_package.py",
    "content": ""
  },
  {
    "path": "tests/data/src/pep518_with_namespace_package-1.0/pyproject.toml",
    "content": "[build-system]\nrequires = [\n    \"setuptools\",\n    \"simple_namespace\",\n]\n"
  },
  {
    "path": "tests/data/src/pep518_with_namespace_package-1.0/setup.cfg",
    "content": "[bdist_wheel]\nuniversal=1\n"
  },
  {
    "path": "tests/data/src/pep518_with_namespace_package-1.0/setup.py",
    "content": "from setuptools import setup\n\nimport simple_namespace.module\n\nsetup(\n    name=\"pep518_with_namespace_package\",\n    version=\"1.0\",\n    py_modules=[\"pep518_with_namespace_package\"],\n)\n"
  },
  {
    "path": "tests/data/src/prjwithdatafile/prjwithdatafile/README.txt",
    "content": "README\r\n======\r\n\r\nTest project file\n"
  },
  {
    "path": "tests/data/src/prjwithdatafile/prjwithdatafile/somemodule.py",
    "content": ""
  },
  {
    "path": "tests/data/src/prjwithdatafile/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"prjwithdatafile\",\n    version=\"1.0\",\n    packages=[\"prjwithdatafile\"],\n    data_files=[\n        (r\"packages1\", [\"prjwithdatafile/README.txt\"]),\n        (r\"packages2\", [\"prjwithdatafile/README.txt\"]),\n    ],\n)\n"
  },
  {
    "path": "tests/data/src/requires_capitalized/setup.py",
    "content": "from setuptools import setup\n\nsetup(name=\"Requires_Capitalized\", version=\"0.1\", install_requires=[\"simple==1.0\"])\n"
  },
  {
    "path": "tests/data/src/requires_requires_capitalized/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"requires_requires_capitalized\",\n    version=\"1.0\",\n    install_requires=[\"requires_Capitalized==0.1\"],\n)\n"
  },
  {
    "path": "tests/data/src/requires_simple/requires_simple/__init__.py",
    "content": "#\n"
  },
  {
    "path": "tests/data/src/requires_simple/setup.py",
    "content": "from setuptools import find_packages, setup\n\nsetup(name=\"requires_simple\", version=\"0.1\", install_requires=[\"simple==1.0\"])\n"
  },
  {
    "path": "tests/data/src/requires_simple_extra/requires_simple_extra.py",
    "content": ""
  },
  {
    "path": "tests/data/src/requires_simple_extra/setup.cfg",
    "content": "[wheel]\nuniversal=1\n"
  },
  {
    "path": "tests/data/src/requires_simple_extra/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"requires_simple_extra\",\n    version=\"0.1\",\n    py_modules=[\"requires_simple_extra\"],\n    extras_require={\"extra\": [\"simple==1.0\"]},\n)\n"
  },
  {
    "path": "tests/data/src/setup_error/setup.py",
    "content": "from setuptools import setup\n\n# This is to get an error that originates from setuptools, which generates a\n# decently sized output.\nsetup(\n    cmdclass={\n        \"egg_info\": \"<make-me-fail>\",\n        \"install\": \"<make-me-fail>\",\n        \"bdist_wheel\": \"<make-me-fail>\",\n    }\n)\n"
  },
  {
    "path": "tests/data/src/simple_namespace/setup.cfg",
    "content": "[bdist_wheel]\nuniversal=1\n"
  },
  {
    "path": "tests/data/src/simple_namespace/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"simple_namespace\",\n    version=\"1.0\",\n    namespace_packages=[\"simple_namespace\"],\n    packages=[\"simple_namespace.module\"],\n)\n"
  },
  {
    "path": "tests/data/src/simple_namespace/simple_namespace/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/simple_namespace/simple_namespace/module/__init__.py",
    "content": ""
  },
  {
    "path": "tests/data/src/simplewheel-1.0/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/simplewheel-1.0/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nimport simplewheel\n\nsetup(\n    name=\"simplewheel\",\n    version=simplewheel.__version__,\n    packages=[\"simplewheel\"],\n)\n"
  },
  {
    "path": "tests/data/src/simplewheel-1.0/simplewheel/__init__.py",
    "content": "__version__ = \"1.0\"\n"
  },
  {
    "path": "tests/data/src/simplewheel-2.0/setup.cfg",
    "content": ""
  },
  {
    "path": "tests/data/src/simplewheel-2.0/setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup\n\nimport simplewheel\n\nsetup(\n    name=\"simplewheel\",\n    version=simplewheel.__version__,\n    packages=[\"simplewheel\"],\n)\n"
  },
  {
    "path": "tests/data/src/simplewheel-2.0/simplewheel/__init__.py",
    "content": "__version__ = \"2.0\"\n"
  },
  {
    "path": "tests/data/src/singlemodule/setup.cfg",
    "content": "[bdist_wheel]\n# This flag says that the code is written to work on both Python 2 and Python\n# 3. If at all possible, it is good practice to do this. If you cannot, you\n# will need to generate wheels for each Python version that you support.\nuniversal=1\n"
  },
  {
    "path": "tests/data/src/singlemodule/setup.py",
    "content": "from setuptools import setup\n\nsetup(\n    name=\"singlemodule\",\n    version=\"0.0.1\",\n    description=\"A sample Python project with a single module\",\n    py_modules=[\"singlemodule\"],\n)\n"
  },
  {
    "path": "tests/data/src/singlemodule/singlemodule.py",
    "content": "def main():\n    \"\"\"Entry point for the application script\"\"\"\n    print(\"Call your main application code here\")\n"
  },
  {
    "path": "tests/data/src/withpyproject/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\"]\n\n# Note: pyproject.toml is always UTF-8 🤡\n"
  },
  {
    "path": "tests/data/src/withpyproject/setup.py",
    "content": "from setuptools import setup\n\nsetup(name=\"withpyproject\", version=\"0.0.1\")\n"
  },
  {
    "path": "tests/functional/__init__.py",
    "content": ""
  },
  {
    "path": "tests/functional/test_bad_url.py",
    "content": "# test the error message returned by pip when\n# a bad \"file:\" URL is passed to it.\n\nfrom typing import Any\n\n\ndef test_filenotfound_error_message(script: Any) -> None:\n    # Test the error message returned when using a bad 'file:' URL.\n    # make pip to fail and get an error message\n    # by running \"pip install -r file:///nonexistent_file\"\n    proc = script.pip(\"install\", \"-r\", \"file:///unexistent_file\", expect_error=True)\n    assert proc.returncode == 1\n    expect = (\n        \"ERROR: 404 Client Error: FileNotFoundError for url: file:///unexistent_file\"\n    )\n    assert proc.stderr.rstrip() == expect\n"
  },
  {
    "path": "tests/functional/test_broken_stdout.py",
    "content": "import os\nimport subprocess\nfrom pathlib import Path\n\n_BROKEN_STDOUT_RETURN_CODE = 120\n\n\ndef setup_broken_stdout_test(\n    args: list[str], deprecated_python: bool\n) -> tuple[str, int]:\n    proc = subprocess.Popen(\n        args,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n    # Call close() on stdout to cause a broken pipe.\n    assert proc.stdout is not None\n    proc.stdout.close()\n    returncode = proc.wait()\n    assert proc.stderr is not None\n    stderr = proc.stderr.read().decode(\"utf-8\")\n\n    expected_msg = \"ERROR: Pipe to stdout was broken\"\n    if deprecated_python:\n        assert expected_msg in stderr\n    else:\n        assert stderr.startswith(expected_msg)\n\n    return stderr, returncode\n\n\ndef test_broken_stdout_pipe(deprecated_python: bool) -> None:\n    \"\"\"\n    Test a broken pipe to stdout.\n    \"\"\"\n    stderr, returncode = setup_broken_stdout_test(\n        [\"pip\", \"list\"],\n        deprecated_python=deprecated_python,\n    )\n\n    # Check that no traceback occurs.\n    assert \"raise BrokenStdoutLoggingError()\" not in stderr\n    assert stderr.count(\"Traceback\") == 0\n\n    assert returncode == _BROKEN_STDOUT_RETURN_CODE\n\n\ndef test_broken_stdout_pipe__log_option(deprecated_python: bool, tmpdir: Path) -> None:\n    \"\"\"\n    Test a broken pipe to stdout when --log is passed.\n    \"\"\"\n    log_path = os.path.join(str(tmpdir), \"log.txt\")\n    stderr, returncode = setup_broken_stdout_test(\n        [\"pip\", \"--log\", log_path, \"list\"],\n        deprecated_python=deprecated_python,\n    )\n\n    # Check that no traceback occurs.\n    assert \"raise BrokenStdoutLoggingError()\" not in stderr\n    assert stderr.count(\"Traceback\") == 0\n\n    assert returncode == _BROKEN_STDOUT_RETURN_CODE\n\n\ndef test_broken_stdout_pipe__verbose(deprecated_python: bool) -> None:\n    \"\"\"\n    Test a broken pipe to stdout with verbose logging enabled.\n    \"\"\"\n    stderr, returncode = setup_broken_stdout_test(\n        [\"pip\", \"-vv\", \"list\"],\n        deprecated_python=deprecated_python,\n    )\n\n    # Check that a traceback occurs and that it occurs at most once.\n    # We permit up to two because the exception can be chained.\n    assert \"raise BrokenStdoutLoggingError()\" in stderr\n    assert 1 <= stderr.count(\"Traceback\") <= 2\n\n    assert returncode == _BROKEN_STDOUT_RETURN_CODE\n"
  },
  {
    "path": "tests/functional/test_build_constraints.py",
    "content": "\"\"\"Tests for the build constraints feature.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom pathlib import Path\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.utils.urls import path_to_url\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    TestPipResult,\n    create_test_package_with_setup,\n)\n\n\ndef _create_simple_test_package(script: PipTestEnvironment, name: str) -> Path:\n    \"\"\"Create a simple test package with minimal setup.\"\"\"\n    return create_test_package_with_setup(\n        script,\n        name=name,\n        version=\"1.0\",\n        py_modules=[name],\n    )\n\n\ndef _create_constraints_file(\n    script: PipTestEnvironment, filename: str, content: str\n) -> Path:\n    \"\"\"Create a constraints file with the given content.\"\"\"\n    constraints_file = script.scratch_path / filename\n    constraints_file.write_text(content)\n    return constraints_file\n\n\ndef _run_pip_install_with_build_constraints(\n    script: PipTestEnvironment,\n    data: TestData,\n    project_dir: Path,\n    build_constraints_file: Path,\n    extra_args: list[str] | None = None,\n    expect_error: bool = False,\n) -> TestPipResult:\n    \"\"\"Run pip install with build constraints and common arguments.\"\"\"\n    args = [\n        \"--no-cache-dir\",\n        \"--build-constraint\",\n        str(build_constraints_file),\n        \"--use-feature\",\n        \"build-constraint\",\n    ]\n\n    if extra_args:\n        args.extend(extra_args)\n\n    args.append(str(project_dir))\n\n    return script.pip_install_local(\n        *args,\n        expect_error=expect_error,\n        build_isolation=True,\n        find_links=data.common_wheels,\n    )\n\n\ndef _run_pip_install_with_build_constraints_no_feature_flag(\n    script: PipTestEnvironment,\n    data: TestData,\n    project_dir: Path,\n    constraints_file: Path,\n) -> TestPipResult:\n    \"\"\"Run pip install with build constraints but without the feature flag.\"\"\"\n    return script.pip_install_local(\n        \"--build-constraint\",\n        str(constraints_file),\n        str(project_dir),\n        build_isolation=True,\n        find_links=data.common_wheels,\n    )\n\n\ndef test_build_constraints_basic_functionality_simple(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"Test that build constraints options are accepted and processed.\"\"\"\n    project_dir = _create_simple_test_package(\n        script=script, name=\"test_build_constraints\"\n    )\n    constraints_file = _create_constraints_file(\n        script=script, filename=\"constraints.txt\", content=\"setuptools>=40.0.0\\n\"\n    )\n    result = _run_pip_install_with_build_constraints(\n        script=script,\n        data=data,\n        project_dir=project_dir,\n        build_constraints_file=constraints_file,\n    )\n    result.assert_installed(\n        \"test-build-constraints\", editable=False, without_files=[\".\"]\n    )\n\n\n@pytest.mark.network\ndef test_build_constraints_vs_regular_constraints_simple(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"Test that build constraints and regular constraints work independently.\"\"\"\n    project_dir = create_test_package_with_setup(\n        script,\n        name=\"test_isolation\",\n        version=\"1.0\",\n        py_modules=[\"test_isolation\"],\n        install_requires=[\"six\"],\n    )\n    build_constraints_file = _create_constraints_file(\n        script=script, filename=\"build_constraints.txt\", content=\"setuptools>=40.0.0\\n\"\n    )\n    regular_constraints_file = _create_constraints_file(\n        script=script, filename=\"constraints.txt\", content=\"six>=1.10.0\\n\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--build-constraint\",\n        build_constraints_file,\n        \"--constraint\",\n        regular_constraints_file,\n        \"--use-feature\",\n        \"build-constraint\",\n        \"--use-pep517\",\n        str(project_dir),\n        expect_error=False,\n    )\n    assert \"Successfully installed\" in result.stdout\n    assert \"test_isolation\" in result.stdout\n\n\ndef test_build_constraints_environment_isolation_simple(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"Test that build constraints work correctly in isolated build environments.\"\"\"\n    project_dir = _create_simple_test_package(script=script, name=\"test_env_isolation\")\n    constraints_file = _create_constraints_file(\n        script=script, filename=\"build_constraints.txt\", content=\"setuptools>=40.0.0\\n\"\n    )\n    result = _run_pip_install_with_build_constraints(\n        script=script,\n        data=data,\n        project_dir=project_dir,\n        build_constraints_file=constraints_file,\n        extra_args=[\"--isolated\"],\n    )\n    result.assert_installed(\"test-env-isolation\", editable=False, without_files=[\".\"])\n\n\ndef test_build_constraints_file_not_found(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"Test behavior when build constraints file doesn't exist.\"\"\"\n    project_dir = _create_simple_test_package(\n        script=script, name=\"test_missing_constraints\"\n    )\n    missing_constraints = script.scratch_path / \"missing_constraints.txt\"\n    result = _run_pip_install_with_build_constraints(\n        script=script,\n        data=data,\n        project_dir=project_dir,\n        build_constraints_file=missing_constraints,\n        expect_error=True,\n    )\n    assert \"Could not open requirements file\" in result.stderr\n    assert \"No such file or directory\" in result.stderr\n\n\ndef test_build_constraints_without_feature_flag(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"Test that --build-constraint automatically enables the feature.\"\"\"\n    project_dir = _create_simple_test_package(script=script, name=\"test_no_feature\")\n    constraints_file = _create_constraints_file(\n        script=script, filename=\"constraints.txt\", content=\"setuptools>=40.0.0\\n\"\n    )\n    result = _run_pip_install_with_build_constraints_no_feature_flag(\n        script=script,\n        data=data,\n        project_dir=project_dir,\n        constraints_file=constraints_file,\n    )\n    # Should succeed now that --build-constraint auto-enables the feature\n    assert result.returncode == 0\n    result.assert_installed(\"test-no-feature\", editable=False, without_files=[\".\"])\n\n\ndef test_constraints_dont_pass_through(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"When build constraints enabled, check PIP_CONSTRAINT won't affect builds.\"\"\"\n    project_dir = create_test_package_with_setup(\n        script,\n        name=\"test_isolation\",\n        version=\"1.0\",\n        py_modules=[\"test_isolation\"],\n    )\n    constraints = _create_constraints_file(\n        script=script, filename=\"constraints.txt\", content=\"setuptools==2000\\n\"\n    )\n    with mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": path_to_url(str(constraints))}):\n        result = script.pip_install_local(\n            \"--no-cache-dir\",\n            str(project_dir),\n            \"--use-feature=build-constraint\",\n            build_isolation=True,\n            find_links=data.common_wheels,\n        )\n    result.assert_installed(\"test_isolation\", editable=False, without_files=[\".\"])\n"
  },
  {
    "path": "tests/functional/test_build_env.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom textwrap import dedent\nfrom typing import Literal\n\nimport pytest\n\nfrom pip._internal.build_env import (\n    BuildEnvironment,\n    BuildEnvironmentInstaller,\n    InprocessBuildEnvironmentInstaller,\n    SubprocessBuildEnvironmentInstaller,\n    _get_system_sitepackages,\n)\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestPipResult,\n    create_basic_wheel_for_package,\n    make_test_finder,\n)\n\nInstallMethod = Literal[\"subprocess\", \"inprocess\"]\nwith_both_installers = pytest.mark.parametrize(\n    \"install_method\", [\"subprocess\", \"inprocess\"]\n)\n\n\ndef indent(text: str, prefix: str) -> str:\n    return \"\\n\".join((prefix if line else \"\") + line for line in text.split(\"\\n\"))\n\n\n@contextmanager\ndef make_test_build_env_installer(\n    method: InstallMethod, finder: PackageFinder\n) -> Generator[BuildEnvironmentInstaller]:\n    if method == \"subprocess\":\n        yield SubprocessBuildEnvironmentInstaller(finder)\n    else:\n        with get_build_tracker() as tracker:\n            yield InprocessBuildEnvironmentInstaller(\n                finder=finder,\n                build_tracker=tracker,\n                wheel_cache=WheelCache(None),  # type: ignore\n            )\n\n\ndef run_with_build_env(\n    script: PipTestEnvironment,\n    setup_script_contents: str,\n    test_script_contents: str | None = None,\n    install_method: InstallMethod = \"subprocess\",\n) -> TestPipResult:\n    build_env_script = script.scratch_path / \"build_env.py\"\n    scratch_path = str(script.scratch_path)\n    build_env_script.write_text(\n        dedent(\n            f\"\"\"\n            import subprocess\n            import sys\n\n            from pip._internal.build_env import (\n                BuildEnvironment,\n                InprocessBuildEnvironmentInstaller,\n                SubprocessBuildEnvironmentInstaller,\n            )\n            from pip._internal.cache import WheelCache\n            from pip._internal.index.collector import LinkCollector\n            from pip._internal.index.package_finder import PackageFinder\n            from pip._internal.models.search_scope import SearchScope\n            from pip._internal.models.selection_prefs import (\n                SelectionPreferences\n            )\n            from pip._internal.operations.build.build_tracker import get_build_tracker\n            from pip._internal.network.session import PipSession\n            from pip._internal.utils.temp_dir import global_tempdir_manager\n\n            link_collector = LinkCollector(\n                session=PipSession(),\n                search_scope=SearchScope.create([{scratch_path!r}], [], False),\n            )\n            selection_prefs = SelectionPreferences(\n                allow_yanked=True,\n            )\n            finder = PackageFinder.create(\n                link_collector=link_collector,\n                selection_prefs=selection_prefs,\n            )\n\n            with global_tempdir_manager(), get_build_tracker() as tracker:\n                if \"{install_method}\" == \"subprocess\":\n                    installer = SubprocessBuildEnvironmentInstaller(finder)\n                else:\n                    installer = InprocessBuildEnvironmentInstaller(\n                        finder=finder,\n                        build_tracker=tracker,\n                        wheel_cache=WheelCache(None),\n                    )\n                build_env = BuildEnvironment(installer)\n            \"\"\"\n        )\n        + indent(dedent(setup_script_contents), \"    \")\n        + indent(\n            dedent(\n                \"\"\"\n                if len(sys.argv) > 1:\n                    with build_env:\n                        subprocess.check_call((sys.executable, sys.argv[1]))\n                \"\"\"\n            ),\n            \"    \",\n        )\n    )\n    args = [\"python\", os.fspath(build_env_script)]\n    if test_script_contents is not None:\n        test_script = script.scratch_path / \"test.py\"\n        test_script.write_text(dedent(test_script_contents))\n        args.append(os.fspath(test_script))\n    return script.run(*args)\n\n\n@with_both_installers\ndef test_build_env_allow_empty_requirements_install(\n    install_method: InstallMethod,\n) -> None:\n    finder = make_test_finder()\n    with make_test_build_env_installer(install_method, finder) as installer:\n        build_env = BuildEnvironment(installer)\n        for prefix in (\"normal\", \"overlay\"):\n            build_env.install_requirements(\n                [], prefix, kind=\"Installing build dependencies\"\n            )\n\n\n@with_both_installers\ndef test_build_env_allow_only_one_install(\n    script: PipTestEnvironment, install_method: InstallMethod\n) -> None:\n    create_basic_wheel_for_package(script, \"foo\", \"1.0\")\n    create_basic_wheel_for_package(script, \"bar\", \"1.0\")\n    finder = make_test_finder(find_links=[os.fspath(script.scratch_path)])\n    with make_test_build_env_installer(install_method, finder) as installer:\n        build_env = BuildEnvironment(installer)\n        for prefix in (\"normal\", \"overlay\"):\n            build_env.install_requirements(\n                [\"foo\"], prefix, kind=f\"installing foo in {prefix}\"\n            )\n            with pytest.raises(AssertionError):\n                build_env.install_requirements(\n                    [\"bar\"], prefix, kind=f\"installing bar in {prefix}\"\n                )\n            with pytest.raises(AssertionError):\n                build_env.install_requirements(\n                    [], prefix, kind=f\"installing in {prefix}\"\n                )\n\n\ndef test_build_env_requirements_check(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"foo\", \"2.0\")\n    create_basic_wheel_for_package(script, \"bar\", \"1.0\")\n    create_basic_wheel_for_package(script, \"bar\", \"3.0\")\n    create_basic_wheel_for_package(script, \"other\", \"0.5\")\n\n    script.pip_install_local(\"-f\", script.scratch_path, \"foo\", \"bar\", \"other\")\n\n    run_with_build_env(\n        script,\n        \"\"\"\n        r = build_env.check_requirements(['foo', 'bar', 'other'])\n        assert r == (set(), {'foo', 'bar', 'other'}), repr(r)\n\n        r = build_env.check_requirements(['foo>1.0', 'bar==3.0'])\n        assert r == (set(), {'foo>1.0', 'bar==3.0'}), repr(r)\n\n        r = build_env.check_requirements(['foo>3.0', 'bar>=2.5'])\n        assert r == (set(), {'foo>3.0', 'bar>=2.5'}), repr(r)\n        \"\"\",\n    )\n\n    run_with_build_env(\n        script,\n        \"\"\"\n        build_env.install_requirements(['foo', 'bar==3.0'], 'normal',\n                                       kind='installing foo in normal')\n\n        r = build_env.check_requirements(['foo', 'bar', 'other'])\n        assert r == (set(), {'other'}), repr(r)\n\n        r = build_env.check_requirements(['foo>1.0', 'bar==3.0'])\n        assert r == (set(), set()), repr(r)\n\n        r = build_env.check_requirements(['foo>3.0', 'bar>=2.5'])\n        assert r == ({('foo==2.0', 'foo>3.0')}, set()), repr(r)\n        \"\"\",\n    )\n\n    run_with_build_env(\n        script,\n        \"\"\"\n        build_env.install_requirements(['foo', 'bar==3.0'], 'normal',\n                                       kind='installing foo in normal')\n        build_env.install_requirements(['bar==1.0'], 'overlay',\n                                       kind='installing foo in overlay')\n\n        r = build_env.check_requirements(['foo', 'bar', 'other'])\n        assert r == (set(), {'other'}), repr(r)\n\n        r = build_env.check_requirements(['foo>1.0', 'bar==3.0'])\n        assert r == ({('bar==1.0', 'bar==3.0')}, set()), repr(r)\n\n        r = build_env.check_requirements(['foo>3.0', 'bar>=2.5'])\n        assert r == ({('bar==1.0', 'bar>=2.5'), ('foo==2.0', 'foo>3.0')}, \\\n            set()), repr(r)\n        \"\"\",\n    )\n\n    run_with_build_env(\n        script,\n        \"\"\"\n        build_env.install_requirements(\n            [\"bar==3.0\"],\n            \"normal\",\n            kind=\"installing bar in normal\",\n        )\n        r = build_env.check_requirements(\n            [\n                \"bar==2.0; python_version < '3.0'\",\n                \"bar==3.0; python_version >= '3.0'\",\n                \"foo==4.0; extra == 'dev'\",\n            ],\n        )\n        assert r == (set(), set()), repr(r)\n        \"\"\",\n    )\n\n\n@with_both_installers\ndef test_build_env_overlay_prefix_has_priority(\n    script: PipTestEnvironment, install_method: InstallMethod\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"2.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"4.3\")\n    result = run_with_build_env(\n        script,\n        \"\"\"\n        build_env.install_requirements(['pkg==2.0'], 'overlay',\n                                       kind='installing pkg==2.0 in overlay')\n        build_env.install_requirements(['pkg==4.3'], 'normal',\n                                       kind='installing pkg==4.3 in normal')\n        \"\"\",\n        \"\"\"\n        print(__import__('pkg').__version__)\n        \"\"\",\n        install_method=install_method,\n    )\n    assert result.stdout.strip() == \"2.0\", str(result)\n\n\nif sys.version_info < (3, 12):\n    BUILD_ENV_ERROR_DEBUG_CODE = r\"\"\"\n            from distutils.sysconfig import get_python_lib\n            print(\n                f'imported `pkg` from `{pkg.__file__}`',\n                file=sys.stderr)\n            print('system sites:\\n  ' + '\\n  '.join(sorted({\n                            get_python_lib(plat_specific=0),\n                            get_python_lib(plat_specific=1),\n                    })), file=sys.stderr)\n    \"\"\"\nelse:\n    BUILD_ENV_ERROR_DEBUG_CODE = r\"\"\"\n            from sysconfig import get_paths\n            paths = get_paths()\n            print(\n                f'imported `pkg` from `{pkg.__file__}`',\n                file=sys.stderr)\n            print('system sites:\\n  ' + '\\n  '.join(sorted({\n                            paths['platlib'],\n                            paths['purelib'],\n                    })), file=sys.stderr)\n    \"\"\"\n\n\n@with_both_installers\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_build_env_isolation(\n    script: PipTestEnvironment, install_method: InstallMethod\n) -> None:\n    # Create dummy `pkg` wheel.\n    pkg_whl = create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n\n    # Install it to site packages.\n    script.pip_install_local(pkg_whl)\n\n    # And a copy in the user site.\n    script.pip_install_local(\"--ignore-installed\", \"--user\", pkg_whl)\n\n    # And to another directory available through a .pth file.\n    target = script.scratch_path / \"pth_install\"\n    script.pip_install_local(\"-t\", target, pkg_whl)\n    (script.site_packages_path / \"build_requires.pth\").write_text(str(target) + \"\\n\")\n\n    # And finally to yet another directory available through PYTHONPATH.\n    target = script.scratch_path / \"pypath_install\"\n    script.pip_install_local(\"-t\", target, pkg_whl)\n    script.environ[\"PYTHONPATH\"] = target\n\n    system_sites = _get_system_sitepackages()\n    # there should always be something to exclude\n    assert system_sites\n\n    run_with_build_env(\n        script,\n        \"\",\n        f\"\"\"\n        import sys\n\n        try:\n            import pkg\n        except ImportError:\n            pass\n        else:\n            {BUILD_ENV_ERROR_DEBUG_CODE}\n            print('sys.path:\\\\n  ' + '\\\\n  '.join(sys.path), file=sys.stderr)\n            sys.exit(1)\n        # second check: direct check of exclusion of system site packages\n        import os\n\n        normalized_path = [os.path.normcase(path) for path in sys.path]\n        for system_path in {system_sites!r}:\n            assert system_path not in normalized_path, \\\n            f\"{{system_path}} found in {{normalized_path}}\"\n        \"\"\",\n        install_method=install_method,\n    )\n"
  },
  {
    "path": "tests/functional/test_cache.py",
    "content": "import json\nimport os\nimport re\nimport shutil\nfrom glob import glob\nfrom typing import Callable\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, TestPipResult\n\n\n@pytest.fixture\ndef cache_dir(script: PipTestEnvironment) -> str:\n    result = script.run(\n        \"python\",\n        \"-c\",\n        \"from pip._internal.locations import USER_CACHE_DIR;print(USER_CACHE_DIR)\",\n    )\n    return result.stdout.strip()\n\n\n@pytest.fixture\ndef http_cache_dir(cache_dir: str) -> str:\n    return os.path.normcase(os.path.join(cache_dir, \"http-v2\"))\n\n\n@pytest.fixture\ndef wheel_cache_dir(cache_dir: str) -> str:\n    return os.path.normcase(os.path.join(cache_dir, \"wheels\"))\n\n\n@pytest.fixture\ndef http_cache_files(http_cache_dir: str) -> list[str]:\n    destination = os.path.join(http_cache_dir, \"arbitrary\", \"pathname\")\n\n    if not os.path.exists(destination):\n        return []\n\n    filenames = glob(os.path.join(destination, \"*\"))\n    return [os.path.join(destination, filename) for filename in filenames]\n\n\n@pytest.fixture\ndef wheel_cache_files(wheel_cache_dir: str) -> list[str]:\n    destination = os.path.join(wheel_cache_dir, \"arbitrary\", \"pathname\")\n\n    if not os.path.exists(destination):\n        return []\n\n    filenames = glob(os.path.join(destination, \"*.whl\"))\n    return [os.path.join(destination, filename) for filename in filenames]\n\n\n@pytest.fixture\ndef populate_http_cache(http_cache_dir: str) -> list[tuple[str, str]]:\n    destination = os.path.join(http_cache_dir, \"arbitrary\", \"pathname\")\n    os.makedirs(destination)\n\n    files = [\n        (\"aaaaaaaaa\", os.path.join(destination, \"aaaaaaaaa\")),\n        (\"bbbbbbbbb\", os.path.join(destination, \"bbbbbbbbb\")),\n        (\"ccccccccc\", os.path.join(destination, \"ccccccccc\")),\n    ]\n\n    for _name, filename in files:\n        with open(filename, \"w\"):\n            pass\n\n    return files\n\n\n@pytest.fixture\ndef populate_wheel_cache(wheel_cache_dir: str) -> list[tuple[str, str]]:\n    destination = os.path.join(wheel_cache_dir, \"arbitrary\", \"pathname\")\n    os.makedirs(destination)\n\n    files = [\n        (\"yyy-1.2.3\", os.path.join(destination, \"yyy-1.2.3-py3-none-any.whl\")),\n        (\"zzz-4.5.6\", os.path.join(destination, \"zzz-4.5.6-py3-none-any.whl\")),\n        (\"zzz-4.5.7\", os.path.join(destination, \"zzz-4.5.7-py3-none-any.whl\")),\n        (\"zzz-7.8.9\", os.path.join(destination, \"zzz-7.8.9-py3-none-any.whl\")),\n    ]\n\n    for _name, filename in files:\n        with open(filename, \"w\"):\n            pass\n\n    return files\n\n\n@pytest.fixture\ndef empty_wheel_cache(wheel_cache_dir: str) -> None:\n    if os.path.exists(wheel_cache_dir):\n        shutil.rmtree(wheel_cache_dir)\n\n\ndef list_matches_wheel(wheel_name: str, result: TestPipResult) -> bool:\n    \"\"\"Returns True if any line in `result`, which should be the output of\n    a `pip cache list` call, matches `wheel_name`.\n\n    E.g., If wheel_name is `foo-1.2.3` it searches for a line starting with\n          `- foo-1.2.3-py3-none-any.whl `.\"\"\"\n    lines = result.stdout.splitlines()\n    expected = f\" - {wheel_name}-py3-none-any.whl \"\n    return any(line.startswith(expected) for line in lines)\n\n\ndef list_matches_wheel_abspath(wheel_name: str, result: TestPipResult) -> bool:\n    \"\"\"Returns True if any line in `result`, which should be the output of\n    a `pip cache list --format=abspath` call, is a valid path and belongs to\n    `wheel_name`.\n\n    E.g., If wheel_name is `foo-1.2.3` it searches for a line starting with\n          `foo-1.2.3-py3-none-any.whl`.\"\"\"\n    lines = result.stdout.splitlines()\n    expected = f\"{wheel_name}-py3-none-any.whl\"\n    return any(\n        (os.path.basename(line).startswith(expected) and os.path.exists(line))\n        for line in lines\n    )\n\n\nRemoveMatches = Callable[[str, TestPipResult], bool]\n\n\n@pytest.fixture\ndef remove_matches_http(http_cache_dir: str) -> RemoveMatches:\n    \"\"\"Returns True if any line in `result`, which should be the output of\n    a `pip cache purge` call, matches `http_filename`.\n\n    E.g., If http_filename is `aaaaaaaaa`, it searches for a line equal to\n    `Removed <http files cache dir>/arbitrary/pathname/aaaaaaaaa`.\n    \"\"\"\n\n    def _remove_matches_http(http_filename: str, result: TestPipResult) -> bool:\n        lines = result.stdout.splitlines()\n\n        # The \"/arbitrary/pathname/\" bit is an implementation detail of how\n        # the `populate_http_cache` fixture is implemented.\n        path = os.path.join(\n            http_cache_dir,\n            \"arbitrary\",\n            \"pathname\",\n            http_filename,\n        )\n        expected = f\"Removed {path}\"\n        return expected in lines\n\n    return _remove_matches_http\n\n\n@pytest.fixture\ndef remove_matches_wheel(wheel_cache_dir: str) -> RemoveMatches:\n    \"\"\"Returns True if any line in `result`, which should be the output of\n    a `pip cache remove`/`pip cache purge` call, matches `wheel_name`.\n\n    E.g., If wheel_name is `foo-1.2.3`, it searches for a line equal to\n    `Removed <wheel cache dir>/arbitrary/pathname/foo-1.2.3-py3-none-any.whl`.\n    \"\"\"\n\n    def _remove_matches_wheel(wheel_name: str, result: TestPipResult) -> bool:\n        lines = result.stdout.splitlines()\n\n        wheel_filename = f\"{wheel_name}-py3-none-any.whl\"\n\n        # The \"/arbitrary/pathname/\" bit is an implementation detail of how\n        # the `populate_wheel_cache` fixture is implemented.\n        path = os.path.join(\n            wheel_cache_dir,\n            \"arbitrary\",\n            \"pathname\",\n            wheel_filename,\n        )\n        expected = f\"Removed {path}\"\n        return expected in lines\n\n    return _remove_matches_wheel\n\n\ndef test_cache_dir(script: PipTestEnvironment, cache_dir: str) -> None:\n    result = script.pip(\"cache\", \"dir\")\n\n    assert os.path.normcase(cache_dir) == result.stdout.strip()\n\n\ndef test_cache_dir_too_many_args(script: PipTestEnvironment, cache_dir: str) -> None:\n    result = script.pip(\"cache\", \"dir\", \"aaa\", expect_error=True)\n\n    assert result.stdout == \"\"\n\n    # This would be `result.stderr == ...`, but pip prints deprecation\n    # warnings on Python 2.7, so we check if the _line_ is in stderr.\n    assert \"ERROR: Too many arguments\" in result.stderr.splitlines()\n\n\n@pytest.mark.usefixtures(\"populate_http_cache\", \"populate_wheel_cache\")\ndef test_cache_info(\n    script: PipTestEnvironment,\n    http_cache_dir: str,\n    wheel_cache_dir: str,\n    wheel_cache_files: list[str],\n) -> None:\n    result = script.pip(\"cache\", \"info\")\n\n    assert (\n        f\"Package index page cache location (pip v23.3+): {http_cache_dir}\"\n        in result.stdout\n    )\n    assert f\"Locally built wheels location: {wheel_cache_dir}\" in result.stdout\n    num_wheels = len(wheel_cache_files)\n    assert f\"Number of locally built wheels: {num_wheels}\" in result.stdout\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list` should return exactly what the\n    populate_wheel_cache fixture adds.\"\"\"\n    result = script.pip(\"cache\", \"list\")\n\n    assert list_matches_wheel(\"yyy-1.2.3\", result)\n    assert list_matches_wheel(\"zzz-4.5.6\", result)\n    assert list_matches_wheel(\"zzz-4.5.7\", result)\n    assert list_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list_abspath(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list --format=abspath` should return full\n    paths of exactly what the populate_wheel_cache fixture adds.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"--format=abspath\")\n\n    assert list_matches_wheel_abspath(\"yyy-1.2.3\", result)\n    assert list_matches_wheel_abspath(\"zzz-4.5.6\", result)\n    assert list_matches_wheel_abspath(\"zzz-4.5.7\", result)\n    assert list_matches_wheel_abspath(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"empty_wheel_cache\")\ndef test_cache_list_with_empty_cache(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list` with an empty cache should print\n    \"No locally built wheels cached.\" and exit.\"\"\"\n    result = script.pip(\"cache\", \"list\")\n    assert result.stdout == \"No locally built wheels cached.\\n\"\n\n\n@pytest.mark.usefixtures(\"empty_wheel_cache\")\ndef test_cache_list_with_empty_cache_abspath(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list --format=abspath` with an empty cache should not\n    print anything and exit.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"--format=abspath\")\n    assert result.stdout.strip() == \"\"\n\n\n@pytest.mark.usefixtures(\"empty_wheel_cache\")\ndef test_cache_purge_with_empty_cache(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache purge` with an empty cache should print a warning\n    and exit without an error code.\"\"\"\n    result = script.pip(\"cache\", \"purge\", allow_stderr_warning=True)\n    assert result.stderr == \"WARNING: No matching packages\\n\"\n    assert result.stdout == \"Files removed: 0 (0 bytes)\\nDirectories removed: 0\\n\"\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_remove_with_bad_pattern(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache remove` with a bad pattern should print a warning\n    and exit without an error code.\"\"\"\n    result = script.pip(\"cache\", \"remove\", \"aaa\", allow_stderr_warning=True)\n    assert result.stderr == 'WARNING: No matching packages for pattern \"aaa\"\\n'\n    assert result.stdout == \"Files removed: 0 (0 bytes)\\nDirectories removed: 0\\n\"\n\n\ndef test_cache_list_too_many_args(script: PipTestEnvironment) -> None:\n    \"\"\"Passing `pip cache list` too many arguments should cause an error.\"\"\"\n    script.pip(\"cache\", \"list\", \"aaa\", \"bbb\", expect_error=True)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list_name_match(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list zzz` should list zzz-4.5.6, zzz-4.5.7,\n    zzz-7.8.9, but nothing else.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"zzz\", \"--verbose\")\n\n    assert not list_matches_wheel(\"yyy-1.2.3\", result)\n    assert list_matches_wheel(\"zzz-4.5.6\", result)\n    assert list_matches_wheel(\"zzz-4.5.7\", result)\n    assert list_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list_name_match_abspath(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list zzz --format=abspath` should list paths of\n    zzz-4.5.6, zzz-4.5.7, zzz-7.8.9, but nothing else.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"zzz\", \"--format=abspath\", \"--verbose\")\n\n    assert not list_matches_wheel_abspath(\"yyy-1.2.3\", result)\n    assert list_matches_wheel_abspath(\"zzz-4.5.6\", result)\n    assert list_matches_wheel_abspath(\"zzz-4.5.7\", result)\n    assert list_matches_wheel_abspath(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list_name_and_version_match(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list zzz-4.5.6` should list zzz-4.5.6, but\n    nothing else.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"zzz-4.5.6\", \"--verbose\")\n\n    assert not list_matches_wheel(\"yyy-1.2.3\", result)\n    assert list_matches_wheel(\"zzz-4.5.6\", result)\n    assert not list_matches_wheel(\"zzz-4.5.7\", result)\n    assert not list_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_list_name_and_version_match_abspath(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache list zzz-4.5.6 --format=abspath` should list path of\n    zzz-4.5.6, but nothing else.\"\"\"\n    result = script.pip(\"cache\", \"list\", \"zzz-4.5.6\", \"--format=abspath\", \"--verbose\")\n\n    assert not list_matches_wheel_abspath(\"yyy-1.2.3\", result)\n    assert list_matches_wheel_abspath(\"zzz-4.5.6\", result)\n    assert not list_matches_wheel_abspath(\"zzz-4.5.7\", result)\n    assert not list_matches_wheel_abspath(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_remove_no_arguments(script: PipTestEnvironment) -> None:\n    \"\"\"Running `pip cache remove` with no arguments should cause an error.\"\"\"\n    script.pip(\"cache\", \"remove\", expect_error=True)\n\n\ndef test_cache_remove_too_many_args(script: PipTestEnvironment) -> None:\n    \"\"\"Passing `pip cache remove` too many arguments should cause an error.\"\"\"\n    script.pip(\"cache\", \"remove\", \"aaa\", \"bbb\", expect_error=True)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_remove_name_match(\n    script: PipTestEnvironment, remove_matches_wheel: RemoveMatches\n) -> None:\n    \"\"\"Running `pip cache remove zzz` should remove zzz-4.5.6 and zzz-7.8.9,\n    but nothing else.\"\"\"\n    result = script.pip(\"cache\", \"remove\", \"zzz\", \"--verbose\")\n\n    assert not remove_matches_wheel(\"yyy-1.2.3\", result)\n    assert remove_matches_wheel(\"zzz-4.5.6\", result)\n    assert remove_matches_wheel(\"zzz-4.5.7\", result)\n    assert remove_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_wheel_cache\")\ndef test_cache_remove_name_and_version_match(\n    script: PipTestEnvironment, remove_matches_wheel: RemoveMatches\n) -> None:\n    \"\"\"Running `pip cache remove zzz-4.5.6` should remove zzz-4.5.6, but\n    nothing else.\"\"\"\n    result = script.pip(\"cache\", \"remove\", \"zzz-4.5.6\", \"--verbose\")\n\n    assert not remove_matches_wheel(\"yyy-1.2.3\", result)\n    assert remove_matches_wheel(\"zzz-4.5.6\", result)\n    assert not remove_matches_wheel(\"zzz-4.5.7\", result)\n    assert not remove_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_http_cache\", \"populate_wheel_cache\")\ndef test_cache_purge(\n    script: PipTestEnvironment,\n    remove_matches_http: RemoveMatches,\n    remove_matches_wheel: RemoveMatches,\n) -> None:\n    \"\"\"Running `pip cache purge` should remove all cached http files and\n    wheels.\"\"\"\n    result = script.pip(\"cache\", \"purge\", \"--verbose\")\n\n    assert remove_matches_http(\"aaaaaaaaa\", result)\n    assert remove_matches_http(\"bbbbbbbbb\", result)\n    assert remove_matches_http(\"ccccccccc\", result)\n\n    assert remove_matches_wheel(\"yyy-1.2.3\", result)\n    assert remove_matches_wheel(\"zzz-4.5.6\", result)\n    assert remove_matches_wheel(\"zzz-4.5.7\", result)\n    assert remove_matches_wheel(\"zzz-7.8.9\", result)\n\n\n@pytest.mark.usefixtures(\"populate_http_cache\", \"populate_wheel_cache\")\ndef test_cache_purge_too_many_args(\n    script: PipTestEnvironment,\n    http_cache_files: list[str],\n    wheel_cache_files: list[str],\n) -> None:\n    \"\"\"Running `pip cache purge aaa` should raise an error and remove no\n    cached http files or wheels.\"\"\"\n    result = script.pip(\"cache\", \"purge\", \"aaa\", \"--verbose\", expect_error=True)\n    assert result.stdout == \"\"\n\n    # This would be `result.stderr == ...`, but pip prints deprecation\n    # warnings on Python 2.7, so we check if the _line_ is in stderr.\n    assert \"ERROR: Too many arguments\" in result.stderr.splitlines()\n\n    # Make sure nothing was deleted.\n    for filename in http_cache_files + wheel_cache_files:\n        assert os.path.exists(filename)\n\n\n@pytest.mark.parametrize(\"command\", [\"info\", \"list\", \"remove\", \"purge\"])\ndef test_cache_abort_when_no_cache_dir(\n    script: PipTestEnvironment, command: str\n) -> None:\n    \"\"\"Running any pip cache command when cache is disabled should\n    abort and log an informative error\"\"\"\n    result = script.pip(\"cache\", command, \"--no-cache-dir\", expect_error=True)\n    assert result.stdout == \"\"\n\n    assert (\n        \"ERROR: pip cache commands can not function\"\n        \" since cache is disabled.\" in result.stderr.splitlines()\n    )\n\n\n@pytest.fixture\ndef populate_wheel_cache_with_empty_dirs(wheel_cache_dir: str) -> None:\n    metadata_dir = os.path.join(wheel_cache_dir, \"metadata_only\")\n    os.makedirs(metadata_dir)\n    with open(os.path.join(metadata_dir, \"metadata.json\"), \"w\"):\n        pass\n\n    empty_dir = os.path.join(wheel_cache_dir, \"completely_empty\")\n    os.makedirs(empty_dir)\n\n    nested_empty = os.path.join(wheel_cache_dir, \"nested\", \"empty\", \"dirs\")\n    os.makedirs(nested_empty)\n\n\n@pytest.fixture\ndef populate_http_cache_with_empty_dirs(cache_dir: str) -> None:\n    http_cache_dir = os.path.join(cache_dir, \"http\")\n    empty1 = os.path.join(http_cache_dir, \"empty1\")\n    empty2 = os.path.join(http_cache_dir, \"empty2\", \"nested\")\n\n    os.makedirs(empty1)\n    os.makedirs(empty2)\n\n\n@pytest.fixture\ndef create_selfcheck_json(cache_dir: str) -> None:\n    selfcheck_path = os.path.join(cache_dir, \"selfcheck.json\")\n    with open(selfcheck_path, \"w\") as statefile:\n        json.dump(\n            {\n                \"/some/prefix\": {\n                    \"last_check\": \"2020-01-01T00:00:00\",\n                    \"pypi_version\": \"20.0.1\",\n                }\n            },\n            statefile,\n        )\n\n\n@pytest.mark.usefixtures(\n    \"populate_wheel_cache_with_empty_dirs\",\n    \"populate_http_cache_with_empty_dirs\",\n    \"create_selfcheck_json\",\n)\ndef test_cache_purge_removes_empty_dirs_and_legacy_files(\n    script: PipTestEnvironment,\n    cache_dir: str,\n    wheel_cache_dir: str,\n) -> None:\n    \"\"\"Test pip cache purge/remove with empty dirs and legacy files.\n\n    Verifies purge removes:\n    - Wheel cache directories without .whl files\n    - HTTP cache empty directories\n    - Legacy selfcheck.json file\n    - Reports correct directory counts\n    Also tests that 'cache remove' works similarly.\n    \"\"\"\n    selfcheck_path = os.path.join(cache_dir, \"selfcheck.json\")\n    http_cache_dir = os.path.join(cache_dir, \"http\")\n    metadata_dir = os.path.join(wheel_cache_dir, \"metadata_only\")\n\n    # Verify setup\n    assert os.path.exists(selfcheck_path)\n    assert os.path.exists(metadata_dir)\n    assert os.path.exists(os.path.join(http_cache_dir, \"empty1\"))\n\n    result = script.pip(\"cache\", \"purge\", \"--verbose\", allow_stderr_warning=True)\n\n    # Verify all cleanup happened\n    assert not os.path.exists(selfcheck_path)\n    assert \"Removed legacy selfcheck.json file\" in result.stdout\n    assert not os.path.exists(metadata_dir)\n    assert not os.path.exists(os.path.join(wheel_cache_dir, \"completely_empty\"))\n    assert not os.path.exists(os.path.join(http_cache_dir, \"empty1\"))\n    assert \"Directories removed:\" in result.stdout\n\n    # Verify directory count is positive\n    dir_count = int(re.findall(r\"Directories removed: (\\d+)\", result.stdout)[0])\n    assert dir_count > 0\n\n\ndef test_cache_purge_with_mixed_content(\n    script: PipTestEnvironment,\n    populate_wheel_cache: list[tuple[str, str]],\n    wheel_cache_dir: str,\n) -> None:\n    \"\"\"Test purge removes both wheel files and empty directories.\"\"\"\n    # Add an empty directory alongside the wheels\n    empty_dir = os.path.join(wheel_cache_dir, \"empty_subdir\")\n    os.makedirs(empty_dir)\n\n    result = script.pip(\"cache\", \"purge\", \"--verbose\")\n\n    # Verify wheels and empty directory were removed\n    for _name, filepath in populate_wheel_cache:\n        assert not os.path.exists(filepath)\n    assert not os.path.exists(empty_dir)\n\n    # Verify counts in output\n    assert \"Files removed:\" in result.stdout\n    assert \"Directories removed:\" in result.stdout\n    files_removed = int(re.findall(r\"Files removed: (\\d+)\", result.stdout)[0])\n    assert files_removed == 4\n"
  },
  {
    "path": "tests/functional/test_check.py",
    "content": "from collections.abc import Collection\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    create_really_basic_wheel,\n    create_test_package_with_setup,\n)\n\n\ndef matches_expected_lines(string: str, expected_lines: Collection[str]) -> bool:\n    # Ignore empty lines\n    output_lines = list(filter(None, string.splitlines()))\n    # We'll match the last n lines, given n lines to match.\n    last_few_output_lines = output_lines[-len(expected_lines) :]\n    # And order does not matter\n    return set(last_few_output_lines) == set(expected_lines)\n\n\ndef test_basic_check_clean(script: PipTestEnvironment) -> None:\n    \"\"\"On a clean environment, check should print a helpful message.\"\"\"\n    result = script.pip(\"check\")\n\n    expected_lines = (\"No broken requirements found.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 0\n\n\ndef test_basic_check_missing_dependency(script: PipTestEnvironment) -> None:\n    # Setup a small project\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        install_requires=[\"missing==0.1\"],\n    )\n    # Let's install pkga without its dependency\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkga-1.0\" in res.stdout, str(res)\n\n    result = script.pip(\"check\", expect_error=True)\n\n    expected_lines = (\"pkga 1.0 requires missing, which is not installed.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_basic_check_broken_dependency(script: PipTestEnvironment) -> None:\n    # Setup pkga depending on pkgb>=1.0\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        install_requires=[\"broken>=1.0\"],\n    )\n    # Let's install pkga without its dependency\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkga-1.0\" in res.stdout, str(res)\n\n    # Setup broken==0.1\n    broken_path = create_test_package_with_setup(\n        script,\n        name=\"broken\",\n        version=\"0.1\",\n    )\n    # Let's install broken==0.1\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        broken_path,\n        \"--no-warn-conflicts\",\n    )\n    assert \"Successfully installed broken-0.1\" in res.stdout, str(res)\n\n    result = script.pip(\"check\", expect_error=True)\n\n    expected_lines = (\"pkga 1.0 has requirement broken>=1.0, but you have broken 0.1.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_basic_check_broken_dependency_and_missing_dependency(\n    script: PipTestEnvironment,\n) -> None:\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        install_requires=[\"broken>=1.0\"],\n    )\n    # Let's install pkga without its dependency\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkga-1.0\" in res.stdout, str(res)\n\n    # Setup broken==0.1\n    broken_path = create_test_package_with_setup(\n        script,\n        name=\"broken\",\n        version=\"0.1\",\n        install_requires=[\"missing\"],\n    )\n    # Let's install broken==0.1\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", broken_path, \"--no-deps\"\n    )\n    assert \"Successfully installed broken-0.1\" in res.stdout, str(res)\n\n    result = script.pip(\"check\", expect_error=True)\n\n    expected_lines = (\n        \"broken 0.1 requires missing, which is not installed.\",\n        \"pkga 1.0 has requirement broken>=1.0, but you have broken 0.1.\",\n    )\n\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_check_complicated_name_missing(script: PipTestEnvironment) -> None:\n    package_a_path = create_test_package_with_setup(\n        script,\n        name=\"package_A\",\n        version=\"1.0\",\n        install_requires=[\"Dependency-B>=1.0\"],\n    )\n\n    # Without dependency\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", package_a_path, \"--no-deps\"\n    )\n    assert (\n        \"Successfully installed package_A-1.0\" in result.stdout\n        or \"Successfully installed package-A-1.0\" in result.stdout\n    ), str(result)\n\n    result = script.pip(\"check\", expect_error=True)\n    expected_lines = (\"package-a 1.0 requires dependency-b, which is not installed.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_check_complicated_name_broken(script: PipTestEnvironment) -> None:\n    package_a_path = create_test_package_with_setup(\n        script,\n        name=\"package_A\",\n        version=\"1.0\",\n        install_requires=[\"Dependency-B>=1.0\"],\n    )\n    dependency_b_path_incompatible = create_test_package_with_setup(\n        script,\n        name=\"dependency-b\",\n        version=\"0.1\",\n    )\n\n    # With broken dependency\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", package_a_path, \"--no-deps\"\n    )\n    assert (\n        \"Successfully installed package_A-1.0\" in result.stdout\n        or \"Successfully installed package-A-1.0\" in result.stdout\n    ), str(result)\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        dependency_b_path_incompatible,\n        \"--no-deps\",\n    )\n    assert \"Successfully installed dependency-b-0.1\" in result.stdout\n\n    result = script.pip(\"check\", expect_error=True)\n    expected_lines = (\n        \"package-a 1.0 has requirement Dependency-B>=1.0, but you have \"\n        \"dependency-b 0.1.\",\n    )\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_check_complicated_name_clean(script: PipTestEnvironment) -> None:\n    package_a_path = create_test_package_with_setup(\n        script,\n        name=\"package_A\",\n        version=\"1.0\",\n        install_requires=[\"Dependency-B>=1.0\"],\n    )\n    dependency_b_path = create_test_package_with_setup(\n        script,\n        name=\"dependency-b\",\n        version=\"1.0\",\n    )\n\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", package_a_path, \"--no-deps\"\n    )\n    assert (\n        \"Successfully installed package_A-1.0\" in result.stdout\n        or \"Successfully installed package-A-1.0\" in result.stdout\n    ), str(result)\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        dependency_b_path,\n        \"--no-deps\",\n    )\n    assert \"Successfully installed dependency-b-1.0\" in result.stdout\n\n    result = script.pip(\"check\")\n    expected_lines = (\"No broken requirements found.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 0\n\n\ndef test_check_considers_conditional_reqs(script: PipTestEnvironment) -> None:\n    package_a_path = create_test_package_with_setup(\n        script,\n        name=\"package_A\",\n        version=\"1.0\",\n        install_requires=[\n            \"Dependency-B>=1.0; python_version != '2.7'\",\n            \"Dependency-B>=2.0; python_version == '2.7'\",\n        ],\n    )\n\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", package_a_path, \"--no-deps\"\n    )\n    assert (\n        \"Successfully installed package_A-1.0\" in result.stdout\n        or \"Successfully installed package-A-1.0\" in result.stdout\n    ), str(result)\n\n    result = script.pip(\"check\", expect_error=True)\n    expected_lines = (\"package-a 1.0 requires dependency-b, which is not installed.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_check_development_versions_are_also_considered(\n    script: PipTestEnvironment,\n) -> None:\n    # Setup pkga depending on pkgb>=1.0\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        install_requires=[\"depend>=1.0\"],\n    )\n    # Let's install pkga without its dependency\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkga-1.0\" in res.stdout, str(res)\n\n    # Setup depend==1.1.0.dev0\n    depend_path = create_test_package_with_setup(\n        script,\n        name=\"depend\",\n        version=\"1.1.0.dev0\",\n    )\n    # Let's install depend==1.1.0.dev0\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        depend_path,\n        \"--no-warn-conflicts\",\n    )\n    assert \"Successfully installed depend-1.1.0.dev0\" in res.stdout, str(res)\n\n    result = script.pip(\"check\")\n    expected_lines = (\"No broken requirements found.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 0\n\n\ndef test_basic_check_broken_metadata(script: PipTestEnvironment) -> None:\n    # Create some corrupt metadata\n    dist_info_dir = script.site_packages_path / \"pkga-1.0.dist-info\"\n    dist_info_dir.mkdir()\n    with open(dist_info_dir / \"METADATA\", \"w\") as f:\n        f.write(\n            \"Metadata-Version: 2.1\\n\"\n            \"Name: pkga\\n\"\n            \"Version: 1.0\\n\"\n            'Requires-Dist: pip; python_version == \"3.4\";extra == \"test\"\\n'\n        )\n\n    result = script.pip(\"check\", expect_error=True)\n\n    assert \"Error parsing dependencies of\" in result.stderr\n    assert result.returncode == 1\n\n\ndef test_check_skip_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that check should not include package\n    present in working directory\n    \"\"\"\n\n    # Create a test package with dependency missing\n    # and create .egg-info dir\n    pkg_path = create_test_package_with_setup(\n        script, name=\"simple\", version=\"1.0\", install_requires=[\"missing==0.1\"]\n    )\n\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    # Check should not complain about broken requirements\n    # when run from package directory\n    result = script.pip(\"check\", cwd=pkg_path)\n    expected_lines = (\"No broken requirements found.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 0\n\n\ndef test_check_include_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that check should include package in working directory\n    if working directory is added in PYTHONPATH\n    \"\"\"\n\n    # Create a test package with dependency missing\n    # and create .egg-info dir\n    pkg_path = create_test_package_with_setup(\n        script, name=\"simple\", version=\"1.0\", install_requires=[\"missing==0.1\"]\n    )\n\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    # Check should mention about missing requirement simple\n    # when run from package directory, when package directory\n    # is in PYTHONPATH\n    result = script.pip(\"check\", expect_error=True, cwd=pkg_path)\n    expected_lines = (\"simple 1.0 requires missing, which is not installed.\",)\n    assert matches_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 1\n\n\ndef test_check_unsupported(\n    script: PipTestEnvironment,\n) -> None:\n    script.scratch_path.joinpath(\"base-0.1.0-py2.py3-none-any.whl\").write_bytes(\n        create_really_basic_wheel(\"base\", \"0.1.0\")\n    )\n    script.pip_install_local(\"base==0.1.0\", find_links=script.scratch_path)\n    with open(\n        script.site_packages_path.joinpath(\"base-0.1.0.dist-info/WHEEL\"), \"a\"\n    ) as f:\n        f.write(\"\\nTag: cp310-cp310-musllinux_1_1_x86_64\\n\")\n    result = script.pip(\"check\", expect_error=True)\n    assert \"base 0.1.0 is not supported on this platform\" in result.stdout\n    assert result.returncode == 1\n"
  },
  {
    "path": "tests/functional/test_cli.py",
    "content": "\"\"\"Basic CLI functionality checks.\"\"\"\n\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom textwrap import dedent\n\nimport pytest\n\nfrom pip._internal.commands import commands_dict\n\nfrom tests.lib import PipTestEnvironment\n\n\n@pytest.mark.parametrize(\n    \"entrypoint\",\n    [\n        (\"fake_pip = pip._internal.main:main\",),\n        (\"fake_pip = pip._internal:main\",),\n        (\"fake_pip = pip:main\",),\n    ],\n)\ndef test_entrypoints_work(entrypoint: str, script: PipTestEnvironment) -> None:\n    if script.zipapp:\n        pytest.skip(\"Zipapp does not include entrypoints\")\n\n    fake_pkg = script.scratch_path / \"fake_pkg\"\n    fake_pkg.mkdir()\n    fake_pkg.joinpath(\"setup.py\").write_text(\n        dedent(\n            f\"\"\"\n    from setuptools import setup\n\n    setup(\n        name=\"fake-pip\",\n        version=\"0.1.0\",\n        entry_points={{\n            \"console_scripts\": [\n                {entrypoint!r}\n            ]\n        }}\n    )\n    \"\"\"\n        )\n    )\n\n    # expect_temp because pip install will generate fake_pkg.egg-info\n    script.pip(\n        \"install\", \"--no-build-isolation\", \"-vvv\", str(fake_pkg), expect_temp=True\n    )\n    result = script.pip(\"-V\")\n    result2 = script.run(\"fake_pip\", \"-V\", allow_stderr_warning=True)\n    assert result.stdout == result2.stdout\n    assert \"old script wrapper\" in result2.stderr\n\n\n@pytest.mark.parametrize(\n    \"command\",\n    sorted(\n        set(commands_dict).symmetric_difference(\n            # Exclude commands that are expected to use the network.\n            {\"install\", \"download\", \"search\", \"index\", \"lock\", \"wheel\"}\n        )\n    ),\n)\ndef test_no_network_imports(command: str, tmp_path: Path) -> None:\n    \"\"\"\n    Verify that commands that don't access the network do NOT import network code.\n\n    This helps to reduce the startup time of these commands.\n\n    Note: This won't catch lazy network imports, but it'll catch top-level\n    network imports which were accidentally added (which is the most likely way\n    to regress anyway).\n    \"\"\"\n    file = tmp_path / f\"imported_modules_for_{command}.txt\"\n    code = f\"\"\"\nimport runpy\nimport sys\n\nsys.argv[1:] = [{command!r}, \"--help\"]\n\ntry:\n    runpy.run_module(\"pip\", alter_sys=True, run_name=\"__main__\")\nfinally:\n    with open({str(file)!r}, \"w\") as f:\n        print(*sys.modules.keys(), sep=\"\\\\n\", file=f)\n    \"\"\"\n    subprocess.run(\n        [sys.executable],\n        input=code,\n        encoding=\"utf-8\",\n        check=True,\n    )\n    imported = file.read_text().splitlines()\n    assert not any(\"pip._internal.index\" in mod for mod in imported)\n    assert not any(\"pip._internal.network\" in mod for mod in imported)\n    assert not any(\"requests\" in mod for mod in imported)\n    assert not any(\"urllib3\" in mod for mod in imported)\n"
  },
  {
    "path": "tests/functional/test_completion.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\nfrom pathlib import Path\nfrom typing import Protocol\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, ScriptFactory, TestData, TestPipResult\n\nCOMPLETION_FOR_SUPPORTED_SHELLS_TESTS = (\n    (\n        \"bash\",\n        \"\"\"\\\n_pip_completion()\n{\n    local IFS=$' \\\\t\\\\n'\n    COMPREPLY=( $( COMP_WORDS=\"${COMP_WORDS[*]}\" \\\\\n                   COMP_CWORD=$COMP_CWORD \\\\\n                   PIP_AUTO_COMPLETE=1 \"$1\" 2>/dev/null ) )\n}\ncomplete -o default -F _pip_completion pip\"\"\",\n    ),\n    (\n        \"fish\",\n        \"\"\"\\\nfunction __fish_complete_pip\n    set -lx COMP_WORDS \\\\\n        (commandline --current-process --tokenize --cut-at-cursor) \\\\\n        (commandline --current-token --cut-at-cursor)\n    set -lx COMP_CWORD (math (count $COMP_WORDS) - 1)\n    set -lx PIP_AUTO_COMPLETE 1\n    set -l completions\n    if string match -q '2.*' $version\n        set completions (eval $COMP_WORDS[1])\n    else\n        set completions ($COMP_WORDS[1])\n    end\n    string split \\\\  -- $completions\nend\ncomplete -fa \"(__fish_complete_pip)\" -c pip\"\"\",\n    ),\n    (\n        \"zsh\",\n        \"\"\"\\\n#compdef -P pip[0-9.]#\n__pip() {\n  compadd $( COMP_WORDS=\"$words[*]\" \\\\\n             COMP_CWORD=$((CURRENT-1)) \\\\\n             PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )\n}\nif [[ $zsh_eval_context[-1] == loadautofunc ]]; then\n  # autoload from fpath, call function directly\n  __pip \"$@\"\nelse\n  # eval/source/. command, register function for later\n  compdef __pip -P 'pip[0-9.]#'\nfi\"\"\",\n    ),\n    (\n        \"powershell\",\n        \"\"\"\\\nif ((Test-Path Function:\\\\TabExpansion) -and -not `\n    (Test-Path Function:\\\\_pip_completeBackup)) {\n    Rename-Item Function:\\\\TabExpansion _pip_completeBackup\n}\nfunction TabExpansion($line, $lastWord) {\n    $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()\n    if ($lastBlock.StartsWith(\"pip \")) {\n        $Env:COMP_WORDS=$lastBlock\n        $Env:COMP_CWORD=$lastBlock.Split().Length - 1\n        $Env:PIP_AUTO_COMPLETE=1\n        (& pip).Split()\n        Remove-Item Env:COMP_WORDS\n        Remove-Item Env:COMP_CWORD\n        Remove-Item Env:PIP_AUTO_COMPLETE\n    }\n    elseif (Test-Path Function:\\\\_pip_completeBackup) {\n        # Fall back on existing tab expansion\n        _pip_completeBackup $line $lastWord\n    }\n}\"\"\",\n    ),\n)\n\n\n@pytest.fixture(scope=\"session\")\ndef script_with_launchers(\n    tmpdir_factory: pytest.TempPathFactory,\n    script_factory: ScriptFactory,\n    common_wheels: Path,\n    pip_src: Path,\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"script_with_launchers\")\n    script = script_factory(tmpdir.joinpath(\"workspace\"))\n    # Re-install pip so we get the launchers.\n    script.pip(\"install\", \"--no-index\", \"-f\", common_wheels, pip_src)\n    return script\n\n\n@pytest.mark.parametrize(\n    \"shell, completion\",\n    COMPLETION_FOR_SUPPORTED_SHELLS_TESTS,\n    ids=[t[0] for t in COMPLETION_FOR_SUPPORTED_SHELLS_TESTS],\n)\ndef test_completion_for_supported_shells(\n    script_with_launchers: PipTestEnvironment, shell: str, completion: str\n) -> None:\n    \"\"\"\n    Test getting completion for bash shell\n    \"\"\"\n    result = script_with_launchers.pip(\"completion\", \"--\" + shell, use_module=False)\n    actual = str(result.stdout)\n    if script_with_launchers.zipapp:\n        # The zipapp reports its name as \"pip.pyz\", but the expected\n        # output assumes \"pip\"\n        actual = actual.replace(\"pip.pyz\", \"pip\")\n    assert completion in actual, actual\n\n\n@pytest.fixture(scope=\"session\")\ndef autocomplete_script(\n    tmpdir_factory: pytest.TempPathFactory, script_factory: ScriptFactory\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"autocomplete_script\")\n    return script_factory(tmpdir.joinpath(\"workspace\"))\n\n\nclass DoAutocomplete(Protocol):\n    def __call__(\n        self,\n        words: str,\n        cword: str,\n        cwd: Path | str | None = None,\n        include_env: bool = True,\n        expect_error: bool = True,\n    ) -> tuple[TestPipResult, PipTestEnvironment]: ...\n\n\n@pytest.fixture\ndef autocomplete(\n    autocomplete_script: PipTestEnvironment, monkeypatch: pytest.MonkeyPatch\n) -> DoAutocomplete:\n    monkeypatch.setattr(autocomplete_script, \"environ\", os.environ.copy())\n    autocomplete_script.environ[\"PIP_AUTO_COMPLETE\"] = \"1\"\n\n    def do_autocomplete(\n        words: str,\n        cword: str,\n        cwd: Path | str | None = None,\n        include_env: bool = True,\n        expect_error: bool = True,\n    ) -> tuple[TestPipResult, PipTestEnvironment]:\n        if include_env:\n            autocomplete_script.environ[\"COMP_WORDS\"] = words\n            autocomplete_script.environ[\"COMP_CWORD\"] = cword\n        result = autocomplete_script.run(\n            \"python\",\n            \"-c\",\n            \"from pip._internal.cli.autocompletion import autocomplete;\"\n            \"autocomplete()\",\n            expect_error=expect_error,\n            cwd=cwd,\n        )\n\n        return result, autocomplete_script\n\n    return do_autocomplete\n\n\ndef test_completion_for_unknown_shell(autocomplete_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test getting completion for an unknown shell\n    \"\"\"\n    error_msg = \"no such option: --myfooshell\"\n    result = autocomplete_script.pip(\"completion\", \"--myfooshell\", expect_error=True)\n    assert error_msg in result.stderr, \"tests for an unknown shell failed\"\n\n\ndef test_completion_without_env_vars(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion <path> after options in command\n    given absolute path\n    \"\"\"\n    res, env = autocomplete(\n        words=\"pip install \", cword=\"\", include_env=False, expect_error=False\n    )\n    assert res.stdout == \"\", \"autocomplete function did not complete\"\n\n\ndef test_completion_alone(autocomplete_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test getting completion for none shell, just pip completion\n    \"\"\"\n    result = autocomplete_script.pip(\"completion\", allow_stderr_error=True)\n    assert (\n        \"ERROR: You must pass --bash or --fish or --powershell or --zsh\"\n        in result.stderr\n    ), (\"completion alone failed -- \" + result.stderr)\n\n\ndef test_completion_for_un_snippet(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion for ``un`` should return uninstall\n    \"\"\"\n\n    res, env = autocomplete(\"pip un\", \"1\")\n    assert res.stdout.strip().split() == [\"uninstall\"], res.stdout\n\n\ndef test_completion_for_default_parameters(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion for ``--`` should contain --help\n    \"\"\"\n\n    res, env = autocomplete(\"pip --\", \"1\")\n    assert \"--help\" in res.stdout, \"autocomplete function could not complete ``--``\"\n\n\ndef test_completion_option_for_command(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion for ``--`` in command (e.g. ``pip search --``)\n    \"\"\"\n\n    res, env = autocomplete(\"pip search --\", \"2\")\n    assert \"--help\" in res.stdout, \"autocomplete function could not complete ``--``\"\n\n\ndef test_completion_short_option(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion for short options after ``-`` (eg. pip -)\n    \"\"\"\n\n    res, env = autocomplete(\"pip -\", \"1\")\n\n    assert (\n        \"-h\" in res.stdout.split()\n    ), \"autocomplete function could not complete short options after ``-``\"\n\n\ndef test_completion_short_option_for_command(autocomplete: DoAutocomplete) -> None:\n    \"\"\"\n    Test getting completion for short options after ``-`` in command\n    (eg. pip search -)\n    \"\"\"\n\n    res, env = autocomplete(\"pip search -\", \"2\")\n\n    assert (\n        \"-h\" in res.stdout.split()\n    ), \"autocomplete function could not complete short options after ``-``\"\n\n\ndef test_completion_files_after_option(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"\n    Test getting completion for <file> or <dir> after options in command\n    (e.g. ``pip install -r``)\n    \"\"\"\n    res, env = autocomplete(\n        words=(\"pip install -r r\"),\n        cword=\"3\",\n        cwd=data.completion_paths,\n    )\n    assert (\n        \"requirements.txt\" in res.stdout\n    ), \"autocomplete function could not complete <file> after options in command\"\n    assert (\n        os.path.join(\"resources\", \"\") in res.stdout\n    ), \"autocomplete function could not complete <dir> after options in command\"\n    assert not any(\n        out in res.stdout for out in (os.path.join(\"REPLAY\", \"\"), \"README.txt\")\n    ), (\n        \"autocomplete function completed <file> or <dir> that \"\n        \"should not be completed\"\n    )\n    if sys.platform != \"win32\":\n        return\n    assert (\n        \"readme.txt\" in res.stdout\n    ), \"autocomplete function could not complete <file> after options in command\"\n    assert (\n        os.path.join(\"replay\", \"\") in res.stdout\n    ), \"autocomplete function could not complete <dir> after options in command\"\n\n\ndef test_completion_not_files_after_option(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"\n    Test not getting completion files after options which not applicable\n    (e.g. ``pip wheel``)\n    \"\"\"\n    res, env = autocomplete(\n        words=(\"pip wheel r\"),\n        cword=\"2\",\n        cwd=data.completion_paths,\n    )\n    assert not any(\n        out in res.stdout\n        for out in (\n            \"requirements.txt\",\n            \"readme.txt\",\n        )\n    ), \"autocomplete function completed <file> when it should not complete\"\n    assert not any(\n        os.path.join(out, \"\") in res.stdout for out in (\"replay\", \"resources\")\n    ), \"autocomplete function completed <dir> when it should not complete\"\n\n\ndef test_pip_install_complete_files(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"``pip install`` autocompletes wheel and sdist files.\"\"\"\n    res, env = autocomplete(\n        words=(\"pip install r\"),\n        cword=\"2\",\n        cwd=data.completion_paths,\n    )\n    assert all(\n        out in res.stdout\n        for out in (\n            \"requirements.txt\",\n            \"resources\",\n        )\n    ), \"autocomplete function could not complete <path>\"\n\n\n@pytest.mark.parametrize(\"cl_opts\", [\"-U\", \"--user\", \"-h\"])\ndef test_completion_not_files_after_nonexpecting_option(\n    autocomplete: DoAutocomplete, data: TestData, cl_opts: str\n) -> None:\n    \"\"\"\n    Test not getting completion files after options which not applicable\n    (e.g. ``pip install``)\n    \"\"\"\n    res, env = autocomplete(\n        words=(f\"pip install {cl_opts} r\"),\n        cword=\"2\",\n        cwd=data.completion_paths,\n    )\n    assert not any(\n        out in res.stdout\n        for out in (\n            \"requirements.txt\",\n            \"readme.txt\",\n        )\n    ), \"autocomplete function completed <file> when it should not complete\"\n    assert not any(\n        os.path.join(out, \"\") in res.stdout for out in (\"replay\", \"resources\")\n    ), \"autocomplete function completed <dir> when it should not complete\"\n\n\ndef test_completion_directories_after_option(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"\n    Test getting completion <dir> after options in command\n    (e.g. ``pip --cache-dir``)\n    \"\"\"\n    res, env = autocomplete(\n        words=(\"pip --cache-dir r\"),\n        cword=\"2\",\n        cwd=data.completion_paths,\n    )\n    assert (\n        os.path.join(\"resources\", \"\") in res.stdout\n    ), \"autocomplete function could not complete <dir> after options\"\n    assert not any(\n        out in res.stdout\n        for out in (\"requirements.txt\", \"README.txt\", os.path.join(\"REPLAY\", \"\"))\n    ), \"autocomplete function completed <dir> when it should not complete\"\n    if sys.platform == \"win32\":\n        assert (\n            os.path.join(\"replay\", \"\") in res.stdout\n        ), \"autocomplete function could not complete <dir> after options\"\n\n\ndef test_completion_subdirectories_after_option(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"\n    Test getting completion <dir> after options in command\n    given path of a directory\n    \"\"\"\n    res, env = autocomplete(\n        words=(\"pip --cache-dir \" + os.path.join(\"resources\", \"\")),\n        cword=\"2\",\n        cwd=data.completion_paths,\n    )\n    assert os.path.join(\"resources\", os.path.join(\"images\", \"\")) in res.stdout, (\n        \"autocomplete function could not complete <dir> \"\n        \"given path of a directory after options\"\n    )\n\n\ndef test_completion_path_after_option(\n    autocomplete: DoAutocomplete, data: TestData\n) -> None:\n    \"\"\"\n    Test getting completion <path> after options in command\n    given absolute path\n    \"\"\"\n    res, env = autocomplete(\n        words=(\"pip install -e \" + os.path.join(data.completion_paths, \"R\")),\n        cword=\"3\",\n    )\n    assert all(\n        os.path.normcase(os.path.join(data.completion_paths, out)) in res.stdout\n        for out in (\"README.txt\", os.path.join(\"REPLAY\", \"\"))\n    ), (\n        \"autocomplete function could not complete <path> \"\n        \"after options in command given absolute path\"\n    )\n\n\n# zsh completion script doesn't contain pip3\n@pytest.mark.parametrize(\"flag\", [\"--bash\", \"--fish\", \"--powershell\"])\ndef test_completion_uses_same_executable_name(\n    autocomplete_script: PipTestEnvironment, flag: str, deprecated_python: bool\n) -> None:\n    executable_name = f\"pip{sys.version_info[0]}\"\n    # Deprecated python versions produce an extra deprecation warning\n    result = autocomplete_script.run(\n        executable_name,\n        \"completion\",\n        flag,\n        expect_stderr=deprecated_python,\n    )\n    assert executable_name in result.stdout\n\n\n@pytest.mark.parametrize(\n    \"subcommand, handler_prefix, expected\",\n    [\n        (\"cache\", \"d\", \"dir\"),\n        (\"cache\", \"in\", \"info\"),\n        (\"cache\", \"l\", \"list\"),\n        (\"cache\", \"re\", \"remove\"),\n        (\"cache\", \"pu\", \"purge\"),\n        (\"config\", \"li\", \"list\"),\n        (\"config\", \"e\", \"edit\"),\n        (\"config\", \"ge\", \"get\"),\n        (\"config\", \"se\", \"set\"),\n        (\"config\", \"unse\", \"unset\"),\n        (\"config\", \"d\", \"debug\"),\n        (\"index\", \"ve\", \"versions\"),\n    ],\n)\ndef test_completion_for_action_handler(\n    subcommand: str, handler_prefix: str, expected: str, autocomplete: DoAutocomplete\n) -> None:\n    res, _ = autocomplete(f\"pip {subcommand} {handler_prefix}\", cword=\"2\")\n\n    assert [expected] == res.stdout.split()\n\n\ndef test_completion_for_action_handler_handler_not_repeated(\n    autocomplete: DoAutocomplete,\n) -> None:\n    res, _ = autocomplete(\"pip cache remove re\", cword=\"3\")\n\n    assert [] == res.stdout.split()\n"
  },
  {
    "path": "tests/functional/test_config_settings.py",
    "content": "from __future__ import annotations\n\nimport json\nimport tarfile\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nimport pytest\n\nfrom pip._internal.utils.urls import path_to_url\n\nfrom tests.lib import PipTestEnvironment, create_basic_sdist_for_package\n\nPYPROJECT_TOML = \"\"\"\\\n[build-system]\nrequires = []\nbuild-backend = \"dummy_backend:main\"\nbackend-path = [\"backend\"]\n\"\"\"\n\nBACKEND_SRC = '''\nimport csv\nimport json\nimport os.path\nfrom zipfile import ZipFile\nimport hashlib\nimport base64\nimport io\n\nWHEEL = \"\"\"\\\nWheel-Version: 1.0\nGenerator: dummy_backend 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n\"\"\"\n\nMETADATA = \"\"\"\\\nMetadata-Version: 2.1\nName: {project}\nVersion: {version}\nSummary: A dummy package\nAuthor: None\nAuthor-email: none@example.org\nLicense: MIT\n{requires_dist}\n\"\"\"\n\ndef make_wheel(z, project, version, requires_dist, files):\n    record = []\n    def add_file(name, data):\n        data = data.encode(\"utf-8\")\n        z.writestr(name, data)\n        digest = hashlib.sha256(data).digest()\n        hash = base64.urlsafe_b64encode(digest).rstrip(b\"=\").decode(\"ASCII\")\n        record.append((name, f\"sha256={hash}\", len(data)))\n    distinfo = f\"{project}-{version}.dist-info\"\n    add_file(f\"{distinfo}/WHEEL\", WHEEL)\n    add_file(f\"{distinfo}/METADATA\", METADATA.format(\n        project=project, version=version, requires_dist=requires_dist\n    ))\n    for name, data in files:\n        add_file(name, data)\n    record_name = f\"{distinfo}/RECORD\"\n    record.append((record_name, \"\", \"\"))\n    b = io.BytesIO()\n    rec = io.TextIOWrapper(b, newline=\"\", encoding=\"utf-8\")\n    w = csv.writer(rec)\n    w.writerows(record)\n    z.writestr(record_name, b.getvalue())\n    rec.close()\n\n\nclass Backend:\n    def build_wheel(\n        self,\n        wheel_directory,\n        config_settings=None,\n        metadata_directory=None\n    ):\n        if config_settings is None:\n            config_settings = {}\n        w = os.path.join(wheel_directory, \"{{name}}-1.0-py3-none-any.whl\")\n        with open(w, \"wb\") as f:\n            with ZipFile(f, \"w\") as z:\n                make_wheel(\n                    z, \"{{name}}\", \"1.0\", \"{{requires_dist}}\",\n                    [(\"{{name}}-config.json\", json.dumps(config_settings))]\n                )\n        return \"{{name}}-1.0-py3-none-any.whl\"\n\n    build_editable = build_wheel\n\nmain = Backend()\n'''\n\n\ndef make_project(\n    path: Path, name: str = \"foo\", dependencies: list[str] | None = None\n) -> tuple[str, str, Path]:\n    version = \"1.0\"\n    project_dir = path / name\n    backend = project_dir / \"backend\"\n    backend.mkdir(parents=True)\n    (project_dir / \"pyproject.toml\").write_text(PYPROJECT_TOML)\n    requires_dist = [f\"Requires-Dist: {dep}\" for dep in dependencies or []]\n    (backend / \"dummy_backend.py\").write_text(\n        BACKEND_SRC.replace(\"{{name}}\", name).replace(\n            \"{{requires_dist}}\", \"\\n\".join(requires_dist)\n        )\n    )\n    return name, version, project_dir\n\n\ndef test_backend_sees_config(script: PipTestEnvironment) -> None:\n    name, version, project_dir = make_project(script.scratch_path)\n    script.pip(\n        \"wheel\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        project_dir,\n    )\n    wheel_file_name = f\"{name}-{version}-py3-none-any.whl\"\n    wheel_file_path = script.cwd / wheel_file_name\n    with open(wheel_file_path, \"rb\") as f:\n        with ZipFile(f) as z:\n            output = z.read(f\"{name}-config.json\")\n            assert json.loads(output) == {\"FOO\": \"Hello\"}\n\n\ndef test_backend_sees_config_reqs(script: PipTestEnvironment) -> None:\n    name, version, project_dir = make_project(script.scratch_path)\n    script.scratch_path.joinpath(\"reqs.txt\").write_text(\n        f\"{project_dir} --config-settings FOO=Hello\"\n    )\n    script.pip(\"wheel\", \"-r\", \"reqs.txt\")\n    wheel_file_name = f\"{name}-{version}-py3-none-any.whl\"\n    wheel_file_path = script.cwd / wheel_file_name\n    with open(wheel_file_path, \"rb\") as f:\n        with ZipFile(f) as z:\n            output = z.read(f\"{name}-config.json\")\n            assert json.loads(output) == {\"FOO\": \"Hello\"}\n\n\ndef test_backend_sees_config_via_constraint(script: PipTestEnvironment) -> None:\n    name, version, project_dir = make_project(script.scratch_path)\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"{name} @ {path_to_url(str(project_dir))}\")\n    script.pip(\n        \"wheel\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        \"-c\",\n        \"constraints.txt\",\n        name,\n    )\n    wheel_file_name = f\"{name}-{version}-py3-none-any.whl\"\n    wheel_file_path = script.cwd / wheel_file_name\n    with open(wheel_file_path, \"rb\") as f:\n        with ZipFile(f) as z:\n            output = z.read(f\"{name}-config.json\")\n            assert json.loads(output) == {\"FOO\": \"Hello\"}\n\n\n@pytest.mark.network\ndef test_backend_sees_config_via_sdist(script: PipTestEnvironment) -> None:\n    name, version, project_dir = make_project(script.scratch_path)\n    dists_dir = script.scratch_path / \"dists\"\n    dists_dir.mkdir()\n    with tarfile.open(dists_dir / f\"{name}-{version}.tar.gz\", \"w:gz\") as dist_tar:\n        dist_tar.add(project_dir, arcname=name)\n    script.pip(\n        \"wheel\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        \"-f\",\n        dists_dir,\n        name,\n    )\n    wheel_file_name = f\"{name}-{version}-py3-none-any.whl\"\n    wheel_file_path = script.cwd / wheel_file_name\n    with open(wheel_file_path, \"rb\") as f:\n        with ZipFile(f) as z:\n            output = z.read(f\"{name}-config.json\")\n            assert json.loads(output) == {\"FOO\": \"Hello\"}\n\n\ndef test_req_file_does_not_see_config(script: PipTestEnvironment) -> None:\n    \"\"\"Test that CLI config settings do not propagate to requirement files.\"\"\"\n    name, _, project_dir = make_project(script.scratch_path)\n    reqs_file = script.scratch_path / \"reqs.txt\"\n    reqs_file.write_text(f\"{project_dir}\")\n    script.pip(\n        \"install\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        \"-r\",\n        reqs_file,\n    )\n    config = script.site_packages_path / f\"{name}-config.json\"\n    with open(config, \"rb\") as f:\n        assert json.load(f) == {}\n\n\ndef test_dep_does_not_see_config(script: PipTestEnvironment) -> None:\n    \"\"\"Test that CLI config settings do not propagate to dependencies.\"\"\"\n    _, _, bar_project_dir = make_project(script.scratch_path, name=\"bar\")\n    _, _, foo_project_dir = make_project(\n        script.scratch_path,\n        name=\"foo\",\n        dependencies=[f\"bar @ {path_to_url(str(bar_project_dir))}\"],\n    )\n    script.pip(\n        \"install\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        foo_project_dir,\n    )\n    foo_config = script.site_packages_path / \"foo-config.json\"\n    with open(foo_config, \"rb\") as f:\n        assert json.load(f) == {\"FOO\": \"Hello\"}\n    bar_config = script.site_packages_path / \"bar-config.json\"\n    with open(bar_config, \"rb\") as f:\n        assert json.load(f) == {}\n\n\ndef test_dep_in_req_file_does_not_see_config(script: PipTestEnvironment) -> None:\n    \"\"\"Test that CLI config settings do not propagate to dependencies found in\n    requirement files.\"\"\"\n    _, _, bar_project_dir = make_project(script.scratch_path, name=\"bar\")\n    _, _, foo_project_dir = make_project(\n        script.scratch_path,\n        name=\"foo\",\n        dependencies=[\"bar\"],\n    )\n    reqs_file = script.scratch_path / \"reqs.txt\"\n    reqs_file.write_text(f\"bar @ {path_to_url(str(bar_project_dir))}\")\n    script.pip(\n        \"install\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        \"-r\",\n        reqs_file,\n        foo_project_dir,\n    )\n    foo_config = script.site_packages_path / \"foo-config.json\"\n    with open(foo_config, \"rb\") as f:\n        assert json.load(f) == {\"FOO\": \"Hello\"}\n    bar_config = script.site_packages_path / \"bar-config.json\"\n    with open(bar_config, \"rb\") as f:\n        assert json.load(f) == {}\n\n\ndef test_install_sees_config(script: PipTestEnvironment) -> None:\n    name, _, project_dir = make_project(script.scratch_path)\n    script.pip(\n        \"install\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        project_dir,\n    )\n    config = script.site_packages_path / f\"{name}-config.json\"\n    with open(config, \"rb\") as f:\n        assert json.load(f) == {\"FOO\": \"Hello\"}\n\n\ndef test_install_sees_config_reqs(script: PipTestEnvironment) -> None:\n    name, _, project_dir = make_project(script.scratch_path)\n    script.scratch_path.joinpath(\"reqs.txt\").write_text(\n        f\"{project_dir} --config-settings FOO=Hello\"\n    )\n    script.pip(\"install\", \"-r\", \"reqs.txt\")\n    config = script.site_packages_path / f\"{name}-config.json\"\n    with open(config, \"rb\") as f:\n        assert json.load(f) == {\"FOO\": \"Hello\"}\n\n\ndef test_install_editable_sees_config(script: PipTestEnvironment) -> None:\n    name, _, project_dir = make_project(script.scratch_path)\n    script.pip(\n        \"install\",\n        \"--config-settings\",\n        \"FOO=Hello\",\n        \"--editable\",\n        project_dir,\n    )\n    config = script.site_packages_path / f\"{name}-config.json\"\n    with open(config, \"rb\") as f:\n        assert json.load(f) == {\"FOO\": \"Hello\"}\n\n\ndef test_install_config_reqs(script: PipTestEnvironment) -> None:\n    name, _, project_dir = make_project(script.scratch_path)\n    a_sdist = create_basic_sdist_for_package(\n        script,\n        \"foo\",\n        \"1.0\",\n        {\"pyproject.toml\": PYPROJECT_TOML, \"backend/dummy_backend.py\": BACKEND_SRC},\n    )\n    script.scratch_path.joinpath(\"reqs.txt\").write_text(\n        f'{project_dir} --config-settings \"--build-option=--cffi\" '\n        '--config-settings \"--build-option=--avx2\" '\n        \"--config-settings FOO=BAR\"\n    )\n    script.pip(\"install\", \"--no-index\", \"-f\", str(a_sdist.parent), \"-r\", \"reqs.txt\")\n    script.assert_installed(foo=\"1.0\")\n    config = script.site_packages_path / f\"{name}-config.json\"\n    with open(config, \"rb\") as f:\n        assert json.load(f) == {\"--build-option\": [\"--cffi\", \"--avx2\"], \"FOO\": \"BAR\"}\n"
  },
  {
    "path": "tests/functional/test_configuration.py",
    "content": "\"\"\"Tests for the config command\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport os\nimport re\nimport subprocess\nimport sys\nimport textwrap\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR\nfrom pip._internal.configuration import CONFIG_BASENAME, Kind\nfrom pip._internal.configuration import get_configuration_files as _get_config_files\nfrom pip._internal.utils.compat import WINDOWS\n\nfrom tests.lib import PipTestEnvironment, TestData\nfrom tests.lib.configuration_helpers import ConfigurationMixin, kinds\nfrom tests.lib.venv import VirtualEnvironment\n\n\ndef get_configuration_files() -> dict[Kind, list[str]]:\n    \"\"\"Wrapper over pip._internal.configuration.get_configuration_files().\"\"\"\n    if WINDOWS:\n        # The user configuration directory is updated in the isolate fixture using the\n        # APPDATA environment variable. This will only take effect in new subprocesses,\n        # however. To ensure that get_configuration_files() never returns stale data,\n        # call it in a subprocess on Windows.\n        code = (\n            \"from pip._internal.configuration import get_configuration_files; \"\n            \"print(get_configuration_files())\"\n        )\n        proc = subprocess.run(\n            [sys.executable, \"-c\", code], capture_output=True, encoding=\"utf-8\"\n        )\n        return ast.literal_eval(proc.stdout)\n    else:\n        return _get_config_files()\n\n\ndef test_no_options_passed_should_error(script: PipTestEnvironment) -> None:\n    result = script.pip(\"config\", expect_error=True)\n    assert result.returncode == ERROR\n\n\nclass TestBasicLoading(ConfigurationMixin):\n    def test_basic_modification_pipeline(self, script: PipTestEnvironment) -> None:\n        script.pip(\"config\", \"get\", \"test.blah\", expect_error=True)\n        script.pip(\"config\", \"set\", \"test.blah\", \"1\")\n\n        result = script.pip(\"config\", \"get\", \"test.blah\")\n        assert result.stdout.strip() == \"1\"\n\n        script.pip(\"config\", \"unset\", \"test.blah\")\n        script.pip(\"config\", \"get\", \"test.blah\", expect_error=True)\n\n    def test_listing_is_correct(self, script: PipTestEnvironment) -> None:\n        script.pip(\"config\", \"set\", \"test.listing-beta\", \"2\")\n        script.pip(\"config\", \"set\", \"test.listing-alpha\", \"1\")\n        script.pip(\"config\", \"set\", \"test.listing-gamma\", \"3\")\n\n        result = script.pip(\"config\", \"list\")\n\n        lines = list(\n            filter(lambda x: x.startswith(\"test.listing-\"), result.stdout.splitlines())\n        )\n\n        expected = \"\"\"\n            test.listing-alpha='1'\n            test.listing-beta='2'\n            test.listing-gamma='3'\n        \"\"\"\n\n        assert lines == textwrap.dedent(expected).strip().splitlines()\n\n    def test_forget_section(self, script: PipTestEnvironment) -> None:\n        result = script.pip(\"config\", \"set\", \"isolated\", \"true\", expect_error=True)\n        assert \"global.isolated\" in result.stderr\n\n    def test_env_var_values(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test that pip configuration set with environment variables\n        is correctly displayed under \"env_var\".\n        \"\"\"\n\n        env_vars = {\n            \"PIP_DEFAULT_TIMEOUT\": \"60\",\n            \"PIP_FIND_LINKS\": \"http://mirror.example.com\",\n        }\n        script.environ.update(env_vars)\n\n        result = script.pip(\"config\", \"debug\")\n        assert \"PIP_DEFAULT_TIMEOUT='60'\" in result.stdout\n        assert \"PIP_FIND_LINKS='http://mirror.example.com'\" in result.stdout\n        assert re.search(r\"env_var:\\n(  .+\\n)+\", result.stdout)\n\n    def test_env_values(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test that custom pip configuration using the environment variable\n        PIP_CONFIG_FILE is correctly displayed under \"env\". This configuration\n        takes place of per-user configuration file displayed under \"user\".\n        \"\"\"\n\n        config_file = script.scratch_path / \"test-pip.cfg\"\n        script.environ[\"PIP_CONFIG_FILE\"] = str(config_file)\n        config_file.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            [global]\n            timeout = 60\n\n            [freeze]\n            timeout = 10\n            \"\"\"\n            )\n        )\n\n        result = script.pip(\"config\", \"debug\")\n        assert f\"{config_file}, exists: True\" in result.stdout\n        assert \"global.timeout: 60\" in result.stdout\n        assert \"freeze.timeout: 10\" in result.stdout\n        assert re.search(r\"env:\\n(  .+\\n)+\", result.stdout)\n\n    def test_user_values(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test that the user pip configuration set using --user\n        is correctly displayed under \"user\".  This configuration takes place\n        of custom path location using the environment variable PIP_CONFIG_FILE\n        displayed under \"env\".\n        \"\"\"\n\n        # Use new config file\n        new_config_file = get_configuration_files()[kinds.USER][1]\n\n        script.pip(\"config\", \"--user\", \"set\", \"global.timeout\", \"60\")\n        script.pip(\"config\", \"--user\", \"set\", \"freeze.timeout\", \"10\")\n\n        result = script.pip(\"config\", \"debug\")\n        assert f\"{new_config_file}, exists: True\" in result.stdout\n        assert \"global.timeout: 60\" in result.stdout\n        assert \"freeze.timeout: 10\" in result.stdout\n        assert re.search(r\"user:\\n(  .+\\n)+\", result.stdout)\n\n    def test_site_values(\n        self, script: PipTestEnvironment, virtualenv: VirtualEnvironment\n    ) -> None:\n        \"\"\"Test that the current environment configuration set using --site\n        is correctly displayed under \"site\".\n        \"\"\"\n\n        # Site config file will be inside the virtualenv\n        site_config_file = virtualenv.location / CONFIG_BASENAME\n\n        script.pip(\"config\", \"--site\", \"set\", \"global.timeout\", \"60\")\n        script.pip(\"config\", \"--site\", \"set\", \"freeze.timeout\", \"10\")\n\n        result = script.pip(\"config\", \"debug\")\n        assert f\"{site_config_file}, exists: True\" in result.stdout\n        assert \"global.timeout: 60\" in result.stdout\n        assert \"freeze.timeout: 10\" in result.stdout\n        assert re.search(r\"site:\\n(  .+\\n)+\", result.stdout)\n\n    def test_global_config_file(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test that the system-wide  configuration can be identified\"\"\"\n\n        # We cannot  write to system-wide files which might have permissions\n        # defined in a way that the tox virtualenvcannot write to those\n        # locations. Additionally we cannot patch those paths since pip config\n        # commands runs inside a subprocess.\n        # So we just check if the file can be identified\n        global_config_file = get_configuration_files()[kinds.GLOBAL][0]\n        result = script.pip(\"config\", \"debug\")\n        assert f\"{global_config_file}, exists:\" in result.stdout\n\n    def test_editor_does_not_exist(self, script: PipTestEnvironment) -> None:\n        \"\"\"Ensure that FileNotFoundError sets filename correctly\"\"\"\n        result = script.pip(\n            \"config\", \"edit\", \"--editor\", \"notrealeditor\", expect_error=True\n        )\n        assert \"notrealeditor\" in result.stderr\n\n    def test_config_separated(\n        self, script: PipTestEnvironment, virtualenv: VirtualEnvironment\n    ) -> None:\n        \"\"\"Test that the pip configuration values in the different config sections\n        are correctly assigned to their origin files.\n        \"\"\"\n\n        # Use new config file\n        new_config_file = get_configuration_files()[kinds.USER][1]\n\n        # Get legacy config file and touch it for testing purposes\n        legacy_config_file = get_configuration_files()[kinds.USER][0]\n        os.makedirs(os.path.dirname(legacy_config_file))\n        open(legacy_config_file, \"a\").close()\n\n        # Site config file\n        site_config_file = virtualenv.location / CONFIG_BASENAME\n\n        script.pip(\"config\", \"--user\", \"set\", \"global.timeout\", \"60\")\n        script.pip(\"config\", \"--site\", \"set\", \"freeze.timeout\", \"10\")\n\n        result = script.pip(\"config\", \"debug\")\n\n        assert (\n            f\"{site_config_file}, exists: True\\n    freeze.timeout: 10\" in result.stdout\n        )\n        assert (\n            f\"{new_config_file}, exists: True\\n    global.timeout: 60\" in result.stdout\n        )\n        assert re.search(\n            (\n                rf\"{re.escape(legacy_config_file)}, \"\n                rf\"exists: True\\n(  {re.escape(new_config_file)}.+\\n)+\"\n            ),\n            result.stdout,\n        )\n\n    @pytest.mark.network\n    def test_editable_mode_default_config(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that setting default editable mode through configuration works\n        as expected.\n        \"\"\"\n        script.pip(\n            \"config\", \"--site\", \"set\", \"install.config-settings\", \"editable_mode=strict\"\n        )\n        to_install = data.src.joinpath(\"simplewheel-1.0\")\n        script.pip(\"install\", \"-e\", to_install)\n        assert os.path.isdir(\n            os.path.join(\n                to_install, \"build\", \"__editable__.simplewheel-1.0-py3-none-any\"\n            )\n        )\n\n    @pytest.mark.network\n    def test_user_config_overrides_global_config_with_empty_value(\n        self, script: PipTestEnvironment, tmpdir: Path\n    ) -> None:\n        \"\"\"Test that user config empty value overrides global config.\"\"\"\n        # Set up global config with proxy\n        global_dir = tmpdir / \"global\"\n        global_pip = global_dir / \"pip\" / \"pip.conf\"\n        global_pip.parent.mkdir(parents=True)\n        global_pip.write_text(\n            \"[global]\\nproxy = http://non_existing_proxy_server.tld\\n\"\n        )\n        script.environ[\"XDG_CONFIG_DIRS\"] = str(global_dir)\n\n        # Set up user config that overrides with empty value\n        user_config_dir = tmpdir / \"user-config\"\n        user_pip_config = user_config_dir / \"pip\" / \"pip.conf\"\n        user_pip_config.parent.mkdir(parents=True)\n        user_pip_config.write_text(\"[global]\\nproxy = \\n\")\n        script.environ[\"PIP_CONFIG_FILE\"] = str(user_pip_config)\n\n        # Install should succeed without trying to use the proxy\n        result = script.pip(\n            \"install\",\n            \"--dry-run\",\n            \"--no-deps\",\n            \"--ignore-installed\",\n            \"--retries\",\n            \"0\",\n            \"--no-cache-dir\",\n            \"requests\",\n        )\n\n        assert \"Would install\" in result.stdout\n"
  },
  {
    "path": "tests/functional/test_debug.py",
    "content": "import re\n\nimport pytest\n\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.commands.debug import create_vendor_txt_map\nfrom pip._internal.utils import compatibility_tags\n\nfrom tests.lib import PipTestEnvironment\n\n\n@pytest.mark.parametrize(\n    \"expected_text\",\n    [\n        \"sys.executable: \",\n        \"sys.getdefaultencoding: \",\n        \"sys.getfilesystemencoding: \",\n        \"locale.getpreferredencoding: \",\n        \"sys.platform: \",\n        \"sys.implementation:\",\n        \"'cert' config value: \",\n        \"REQUESTS_CA_BUNDLE: \",\n        \"CURL_CA_BUNDLE: \",\n        \"pip._vendor.certifi.where(): \",\n        \"pip._vendor.DEBUNDLED: \",\n        \"vendored library versions:\",\n    ],\n)\ndef test_debug(script: PipTestEnvironment, expected_text: str) -> None:\n    \"\"\"\n    Check that certain strings are present in the output.\n    \"\"\"\n    args = [\"debug\"]\n    result = script.pip(*args, allow_stderr_warning=True)\n    stdout = result.stdout\n\n    assert expected_text in stdout\n\n\ndef test_debug__library_versions(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Check the library versions normal output.\n    \"\"\"\n    args = [\"debug\"]\n    result = script.pip(*args, allow_stderr_warning=True)\n    print(result.stdout)\n\n    vendored_versions = create_vendor_txt_map()\n    for name, value in vendored_versions.items():\n        match = re.search(rf\"{name}==(\\S+)\", result.stdout)\n        assert match is not None, f\"Could not find {name} in output\"\n        assert Version(match.group(1)) == Version(value)\n\n\n@pytest.mark.parametrize(\n    \"args\",\n    [\n        [],\n        [\"--verbose\"],\n    ],\n)\ndef test_debug__tags(script: PipTestEnvironment, args: list[str]) -> None:\n    \"\"\"\n    Check the compatible tag output.\n    \"\"\"\n    args = [\"debug\"] + args\n    result = script.pip(*args, allow_stderr_warning=True)\n    stdout = result.stdout\n\n    tags = compatibility_tags.get_supported()\n    expected_tag_header = f\"Compatible tags: {len(tags)}\"\n    assert expected_tag_header in stdout\n\n    show_verbose_note = \"--verbose\" not in args\n    assert (\n        \"...\\n  [First 10 tags shown. Pass --verbose to show all.]\" in stdout\n    ) == show_verbose_note\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        ([\"--python-version\", \"3.7\"], \"(target: version_info='3.7')\"),\n    ],\n)\ndef test_debug__target_options(\n    script: PipTestEnvironment, args: list[str], expected: str\n) -> None:\n    \"\"\"\n    Check passing target-related options.\n    \"\"\"\n    args = [\"debug\"] + args\n    result = script.pip(*args, allow_stderr_warning=True)\n    stdout = result.stdout\n\n    assert \"Compatible tags: \" in stdout\n    assert expected in stdout\n"
  },
  {
    "path": "tests/functional/test_download.py",
    "content": "import http.server\nimport os\nimport re\nimport shutil\nimport textwrap\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom typing import Callable\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR\nfrom pip._internal.utils.urls import path_to_url\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    ScriptFactory,\n    TestData,\n    TestPipResult,\n    create_really_basic_wheel,\n)\nfrom tests.lib.server import MockServer, file_response\n\n\ndef fake_wheel(data: TestData, wheel_path: str) -> None:\n    wheel_name = os.path.basename(wheel_path)\n    name, version, rest = wheel_name.split(\"-\", 2)\n    wheel_data = create_really_basic_wheel(name, version)\n    data.packages.joinpath(wheel_path).write_bytes(wheel_data)\n\n\ndef test_download_if_requested(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    It should download (in the scratch path) and not install if requested.\n    \"\"\"\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"-d\",\n        \"pip_downloads\",\n        \"INITools==0.1\",\n        \"-f\",\n        data.pypi_packages,\n        \"--no-build-isolation\",\n    )\n    result.did_create(Path(\"scratch\") / \"pip_downloads\" / \"INITools-0.1.tar.gz\")\n    result.did_not_create(script.site_packages / \"initools\")\n\n\ndef test_basic_download_setuptools(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    It should download (in the scratch path) and not install if requested.\n    \"\"\"\n    result = script.pip(\n        \"download\", \"setuptools\", \"--no-index\", \"-f\", data.common_wheels\n    )\n    setuptools_prefix = str(Path(\"scratch\") / \"setuptools\")\n    assert any(os.fspath(p).startswith(setuptools_prefix) for p in result.files_created)\n\n\ndef test_download_wheel(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test using \"pip download\" to download a *.whl archive.\n    \"\"\"\n    # This test needs --no-build-isolation because `meta` depends on `simple`\n    # which is a source distribution for which it needs to prepare metadata\n    # to look for transitive dependencies.\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"meta\",\n    )\n    result.did_create(Path(\"scratch\") / \"meta-1.0-py2.py3-none-any.whl\")\n    result.did_not_create(script.site_packages / \"piptestpackage\")\n\n\ndef test_single_download_from_requirements_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    It should support download (in the scratch path) from a\n    requirements file\n    \"\"\"\n    req_file = script.temporary_file(\"test-req.txt\", \"INITools==0.1\")\n    result = script.pip(\n        \"download\",\n        \"-r\",\n        req_file,\n        \"--no-index\",\n        \"-f\",\n        data.pypi_packages,\n        \"--no-build-isolation\",\n    )\n    result.did_create(Path(\"scratch\") / \"INITools-0.1.tar.gz\")\n    result.did_not_create(script.site_packages / \"initools\")\n\n\n@pytest.mark.network\ndef test_basic_download_should_download_dependencies(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    It should download dependencies (in the scratch path)\n    \"\"\"\n    result = script.pip(\"download\", \"Paste[openid]==1.7.5.1\", \"-d\", \".\")\n    result.did_create(Path(\"scratch\") / \"Paste-1.7.5.1.tar.gz\")\n    openid_tarball_prefix = str(Path(\"scratch\") / \"python-openid-\")\n    assert any(\n        os.fspath(path).startswith(openid_tarball_prefix)\n        for path in result.files_created\n    )\n    result.did_not_create(script.site_packages / \"openid\")\n\n\ndef test_download_wheel_archive(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    It should download a wheel archive path\n    \"\"\"\n    wheel_filename = \"colander-0.9.9-py2.py3-none-any.whl\"\n    wheel_path = \"/\".join((data.find_links, wheel_filename))\n    result = script.pip(\"download\", wheel_path, \"-d\", \".\", \"--no-deps\")\n    result.did_create(Path(\"scratch\") / wheel_filename)\n\n\ndef test_download_should_download_wheel_deps(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    It should download dependencies for wheels(in the scratch path)\n    \"\"\"\n    wheel_filename = \"colander-0.9.9-py2.py3-none-any.whl\"\n    dep_filename = \"translationstring-1.1.tar.gz\"\n    wheel_path = \"/\".join((data.find_links, wheel_filename))\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        wheel_path,\n        \"-d\",\n        \".\",\n        \"--find-links\",\n        data.find_links,\n        \"--no-index\",\n    )\n    result.did_create(Path(\"scratch\") / wheel_filename)\n    result.did_create(Path(\"scratch\") / dep_filename)\n\n\ndef test_download_should_skip_existing_files(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    It should not download files already existing in the scratch dir\n    \"\"\"\n    req_file = script.temporary_file(\"reqs.txt\", \"simplewheel==1.0\")\n    result = script.pip(\"download\", \"-r\", req_file, \"-f\", data.packages, \"--no-index\")\n    result.did_create(Path(\"scratch\") / \"simplewheel-1.0-py2.py3-none-any.whl\")\n    result.did_not_create(script.site_packages / \"simplewheel\")\n\n    # adding second package to test-req.txt\n    script.temporary_file(req_file, \"simplewheel==1.0\\nsimple.dist\")\n\n    # only the second package should be downloaded\n    result = script.pip(\"download\", \"-r\", req_file, \"-f\", data.packages, \"--no-index\")\n    assert any(\n        os.fspath(path).startswith(str(Path(\"scratch\") / \"simple.dist\"))\n        for path in result.files_created\n    )\n    result.did_not_create(Path(\"scratch\") / \"simplewheel-1.0-py2.py3-none-any.whl\")\n    result.did_not_create(script.site_packages / \"simplewheel\")\n    result.did_not_create(script.site_packages / \"simpledist\")\n\n\n@pytest.mark.network\ndef test_download_vcs_link(script: PipTestEnvironment) -> None:\n    \"\"\"\n    It should allow -d flag for vcs links, regression test for issue #798.\n    \"\"\"\n    result = script.pip(\n        \"download\", \"-d\", \".\", \"git+https://github.com/pypa/pip-test-package.git\"\n    )\n    result.did_create(Path(\"scratch\") / \"pip-test-package-0.1.1.zip\")\n    result.did_not_create(script.site_packages / \"piptestpackage\")\n\n\ndef test_only_binary_set_then_download_specific_platform(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Confirm that specifying an interpreter/platform constraint\n    is allowed when ``--only-binary=:all:`` is set.\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n\ndef test_no_deps_set_then_download_specific_platform(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Confirm that specifying an interpreter/platform constraint\n    is allowed when ``--no-deps`` is set.\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--no-deps\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n\ndef test_download_specific_platform_fails(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Confirm that specifying an interpreter/platform constraint\n    enforces that ``--no-deps`` or ``--only-binary=:all:`` is set.\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake\",\n        expect_error=True,\n    )\n    assert \"--only-binary=:all:\" in result.stderr\n\n\ndef test_no_binary_set_then_download_specific_platform_fails(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Confirm that specifying an interpreter/platform constraint\n    enforces that ``--only-binary=:all:`` is set without ``--no-binary``.\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--no-binary=fake\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake\",\n        expect_error=True,\n    )\n    assert \"--only-binary=:all:\" in result.stderr\n\n\ndef test_download_specify_platform(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test using \"pip download --platform\" to download a .whl archive\n    supported for a specific platform\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n\n    # Confirm that universal wheels are returned even for specific\n    # platforms.\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"macosx_10_9_x86_64\",\n        \"fake\",\n    )\n\n    data.reset()\n    fake_wheel(data, \"fake-1.0-py2.py3-none-macosx_10_9_x86_64.whl\")\n    fake_wheel(data, \"fake-2.0-py2.py3-none-linux_x86_64.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"macosx_10_10_x86_64\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-macosx_10_9_x86_64.whl\")\n\n    # OSX platform wheels are not backward-compatible.\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"macosx_10_8_x86_64\",\n        \"fake\",\n        expect_error=True,\n    )\n\n    # No linux wheel provided for this version.\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake==1\",\n        expect_error=True,\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"fake==2\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-2.0-py2.py3-none-linux_x86_64.whl\")\n\n    # Test with multiple supported platforms specified.\n    data.reset()\n    fake_wheel(data, \"fake-3.0-py2.py3-none-linux_x86_64.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--platform\",\n        \"manylinux1_x86_64\",\n        \"--platform\",\n        \"linux_x86_64\",\n        \"--platform\",\n        \"any\",\n        \"fake==3\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-3.0-py2.py3-none-linux_x86_64.whl\")\n\n\nclass TestDownloadPlatformManylinuxes:\n    \"\"\"\n    \"pip download --platform\" downloads a .whl archive supported for\n    manylinux platforms.\n    \"\"\"\n\n    @pytest.mark.parametrize(\n        \"platform\",\n        [\n            \"linux_x86_64\",\n            \"manylinux1_x86_64\",\n            \"manylinux2010_x86_64\",\n            \"manylinux2014_x86_64\",\n        ],\n    )\n    def test_download_universal(\n        self, platform: str, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"\n        Universal wheels are returned even for specific platforms.\n        \"\"\"\n        fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n        result = script.pip(\n            \"download\",\n            \"--no-index\",\n            \"--find-links\",\n            data.find_links,\n            \"--only-binary=:all:\",\n            \"--dest\",\n            \".\",\n            \"--platform\",\n            platform,\n            \"fake\",\n        )\n        result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n    @pytest.mark.parametrize(\n        \"wheel_abi,platform\",\n        [\n            (\"manylinux1_x86_64\", \"manylinux1_x86_64\"),\n            (\"manylinux1_x86_64\", \"manylinux2010_x86_64\"),\n            (\"manylinux2010_x86_64\", \"manylinux2010_x86_64\"),\n            (\"manylinux1_x86_64\", \"manylinux2014_x86_64\"),\n            (\"manylinux2010_x86_64\", \"manylinux2014_x86_64\"),\n            (\"manylinux2014_x86_64\", \"manylinux2014_x86_64\"),\n        ],\n    )\n    def test_download_compatible_manylinuxes(\n        self,\n        wheel_abi: str,\n        platform: str,\n        script: PipTestEnvironment,\n        data: TestData,\n    ) -> None:\n        \"\"\"\n        Earlier manylinuxes are compatible with later manylinuxes.\n        \"\"\"\n        wheel = f\"fake-1.0-py2.py3-none-{wheel_abi}.whl\"\n        fake_wheel(data, wheel)\n        result = script.pip(\n            \"download\",\n            \"--no-index\",\n            \"--find-links\",\n            data.find_links,\n            \"--only-binary=:all:\",\n            \"--dest\",\n            \".\",\n            \"--platform\",\n            platform,\n            \"fake\",\n        )\n        result.did_create(Path(\"scratch\") / wheel)\n\n    def test_explicit_platform_only(\n        self, data: TestData, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        When specifying the platform, manylinux1 needs to be the\n        explicit platform--it won't ever be added to the compatible\n        tags.\n        \"\"\"\n        fake_wheel(data, \"fake-1.0-py2.py3-none-linux_x86_64.whl\")\n        script.pip(\n            \"download\",\n            \"--no-index\",\n            \"--find-links\",\n            data.find_links,\n            \"--only-binary=:all:\",\n            \"--dest\",\n            \".\",\n            \"--platform\",\n            \"linux_x86_64\",\n            \"fake\",\n        )\n\n\ndef test_download__python_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test using \"pip download --python-version\" to download a .whl archive\n    supported for a specific interpreter\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"2\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"3\",\n        \"fake\",\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"27\",\n        \"fake\",\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"33\",\n        \"fake\",\n    )\n\n    data.reset()\n    fake_wheel(data, \"fake-1.0-py2-none-any.whl\")\n    fake_wheel(data, \"fake-2.0-py3-none-any.whl\")\n\n    # No py3 provided for version 1.\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"3\",\n        \"fake==1.0\",\n        expect_error=True,\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"2\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"26\",\n        \"fake\",\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"3\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-2.0-py3-none-any.whl\")\n\n\ndef make_wheel_with_python_requires(\n    script: PipTestEnvironment, package_name: str, python_requires: str\n) -> Path:\n    \"\"\"\n    Create a wheel using the given python_requires.\n\n    :return: the path to the wheel file.\n    \"\"\"\n    package_dir = script.scratch_path / package_name\n    package_dir.mkdir()\n\n    text = textwrap.dedent(\n        \"\"\"\\\n    from setuptools import setup\n    setup(name='{}',\n          python_requires='{}',\n          version='1.0')\n    \"\"\"\n    ).format(package_name, python_requires)\n    package_dir.joinpath(\"setup.py\").write_text(text)\n    script.run(\n        \"python\",\n        \"setup.py\",\n        \"bdist_wheel\",\n        \"--universal\",\n        cwd=package_dir,\n    )\n\n    file_name = f\"{package_name}-1.0-py2.py3-none-any.whl\"\n    return package_dir / \"dist\" / file_name\n\n\ndef test_download__python_version_used_for_python_requires(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that --python-version is used for the Requires-Python check.\n    \"\"\"\n    wheel_path = make_wheel_with_python_requires(\n        script,\n        \"mypackage\",\n        python_requires=\"==3.2\",\n    )\n    wheel_dir = os.path.dirname(wheel_path)\n\n    def make_args(python_version: str) -> list[str]:\n        return [\n            \"download\",\n            \"--no-index\",\n            \"--find-links\",\n            wheel_dir,\n            \"--only-binary=:all:\",\n            \"--dest\",\n            \".\",\n            \"--python-version\",\n            python_version,\n            \"mypackage==1.0\",\n        ]\n\n    args = make_args(\"33\")\n    result = script.pip(*args, expect_error=True)\n    expected_err = (\n        \"ERROR: Package 'mypackage' requires a different Python: 3.3.0 not in '==3.2'\"\n    )\n    assert expected_err in result.stderr, f\"stderr: {result.stderr}\"\n\n    # Now try with a --python-version that satisfies the Requires-Python.\n    args = make_args(\"32\")\n    script.pip(*args)  # no exception\n\n\ndef test_download_ignore_requires_python_dont_fail_with_wrong_python(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test that --ignore-requires-python ignores Requires-Python check.\n    \"\"\"\n    wheel_path = make_wheel_with_python_requires(\n        script,\n        \"mypackage\",\n        python_requires=\"==999\",\n    )\n    wheel_dir = os.path.dirname(wheel_path)\n\n    result = script.pip(\n        \"download\",\n        \"--ignore-requires-python\",\n        \"--no-index\",\n        \"--find-links\",\n        wheel_dir,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"mypackage==1.0\",\n    )\n    result.did_create(Path(\"scratch\") / \"mypackage-1.0-py2.py3-none-any.whl\")\n\n\ndef test_download_specify_abi(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test using \"pip download --abi\" to download a .whl archive\n    supported for a specific abi\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"--abi\",\n        \"fake_abi\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"--abi\",\n        \"none\",\n        \"fake\",\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--abi\",\n        \"cp27m\",\n        \"fake\",\n    )\n\n    data.reset()\n    fake_wheel(data, \"fake-1.0-fk2-fakeabi-fake_platform.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"2\",\n        \"--implementation\",\n        \"fk\",\n        \"--platform\",\n        \"fake_platform\",\n        \"--abi\",\n        \"fakeabi\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-fk2-fakeabi-fake_platform.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"--platform\",\n        \"fake_platform\",\n        \"--abi\",\n        \"none\",\n        \"fake\",\n        expect_error=True,\n    )\n\n    data.reset()\n    fake_wheel(data, \"fake-1.0-fk2-otherabi-fake_platform.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--python-version\",\n        \"2\",\n        \"--implementation\",\n        \"fk\",\n        \"--platform\",\n        \"fake_platform\",\n        \"--abi\",\n        \"fakeabi\",\n        \"--abi\",\n        \"otherabi\",\n        \"--abi\",\n        \"none\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-fk2-otherabi-fake_platform.whl\")\n\n\ndef test_download_specify_implementation(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test using \"pip download --abi\" to download a .whl archive\n    supported for a specific abi\n    \"\"\"\n    fake_wheel(data, \"fake-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-py2.py3-none-any.whl\")\n\n    data.reset()\n    fake_wheel(data, \"fake-1.0-fk3-none-any.whl\")\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"--python-version\",\n        \"3\",\n        \"fake\",\n    )\n    result.did_create(Path(\"scratch\") / \"fake-1.0-fk3-none-any.whl\")\n\n    result = script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--dest\",\n        \".\",\n        \"--implementation\",\n        \"fk\",\n        \"--python-version\",\n        \"2\",\n        \"fake\",\n        expect_error=True,\n    )\n\n\ndef test_download_exit_status_code_when_no_requirements(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test download exit status code when no requirements specified\n    \"\"\"\n    result = script.pip(\"download\", expect_error=True)\n    assert \"You must give at least one requirement to download\" in result.stderr\n    assert result.returncode == ERROR\n\n\ndef test_download_exit_status_code_when_blank_requirements_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test download exit status code when blank requirements file specified\n    \"\"\"\n    script.scratch_path.joinpath(\"blank.txt\").write_text(\"\\n\")\n    script.pip(\"download\", \"-r\", \"blank.txt\")\n\n\ndef test_download_prefer_binary_when_tarball_higher_than_wheel(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    fake_wheel(data, \"source-0.8-py2.py3-none-any.whl\")\n    result = script.pip(\n        \"download\",\n        \"--prefer-binary\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"source\",\n    )\n    result.did_create(Path(\"scratch\") / \"source-0.8-py2.py3-none-any.whl\")\n    result.did_not_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n\n\ndef test_prefer_binary_tarball_higher_than_wheel_req_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    fake_wheel(data, \"source-0.8-py2.py3-none-any.whl\")\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n                --prefer-binary\n                 source\n                \"\"\"\n        )\n    )\n    result = script.pip(\n        \"download\",\n        \"-r\",\n        script.scratch_path / \"test-req.txt\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n    )\n\n    result.did_create(Path(\"scratch\") / \"source-0.8-py2.py3-none-any.whl\")\n    result.did_not_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n\n\ndef test_download_prefer_binary_when_wheel_doesnt_satisfy_req(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    fake_wheel(data, \"source-0.8-py2.py3-none-any.whl\")\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        source>0.9\n        \"\"\"\n        )\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--prefer-binary\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"-r\",\n        script.scratch_path / \"test-req.txt\",\n    )\n    result.did_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n    result.did_not_create(Path(\"scratch\") / \"source-0.8-py2.py3-none-any.whl\")\n\n\ndef test_prefer_binary_when_wheel_doesnt_satisfy_req_req_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    fake_wheel(data, \"source-0.8-py2.py3-none-any.whl\")\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        --prefer-binary\n        source>0.9\n        \"\"\"\n        )\n    )\n\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"-r\",\n        script.scratch_path / \"test-req.txt\",\n    )\n    result.did_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n    result.did_not_create(Path(\"scratch\") / \"source-0.8-py2.py3-none-any.whl\")\n\n\ndef test_download_prefer_binary_when_only_tarball_exists(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--prefer-binary\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"source\",\n    )\n    result.did_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n\n\ndef test_prefer_binary_when_only_tarball_exists_req_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            --prefer-binary\n            source\n            \"\"\"\n        )\n    )\n    result = script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-d\",\n        \".\",\n        \"-r\",\n        script.scratch_path / \"test-req.txt\",\n    )\n    result.did_create(Path(\"scratch\") / \"source-1.0.tar.gz\")\n\n\n@pytest.fixture(scope=\"session\")\ndef shared_script(\n    tmpdir_factory: pytest.TempPathFactory, script_factory: ScriptFactory\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"download_shared_script\")\n    script = script_factory(tmpdir.joinpath(\"workspace\"))\n    return script\n\n\ndef test_download_file_url(\n    shared_script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    download_dir = tmpdir / \"download\"\n    download_dir.mkdir()\n    downloaded_path = download_dir / \"simple-1.0.tar.gz\"\n\n    simple_pkg = shared_data.packages / \"simple-1.0.tar.gz\"\n\n    shared_script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"-d\",\n        str(download_dir),\n        \"--no-index\",\n        simple_pkg.as_uri(),\n    )\n\n    assert downloaded_path.exists()\n    assert simple_pkg.read_bytes() == downloaded_path.read_bytes()\n\n\ndef test_download_file_url_existing_ok_download(\n    shared_script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    download_dir = tmpdir / \"download\"\n    download_dir.mkdir()\n    downloaded_path = download_dir / \"simple-1.0.tar.gz\"\n    fake_existing_package = shared_data.packages / \"simple-2.0.tar.gz\"\n    shutil.copy(str(fake_existing_package), str(downloaded_path))\n    downloaded_path_bytes = downloaded_path.read_bytes()\n\n    simple_pkg = shared_data.packages / \"simple-1.0.tar.gz\"\n    url = f\"{simple_pkg.as_uri()}#sha256={sha256(downloaded_path_bytes).hexdigest()}\"\n\n    shared_script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"-d\",\n        str(download_dir),\n        url,\n        \"--disable-pip-version-check\",\n    )\n\n    assert downloaded_path_bytes == downloaded_path.read_bytes()\n\n\ndef test_download_file_url_existing_bad_download(\n    shared_script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    download_dir = tmpdir / \"download\"\n    download_dir.mkdir()\n    downloaded_path = download_dir / \"simple-1.0.tar.gz\"\n    fake_existing_package = shared_data.packages / \"simple-2.0.tar.gz\"\n    shutil.copy(str(fake_existing_package), str(downloaded_path))\n\n    simple_pkg = shared_data.packages / \"simple-1.0.tar.gz\"\n    simple_pkg_bytes = simple_pkg.read_bytes()\n    url = f\"{simple_pkg.as_uri()}#sha256={sha256(simple_pkg_bytes).hexdigest()}\"\n\n    result = shared_script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"-d\",\n        str(download_dir),\n        url,\n        allow_stderr_warning=True,  # bad hash\n    )\n\n    assert simple_pkg_bytes == downloaded_path.read_bytes()\n    assert \"WARNING: Previously-downloaded file\" in result.stderr\n    assert \"has bad hash. Re-downloading.\" in result.stderr\n\n\ndef test_download_http_url_bad_hash(\n    shared_script: PipTestEnvironment,\n    shared_data: TestData,\n    tmpdir: Path,\n    mock_server: MockServer,\n) -> None:\n    \"\"\"\n    If already-downloaded file has bad checksum, re-download.\n    \"\"\"\n    download_dir = tmpdir / \"download\"\n    download_dir.mkdir()\n    downloaded_path = download_dir / \"simple-1.0.tar.gz\"\n    fake_existing_package = shared_data.packages / \"simple-2.0.tar.gz\"\n    shutil.copy(str(fake_existing_package), str(downloaded_path))\n\n    simple_pkg = shared_data.packages / \"simple-1.0.tar.gz\"\n    simple_pkg_bytes = simple_pkg.read_bytes()\n    digest = sha256(simple_pkg_bytes).hexdigest()\n    mock_server.set_responses([file_response(simple_pkg)])\n    mock_server.start()\n    base_address = f\"http://{mock_server.host}:{mock_server.port}\"\n    url = f\"{base_address}/simple-1.0.tar.gz#sha256={digest}\"\n\n    result = shared_script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"-d\",\n        str(download_dir),\n        url,\n        allow_stderr_warning=True,  # bad hash\n    )\n\n    assert simple_pkg_bytes == downloaded_path.read_bytes()\n    assert \"WARNING: Previously-downloaded file\" in result.stderr\n    assert \"has bad hash. Re-downloading.\" in result.stderr\n\n    mock_server.stop()\n    requests = mock_server.get_requests()\n    assert len(requests) == 1\n    assert requests[0][\"PATH_INFO\"] == \"/simple-1.0.tar.gz\"\n    assert requests[0][\"HTTP_ACCEPT_ENCODING\"] == \"identity\"\n\n\ndef test_download_editable(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test 'pip download' of editables in requirement file.\n    \"\"\"\n    editable_path = str(data.src / \"simplewheel-1.0\").replace(os.path.sep, \"/\")\n    requirements_path = tmpdir / \"requirements.txt\"\n    requirements_path.write_text(\"-e \" + editable_path + \"\\n\")\n    download_dir = tmpdir / \"download_dir\"\n    script.pip(\n        \"download\",\n        \"--no-build-isolation\",\n        \"--no-deps\",\n        \"-r\",\n        str(requirements_path),\n        \"-d\",\n        str(download_dir),\n    )\n    downloads = os.listdir(download_dir)\n    assert len(downloads) == 1\n    assert downloads[0].endswith(\".zip\")\n\n\n@pytest.fixture\ndef download_local_html_index(\n    script: PipTestEnvironment,\n    html_index_for_packages: Path,\n    tmpdir: Path,\n) -> Callable[..., tuple[TestPipResult, Path]]:\n    \"\"\"Execute `pip download` against a generated PyPI index.\"\"\"\n    download_dir = tmpdir / \"download_dir\"\n\n    def run_for_generated_index(\n        args: list[str],\n        allow_error: bool = False,\n    ) -> tuple[TestPipResult, Path]:\n        \"\"\"\n        Produce a PyPI directory structure pointing to the specified packages, then\n        execute `pip download -i ...` pointing to our generated index.\n        \"\"\"\n        pip_args = [\n            \"download\",\n            \"--no-build-isolation\",\n            \"-d\",\n            str(download_dir),\n            \"-i\",\n            path_to_url(str(html_index_for_packages)),\n            *args,\n        ]\n        result = script.pip(*pip_args, allow_error=allow_error)\n        return (result, download_dir)\n\n    return run_for_generated_index\n\n\n@pytest.fixture\ndef download_server_html_index(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n    html_index_with_onetime_server: http.server.ThreadingHTTPServer,\n) -> Callable[..., tuple[TestPipResult, Path]]:\n    \"\"\"Execute `pip download` against a generated PyPI index.\"\"\"\n    download_dir = tmpdir / \"download_dir\"\n\n    def run_for_generated_index(\n        args: list[str],\n        allow_error: bool = False,\n    ) -> tuple[TestPipResult, Path]:\n        \"\"\"\n        Produce a PyPI directory structure pointing to the specified packages, then\n        execute `pip download -i ...` pointing to our generated index.\n        \"\"\"\n        pip_args = [\n            \"download\",\n            \"--no-build-isolation\",\n            \"-d\",\n            str(download_dir),\n            \"-i\",\n            \"http://localhost:8000\",\n            *args,\n        ]\n        result = script.pip(*pip_args, allow_error=allow_error)\n        return (result, download_dir)\n\n    return run_for_generated_index\n\n\n@pytest.mark.parametrize(\n    \"requirement_to_download, expected_outputs\",\n    [\n        (\"simple2==1.0\", [\"simple-1.0.tar.gz\", \"simple2-1.0.tar.gz\"]),\n        (\"simple==2.0\", [\"simple-2.0.tar.gz\"]),\n        (\n            \"colander\",\n            [\"colander-0.9.9-py2.py3-none-any.whl\", \"translationstring-1.1.tar.gz\"],\n        ),\n        (\n            \"compilewheel\",\n            [\"compilewheel-1.0-py2.py3-none-any.whl\", \"simple-1.0.tar.gz\"],\n        ),\n    ],\n)\ndef test_download_metadata(\n    download_local_html_index: Callable[..., tuple[TestPipResult, Path]],\n    requirement_to_download: str,\n    expected_outputs: list[str],\n) -> None:\n    \"\"\"Verify that if a data-dist-info-metadata attribute is present, then it is used\n    instead of the actual dist's METADATA.\"\"\"\n    _, download_dir = download_local_html_index(\n        [requirement_to_download],\n    )\n    assert sorted(os.listdir(download_dir)) == expected_outputs\n\n\n@pytest.mark.parametrize(\n    \"requirement_to_download, expected_outputs, doubled_path\",\n    [\n        (\n            \"simple2==1.0\",\n            [\"simple-1.0.tar.gz\", \"simple2-1.0.tar.gz\"],\n            \"/simple2/simple2-1.0.tar.gz\",\n        ),\n        (\"simple==2.0\", [\"simple-2.0.tar.gz\"], \"/simple/simple-2.0.tar.gz\"),\n        (\n            \"colander\",\n            [\"colander-0.9.9-py2.py3-none-any.whl\", \"translationstring-1.1.tar.gz\"],\n            \"/colander/colander-0.9.9-py2.py3-none-any.whl\",\n        ),\n        (\n            \"compilewheel\",\n            [\n                \"compilewheel-1.0-py2.py3-none-any.whl\",\n                \"simple-1.0.tar.gz\",\n            ],\n            \"/compilewheel/compilewheel-1.0-py2.py3-none-any.whl\",\n        ),\n    ],\n)\ndef test_download_metadata_server(\n    download_server_html_index: Callable[..., tuple[TestPipResult, Path]],\n    requirement_to_download: str,\n    expected_outputs: list[str],\n    doubled_path: str,\n) -> None:\n    \"\"\"Verify that if a data-dist-info-metadata attribute is present, then it is used\n    instead of the actual dist's METADATA.\n\n    Additionally, verify that each dist is downloaded exactly once using a mock server.\n\n    This is a regression test for issue https://github.com/pypa/pip/issues/11847.\n    \"\"\"\n    _, download_dir = download_server_html_index(\n        [requirement_to_download, \"--no-cache-dir\"],\n    )\n    assert sorted(os.listdir(download_dir)) == expected_outputs\n    shutil.rmtree(download_dir)\n    result, _ = download_server_html_index(\n        [requirement_to_download, \"--no-cache-dir\"],\n        allow_error=True,\n    )\n    assert result.returncode != 0\n    expected_msg = f\"File {doubled_path} not available more than once!\"\n    assert expected_msg in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"requirement_to_download, real_hash\",\n    [\n        (\n            \"simple==3.0\",\n            \"95e0f200b6302989bcf2cead9465cf229168295ea330ca30d1ffeab5c0fed996\",\n        ),\n        (\n            \"has-script\",\n            \"16ba92d7f6f992f6de5ecb7d58c914675cf21f57f8e674fb29dcb4f4c9507e5b\",\n        ),\n    ],\n)\ndef test_incorrect_metadata_hash(\n    download_local_html_index: Callable[..., tuple[TestPipResult, Path]],\n    requirement_to_download: str,\n    real_hash: str,\n) -> None:\n    \"\"\"Verify that if a hash for data-dist-info-metadata is provided, it must match the\n    actual hash of the metadata file.\"\"\"\n    result, _ = download_local_html_index(\n        [requirement_to_download],\n        allow_error=True,\n    )\n    assert result.returncode != 0\n    expected_msg = f\"\"\"\\\n        Expected sha256 wrong-hash\n             Got        {real_hash}\"\"\"\n    assert expected_msg in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"requirement_to_download, expected_url\",\n    [\n        (\"simple2==2.0\", \"simple2-2.0.tar.gz.metadata\"),\n        (\"priority\", \"priority-1.0-py2.py3-none-any.whl.metadata\"),\n    ],\n)\ndef test_metadata_not_found(\n    download_local_html_index: Callable[..., tuple[TestPipResult, Path]],\n    requirement_to_download: str,\n    expected_url: str,\n) -> None:\n    \"\"\"Verify that if a data-dist-info-metadata attribute is provided, that pip will\n    fetch the .metadata file at the location specified by PEP 658, and error\n    if unavailable.\"\"\"\n    result, _ = download_local_html_index(\n        [requirement_to_download],\n        allow_error=True,\n    )\n    assert result.returncode != 0\n    expected_re = re.escape(expected_url)\n    pattern = re.compile(\n        f\"ERROR: 404 Client Error: FileNotFoundError for url:.*{expected_re}\"\n    )\n    assert pattern.search(result.stderr), (pattern, result.stderr)\n\n\ndef test_produces_error_for_mismatched_package_name_in_metadata(\n    download_local_html_index: Callable[..., tuple[TestPipResult, Path]],\n) -> None:\n    \"\"\"Verify that the package name from the metadata matches the requested package.\"\"\"\n    result, _ = download_local_html_index(\n        [\"simple2==3.0\"],\n        allow_error=True,\n    )\n    assert result.returncode != 0\n    assert (\n        \"simple2-3.0.tar.gz has inconsistent Name: expected 'simple2', but metadata \"\n        \"has 'not-simple2'\"\n    ) in result.stdout\n\n\n@pytest.mark.parametrize(\n    \"requirement\",\n    [\n        \"requires-simple-extra==0.1\",\n        \"REQUIRES_SIMPLE-EXTRA==0.1\",\n        \"REQUIRES....simple-_-EXTRA==0.1\",\n    ],\n)\ndef test_canonicalizes_package_name_before_verifying_metadata(\n    download_local_html_index: Callable[..., tuple[TestPipResult, Path]],\n    requirement: str,\n) -> None:\n    \"\"\"Verify that the package name from the command line and the package's\n    METADATA are both canonicalized before comparison.\n\n    Regression test for https://github.com/pypa/pip/issues/12038\n    \"\"\"\n    result, download_dir = download_local_html_index(\n        [requirement],\n        allow_error=True,\n    )\n    assert result.returncode == 0\n    assert os.listdir(download_dir) == [\n        \"requires_simple_extra-0.1-py2.py3-none-any.whl\",\n    ]\n"
  },
  {
    "path": "tests/functional/test_fast_deps.py",
    "content": "import fnmatch\nimport json\nimport os\nimport pathlib\nimport re\nfrom collections.abc import Iterable\nfrom os.path import basename\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.utils.misc import hash_file\n\nfrom tests.lib import PipTestEnvironment, TestData, TestPipResult\n\n\ndef pip(script: PipTestEnvironment, command: str, requirement: str) -> TestPipResult:\n    return script.pip(\n        command,\n        \"--prefer-binary\",\n        \"--no-cache-dir\",\n        \"--use-feature=fast-deps\",\n        requirement,\n        allow_stderr_warning=True,\n    )\n\n\ndef assert_installed(script: PipTestEnvironment, names: str) -> None:\n    list_output = json.loads(script.pip(\"list\", \"--format=json\").stdout)\n    installed = {canonicalize_name(item[\"name\"]) for item in list_output}\n    assert installed.issuperset(map(canonicalize_name, names))\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\n    \"requirement, expected\",\n    [\n        (\"Paste==3.4.2\", (\"Paste\", \"six\")),\n        (\"Paste[flup]==3.4.2\", (\"Paste\", \"six\", \"flup\")),\n    ],\n)\ndef test_install_from_pypi(\n    requirement: str, expected: str, script: PipTestEnvironment\n) -> None:\n    pip(script, \"install\", requirement)\n    assert_installed(script, expected)\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\n    \"requirement, expected\",\n    [\n        (\"Paste==3.4.2\", (\"Paste-3.4.2-*.whl\", \"six-*.whl\")),\n        (\"Paste[flup]==3.4.2\", (\"Paste-3.4.2-*.whl\", \"six-*.whl\", \"flup-*\")),\n    ],\n)\ndef test_download_from_pypi(\n    requirement: str, expected: Iterable[str], script: PipTestEnvironment\n) -> None:\n    result = pip(script, \"download\", requirement)\n    created = [basename(f) for f in result.files_created]\n    assert all(fnmatch.filter(created, f) for f in expected)\n\n\n@pytest.mark.network\ndef test_build_wheel_with_deps(data: TestData, script: PipTestEnvironment) -> None:\n    result = pip(script, \"wheel\", os.fspath(data.packages / \"requiresPaste\"))\n    created = [basename(f) for f in result.files_created]\n    assert fnmatch.filter(created, \"requirespaste-3.1.4-*.whl\")\n    assert fnmatch.filter(created, \"Paste-3.4.2-*.whl\")\n    assert fnmatch.filter(created, \"six-*.whl\")\n\n\n@pytest.mark.network\ndef test_require_hash(script: PipTestEnvironment, tmp_path: pathlib.Path) -> None:\n    reqs = tmp_path / \"requirements.txt\"\n    reqs.write_text(\n        \"idna==2.10\"\n        \" --hash=sha256:\"\n        \"b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0\"\n        \" --hash=sha256:\"\n        \"b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6\"\n    )\n    result = script.pip(\n        \"download\",\n        \"--use-feature=fast-deps\",\n        \"-r\",\n        str(reqs),\n        allow_stderr_warning=True,\n    )\n    created = [basename(f) for f in result.files_created]\n    assert fnmatch.filter(created, \"idna-2.10*\")\n\n\n@pytest.mark.network\ndef test_hash_mismatch(script: PipTestEnvironment, tmp_path: pathlib.Path) -> None:\n    reqs = tmp_path / \"requirements.txt\"\n    reqs.write_text(\"idna==2.10 --hash=sha256:irna\")\n    result = script.pip(\n        \"download\",\n        \"--use-feature=fast-deps\",\n        \"-r\",\n        str(reqs),\n        expect_error=True,\n    )\n    assert \"DO NOT MATCH THE HASHES\" in result.stderr\n\n\n@pytest.mark.network\ndef test_hash_mismatch_existing_download_for_metadata_only_wheel(\n    script: PipTestEnvironment, tmp_path: pathlib.Path\n) -> None:\n    \"\"\"Metadata-only wheels from PEP 658 or fast-deps check for hash matching in\n    a separate code path than when the wheel is downloaded all at once. Make sure we\n    still check for hash mismatches.\"\"\"\n    reqs = tmp_path / \"requirements.txt\"\n    reqs.write_text(\"idna==2.10\")\n    dl_dir = tmp_path / \"downloads\"\n    dl_dir.mkdir()\n    idna_wheel = dl_dir / \"idna-2.10-py2.py3-none-any.whl\"\n    idna_wheel.write_text(\"asdf\")\n    result = script.pip(\n        \"download\",\n        # Ensure that we have a metadata-only dist for idna.\n        \"--use-feature=fast-deps\",\n        \"-r\",\n        str(reqs),\n        \"-d\",\n        str(dl_dir),\n        allow_stderr_warning=True,\n    )\n    assert re.search(\n        r\"WARNING: Previously-downloaded file.*has bad hash\", result.stderr\n    )\n    # This is the correct hash for idna==2.10.\n    assert (\n        hash_file(str(idna_wheel))[0].hexdigest()\n        == \"b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0\"\n    )\n"
  },
  {
    "path": "tests/functional/test_freeze.py",
    "content": "import os\nimport re\nimport sys\nimport textwrap\nfrom doctest import ELLIPSIS, OutputChecker\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.models.direct_url import DirectUrl, DirInfo\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    _create_test_package,\n    _create_test_package_with_srcdir,\n    _git_commit,\n    _vcs_add,\n    create_test_package_with_setup,\n    need_bzr,\n    need_mercurial,\n    need_svn,\n    wheel,\n)\nfrom tests.lib.venv import VirtualEnvironment\n\ndistribute_re = re.compile(\"^distribute==[0-9.]+\\n\", re.MULTILINE)\n\n\ndef _check_output(result: str, expected: str) -> None:\n    checker = OutputChecker()\n    actual = str(result)\n\n    # FIXME!  The following is a TOTAL hack.  For some reason the\n    # __str__ result for pkg_resources.Requirement gets downcased on\n    # Windows.  Since INITools is the only package we're installing\n    # in this file with funky case requirements, I'm forcibly\n    # upcasing it.  You can also normalize everything to lowercase,\n    # but then you have to remember to upcase <BLANKLINE>.  The right\n    # thing to do in the end is probably to find out how to report\n    # the proper fully-cased package name in our error message.\n    if sys.platform == \"win32\":\n        actual = actual.replace(\"initools\", \"INITools\")\n\n    # This allows our existing tests to work when run in a context\n    # with distribute installed.\n    actual = distribute_re.sub(\"\", actual)\n\n    def banner(msg: str) -> str:\n        return f\"\\n========== {msg} ==========\\n\"\n\n    assert checker.check_output(expected, actual, ELLIPSIS), (\n        banner(\"EXPECTED\") + expected + banner(\"ACTUAL\") + actual + banner(6 * \"=\")\n    )\n\n\ndef test_basic_freeze(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Some tests of freeze, first we have to install some stuff.  Note that\n    the test is a little crude at the end because Python 2.5+ adds egg\n    info to the standard library, so stuff like wsgiref will show up in\n    the freezing.  (Probably that should be accounted for in pip, but\n    currently it is not).\n\n    \"\"\"\n    script.scratch_path.joinpath(\"initools-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        simple==2.0\n        # and something else to test out:\n        simple2<=3.0\n        \"\"\"\n        )\n    )\n    script.pip_install_local(\n        \"-r\",\n        script.scratch_path / \"initools-req.txt\",\n    )\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        ...simple==2.0\n        simple2==3.0...\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\ndef test_freeze_with_pip(script: PipTestEnvironment) -> None:\n    \"\"\"Test that pip shows itself only when --all is used\"\"\"\n    result = script.pip(\"freeze\")\n    assert \"pip==\" not in result.stdout\n    result = script.pip(\"freeze\", \"--all\")\n    assert \"pip==\" in result.stdout\n\n\ndef test_freeze_with_setuptools(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that pip shows setuptools only when --all is used on Python < 3.12,\n    otherwise it should be shown in default freeze output.\n    \"\"\"\n\n    result = script.pip(\"freeze\", \"--all\")\n    assert \"setuptools==\" in result.stdout\n\n    # Test the default behavior (without --all)\n    result = script.pip(\"freeze\")\n\n    should_suppress = sys.version_info < (3, 12)\n    if should_suppress:\n        # setuptools should be hidden in default freeze output\n        assert \"setuptools==\" not in result.stdout, (\n            f\"setuptools should be suppressed in Python {sys.version_info[:2]} \"\n            f\"but was found in freeze output: {result.stdout}\"\n        )\n    else:\n        # setuptools should be shown in default freeze output\n        assert \"setuptools==\" in result.stdout, (\n            f\"setuptools should be shown in Python {sys.version_info[:2]} \"\n            f\"but was not found in freeze output: {result.stdout}\"\n        )\n\n    # --all should always show setuptools regardless of version\n    result_all = script.pip(\"freeze\", \"--all\")\n    assert \"setuptools==\" in result_all.stdout\n\n\ndef test_exclude_and_normalization(script: PipTestEnvironment, tmpdir: Path) -> None:\n    req_path = wheel.make_wheel(name=\"Normalizable_Name\", version=\"1.0\").save_to_dir(\n        tmpdir\n    )\n    script.pip(\"install\", \"--no-index\", req_path)\n    result = script.pip(\"freeze\")\n    assert \"Normalizable_Name\" in result.stdout\n    result = script.pip(\"freeze\", \"--exclude\", \"normalizablE-namE\")\n    assert \"Normalizable_Name\" not in result.stdout\n\n\ndef test_freeze_multiple_exclude_with_all(script: PipTestEnvironment) -> None:\n    result = script.pip(\"freeze\", \"--all\")\n    assert \"pip==\" in result.stdout\n    assert \"setuptools==\" in result.stdout\n    result = script.pip(\n        \"freeze\", \"--all\", \"--exclude\", \"pip\", \"--exclude\", \"setuptools\"\n    )\n    assert \"pip==\" not in result.stdout\n    assert \"setuptools==\" not in result.stdout\n\n\ndef test_freeze_with_invalid_names(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that invalid names produce warnings and are passed over gracefully.\n    \"\"\"\n\n    def fake_install(pkgname: str, dest: str) -> None:\n        egg_info_path = os.path.join(\n            dest,\n            \"{}-1.0-py{}.{}.egg-info\".format(\n                pkgname.replace(\"-\", \"_\"), sys.version_info[0], sys.version_info[1]\n            ),\n        )\n        with open(egg_info_path, \"w\") as egg_info_file:\n            egg_info_file.write(\n                textwrap.dedent(\n                    f\"\"\"\\\n                Metadata-Version: 1.0\n                Name: {pkgname}\n                Version: 1.0\n                \"\"\"\n                )\n            )\n\n    valid_pkgnames = (\"middle-dash\", \"middle_underscore\", \"middle.dot\")\n    invalid_pkgnames = (\n        \"-leadingdash\",\n        \"_leadingunderscore\",\n        \".leadingdot\",\n        \"trailingdash-\",\n        \"trailingunderscore_\",\n        \"trailingdot.\",\n    )\n    for pkgname in valid_pkgnames + invalid_pkgnames:\n        fake_install(pkgname, os.fspath(script.site_packages_path))\n\n    result = script.pip(\"freeze\", expect_stderr=True)\n\n    # Check all valid names are in the output.\n    output_lines = {line.strip() for line in result.stdout.splitlines()}\n    for name in valid_pkgnames:\n        assert f\"{name}==1.0\" in output_lines\n\n    # Check all invalid names are excluded from the output.\n    canonical_invalid_names = {canonicalize_name(n) for n in invalid_pkgnames}\n    for line in output_lines:\n        output_name, _, _ = line.partition(\"=\")\n        assert canonicalize_name(output_name) not in canonical_invalid_names\n\n    # The invalid names should be logged.\n    for name in canonical_invalid_names:\n        assert f\"Ignoring invalid distribution {name} (\" in result.stderr\n\n\n@pytest.mark.git\ndef test_freeze_editable_not_vcs(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test an editable install that is not version controlled.\n    \"\"\"\n    pkg_path = _create_test_package(script.scratch_path)\n    # Rename the .git directory so the directory is no longer recognized\n    # as a VCS directory.\n    os.rename(os.path.join(pkg_path, \".git\"), os.path.join(pkg_path, \".bak\"))\n    script.pip(\"install\", \"--no-build-isolation\", \"-e\", pkg_path)\n    result = script.pip(\"freeze\")\n\n    # We need to apply os.path.normcase() to the path since that is what\n    # the freeze code does.\n    expected = textwrap.dedent(\n        f\"\"\"\\\n    ...# Editable install with no version control (version...pkg==0.1)\n    -e {os.path.normcase(pkg_path)}\n    ...\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.git\ndef test_freeze_editable_git_with_no_remote(\n    script: PipTestEnvironment, deprecated_python: bool\n) -> None:\n    \"\"\"\n    Test an editable Git install with no remote url.\n    \"\"\"\n    pkg_path = _create_test_package(script.scratch_path)\n    script.pip(\"install\", \"--no-build-isolation\", \"-e\", pkg_path)\n    result = script.pip(\"freeze\")\n\n    if not deprecated_python:\n        assert result.stderr == \"\"\n\n    # We need to apply os.path.normcase() to the path since that is what\n    # the freeze code does.\n    expected = textwrap.dedent(\n        f\"\"\"\\\n    ...# Editable Git install with no remote (version...pkg==0.1)\n    -e {os.path.normcase(pkg_path)}\n    ...\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\n@need_svn\ndef test_freeze_svn(script: PipTestEnvironment) -> None:\n    \"\"\"Test freezing a svn checkout\"\"\"\n\n    checkout_path = _create_test_package(script.scratch_path, vcs=\"svn\")\n\n    # Install with develop\n    script.run(\"python\", \"setup.py\", \"develop\", cwd=checkout_path, expect_stderr=True)\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        ...-e svn+...#egg=version_pkg\n        ...\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.git\n@pytest.mark.xfail(\n    condition=True,\n    reason=\"xfail means editable is not in output\",\n    run=True,\n    strict=True,\n)\ndef test_freeze_exclude_editable(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test excluding editable from freezing list.\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package(script.scratch_path)\n\n    result = script.run(\n        \"git\",\n        \"clone\",\n        os.fspath(pkg_version),\n        \"pip-test-package\",\n        expect_stderr=True,\n    )\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=repo_dir,\n        expect_stderr=True,\n    )\n    result = script.pip(\"freeze\", \"--exclude-editable\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e git+...#egg=version_pkg\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.git\ndef test_freeze_git_clone(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Git clone.\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package(script.scratch_path)\n\n    result = script.run(\n        \"git\",\n        \"clone\",\n        os.fspath(pkg_version),\n        \"pip-test-package\",\n        expect_stderr=True,\n    )\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=repo_dir,\n        expect_stderr=True,\n    )\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e git+...#egg=version_pkg\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n    # Check that slashes in branch or tag names are translated.\n    # See also issue #1083: https://github.com/pypa/pip/issues/1083\n    script.run(\n        \"git\",\n        \"checkout\",\n        \"-b\",\n        \"branch/name/with/slash\",\n        cwd=repo_dir,\n        expect_stderr=True,\n    )\n    # Create a new commit to ensure that the commit has only one branch\n    # or tag name associated to it (to avoid the non-determinism reported\n    # in issue #1867).\n    (repo_dir / \"newfile\").touch()\n    script.run(\"git\", \"add\", \"newfile\", cwd=repo_dir)\n    _git_commit(script, repo_dir, message=\"...\")\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e ...@...#egg=version_pkg\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.git\ndef test_freeze_git_clone_srcdir(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Git clone where setup.py is in a subdirectory\n    relative the repo root and the source code is in a subdirectory\n    relative to setup.py.\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package_with_srcdir(script.scratch_path)\n\n    result = script.run(\n        \"git\",\n        \"clone\",\n        os.fspath(pkg_version),\n        \"pip-test-package\",\n        expect_stderr=True,\n    )\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=repo_dir / \"subdir\",\n        expect_stderr=True,\n    )\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e git+...#egg=version_pkg&subdirectory=subdir\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n\n@need_mercurial\ndef test_freeze_mercurial_clone_srcdir(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Mercurial clone where setup.py is in a subdirectory\n    relative to the repo root and the source code is in a subdirectory\n    relative to setup.py.\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package_with_srcdir(script.scratch_path, vcs=\"hg\")\n\n    result = script.run(\"hg\", \"clone\", os.fspath(pkg_version), \"pip-test-package\")\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\"python\", \"setup.py\", \"develop\", cwd=repo_dir / \"subdir\")\n    result = script.pip(\"freeze\")\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e hg+...#egg=version_pkg&subdirectory=subdir\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.git\ndef test_freeze_git_remote(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Git clone.\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package(script.scratch_path)\n\n    result = script.run(\n        \"git\",\n        \"clone\",\n        os.fspath(pkg_version),\n        \"pip-test-package\",\n        expect_stderr=True,\n    )\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=repo_dir,\n        expect_stderr=True,\n    )\n    origin_remote = pkg_version\n    # check frozen remote after clone\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = (\n        textwrap.dedent(\n            \"\"\"\n            ...-e git+{remote}@...#egg=version_pkg\n            ...\n        \"\"\"\n        )\n        .format(remote=origin_remote.as_uri())\n        .strip()\n    )\n    _check_output(result.stdout, expected)\n    # check frozen remote when there is no remote named origin\n    script.run(\"git\", \"remote\", \"rename\", \"origin\", \"other\", cwd=repo_dir)\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = (\n        textwrap.dedent(\n            \"\"\"\n            ...-e git+{remote}@...#egg=version_pkg\n            ...\n        \"\"\"\n        )\n        .format(remote=origin_remote.as_uri())\n        .strip()\n    )\n    _check_output(result.stdout, expected)\n    # When the remote is a local path, it must exist.\n    # If it doesn't, it gets flagged as invalid.\n    other_remote = f\"{pkg_version}-other\"\n    script.run(\"git\", \"remote\", \"set-url\", \"other\", other_remote, cwd=repo_dir)\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = os.path.normcase(\n        textwrap.dedent(\n            f\"\"\"\n            ...# Editable Git...(version...pkg...)...\n            # '{other_remote}'\n            -e {repo_dir}...\n        \"\"\"\n        ).strip()\n    )\n    _check_output(os.path.normcase(result.stdout), expected)\n    # when there are more than one origin, priority is given to the\n    # remote named origin\n    script.run(\"git\", \"remote\", \"add\", \"origin\", os.fspath(origin_remote), cwd=repo_dir)\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = (\n        textwrap.dedent(\n            \"\"\"\n            ...-e git+{remote}@...#egg=version_pkg\n            ...\n        \"\"\"\n        )\n        .format(remote=origin_remote.as_uri())\n        .strip()\n    )\n    _check_output(result.stdout, expected)\n\n\n@need_mercurial\ndef test_freeze_mercurial_clone(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Mercurial clone.\n\n    \"\"\"\n    # Returns path to a generated package called \"version_pkg\"\n    pkg_version = _create_test_package(script.scratch_path, vcs=\"hg\")\n\n    result = script.run(\n        \"hg\",\n        \"clone\",\n        os.fspath(pkg_version),\n        \"pip-test-package\",\n        expect_stderr=True,\n    )\n    repo_dir = script.scratch_path / \"pip-test-package\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=repo_dir,\n        expect_stderr=True,\n    )\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\n            ...-e hg+...#egg=version_pkg\n            ...\n        \"\"\"\n    ).strip()\n    _check_output(result.stdout, expected)\n\n\n@need_bzr\ndef test_freeze_bazaar_clone(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freezing a Bazaar clone.\n\n    \"\"\"\n    try:\n        checkout_path = _create_test_package(script.scratch_path, vcs=\"bazaar\")\n    except OSError as e:\n        pytest.fail(f\"Invoking `bzr` failed: {e}\")\n\n    result = script.run(\"bzr\", \"checkout\", os.fspath(checkout_path), \"bzr-package\")\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"develop\",\n        cwd=script.scratch_path / \"bzr-package\",\n        expect_stderr=True,\n    )\n    result = script.pip(\"freeze\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        ...-e bzr+file://...@1#egg=version_pkg\n        ...\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\n@need_mercurial\n@pytest.mark.git\n@pytest.mark.parametrize(\n    \"outer_vcs, inner_vcs\",\n    [(\"hg\", \"git\"), (\"git\", \"hg\")],\n)\ndef test_freeze_nested_vcs(\n    script: PipTestEnvironment, outer_vcs: str, inner_vcs: str\n) -> None:\n    \"\"\"Test VCS can be correctly freezed when resides inside another VCS repo.\"\"\"\n    # Create Python package.\n    pkg_path = _create_test_package(script.scratch_path, vcs=inner_vcs)\n\n    # Create outer repo to clone into.\n    root_path = script.scratch_path.joinpath(\"test_freeze_nested_vcs\")\n    root_path.mkdir()\n    root_path.joinpath(\".hgignore\").write_text(\"src\")\n    root_path.joinpath(\".gitignore\").write_text(\"src\")\n    _vcs_add(script, root_path, outer_vcs)\n\n    # Clone Python package into inner directory and install it.\n    src_path = root_path.joinpath(\"src\")\n    src_path.mkdir()\n    script.run(\n        inner_vcs,\n        \"clone\",\n        os.fspath(pkg_path),\n        os.fspath(src_path),\n        expect_stderr=True,\n    )\n    script.pip(\"install\", \"--no-build-isolation\", \"-e\", src_path, expect_stderr=True)\n\n    # Check the freeze output recognizes the inner VCS.\n    result = script.pip(\"freeze\", expect_stderr=True)\n    _check_output(\n        result.stdout,\n        f\"...-e {inner_vcs}+...#egg=version_pkg\\n...\",\n    )\n\n\n# used by the test_freeze_with_requirement_* tests below\n_freeze_req_opts = textwrap.dedent(\n    \"\"\"\\\n    # Unchanged requirements below this line\n    -r ignore.txt\n    --requirement ignore.txt\n    -f http://ignore\n    -i http://ignore\n    --pre\n    --trusted-host url\n    --process-dependency-links\n    --extra-index-url http://ignore\n    --find-links http://ignore\n    --index-url http://ignore\n    --use-feature resolvelib\n\"\"\"\n)\n\n\ndef test_freeze_with_requirement_option_file_url_egg_not_installed(\n    script: PipTestEnvironment, deprecated_python: bool\n) -> None:\n    \"\"\"\n    Test \"freeze -r requirements.txt\" with a local file URL whose egg name\n    is not installed.\n    \"\"\"\n\n    url = \"file:///my-package.tar.gz#egg=Does.Not-Exist\"\n    requirements_path = script.scratch_path.joinpath(\"requirements.txt\")\n    requirements_path.write_text(url + \"\\n\")\n\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"requirements.txt\",\n        expect_stderr=True,\n    )\n    expected_err = (\n        f\"WARNING: Requirement file [requirements.txt] contains {url}, \"\n        \"but package 'Does.Not-Exist' is not installed\\n\"\n    )\n    if deprecated_python:\n        assert expected_err in result.stderr\n    else:\n        assert expected_err == result.stderr\n\n\ndef test_freeze_with_requirement_option(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that new requirements are created correctly with --requirement hints\n\n    \"\"\"\n\n    script.scratch_path.joinpath(\"hint1.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        INITools==0.1\n        NoExist==4.2  # A comment that ensures end of line comments work.\n        simple==3.0; python_version > '1.0'\n        \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    script.scratch_path.joinpath(\"hint2.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        iniTools==0.1\n        Noexist==4.2  # A comment that ensures end of line comments work.\n        Simple==3.0; python_version > '1.0'\n        \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    result = script.pip_install_local(\"initools==0.2\")\n    result = script.pip_install_local(\"simple\")\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"hint1.txt\",\n        expect_stderr=True,\n    )\n    expected = textwrap.dedent(\n        \"\"\"\\\n        INITools==0.2\n        simple==3.0\n    \"\"\"\n    )\n    expected += _freeze_req_opts\n    expected += \"## The following requirements were added by pip freeze:...\"\n    _check_output(result.stdout, expected)\n    assert (\n        \"Requirement file [hint1.txt] contains NoExist==4.2, but package \"\n        \"'NoExist' is not installed\"\n    ) in result.stderr\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"hint2.txt\",\n        expect_stderr=True,\n    )\n    _check_output(result.stdout, expected)\n    assert (\n        \"Requirement file [hint2.txt] contains Noexist==4.2, but package \"\n        \"'Noexist' is not installed\"\n    ) in result.stderr\n\n\ndef test_freeze_with_requirement_option_multiple(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that new requirements are created correctly with multiple\n    --requirement hints\n\n    \"\"\"\n    script.scratch_path.joinpath(\"hint1.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        INITools==0.1\n        NoExist==4.2\n        simple==3.0; python_version > '1.0'\n    \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    script.scratch_path.joinpath(\"hint2.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        NoExist2==2.0\n        simple2==1.0\n    \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    result = script.pip_install_local(\"initools==0.2\")\n    result = script.pip_install_local(\"simple\")\n    result = script.pip_install_local(\"simple2==1.0\")\n    result = script.pip_install_local(\"meta\")\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"hint1.txt\",\n        \"--requirement\",\n        \"hint2.txt\",\n        expect_stderr=True,\n    )\n    expected = textwrap.dedent(\n        \"\"\"\\\n        INITools==0.2\n        simple==1.0\n    \"\"\"\n    )\n    expected += _freeze_req_opts\n    expected += textwrap.dedent(\n        \"\"\"\\\n        simple2==1.0\n    \"\"\"\n    )\n    expected += \"## The following requirements were added by pip freeze:\"\n    expected += \"\\n\" + textwrap.dedent(\n        \"\"\"\\\n        ...meta==1.0...\n    \"\"\"\n    )\n    _check_output(result.stdout, expected)\n    assert (\n        \"Requirement file [hint1.txt] contains NoExist==4.2, but package \"\n        \"'NoExist' is not installed\"\n    ) in result.stderr\n    assert (\n        \"Requirement file [hint2.txt] contains NoExist2==2.0, but package \"\n        \"'NoExist2' is not installed\"\n    ) in result.stderr\n    # any options like '--index-url http://ignore' should only be emitted once\n    # even if they are listed in multiple requirements files\n    assert result.stdout.count(\"--index-url http://ignore\") == 1\n\n\ndef test_freeze_with_requirement_option_package_repeated_one_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test freezing with single requirements file that contains a package\n    multiple times\n    \"\"\"\n    script.scratch_path.joinpath(\"hint1.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        simple2\n        simple2\n        NoExist\n    \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    result = script.pip_install_local(\"simple2==1.0\")\n    result = script.pip_install_local(\"meta\")\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"hint1.txt\",\n        expect_stderr=True,\n    )\n    expected_out = textwrap.dedent(\n        \"\"\"\\\n        simple2==1.0\n    \"\"\"\n    )\n    expected_out += _freeze_req_opts\n    expected_out += \"## The following requirements were added by pip freeze:\"\n    expected_out += \"\\n\" + textwrap.dedent(\n        \"\"\"\\\n        ...meta==1.0...\n    \"\"\"\n    )\n    _check_output(result.stdout, expected_out)\n    err1 = (\n        \"Requirement file [hint1.txt] contains NoExist, \"\n        \"but package 'NoExist' is not installed\\n\"\n    )\n    err2 = \"Requirement simple2 included multiple times [hint1.txt]\\n\"\n    assert err1 in result.stderr\n    assert err2 in result.stderr\n    # there shouldn't be any other 'is not installed' warnings\n    assert result.stderr.count(\"is not installed\") == 1\n\n\ndef test_freeze_with_requirement_option_package_repeated_multi_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test freezing with multiple requirements file that contain a package\n    \"\"\"\n    script.scratch_path.joinpath(\"hint1.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        simple\n    \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    script.scratch_path.joinpath(\"hint2.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        simple\n        NoExist\n    \"\"\"\n        )\n        + _freeze_req_opts\n    )\n    result = script.pip_install_local(\"simple==1.0\")\n    result = script.pip_install_local(\"meta\")\n    result = script.pip(\n        \"freeze\",\n        \"--requirement\",\n        \"hint1.txt\",\n        \"--requirement\",\n        \"hint2.txt\",\n        expect_stderr=True,\n    )\n    expected_out = textwrap.dedent(\n        \"\"\"\\\n        simple==1.0\n    \"\"\"\n    )\n    expected_out += _freeze_req_opts\n    expected_out += \"## The following requirements were added by pip freeze:\"\n    expected_out += \"\\n\" + textwrap.dedent(\n        \"\"\"\\\n        ...meta==1.0...\n    \"\"\"\n    )\n    _check_output(result.stdout, expected_out)\n\n    err1 = (\n        \"Requirement file [hint2.txt] contains NoExist, but package \"\n        \"'NoExist' is not installed\\n\"\n    )\n    err2 = \"Requirement simple included multiple times [hint1.txt, hint2.txt]\\n\"\n    assert err1 in result.stderr\n    assert err2 in result.stderr\n    # there shouldn't be any other 'is not installed' warnings\n    assert result.stderr.count(\"is not installed\") == 1\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_freeze_user(\n    script: PipTestEnvironment, virtualenv: VirtualEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Testing freeze with --user, first we have to install some stuff.\n    \"\"\"\n    script.pip_install_local(\"--find-links\", data.find_links, \"--user\", \"simple==2.0\")\n    script.pip_install_local(\"--find-links\", data.find_links, \"simple2==3.0\")\n    result = script.pip(\"freeze\", \"--user\", expect_stderr=True)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple==2.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n    assert \"simple2\" not in result.stdout\n\n\ndef test_freeze_path(tmpdir: Path, script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test freeze with --path.\n    \"\"\"\n    script.pip_install_local(\"--target\", tmpdir, \"simple==2.0\")\n    result = script.pip(\"freeze\", \"--path\", tmpdir)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple==2.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_freeze_path_exclude_user(\n    tmpdir: Path, script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test freeze with --path and make sure packages from --user are not picked\n    up.\n    \"\"\"\n    script.pip_install_local(\"--find-links\", data.find_links, \"--user\", \"simple2\")\n    script.pip_install_local(\"--target\", tmpdir, \"simple==1.0\")\n    result = script.pip(\"freeze\", \"--user\")\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple2==3.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n    result = script.pip(\"freeze\", \"--path\", tmpdir)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple==1.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\ndef test_freeze_path_multiple(\n    tmpdir: Path, script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test freeze with multiple --path arguments.\n    \"\"\"\n    path1 = tmpdir / \"path1\"\n    os.mkdir(path1)\n    path2 = tmpdir / \"path2\"\n    os.mkdir(path2)\n    script.pip_install_local(\"--target\", path1, \"simple==2.0\")\n    script.pip_install_local(\"--target\", path2, \"simple2==3.0\")\n    result = script.pip(\"freeze\", \"--path\", path1)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple==2.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n    result = script.pip(\"freeze\", \"--path\", path1, \"--path\", path2)\n    expected = textwrap.dedent(\n        \"\"\"\\\n        simple==2.0\n        simple2==3.0\n        <BLANKLINE>\"\"\"\n    )\n    _check_output(result.stdout, expected)\n\n\ndef test_freeze_direct_url_archive(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    req = \"simple @ \" + shared_data.packages.joinpath(\"simple-2.0.tar.gz\").as_uri()\n    script.pip(\"install\", \"--no-build-isolation\", req)\n    result = script.pip(\"freeze\")\n    assert req in result.stdout\n\n\ndef test_freeze_skip_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that freeze should not include package\n    present in working directory\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    # Freeze should not include package simple when run from package directory\n    result = script.pip(\"freeze\", cwd=pkg_path)\n    assert \"simple\" not in result.stdout\n\n\ndef test_freeze_include_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that freeze should include package in working directory\n    if working directory is added in PYTHONPATH\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    # Freeze should include package simple when run from package directory,\n    # when package directory is in PYTHONPATH\n    result = script.pip(\"freeze\", cwd=pkg_path)\n    assert \"simple==1.0\" in result.stdout\n\n\ndef test_freeze_pep610_editable(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that a package installed with a direct_url.json with editable=true\n    is correctly frozeon as editable.\n    \"\"\"\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpkg\")\n    result = script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    direct_url_path = result.get_created_direct_url_path(\"testpkg\")\n    assert direct_url_path\n    # patch direct_url.json to simulate an editable install\n    with open(direct_url_path) as f:\n        direct_url = DirectUrl.from_json(f.read())\n    assert isinstance(direct_url.info, DirInfo)\n    direct_url.info.editable = True\n    with open(direct_url_path, \"w\") as f:\n        f.write(direct_url.to_json())\n    result = script.pip(\"freeze\")\n    assert \"# Editable Git install with no remote (testpkg==0.1)\" in result.stdout\n"
  },
  {
    "path": "tests/functional/test_hash.py",
    "content": "\"\"\"Tests for the ``pip hash`` command\"\"\"\n\nfrom pathlib import Path\n\nfrom tests.lib import PipTestEnvironment\n\n\ndef test_basic_hash(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"Run 'pip hash' through its default behavior.\"\"\"\n    expected = (\n        \"--hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425\"\n        \"e73043362938b9824\"\n    )\n    result = script.pip(\"hash\", _hello_file(tmpdir))\n    assert expected in str(result)\n\n\ndef test_good_algo_option(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"Make sure the -a option works.\"\"\"\n    expected = (\n        \"--hash=sha512:9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caad\"\n        \"ae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e\"\n        \"5c3adef46f73bcdec043\"\n    )\n    result = script.pip(\"hash\", \"-a\", \"sha512\", _hello_file(tmpdir))\n    assert expected in str(result)\n\n\ndef test_bad_algo_option(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"Make sure the -a option raises an error when given a bad operand.\"\"\"\n    result = script.pip(\n        \"hash\", \"-a\", \"invalidname\", _hello_file(tmpdir), expect_error=True\n    )\n    assert \"invalid choice: 'invalidname'\" in str(result)\n\n\ndef _hello_file(tmpdir: Path) -> Path:\n    \"\"\"Return a temp file to hash containing \"hello\".\"\"\"\n    file = tmpdir / \"hashable\"\n    file.write_text(\"hello\")\n    return file\n"
  },
  {
    "path": "tests/functional/test_help.py",
    "content": "import functools\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._vendor.rich.text import Text\n\nimport pip._internal.cli.parser\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.commands import commands_dict, create_command\nfrom pip._internal.exceptions import CommandError\n\nfrom tests.lib import InMemoryPip, PipTestEnvironment\n\n\ndef test_run_method_should_return_success_when_finds_command_name() -> None:\n    \"\"\"\n    Test HelpCommand.run for existing command\n    \"\"\"\n    options_mock = Mock()\n    args = [\"freeze\"]\n    help_cmd = create_command(\"help\")\n    status = help_cmd.run(options_mock, args)\n    assert status == SUCCESS\n\n\ndef test_run_method_should_return_success_when_command_name_not_specified() -> None:\n    \"\"\"\n    Test HelpCommand.run when there are no args\n    \"\"\"\n    options_mock = Mock()\n    help_cmd = create_command(\"help\")\n    status = help_cmd.run(options_mock, [])\n    assert status == SUCCESS\n\n\ndef test_run_method_should_raise_command_error_when_command_does_not_exist() -> None:\n    \"\"\"\n    Test HelpCommand.run for non-existing command\n    \"\"\"\n    options_mock = Mock()\n    args = [\"mycommand\"]\n    help_cmd = create_command(\"help\")\n\n    with pytest.raises(CommandError):\n        help_cmd.run(options_mock, args)\n\n\ndef test_help_command_should_exit_status_ok_when_command_exists(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test `help` command for existing command\n    \"\"\"\n    result = script.pip(\"help\", \"freeze\")\n    assert result.returncode == SUCCESS\n\n\ndef test_help_command_should_exit_status_ok_when_no_cmd_is_specified(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test `help` command for no command\n    \"\"\"\n    result = script.pip(\"help\")\n    assert result.returncode == SUCCESS\n\n\ndef test_help_command_should_exit_status_error_when_cmd_does_not_exist(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test `help` command for non-existing command\n    \"\"\"\n    result = script.pip(\"help\", \"mycommand\", expect_error=True)\n    assert result.returncode == ERROR\n\n\ndef test_help_command_redact_auth_from_url(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test `help` on various subcommands redact auth from url\n    \"\"\"\n    script.environ[\"PIP_INDEX_URL\"] = \"https://user:secret@example.com\"\n    result = script.pip(\"install\", \"--help\")\n    assert result.returncode == SUCCESS\n    assert \"secret\" not in result.stdout\n\n\ndef test_help_command_redact_auth_from_url_with_extra_index_url(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test `help` on various subcommands redact auth from url with extra index url\n    \"\"\"\n    script.environ[\"PIP_INDEX_URL\"] = \"https://user:secret@example.com\"\n    script.environ[\"PIP_EXTRA_INDEX_URL\"] = \"https://user:secret@example2.com\"\n    result = script.pip(\"install\", \"--help\")\n    assert result.returncode == SUCCESS\n    assert \"secret\" not in result.stdout\n\n\ndef test_help_commands_equally_functional(in_memory_pip: InMemoryPip) -> None:\n    \"\"\"\n    Test if `pip help` and 'pip --help' behave the same way.\n    \"\"\"\n    results = list(map(in_memory_pip.pip, (\"help\", \"--help\")))\n    results.append(in_memory_pip.pip())\n\n    out = (x.stdout for x in results)\n    ret = (x.returncode for x in results)\n\n    msg = '\"pip --help\" != \"pip help\" != \"pip\"'\n    assert len(set(out)) == 1, \"output of: \" + msg\n    assert sum(ret) == 0, \"exit codes of: \" + msg\n    assert all(len(o) > 0 for o in out)\n\n    for name in commands_dict:\n        assert (\n            in_memory_pip.pip(\"help\", name).stdout\n            == in_memory_pip.pip(name, \"--help\").stdout\n            != \"\"\n        )\n\n\n@pytest.mark.parametrize(\"envvar\", [\"\", \"NO_COLOR\", \"PIP_NO_COLOR\"])\ndef test_help_command_colors(\n    in_memory_pip: InMemoryPip, monkeypatch: pytest.MonkeyPatch, envvar: str\n) -> None:\n    \"\"\"\n    Test if color disables correctly.\n    \"\"\"\n    monkeypatch.delenv(\"NO_COLOR\", raising=False)\n    monkeypatch.delenv(\"PIP_NO_COLOR\", raising=False)\n    monkeypatch.delenv(\"FORCE_COLOR\", raising=False)\n\n    PipConsole = pip._internal.cli.parser.PipConsole\n\n    TestConsole = functools.partial(\n        PipConsole, force_terminal=True, color_system=\"standard\", width=80\n    )\n    monkeypatch.setattr(pip._internal.cli.parser, \"PipConsole\", TestConsole)\n\n    if envvar:\n        monkeypatch.setenv(envvar, \"1\")\n\n    res = in_memory_pip.pip(\"help\")\n    text = Text.from_ansi(res.stdout)\n\n    bold_spans = [s for s in text.spans if getattr(s.style, \"bold\", None)]\n    bold_text = [text.plain[s.start : s.end] for s in bold_spans]\n\n    assert bold_text == [\"Usage:\", \"Commands:\", \"General Options:\"]\n\n    for span in bold_spans:\n        style = span.style\n        assert not isinstance(style, str)\n        if envvar:\n            assert style.color is None\n        else:\n            assert style.color is not None\n"
  },
  {
    "path": "tests/functional/test_index.py",
    "content": "import json\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.commands import create_command\n\nfrom tests.lib import PipTestEnvironment, make_wheel\n\n\n@pytest.mark.network\ndef test_json_structured_output(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that --json flag returns structured output\n    \"\"\"\n    output = script.pip(\"index\", \"versions\", \"pip\", \"--json\", allow_stderr_warning=True)\n    structured_output = json.loads(output.stdout)\n\n    assert isinstance(structured_output, dict)\n    assert \"name\" in structured_output\n    assert structured_output[\"name\"] == \"pip\"\n    assert \"latest\" in structured_output\n    assert isinstance(structured_output[\"latest\"], str)\n    assert \"versions\" in structured_output\n    assert isinstance(structured_output[\"versions\"], list)\n    assert (\n        \"20.2.3, 20.2.2, 20.2.1, 20.2, 20.1.1, 20.1, 20.0.2\"\n        \", 20.0.1, 19.3.1, 19.3, 19.2.3, 19.2.2, 19.2.1, 19.2, 19.1.1\"\n        \", 19.1, 19.0.3, 19.0.2, 19.0.1, 19.0, 18.1, 18.0, 10.0.1, 10.0.0, \"\n        \"9.0.3, 9.0.2, 9.0.1, 9.0.0, 8.1.2, 8.1.1, \"\n        \"8.1.0, 8.0.3, 8.0.2, 8.0.1, 8.0.0, 7.1.2, 7.1.1, 7.1.0, 7.0.3, \"\n        \"7.0.2, 7.0.1, 7.0.0, 6.1.1, 6.1.0, 6.0.8, 6.0.7, 6.0.6, 6.0.5, \"\n        \"6.0.4, 6.0.3, 6.0.2, 6.0.1, 6.0, 1.5.6, 1.5.5, 1.5.4, 1.5.3, \"\n        \"1.5.2, 1.5.1, 1.5, 1.4.1, 1.4, 1.3.1, 1.3, 1.2.1, 1.2, 1.1, 1.0.2,\"\n        \" 1.0.1, 1.0, 0.8.3, 0.8.2, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.3, \"\n        \"0.6.2, 0.6.1, 0.6, 0.5.1, 0.5, 0.4, 0.3.1, \"\n        \"0.3, 0.2.1, 0.2\" in \", \".join(structured_output[\"versions\"])\n    )\n\n\n@pytest.mark.network\ndef test_list_all_versions_basic_search(script: PipTestEnvironment) -> None:\n    \"\"\"\n    End to end test of index versions command.\n    \"\"\"\n    output = script.pip(\"index\", \"versions\", \"pip\", allow_stderr_warning=True)\n    assert \"Available versions:\" in output.stdout\n    assert (\n        \"20.2.3, 20.2.2, 20.2.1, 20.2, 20.1.1, 20.1, 20.0.2\"\n        \", 20.0.1, 19.3.1, 19.3, 19.2.3, 19.2.2, 19.2.1, 19.2, 19.1.1\"\n        \", 19.1, 19.0.3, 19.0.2, 19.0.1, 19.0, 18.1, 18.0, 10.0.1, 10.0.0, \"\n        \"9.0.3, 9.0.2, 9.0.1, 9.0.0, 8.1.2, 8.1.1, \"\n        \"8.1.0, 8.0.3, 8.0.2, 8.0.1, 8.0.0, 7.1.2, 7.1.1, 7.1.0, 7.0.3, \"\n        \"7.0.2, 7.0.1, 7.0.0, 6.1.1, 6.1.0, 6.0.8, 6.0.7, 6.0.6, 6.0.5, \"\n        \"6.0.4, 6.0.3, 6.0.2, 6.0.1, 6.0, 1.5.6, 1.5.5, 1.5.4, 1.5.3, \"\n        \"1.5.2, 1.5.1, 1.5, 1.4.1, 1.4, 1.3.1, 1.3, 1.2.1, 1.2, 1.1, 1.0.2,\"\n        \" 1.0.1, 1.0, 0.8.3, 0.8.2, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.3, \"\n        \"0.6.2, 0.6.1, 0.6, 0.5.1, 0.5, 0.4, 0.3.1, \"\n        \"0.3, 0.2.1, 0.2\" in output.stdout\n    )\n\n\n@pytest.mark.network\ndef test_list_all_versions_search_with_pre(script: PipTestEnvironment) -> None:\n    \"\"\"\n    See that adding the --pre flag adds pre-releases\n    \"\"\"\n    output = script.pip(\"index\", \"versions\", \"pip\", \"--pre\", allow_stderr_warning=True)\n    assert \"Available versions:\" in output.stdout\n    assert (\n        \"20.2.3, 20.2.2, 20.2.1, 20.2, 20.2b1, 20.1.1, 20.1, 20.1b1, 20.0.2\"\n        \", 20.0.1, 19.3.1, 19.3, 19.2.3, 19.2.2, 19.2.1, 19.2, 19.1.1\"\n        \", 19.1, 19.0.3, 19.0.2, 19.0.1, 19.0, 18.1, 18.0, 10.0.1, 10.0.0, \"\n        \"10.0.0b2, 10.0.0b1, 9.0.3, 9.0.2, 9.0.1, 9.0.0, 8.1.2, 8.1.1, \"\n        \"8.1.0, 8.0.3, 8.0.2, 8.0.1, 8.0.0, 7.1.2, 7.1.1, 7.1.0, 7.0.3, \"\n        \"7.0.2, 7.0.1, 7.0.0, 6.1.1, 6.1.0, 6.0.8, 6.0.7, 6.0.6, 6.0.5, \"\n        \"6.0.4, 6.0.3, 6.0.2, 6.0.1, 6.0, 1.5.6, 1.5.5, 1.5.4, 1.5.3, \"\n        \"1.5.2, 1.5.1, 1.5, 1.4.1, 1.4, 1.3.1, 1.3, 1.2.1, 1.2, 1.1, 1.0.2,\"\n        \" 1.0.1, 1.0, 0.8.3, 0.8.2, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.3, \"\n        \"0.6.2, 0.6.1, 0.6, 0.5.1, 0.5, 0.4, 0.3.1, \"\n        \"0.3, 0.2.1, 0.2\" in output.stdout\n    )\n\n\n@pytest.mark.network\ndef test_list_all_versions_returns_no_matches_found_when_name_not_exact() -> None:\n    \"\"\"\n    Test that non exact name do not match\n    \"\"\"\n    command = create_command(\"index\")\n    cmdline = \"versions pand\"\n    with command.main_context():\n        options, args = command.parse_args(cmdline.split())\n        status = command.run(options, args)\n    assert status == ERROR\n\n\n@pytest.mark.network\ndef test_list_all_versions_returns_matches_found_when_name_is_exact() -> None:\n    \"\"\"\n    Test that exact name matches\n    \"\"\"\n    command = create_command(\"index\")\n    cmdline = \"versions pandas\"\n    with command.main_context():\n        options, args = command.parse_args(cmdline.split())\n        status = command.run(options, args)\n    assert status == SUCCESS\n\n\ndef test_index_versions_all_releases_for_package(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --all-releases shows prereleases for specific package.\"\"\"\n    # Create fake local package index with prerelease\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.mkdir()\n    make_wheel(\"simple\", \"1.0\").save_to_dir(wheelhouse_path)\n    make_wheel(\"simple\", \"2.0a1\").save_to_dir(wheelhouse_path)\n\n    # Without --all-releases, should only show stable versions\n    result = script.pip(\n        \"index\",\n        \"versions\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"simple\",\n    )\n    assert \"1.0\" in result.stdout\n    assert \"2.0a1\" not in result.stdout\n\n    # With --all-releases for simple, should show prereleases\n    result = script.pip(\n        \"index\",\n        \"versions\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--all-releases=simple\",\n        \"simple\",\n    )\n    assert \"1.0\" in result.stdout\n    assert \"2.0a1\" in result.stdout\n\n\ndef test_index_versions_only_final_for_package(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --only-final filters prereleases for specific package.\"\"\"\n    # Create fake local package index with prerelease\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.mkdir()\n    make_wheel(\"simple\", \"1.0\").save_to_dir(wheelhouse_path)\n    make_wheel(\"simple\", \"2.0a1\").save_to_dir(wheelhouse_path)\n\n    # With --only-final for simple, should not show prereleases (same as default)\n    result = script.pip(\n        \"index\",\n        \"versions\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--only-final=simple\",\n        \"simple\",\n    )\n    assert \"1.0\" in result.stdout\n    assert \"2.0a1\" not in result.stdout\n"
  },
  {
    "path": "tests/functional/test_index_invalid_wheels.py",
    "content": "\"\"\"Test that pip index versions handles invalid (non-PEP 440) wheel filenames.\n\nThis test was added for robustness after legacy wheel filename support\nwas removed in pip 25.3.\n\"\"\"\n\nimport json\nimport textwrap\nfrom pathlib import Path\n\nfrom tests.lib import PipTestEnvironment\nfrom tests.lib.wheel import make_wheel\n\n\ndef _create_test_index_with_invalid_wheels(\n    tmpdir: Path, package_name: str = \"pkg\"\n) -> Path:\n    \"\"\"Create a test index with both valid and invalid wheel filenames.\n\n    Returns the path to the index directory.\n    \"\"\"\n    # Create test index\n    index_dir = tmpdir / \"test_index\"\n    index_dir.mkdir()\n\n    (index_dir / \"index.html\").write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n        <!DOCTYPE html>\n        <html>\n          <body><a href=\"{package_name}/index.html\">{package_name}</a></body>\n        </html>\n        \"\"\"\n        )\n    )\n\n    pkg_dir = index_dir / package_name\n    pkg_dir.mkdir()\n\n    valid_wheels = [\n        (f\"{package_name}-1.0.0-py3-none-any.whl\", \"1.0.0\"),\n        (f\"{package_name}-2.0.0-py3-none-any.whl\", \"2.0.0\"),\n    ]\n    invalid_wheels = [\n        (f\"{package_name}-3.0_1-py3-none-any.whl\", \"3.0\"),  # underscore in version\n        (f\"{package_name}-_bad_-py3-none-any.wh\", \"0.0.0\"),  # no version\n        (\n            f\"{package_name}-5.0.0_build1-py3-none-any.whl\",\n            \"5.0.0\",\n        ),  # underscore in build tag\n    ]\n\n    all_wheels = valid_wheels + invalid_wheels\n    for wheel_name, version in all_wheels:\n        wheel = make_wheel(name=package_name, version=version)\n        wheel.save_to(pkg_dir / wheel_name)\n\n    # Create package index\n    links = [\n        f'<a href=\"{wheel_name}\">{wheel_name}</a><br/>' for wheel_name, _ in all_wheels\n    ]\n    (pkg_dir / \"index.html\").write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n        <!DOCTYPE html>\n        <html>\n          <body>\n            {''.join(links)}\n          </body>\n        </html>\n        \"\"\"\n        )\n    )\n\n    return index_dir\n\n\ndef test_index_versions_ignores_invalid_wheel_names(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n) -> None:\n    \"\"\"Test that pip index versions ignores invalid wheel names.\"\"\"\n    index_dir = _create_test_index_with_invalid_wheels(tmpdir)\n\n    # Run pip index versions with JSON output\n    result = script.pip(\n        \"index\", \"versions\", \"pkg\", \"--json\", \"--index-url\", index_dir.as_uri()\n    )\n\n    assert result.returncode == 0\n\n    output = json.loads(result.stdout)\n    assert output[\"name\"] == \"pkg\"\n    assert output[\"latest\"] == \"2.0.0\"\n\n    expected_versions = [\"2.0.0\", \"1.0.0\"]\n    assert output[\"versions\"] == expected_versions\n\n\ndef test_install_ignores_invalid_wheel_names(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n) -> None:\n    \"\"\"Test that pip install ignores invalid wheel names and installs valid ones.\"\"\"\n    index_dir = _create_test_index_with_invalid_wheels(tmpdir)\n\n    # Run pip install - should ignore invalid wheels and install the latest valid one\n    result = script.pip(\n        \"install\", \"pkg\", \"--no-cache-dir\", \"--index-url\", index_dir.as_uri()\n    )\n\n    assert result.returncode == 0\n    script.assert_installed(pkg=\"2.0.0\")\n"
  },
  {
    "path": "tests/functional/test_inspect.py",
    "content": "import json\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, ScriptFactory, TestData\n\n\n@pytest.fixture\ndef simple_script(\n    tmpdir_factory: pytest.TempPathFactory,\n    script_factory: ScriptFactory,\n    shared_data: TestData,\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"pip_test_package\")\n    script = script_factory(tmpdir.joinpath(\"workspace\"))\n    script.pip(\n        \"install\",\n        \"-f\",\n        shared_data.find_links,\n        \"--no-index\",\n        \"simplewheel==1.0\",\n    )\n    return script\n\n\ndef test_inspect_basic(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test default behavior of inspect command.\n    \"\"\"\n    result = simple_script.pip(\"inspect\")\n    report = json.loads(result.stdout)\n    installed_by_name = {i[\"metadata\"][\"name\"]: i for i in report[\"installed\"]}\n    # Coverage is only installed if test coverage is being collected.\n    installed_by_name.pop(\"coverage\", None)\n    assert len(installed_by_name) == 3\n    assert installed_by_name.keys() == {\n        \"pip\",\n        \"setuptools\",\n        \"simplewheel\",\n    }\n    assert installed_by_name[\"simplewheel\"][\"metadata\"][\"version\"] == \"1.0\"\n    assert installed_by_name[\"simplewheel\"][\"requested\"] is True\n    assert installed_by_name[\"simplewheel\"][\"installer\"] == \"pip\"\n    assert \"environment\" in report\n"
  },
  {
    "path": "tests/functional/test_install.py",
    "content": "from __future__ import annotations\n\nimport hashlib\nimport io\nimport os\nimport re\nimport ssl\nimport sys\nimport sysconfig\nimport tarfile\nimport textwrap\nfrom collections.abc import Iterable\nfrom os.path import curdir, join, pardir\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.models.direct_url import DirectUrl\nfrom pip._internal.models.index import PyPI, TestPyPI\nfrom pip._internal.utils.misc import rmtree\nfrom pip._internal.utils.urls import path_to_url\n\nfrom tests.lib import (\n    CertFactory,\n    PipTestEnvironment,\n    ResolverVariant,\n    TestData,\n    TestPipResult,\n    _create_svn_repo,\n    _create_test_package,\n    create_basic_wheel_for_package,\n    create_test_package_with_setup,\n    need_bzr,\n    need_mercurial,\n    need_svn,\n    pyversion,\n    requirements_file,\n)\nfrom tests.lib.local_repos import local_checkout\nfrom tests.lib.server import (\n    file_response,\n    make_mock_server,\n    package_page,\n    server_running,\n)\n\n\n@pytest.mark.parametrize(\"command\", [\"install\", \"wheel\"])\n@pytest.mark.parametrize(\"variant\", [\"missing_setuptools\", \"bad_setuptools\"])\ndef test_pep518_uses_build_env(\n    script: PipTestEnvironment,\n    data: TestData,\n    common_wheels: Path,\n    command: str,\n    variant: str,\n) -> None:\n    if variant == \"missing_setuptools\":\n        script.pip(\"uninstall\", \"-y\", \"setuptools\")\n    elif variant == \"bad_setuptools\":\n        setuptools_mod = script.site_packages_path.joinpath(\"setuptools.py\")\n        with open(setuptools_mod, \"a\") as f:\n            f.write('\\nraise ImportError(\"toto\")')\n    else:\n        raise ValueError(variant)\n    script.pip(\n        command,\n        \"--no-index\",\n        \"-f\",\n        common_wheels,\n        \"-f\",\n        data.packages,\n        data.src.joinpath(\"pep518-3.0\"),\n    )\n\n\ndef test_pep518_build_env_uses_same_pip(\n    script: PipTestEnvironment,\n    data: TestData,\n    pip_src: Path,\n    common_wheels: Path,\n    deprecated_python: bool,\n) -> None:\n    \"\"\"Ensure the subprocess call to pip for installing the\n    build dependencies is using the same version of pip.\n    \"\"\"\n    with open(script.scratch_path / \"pip.py\", \"w\") as fp:\n        fp.write(\"raise ImportError\")\n    script.run(\n        \"python\",\n        os.fspath(pip_src / \"src/pip\"),\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        os.fspath(common_wheels),\n        \"-f\",\n        os.fspath(data.packages),\n        os.fspath(data.src.joinpath(\"pep518-3.0\")),\n        expect_stderr=deprecated_python,\n    )\n\n\ndef test_pep518_refuses_conflicting_requires(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    create_basic_wheel_for_package(script, \"setuptools\", \"1.0\")\n    create_basic_wheel_for_package(script, \"wheel\", \"1.0\")\n    project_dir = data.src.joinpath(\"pep518_conflicting_requires\")\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        script.scratch_path,\n        project_dir,\n        expect_error=True,\n    )\n    assert result.returncode != 0\n    assert (\n        f\"Some build dependencies for {project_dir.as_uri()} conflict \"\n        \"with PEP 517/518 supported \"\n        \"requirements: setuptools==1.0 is incompatible with \"\n        \"setuptools>=40.8.0.\"\n    ) in result.stderr, str(result)\n\n\ndef test_pep518_refuses_invalid_requires(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path\n) -> None:\n    result = script.pip(\n        \"install\",\n        \"-f\",\n        common_wheels,\n        data.src.joinpath(\"pep518_invalid_requires\"),\n        expect_error=True,\n    )\n    assert result.returncode == 1\n\n    # Ensure the relevant things are mentioned.\n    assert \"PEP 518\" in result.stderr\n    assert \"not a list of strings\" in result.stderr\n    assert \"build-system.requires\" in result.stderr\n    assert \"pyproject.toml\" in result.stderr\n\n\ndef test_pep518_refuses_invalid_build_system(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path\n) -> None:\n    result = script.pip(\n        \"install\",\n        \"-f\",\n        common_wheels,\n        data.src.joinpath(\"pep518_invalid_build_system\"),\n        expect_error=True,\n    )\n    assert result.returncode == 1\n\n    # Ensure the relevant things are mentioned.\n    assert \"PEP 518\" in result.stderr\n    assert \"mandatory `requires` key\" in result.stderr\n    assert \"[build-system] table\" in result.stderr\n    assert \"pyproject.toml\" in result.stderr\n\n\ndef test_pep518_allows_missing_requires(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    result = script.pip_install_local(\n        \"-f\",\n        data.common_wheels,\n        data.src / \"pep518_missing_requires\",\n        build_isolation=True,\n        expect_stderr=True,\n    )\n    # Make sure we don't warn when this occurs.\n    assert \"PEP 518\" not in result.stderr\n\n    # We want it to go through isolation for now.\n    assert \"Installing build dependencies\" in result.stdout, result.stdout\n\n    assert result.returncode == 0\n    assert result.files_created\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_pep518_with_user_pip(\n    script: PipTestEnvironment, pip_src: Path, data: TestData, common_wheels: Path\n) -> None:\n    \"\"\"\n    Check that build dependencies are installed into the build\n    environment without using build isolation for the pip invocation.\n\n    To ensure that we're not using build isolation when installing\n    the build dependencies, we install a user copy of pip in the\n    non-isolated environment, and break pip in the system site-packages,\n    so that isolated uses of pip will fail.\n    \"\"\"\n    script.pip_install_local(\"flit-core\", \"-f\", common_wheels)\n    script.pip_install_local(\n        \"--ignore-installed\",\n        \"--user\",\n        pip_src,\n        build_isolation=False,\n        # WARNING: The scripts pip, pip3, ... are installed in ... which is not on PATH\n        allow_stderr_warning=True,\n    )\n    system_pip_dir = script.site_packages_path / \"pip\"\n    assert not system_pip_dir.exists()\n    system_pip_dir.mkdir()\n    with open(system_pip_dir / \"__init__.py\", \"w\") as fp:\n        fp.write(\"raise ImportError\\n\")\n    script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        common_wheels,\n        \"-f\",\n        data.packages,\n        data.src.joinpath(\"pep518-3.0\"),\n    )\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep518_with_extra_and_markers(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path, flag: str\n) -> None:\n    script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        common_wheels,\n        \"-f\",\n        data.find_links,\n        data.src.joinpath(\"pep518_with_extra_and_markers-1.0\"),\n        flag,\n    )\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep518_with_namespace_package(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path, flag: str\n) -> None:\n    script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        common_wheels,\n        \"-f\",\n        data.find_links,\n        data.src.joinpath(\"pep518_with_namespace_package-1.0\"),\n        flag,\n        use_module=True,\n    )\n\n\n@pytest.mark.parametrize(\"command\", [\"install\", \"wheel\"])\n@pytest.mark.parametrize(\n    \"package\",\n    [\"pep518_forkbomb\", \"pep518_twin_forkbombs_first\", \"pep518_twin_forkbombs_second\"],\n)\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep518_forkbombs(\n    script: PipTestEnvironment,\n    data: TestData,\n    common_wheels: Path,\n    command: str,\n    package: str,\n    flag: str,\n) -> None:\n    package_source = next(data.packages.glob(package + \"-[0-9]*.tar.gz\"))\n    result = script.pip(\n        command,\n        \"--no-index\",\n        \"-v\",\n        \"-f\",\n        common_wheels,\n        \"-f\",\n        data.find_links,\n        package,\n        flag,\n        expect_error=True,\n    )\n    assert (\n        \"{1} is already being built: {0} from {1}\".format(\n            package,\n            package_source.as_uri(),\n        )\n        in result.stderr\n    ), str(result)\n\n\ndef test_pip_second_command_line_interface_works(\n    script: PipTestEnvironment,\n    pip_src: Path,\n    data: TestData,\n    common_wheels: Path,\n    deprecated_python: bool,\n) -> None:\n    \"\"\"\n    Check if ``pip<PYVERSION>`` commands behaves equally\n    \"\"\"\n    # Re-install pip so we get the launchers.\n    script.pip(\"install\", \"--no-index\", \"-f\", common_wheels, pip_src)\n    args = [f\"pip{pyversion}\"]\n    args.extend([\"install\", \"simplewheel==2.0\"])\n    args.extend([\"-f\", str(data.packages), \"--no-index\"])\n    result = script.run(*args)\n    dist_info_folder = script.site_packages / \"simplewheel-2.0.dist-info\"\n    initools_folder = script.site_packages / \"simplewheel\"\n    result.did_create(dist_info_folder)\n    result.did_create(initools_folder)\n\n\ndef test_install_exit_status_code_when_no_requirements(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test install exit status code when no requirements specified\n    \"\"\"\n    result = script.pip(\"install\", expect_error=True)\n    assert \"You must give at least one requirement to install\" in result.stderr\n    assert result.returncode == ERROR\n\n\ndef test_install_exit_status_code_when_blank_requirements_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test install exit status code when blank requirements file specified\n    \"\"\"\n    script.scratch_path.joinpath(\"blank.txt\").write_text(\"\\n\")\n    script.pip(\"install\", \"-r\", \"blank.txt\")\n\n\ndef test_install_exit_status_code_when_empty_dependency_group(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test install exit status code is 0 when empty dependency group specified\n    \"\"\"\n    script.scratch_path.joinpath(\"pyproject.toml\").write_text(\n        \"\"\"\\\n[dependency-groups]\nempty = []\n\"\"\"\n    )\n    script.pip(\"install\", \"--group\", \"empty\")\n\n\n@pytest.mark.parametrize(\"file_exists\", [True, False])\ndef test_install_dependency_group_bad_filename_error(\n    script: PipTestEnvironment, file_exists: bool\n) -> None:\n    \"\"\"\n    Test install exit status code is 2 (usage error) when a dependency group path is\n    specified which isn't a `pyproject.toml`\n    \"\"\"\n    if file_exists:\n        script.scratch_path.joinpath(\"not-pyproject.toml\").write_text(\n            textwrap.dedent(\n                \"\"\"\n                [dependency-groups]\n                publish = [\"twine\"]\n                \"\"\"\n            )\n        )\n    result = script.pip(\n        \"install\", \"--group\", \"not-pyproject.toml:publish\", expect_error=True\n    )\n    assert \"group paths use 'pyproject.toml' filenames\" in result.stderr\n    assert result.returncode == 2\n\n\n@pytest.mark.network\ndef test_basic_install_from_pypi(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a package from PyPI.\n    \"\"\"\n    result = script.pip(\"install\", \"INITools==0.2\")\n    dist_info_folder = script.site_packages / \"initools-0.2.dist-info\"\n    initools_folder = script.site_packages / \"initools\"\n    result.did_create(dist_info_folder)\n    result.did_create(initools_folder)\n\n    # Should not display where it's looking for files\n    assert \"Looking in indexes: \" not in result.stdout\n    assert \"Looking in links: \" not in result.stdout\n\n    # Ensure that we don't print the full URL.\n    #    The URL should be trimmed to only the last part of the path in it,\n    #    when installing from PyPI. The assertion here only checks for\n    #    `https://` since that's likely to show up if we're not trimming in\n    #    the correct circumstances.\n    assert \"https://\" not in result.stdout\n\n\ndef test_basic_editable_install(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test editable installation.\n    \"\"\"\n    result = script.pip(\"install\", \"-e\", \"INITools==0.2\", expect_error=True)\n    assert \"INITools==0.2 is not a valid editable requirement\" in result.stderr\n    assert not result.files_created\n\n\n@need_svn\ndef test_basic_install_editable_from_svn(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test checking out from svn.\n    \"\"\"\n    checkout_path = _create_test_package(script.scratch_path)\n    repo_url = _create_svn_repo(script.scratch_path, checkout_path)\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"-e\", \"svn+\" + repo_url + \"#egg=version-pkg\"\n    )\n    result.assert_installed(\"version_pkg\", with_files=[\".svn\"])\n\n\ndef _test_install_editable_from_git(script: PipTestEnvironment) -> None:\n    \"\"\"Test cloning from Git.\"\"\"\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpackage\", vcs=\"git\")\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        f\"git+{pkg_path.as_uri()}#egg=testpackage\",\n    ]\n    result = script.pip(*args)\n    result.assert_installed(\"testpackage\", with_files=[\".git\"])\n\n\ndef test_basic_install_editable_from_git(script: PipTestEnvironment) -> None:\n    _test_install_editable_from_git(script)\n\n\ndef test_install_editable_from_git_autobuild_wheel(script: PipTestEnvironment) -> None:\n    _test_install_editable_from_git(script)\n\n\n@pytest.mark.network\ndef test_install_editable_uninstalls_existing(\n    data: TestData, script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that installing an editable uninstalls a previously installed\n    non-editable version.\n    https://github.com/pypa/pip/issues/1548\n    https://github.com/pypa/pip/pull/1552\n    \"\"\"\n    to_install = data.packages.joinpath(\"pip_test_package-0.1.tar.gz\")\n    result = script.pip_install_local(to_install)\n    assert \"Successfully installed pip-test-package\" in result.stdout\n    result.assert_installed(\n        \"piptestpackage\", dist_name=\"pip-test-package\", editable=False\n    )\n\n    result = script.pip(\n        \"install\",\n        \"-e\",\n        \"{dir}#egg=pip-test-package\".format(\n            dir=local_checkout(\n                \"git+https://github.com/pypa/pip-test-package.git\",\n                tmpdir,\n            )\n        ),\n    )\n    result.assert_installed(\n        \"piptestpackage\", dist_name=\"pip-test-package\", with_files=[\".git\"]\n    )\n    assert \"Found existing installation: pip-test-package 0.1\" in result.stdout\n    assert \"Uninstalling pip-test-package-\" in result.stdout\n    assert \"Successfully uninstalled pip-test-package\" in result.stdout\n\n\ndef test_install_editable_uninstalls_existing_from_path(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that installing an editable uninstalls a previously installed\n    non-editable version from path\n    \"\"\"\n    to_install = data.src.joinpath(\"simplewheel-1.0\")\n    result = script.pip_install_local(to_install)\n    assert \"Successfully installed simplewheel\" in result.stdout\n    simple_folder = script.site_packages / \"simplewheel\"\n    result.assert_installed(\"simplewheel\", editable=False)\n    result.did_create(simple_folder)\n\n    result = script.pip_install_local(\"-e\", to_install)\n    script.assert_installed_editable(\"simplewheel\")\n    assert \"Found existing installation: simplewheel 1.0\" in result.stdout\n    assert \"Uninstalling simplewheel-\" in result.stdout\n    assert \"Successfully uninstalled simplewheel\" in result.stdout\n    assert simple_folder in result.files_deleted, str(result.stdout)\n\n\n@need_mercurial\ndef test_basic_install_editable_from_hg(script: PipTestEnvironment) -> None:\n    \"\"\"Test cloning and hg+file install from Mercurial.\"\"\"\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpackage\", vcs=\"hg\")\n    url = f\"hg+{pkg_path.as_uri()}#egg=testpackage\"\n    assert url.startswith(\"hg+file\")\n    args = [\"install\", \"--no-build-isolation\", \"-e\", url]\n    result = script.pip(*args)\n    result.assert_installed(\"testpackage\", with_files=[\".hg\"])\n\n\n@need_mercurial\ndef test_vcs_url_final_slash_normalization(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that presence or absence of final slash in VCS URL is normalized.\n    \"\"\"\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpackage\", vcs=\"hg\")\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        f\"hg+{pkg_path.as_uri()}/#egg=testpackage\",\n    ]\n    result = script.pip(*args)\n    result.assert_installed(\"testpackage\", with_files=[\".hg\"])\n\n\n@need_bzr\ndef test_install_editable_from_bazaar(script: PipTestEnvironment) -> None:\n    \"\"\"Test checking out from Bazaar.\"\"\"\n    pkg_path = _create_test_package(\n        script.scratch_path, name=\"testpackage\", vcs=\"bazaar\"\n    )\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        f\"bzr+{pkg_path.as_uri()}/#egg=testpackage\",\n    ]\n    result = script.pip(*args)\n    result.assert_installed(\"testpackage\", with_files=[\".bzr\"])\n\n\ndef test_vcs_url_urlquote_normalization(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that urlquoted characters are normalized for repo URL comparison.\n    \"\"\"\n    pkg_path = _create_test_package(\n        script.scratch_path, name=\"django_wikiapp\", vcs=\"git\"\n    )\n    url = f\"git+{pkg_path.as_uri().replace('django_', 'django%5F')}/#egg=django_wikiapp\"\n    script.pip(\"install\", \"--no-build-isolation\", \"-e\", url)\n\n\n@pytest.mark.parametrize(\"resolver\", [\"\", \"--use-deprecated=legacy-resolver\"])\ndef test_basic_install_from_local_directory(\n    script: PipTestEnvironment, data: TestData, resolver: str\n) -> None:\n    \"\"\"\n    Test installing from a local directory.\n    \"\"\"\n    args = [\"install\", \"--no-build-isolation\"]\n    if resolver:\n        args.append(resolver)\n    to_install = data.packages.joinpath(\"FSPkg\")\n    args.append(os.fspath(to_install))\n    result = script.pip(*args)\n    fspkg_folder = script.site_packages / \"fspkg\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    result.did_create(fspkg_folder)\n    result.did_create(dist_info_folder)\n\n\n@pytest.mark.parametrize(\n    \"test_type,editable\",\n    [\n        (\"rel_path\", False),\n        (\"rel_path\", True),\n        (\"rel_url\", False),\n        (\"rel_url\", True),\n        (\"embedded_rel_path\", False),\n        (\"embedded_rel_path\", True),\n    ],\n)\ndef test_basic_install_relative_directory(\n    script: PipTestEnvironment, data: TestData, test_type: str, editable: bool\n) -> None:\n    \"\"\"\n    Test installing a requirement using a relative path.\n    \"\"\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    package_folder = script.site_packages / \"fspkg\"\n\n    # Compute relative install path to FSPkg from scratch path.\n    full_rel_path = Path(\n        os.path.relpath(data.packages.joinpath(\"FSPkg\"), script.scratch_path)\n    )\n    full_rel_url = f\"file:{full_rel_path.as_posix()}#egg=FSPkg\"\n    embedded_rel_path = script.scratch_path.joinpath(full_rel_path)\n\n    req_path = {\n        \"rel_path\": os.fspath(full_rel_path),\n        \"rel_url\": full_rel_url,\n        \"embedded_rel_path\": os.fspath(embedded_rel_path),\n    }[test_type]\n\n    # Install as either editable or not.\n    if not editable:\n        result = script.pip(\n            \"install\", \"--no-build-isolation\", req_path, cwd=script.scratch_path\n        )\n        result.did_create(dist_info_folder)\n        result.did_create(package_folder)\n    else:\n        # Editable install.\n        result = script.pip(\n            \"install\", \"--no-build-isolation\", \"-e\", req_path, cwd=script.scratch_path\n        )\n        direct_url = result.get_created_direct_url(\"fspkg\")\n        assert direct_url\n        assert direct_url.is_local_editable()\n\n\ndef test_install_quiet(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that install -q is actually quiet.\n    \"\"\"\n    # Apparently if pip install -q is not actually quiet, then it breaks\n    # everything. See:\n    #   https://github.com/pypa/pip/issues/3418\n    #   https://github.com/docker-library/python/issues/83\n    to_install = data.packages.joinpath(\"FSPkg\")\n    result = script.pip(\"install\", \"--no-build-isolation\", \"-qqq\", to_install)\n    assert result.stdout == \"\"\n    assert result.stderr == \"\"\n\n\ndef test_hashed_install_success(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that installing various sorts of requirements with correct hashes\n    works.\n\n    Test file URLs and index packages (which become HTTP URLs behind the\n    scenes).\n\n    \"\"\"\n    file_url = data.packages.joinpath(\"simple-1.0.tar.gz\").resolve().as_uri()\n    with requirements_file(\n        \"simple2==1.0 --hash=sha256:9336af72ca661e6336eb87bc7de3e8844d853e\"\n        \"3848c2b9bbd2e8bf01db88c2c7\\n\"\n        f\"{file_url} --hash=sha256:393043e672415891885c9a2a0929b1af95fb866d6c\"\n        \"a016b42d2e6ce53619b653\",\n        tmpdir,\n    ) as reqs_file:\n        script.pip_install_local(\"-r\", reqs_file.resolve())\n\n\ndef test_hashed_install_failure(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"Test that wrong hashes stop installation.\n\n    This makes sure prepare_files() is called in the course of installation\n    and so has the opportunity to halt if hashes are wrong. Checks on various\n    kinds of hashes are in test_req.py.\n\n    \"\"\"\n    with requirements_file(\n        \"simple2==1.0 --hash=sha256:9336af72ca661e6336eb87b\"\n        \"c7de3e8844d853e3848c2b9bbd2e8bf01db88c2c\\n\",\n        tmpdir,\n    ) as reqs_file:\n        result = script.pip_install_local(\"-r\", reqs_file.resolve(), expect_error=True)\n    assert len(result.files_created) == 0\n\n\ndef test_case_insensitive_hashed_install_success(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"Test that hashes that differ only by case don't halt installation.\"\"\"\n    with requirements_file(\n        \"simple2==1.0 --hash=sha256:9336AF72CA661E6336EB87BC7DE3E8844D853E\"\n        \"3848C2B9BBD2E8BF01DB88C2C7\\n\",\n        tmpdir,\n    ) as reqs_file:\n        script.pip_install_local(\"-r\", reqs_file.resolve())\n\n\ndef test_link_hash_pass_require_hashes(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"Test that a good hash in user provided direct URL is\n    considered valid for --require-hashes.\"\"\"\n    url = path_to_url(str(shared_data.packages.joinpath(\"simple-1.0.tar.gz\")))\n    url = (\n        f\"{url}#sha256=\"\n        \"393043e672415891885c9a2a0929b1af95fb866d6ca016b42d2e6ce53619b653\"\n    )\n    script.pip_install_local(\"--no-deps\", \"--require-hashes\", url)\n\n\ndef test_bad_link_hash_install_failure(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"Test that wrong hash in direct URL stops installation.\"\"\"\n    url = path_to_url(str(shared_data.packages.joinpath(\"simple-1.0.tar.gz\")))\n    url = f\"{url}#sha256=invalidhash\"\n    result = script.pip_install_local(\"--no-deps\", url, expect_error=True)\n    assert \"THESE PACKAGES DO NOT MATCH THE HASHES\" in result.stderr\n\n\ndef test_bad_link_hash_good_user_hash_install_success(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    \"\"\"Test that wrong hash in direct URL ignored when good --hash provided.\n\n    This behaviour may be accidental?\n    \"\"\"\n    url = path_to_url(str(shared_data.packages.joinpath(\"simple-1.0.tar.gz\")))\n    url = f\"{url}#sha256=invalidhash\"\n    digest = \"393043e672415891885c9a2a0929b1af95fb866d6ca016b42d2e6ce53619b653\"\n    with requirements_file(\n        f\"simple @ {url} --hash sha256:{digest}\", tmp_path\n    ) as reqs_file:\n        script.pip_install_local(\"--no-deps\", \"--require-hashes\", \"-r\", reqs_file)\n\n\ndef test_link_hash_in_dep_fails_require_hashes(\n    script: PipTestEnvironment, tmp_path: Path, shared_data: TestData\n) -> None:\n    \"\"\"Test that a good hash in direct URL dependency is not considered\n    for --require-hashes.\"\"\"\n    # Create a project named pkga that depends on the simple-1.0.tar.gz with a direct\n    # URL including a hash.\n    simple_url = path_to_url(str(shared_data.packages.joinpath(\"simple-1.0.tar.gz\")))\n    simple_url_with_hash = (\n        f\"{simple_url}#sha256=\"\n        \"393043e672415891885c9a2a0929b1af95fb866d6ca016b42d2e6ce53619b653\"\n    )\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n            dependencies = [\"simple @ {simple_url_with_hash}\"]\n            \"\"\"\n        )\n    )\n    # Build a wheel for pkga and compute its hash.\n    wheelhouse = tmp_path / \"wheehouse\"\n    wheelhouse.mkdir()\n    script.pip(\n        \"wheel\", \"--no-build-isolation\", \"--no-deps\", \"-w\", wheelhouse, project_path\n    )\n    digest = hashlib.sha256(\n        wheelhouse.joinpath(\"pkga-1.0-py3-none-any.whl\").read_bytes()\n    ).hexdigest()\n    # Install pkga from a requirements file with hash, using --require-hashes.\n    # This should fail because we have not provided a hash for the 'simple' dependency.\n    with requirements_file(f\"pkga==1.0 --hash sha256:{digest}\", tmp_path) as reqs_file:\n        result = script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--require-hashes\",\n            \"--no-index\",\n            \"-f\",\n            wheelhouse,\n            \"-r\",\n            reqs_file,\n            expect_error=True,\n        )\n    assert \"Hashes are required in --require-hashes mode\" in result.stderr\n\n\ndef test_bad_link_hash_in_dep_install_failure(\n    script: PipTestEnvironment, tmp_path: Path, shared_data: TestData\n) -> None:\n    \"\"\"Test that wrong hash in direct URL dependency stops installation.\"\"\"\n    url = path_to_url(str(shared_data.packages.joinpath(\"simple-1.0.tar.gz\")))\n    url = f\"{url}#sha256=invalidhash\"\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n            dependencies = [\"simple @ {url}\"]\n            \"\"\"\n        )\n    )\n    result = script.pip_install_local(\n        \"--no-build-isolation\", project_path, expect_error=True\n    )\n    assert \"THESE PACKAGES DO NOT MATCH THE HASHES\" in result.stderr, result.stderr\n\n\ndef test_hashed_install_from_cache(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that installing from a cached built wheel works and that the hash is verified\n    against the hash of the original source archived stored in the cache entry.\n    \"\"\"\n    with requirements_file(\n        \"simple2==1.0 --hash=sha256:\"\n        \"9336af72ca661e6336eb87bc7de3e8844d853e3848c2b9bbd2e8bf01db88c2c7\\n\",\n        tmpdir,\n    ) as reqs_file:\n        result = script.pip_install_local(\n            \"--no-build-isolation\", \"-r\", reqs_file.resolve()\n        )\n        assert \"Created wheel for simple2\" in result.stdout\n        script.pip(\"uninstall\", \"simple2\", \"-y\")\n        result = script.pip_install_local(\n            \"--no-build-isolation\", \"-r\", reqs_file.resolve()\n        )\n        assert \"Using cached simple2\" in result.stdout\n    # now try with an invalid hash\n    with requirements_file(\n        \"simple2==1.0 --hash=sha256:invalid\\n\",\n        tmpdir,\n    ) as reqs_file:\n        script.pip(\"uninstall\", \"simple2\", \"-y\")\n        result = script.pip_install_local(\n            \"--no-build-isolation\",\n            \"-r\",\n            reqs_file.resolve(),\n            expect_error=True,\n        )\n        assert (\n            \"WARNING: The hashes of the source archive found in cache entry \"\n            \"don't match, ignoring cached built wheel and re-downloading source.\"\n        ) in result.stderr\n        assert \"Using cached simple2\" in result.stdout\n        assert \"ERROR: THESE PACKAGES DO NOT MATCH THE HASHES\" in result.stderr\n\n\ndef assert_re_match(pattern: str, text: str) -> None:\n    assert re.search(pattern, text), f\"Could not find {pattern!r} in {text!r}\"\n\n\n@pytest.mark.network\n@pytest.mark.skip(\"Fails on new resolver\")\ndef test_hashed_install_failure_later_flag(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    with requirements_file(\n        \"blessings==1.0\\n\"\n        \"tracefront==0.1 --hash=sha256:somehash\\n\"\n        \"https://files.pythonhosted.org/packages/source/m/more-itertools/\"\n        \"more-itertools-1.0.tar.gz#md5=b21850c3cfa7efbb70fd662ab5413bdd\\n\"\n        \"https://files.pythonhosted.org/\"\n        \"packages/source/p/peep/peep-3.1.1.tar.gz\\n\",\n        tmpdir,\n    ) as reqs_file:\n        result = script.pip(\"install\", \"-r\", reqs_file.resolve(), expect_error=True)\n\n    assert_re_match(\n        r\"Hashes are required in --require-hashes mode, but they are \"\n        r\"missing .*\\n\"\n        r\"    https://files\\.pythonhosted\\.org/packages/source/p/peep/peep\"\n        r\"-3\\.1\\.1\\.tar\\.gz --hash=sha256:[0-9a-f]+\\n\"\n        r\"    blessings==1.0 --hash=sha256:[0-9a-f]+\\n\"\n        r\"THESE PACKAGES DO NOT MATCH THE HASHES.*\\n\"\n        r\"    tracefront==0.1 .*:\\n\"\n        r\"        Expected sha256 somehash\\n\"\n        r\"             Got        [0-9a-f]+\",\n        result.stderr,\n    )\n\n\ndef test_install_from_local_directory_with_in_tree_build(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing from a local directory with default in tree build.\n    \"\"\"\n    to_install = data.packages.joinpath(\"FSPkg\")\n\n    in_tree_build_dir = to_install / \"build\"\n    assert not in_tree_build_dir.exists()\n    result = script.pip(\"install\", \"--no-build-isolation\", to_install)\n    fspkg_folder = script.site_packages / \"fspkg\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    result.did_create(fspkg_folder)\n    result.did_create(dist_info_folder)\n    assert in_tree_build_dir.exists()\n\n\ndef test_install_from_local_directory_with_no_setup_py(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing from a local directory with no 'setup.py'.\n    \"\"\"\n    result = script.pip(\"install\", data.root, expect_error=True)\n    assert not result.files_created\n    assert \"Neither 'setup.py' nor 'pyproject.toml' found.\" in result.stderr\n\n\ndef test_editable_install__local_dir_no_setup_py(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing in editable mode from a local directory with no setup.py.\n    \"\"\"\n    result = script.pip(\"install\", \"-e\", data.root, expect_error=True)\n    assert not result.files_created\n    assert (\n        \"does not appear to be a Python project: \"\n        \"neither 'setup.py' nor 'pyproject.toml' found\" in result.stderr\n    )\n\n\ndef test_editable_install__local_dir_setup_requires_with_pyproject(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"\n    Test installing in editable mode from a local directory with a setup.py\n    that has setup_requires and a pyproject.toml.\n\n    https://github.com/pypa/pip/issues/10573\n    \"\"\"\n    local_dir = script.scratch_path.joinpath(\"temp\")\n    local_dir.mkdir()\n    pyproject_path = local_dir.joinpath(\"pyproject.toml\")\n    pyproject_path.write_text(\"\")\n    setup_py_path = local_dir.joinpath(\"setup.py\")\n    setup_py_path.write_text(\n        \"from setuptools import setup\\n\"\n        \"setup(name='dummy', setup_requires=['simplewheel'])\\n\"\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--find-links\",\n        shared_data.find_links,\n        \"-e\",\n        local_dir,\n    )\n\n\ndef test_install_pre__setup_requires_with_pyproject(\n    script: PipTestEnvironment, shared_data: TestData, common_wheels: Path\n) -> None:\n    \"\"\"\n    Test installing with a pre-release build dependency declared in both\n    setup.py and pyproject.toml.\n\n    https://github.com/pypa/pip/issues/10573\n    \"\"\"\n    depends_package = \"prerelease_dependency\"\n    depends_path = create_basic_wheel_for_package(script, depends_package, \"1.0.0a1\")\n\n    local_dir = script.scratch_path.joinpath(\"temp\")\n    local_dir.mkdir()\n    pyproject_path = local_dir.joinpath(\"pyproject.toml\")\n    pyproject_path.write_text(\n        \"[build-system]\\n\"\n        f'requires = [\"setuptools\", \"{depends_package}\"]\\n'\n        'build-backend = \"setuptools.build_meta\"\\n'\n    )\n    setup_py_path = local_dir.joinpath(\"setup.py\")\n    setup_py_path.write_text(\n        \"from setuptools import setup\\n\"\n        f\"setup(name='dummy', setup_requires=['{depends_package}'])\\n\"\n    )\n\n    script.pip(\n        \"install\",\n        \"--pre\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        common_wheels,\n        \"--find-links\",\n        depends_path.parent,\n        local_dir,\n    )\n\n\n@pytest.mark.network\ndef test_upgrade_argparse_shadowed(script: PipTestEnvironment) -> None:\n    # If argparse is installed - even if shadowed for imported - we support\n    # upgrading it and properly remove the older versions files.\n    script.pip(\"install\", \"argparse==1.3\")\n    result = script.pip(\"install\", \"argparse>=1.4\")\n    assert \"Not uninstalling argparse\" not in result.stdout\n\n\ndef test_install_curdir(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing current directory ('.').\n    \"\"\"\n    run_from = data.packages.joinpath(\"FSPkg\")\n    # Python 2.4 Windows balks if this exists already\n    egg_info = join(run_from, \"FSPkg.egg-info\")\n    if os.path.isdir(egg_info):\n        rmtree(egg_info)\n    result = script.pip(\"install\", \"--no-build-isolation\", curdir, cwd=run_from)\n    fspkg_folder = script.site_packages / \"fspkg\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    result.did_create(fspkg_folder)\n    result.did_create(dist_info_folder)\n\n\ndef test_install_pardir(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing parent directory ('..').\n    \"\"\"\n    run_from = data.packages.joinpath(\"FSPkg\", \"fspkg\")\n    result = script.pip(\"install\", \"--no-build-isolation\", pardir, cwd=run_from)\n    fspkg_folder = script.site_packages / \"fspkg\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    result.did_create(fspkg_folder)\n    result.did_create(dist_info_folder)\n\n\ndef test_install_with_hacked_egg_info(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    test installing a package which defines its own egg_info class\n    \"\"\"\n    run_from = data.packages.joinpath(\"HackedEggInfo\")\n    result = script.pip(\"install\", \"--no-build-isolation\", \".\", cwd=run_from)\n    assert \"Successfully installed hackedegginfo-0.0.0\\n\" in result.stdout\n\n\ndef test_install_package_with_same_name_in_curdir(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing a package with the same name of a local folder\n    \"\"\"\n    script.scratch_path.joinpath(\"six==1.17.0\").mkdir()\n    result = script.pip_install_local(\"six==1.17.0\", \"-f\", data.pypi_packages)\n    dist_info_folder = script.site_packages / \"six-1.17.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n\nmock100_setup_py = textwrap.dedent(\n    \"\"\"\\\n                        from setuptools import setup\n                        setup(name='mock',\n                              version='100.1')\"\"\"\n)\n\n\ndef test_install_folder_using_dot_slash(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a folder using pip install ./foldername\n    \"\"\"\n    script.scratch_path.joinpath(\"mock\").mkdir()\n    pkg_path = script.scratch_path / \"mock\"\n    pkg_path.joinpath(\"setup.py\").write_text(mock100_setup_py)\n    result = script.pip(\"install\", \"--no-build-isolation\", \"./mock\")\n    dist_info_folder = script.site_packages / \"mock-100.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_install_folder_using_slash_in_the_end(script: PipTestEnvironment) -> None:\n    r\"\"\"\n    Test installing a folder using pip install foldername/ or foldername\\\n    \"\"\"\n    script.scratch_path.joinpath(\"mock\").mkdir()\n    pkg_path = script.scratch_path / \"mock\"\n    pkg_path.joinpath(\"setup.py\").write_text(mock100_setup_py)\n    result = script.pip(\"install\", \"--no-build-isolation\", \"mock\" + os.path.sep)\n    dist_info_folder = script.site_packages / \"mock-100.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_install_folder_using_relative_path(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a folder using pip install folder1/folder2\n    \"\"\"\n    script.scratch_path.joinpath(\"initools\").mkdir()\n    script.scratch_path.joinpath(\"initools\", \"mock\").mkdir()\n    pkg_path = script.scratch_path / \"initools\" / \"mock\"\n    pkg_path.joinpath(\"setup.py\").write_text(mock100_setup_py)\n    result = script.pip(\"install\", \"--no-build-isolation\", Path(\"initools\") / \"mock\")\n    dist_info_folder = script.site_packages / \"mock-100.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_install_package_which_contains_dev_in_name(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing package from PyPI which contains 'dev' in name\n    \"\"\"\n    result = script.pip_install_local(\n        \"django_devserver==0.8.0\", \"-f\", data.pypi_packages\n    )\n    devserver_folder = script.site_packages / \"devserver\"\n    dist_info_folder = script.site_packages / \"django_devserver-0.8.0.dist-info\"\n    result.did_create(devserver_folder)\n    result.did_create(dist_info_folder)\n\n\ndef test_install_package_with_target(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a package using pip install --target\n    \"\"\"\n    target_dir = script.scratch_path / \"target\"\n    result = script.pip_install_local(\"-t\", target_dir, \"simple==1.0\")\n    result.did_create(Path(\"scratch\") / \"target\" / \"simple\")\n\n    # Test repeated call without --upgrade, no files should have changed\n    result = script.pip_install_local(\n        \"-t\",\n        target_dir,\n        \"simple==1.0\",\n        expect_stderr=True,\n    )\n    result.did_not_update(Path(\"scratch\") / \"target\" / \"simple\")\n\n    # Test upgrade call, check that new version is installed\n    result = script.pip_install_local(\"--upgrade\", \"-t\", target_dir, \"simple==2.0\")\n    result.did_update(Path(\"scratch\") / \"target\" / \"simple\")\n    dist_info_folder = Path(\"scratch\") / \"target\" / \"simple-2.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n    # Test install and upgrade of single-module package\n    result = script.pip_install_local(\"-t\", target_dir, \"singlemodule==0.0.0\")\n    singlemodule_py = Path(\"scratch\") / \"target\" / \"singlemodule.py\"\n    result.did_create(singlemodule_py)\n\n    result = script.pip_install_local(\n        \"-t\", target_dir, \"singlemodule==0.0.1\", \"--upgrade\"\n    )\n    result.did_update(singlemodule_py)\n\n\n@pytest.mark.parametrize(\"target_option\", [\"--target\", \"-t\"])\ndef test_install_package_to_usersite_with_target_must_fail(\n    script: PipTestEnvironment, target_option: str\n) -> None:\n    \"\"\"\n    Test that installing package to usersite with target\n    must raise error\n    \"\"\"\n    target_dir = script.scratch_path / \"target\"\n    result = script.pip_install_local(\n        \"--user\", target_option, target_dir, \"simple==1.0\", expect_error=True\n    )\n    assert \"Can not combine '--user' and '--target'\" in result.stderr, str(result)\n\n\ndef test_install_nonlocal_compatible_wheel(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    target_dir = script.scratch_path / \"target\"\n\n    # Test install with --target\n    result = script.pip(\n        \"install\",\n        \"-t\",\n        target_dir,\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--python-version\",\n        \"3\",\n        \"--platform\",\n        \"fakeplat\",\n        \"--abi\",\n        \"fakeabi\",\n        \"simplewheel\",\n    )\n    assert result.returncode == SUCCESS\n\n    distinfo = Path(\"scratch\") / \"target\" / \"simplewheel-2.0.dist-info\"\n    result.did_create(distinfo)\n\n    # Test install without --target\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        \"--only-binary=:all:\",\n        \"--python-version\",\n        \"3\",\n        \"--platform\",\n        \"fakeplat\",\n        \"--abi\",\n        \"fakeabi\",\n        \"simplewheel\",\n        expect_error=True,\n    )\n    assert result.returncode == ERROR\n\n\ndef test_install_nonlocal_compatible_wheel_path(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    target_dir = script.scratch_path / \"target\"\n\n    # Test a full path requirement\n    result = script.pip(\n        \"install\",\n        \"-t\",\n        target_dir,\n        \"--no-index\",\n        \"--only-binary=:all:\",\n        Path(data.packages) / \"simplewheel-2.0-py3-fakeabi-fakeplat.whl\",\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert result.returncode == ERROR\n    else:\n        assert result.returncode == SUCCESS\n\n        distinfo = Path(\"scratch\") / \"target\" / \"simplewheel-2.0.dist-info\"\n        result.did_create(distinfo)\n\n    # Test a full path requirement (without --target)\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--only-binary=:all:\",\n        Path(data.packages) / \"simplewheel-2.0-py3-fakeabi-fakeplat.whl\",\n        expect_error=True,\n    )\n    assert result.returncode == ERROR\n\n\n@pytest.mark.parametrize(\"opt\", [\"--target\", \"--prefix\"])\ndef test_install_with_target_or_prefix_and_scripts_no_warning(\n    opt: str, script: PipTestEnvironment\n) -> None:\n    \"\"\"\n    Test that installing with --target does not trigger the \"script not\n    in PATH\" warning (issue #5201)\n    \"\"\"\n    target_dir = script.scratch_path / \"target\"\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.mkdir()\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              version='0.1',\n              py_modules=[\"pkga\"],\n              entry_points={\n                  'console_scripts': ['pkga=pkga:main']\n              }\n        )\n    \"\"\"\n        )\n    )\n    pkga_path.joinpath(\"pkga.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        def main(): pass\n    \"\"\"\n        )\n    )\n    result = script.pip(\"install\", \"--no-build-isolation\", opt, target_dir, pkga_path)\n    # This assertion isn't actually needed, if we get the script warning\n    # the script.pip() call will fail with \"stderr not expected\". But we\n    # leave the assertion to make the intention of the code clearer.\n    assert \"--no-warn-script-location\" not in result.stderr, str(result)\n\n\ndef test_install_package_with_root(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing a package using pip install --root\n    \"\"\"\n    root_dir = script.scratch_path / \"root\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--root\",\n        root_dir,\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n    normal_install_path = os.fspath(\n        script.base_path / script.site_packages / \"simple-1.0.dist-info\"\n    )\n    # use a function borrowed from distutils\n    # to change the root exactly how the --root option does it\n    from pip._internal.locations.base import change_root\n\n    root_path = change_root(os.path.join(script.scratch, \"root\"), normal_install_path)\n    result.did_create(root_path)\n\n    # Should show find-links location in output\n    assert \"Looking in indexes: \" not in result.stdout\n    assert \"Looking in links: \" in result.stdout\n\n\ndef test_install_package_with_prefix(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing a package using pip install --prefix\n    \"\"\"\n    prefix_path = script.scratch_path / \"prefix\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--prefix\",\n        prefix_path,\n        \"-f\",\n        data.find_links,\n        \"--no-binary\",\n        \"simple\",\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n\n    rel_prefix_path = script.scratch / \"prefix\"\n    install_path = join(\n        sysconfig.get_path(\"purelib\", vars={\"base\": rel_prefix_path}),\n        \"simple-1.0.dist-info\",\n    )\n    result.did_create(install_path)\n\n\ndef _test_install_editable_with_prefix(\n    script: PipTestEnvironment, files: dict[str, str]\n) -> TestPipResult:\n    # make a dummy project\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.mkdir()\n\n    for fn, contents in files.items():\n        pkga_path.joinpath(fn).write_text(textwrap.dedent(contents))\n\n    if hasattr(sys, \"pypy_version_info\"):\n        site_packages = os.path.join(\n            \"prefix\", \"lib\", f\"python{pyversion}\", \"site-packages\"\n        )\n    else:\n        site_packages = sysconfig.get_path(\"purelib\", vars={\"base\": \"prefix\"})\n\n    # make sure target path is in PYTHONPATH\n    pythonpath = script.scratch_path / site_packages\n    pythonpath.mkdir(parents=True)\n    script.environ[\"PYTHONPATH\"] = pythonpath\n\n    # install pkga package into the absolute prefix directory\n    prefix_path = script.scratch_path / \"prefix\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--editable\",\n        pkga_path,\n        \"--prefix\",\n        prefix_path,\n    )\n\n    # assert pkga is installed at correct location\n    install_path = (\n        script.scratch / site_packages / \"pkga-0.1.dist-info\" / \"direct_url.json\"\n    )\n    result.did_create(install_path)\n\n    return result\n\n\ndef test_install_editable_with_target(script: PipTestEnvironment) -> None:\n    pkg_path = script.scratch_path / \"pkg\"\n    pkg_path.mkdir()\n    pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(\n            name='pkg',\n            install_requires=['simplewheel==2.0']\n        )\n    \"\"\"\n        )\n    )\n\n    target = script.scratch_path / \"target\"\n    target.mkdir()\n    result = script.pip_install_local(\"-e\", pkg_path, \"--target\", target)\n\n    direct_url_path = result.get_created_direct_url_path(\"pkg\")\n    assert direct_url_path\n    assert direct_url_path.parent.parent == target\n    direct_url = DirectUrl.from_json(direct_url_path.read_text())\n    assert direct_url.is_local_editable()\n    result.did_create(script.scratch / \"target\" / \"simplewheel\" / \"__init__.py\")\n\n\ndef test_install_editable_with_prefix_setup_py(script: PipTestEnvironment) -> None:\n    setup_py = \"\"\"\nfrom setuptools import setup\nsetup(name='pkga', version='0.1')\n\"\"\"\n    _test_install_editable_with_prefix(script, {\"setup.py\": setup_py})\n\n\ndef test_install_package_conflict_prefix_and_user(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing a package using pip install --prefix --user errors out\n    \"\"\"\n    prefix_path = script.scratch_path / \"prefix\"\n    result = script.pip(\n        \"install\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--user\",\n        \"--prefix\",\n        prefix_path,\n        \"simple==1.0\",\n        expect_error=True,\n        quiet=True,\n    )\n    assert \"Can not combine '--user' and '--prefix'\" in result.stderr\n\n\ndef test_install_package_that_emits_unicode(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Install a package with a setup.py that emits UTF-8 output and then fails.\n\n    Refs https://github.com/pypa/pip/issues/326\n    \"\"\"\n    to_install = data.packages.joinpath(\"BrokenEmitsUTF8\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        to_install,\n        expect_error=True,\n        expect_temp=True,\n        quiet=True,\n    )\n    assert (\n        \"FakeError: this package designed to fail on install\" in result.stderr\n    ), f\"stderr: {result.stderr}\"\n    assert \"UnicodeDecodeError\" not in result.stderr\n    assert \"UnicodeDecodeError\" not in result.stdout\n\n\ndef test_install_package_with_utf8_setup(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Install a package with a setup.py that declares a utf-8 encoding.\"\"\"\n    to_install = data.packages.joinpath(\"SetupPyUTF8\")\n    script.pip(\"install\", \"--no-build-isolation\", to_install)\n\n\ndef test_install_package_with_latin1_setup(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Install a package with a setup.py that declares a latin-1 encoding.\"\"\"\n    to_install = data.packages.joinpath(\"SetupPyLatin1\")\n    script.pip(\"install\", \"--no-build-isolation\", to_install)\n\n\ndef test_url_req_case_mismatch_no_index(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    tar ball url requirements (with no egg fragment), that happen to have upper\n    case project names, should be considered equal to later requirements that\n    reference the project name using lower case.\n\n    tests/data/packages contains Upper-1.0.tar.gz and Upper-2.0.tar.gz\n    'requiresupper' has install_requires = ['upper']\n    \"\"\"\n    Upper = \"/\".join((data.find_links, \"Upper-1.0.tar.gz\"))\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        Upper,\n        \"requiresupper\",\n    )\n\n    # only Upper-1.0.tar.gz should get installed.\n    dist_info_folder = script.site_packages / \"upper-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"upper-2.0.dist-info\"\n    result.did_not_create(dist_info_folder)\n\n\ndef test_url_req_case_mismatch_file_index(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    tar ball url requirements (with no egg fragment), that happen to have upper\n    case project names, should be considered equal to later requirements that\n    reference the project name using lower case.\n\n    tests/data/packages3 contains Dinner-1.0.tar.gz and Dinner-2.0.tar.gz\n    'requiredinner' has install_requires = ['dinner']\n\n    This test is similar to test_url_req_case_mismatch_no_index; that test\n    tests behaviour when using \"--no-index -f\", while this one does the same\n    test when using \"--index-url\". Unfortunately this requires a different\n    set of packages as it requires a prepared index.html file and\n    subdirectory-per-package structure.\n    \"\"\"\n    Dinner = \"/\".join((data.find_links3, \"dinner\", \"Dinner-1.0.tar.gz\"))\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        data.find_links3,\n        Dinner,\n        \"requiredinner\",\n    )\n\n    # only Dinner-1.0.tar.gz should get installed.\n    dist_info_folder = script.site_packages / \"dinner-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"dinner-2.0.dist-info\"\n    result.did_not_create(dist_info_folder)\n\n\ndef test_url_incorrect_case_no_index(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Same as test_url_req_case_mismatch_no_index, except testing for the case\n    where the incorrect case is given in the name of the package to install\n    rather than in a requirements file.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"upper\",\n    )\n\n    # only Upper-2.0.tar.gz should get installed.\n    dist_info_folder = script.site_packages / \"upper-1.0.dist-info\"\n    result.did_not_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"upper-2.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_url_incorrect_case_file_index(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Same as test_url_req_case_mismatch_file_index, except testing for the case\n    where the incorrect case is given in the name of the package to install\n    rather than in a requirements file.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        data.find_links3,\n        \"dinner\",\n        expect_stderr=True,\n    )\n\n    # only Dinner-2.0.tar.gz should get installed.\n    dist_info_folder = script.site_packages / \"dinner-1.0.dist-info\"\n    result.did_not_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"dinner-2.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n    # Should show index-url location in output\n    assert \"Looking in indexes: \" in result.stdout\n    assert \"Looking in links: \" not in result.stdout\n\n\ndef test_compiles_pyc(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing with --compile on\n    \"\"\"\n    del script.environ[\"PYTHONDONTWRITEBYTECODE\"]\n    script.pip_install_local(\n        \"--compile\", \"--no-binary=:all:\", \"INITools==0.2\", \"-f\", data.pypi_packages\n    )\n\n    # There are many locations for the __init__.pyc file so attempt to find\n    #   any of them\n    exists = [\n        os.path.exists(script.site_packages_path / \"initools/__init__.pyc\"),\n        *script.site_packages_path.glob(\"initools/__pycache__/__init__*.pyc\"),\n    ]\n\n    assert any(exists)\n\n\ndef test_no_compiles_pyc(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing from wheel with --compile on\n    \"\"\"\n    del script.environ[\"PYTHONDONTWRITEBYTECODE\"]\n    script.pip_install_local(\n        \"--no-compile\", \"--no-binary=:all:\", \"INITools==0.2\", \"-f\", data.pypi_packages\n    )\n\n    # There are many locations for the __init__.pyc file so attempt to find\n    #   any of them\n    exists = [\n        os.path.exists(script.site_packages_path / \"initools/__init__.pyc\"),\n        *script.site_packages_path.glob(\"initools/__pycache__/__init__*.pyc\"),\n    ]\n\n    assert not any(exists)\n\n\ndef test_install_upgrade_editable_depending_on_other_editable(\n    script: PipTestEnvironment,\n) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    script.pip(\"install\", \"--no-build-isolation\", \"--editable\", pkga_path)\n    result = script.pip(\"list\", \"--format=freeze\")\n    assert \"pkga==0.1\" in result.stdout\n\n    script.scratch_path.joinpath(\"pkgb\").mkdir()\n    pkgb_path = script.scratch_path / \"pkgb\"\n    pkgb_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkgb',\n              version='0.1',\n              install_requires=['pkga'])\n    \"\"\"\n        )\n    )\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--upgrade\",\n        \"--editable\",\n        pkgb_path,\n        \"--no-index\",\n    )\n    result = script.pip(\"list\", \"--format=freeze\")\n    assert \"pkgb==0.1\" in result.stdout\n\n\ndef test_install_subprocess_output_handling(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache\",\n        os.fspath(data.src.joinpath(\"chattymodule\")),\n    ]\n\n    # Regular install should not show output from the chatty setup.py\n    result = script.pip(*args)\n    assert 0 == result.stdout.count(\"HELLO FROM CHATTYMODULE\")\n    script.pip(\"uninstall\", \"-y\", \"chattymodule\")\n\n    # With --verbose we should show the output.\n    # Only count examples with sys.argv[1] == egg_info, because we call\n    # setup.py multiple times, which should not count as duplicate output.\n    result = script.pip(*(args + [\"--verbose\"]), expect_stderr=True)\n    assert 1 == result.stderr.count(\n        \"HELLO FROM CHATTYMODULE prepare_metadata_for_build_wheel\"\n    )\n    assert 1 == result.stderr.count(\"HELLO FROM CHATTYMODULE build_wheel\")\n    script.pip(\"uninstall\", \"-y\", \"chattymodule\")\n\n    # If the install fails, then we *should* show the output... but only once,\n    # even if --verbose is given.\n    result = script.pip(*(args + [\"--config-setting=fail=1\"]), expect_error=True)\n    assert 1 == result.stderr.count(\"I DIE, I DIE\")\n    assert 1 == result.stderr.count(\"I DIE, I DIE in prepare_metadata_for_build_wheel\")\n\n    result = script.pip(\n        *(args + [\"--config-setting=fail=1\", \"--verbose\"]), expect_error=True\n    )\n    assert 1 == result.stderr.count(\"I DIE, I DIE\")\n    assert 1 == result.stderr.count(\"I DIE, I DIE in prepare_metadata_for_build_wheel\")\n\n\ndef test_install_log(script: PipTestEnvironment, data: TestData, tmpdir: Path) -> None:\n    # test that verbose logs go to \"--log\" file\n    f = tmpdir.joinpath(\"log.txt\")\n    result = script.pip(\n        f\"--log={f}\",\n        \"install\",\n        \"--no-build-isolation\",\n        data.src.joinpath(\"chattymodule\"),\n    )\n    assert 0 == result.stdout.count(\"HELLO FROM CHATTYMODULE\")\n    with open(f) as fp:\n        # one from prepare_metadata_for_build_wheel, one from build_wheel\n        assert 2 == fp.read().count(\"HELLO FROM CHATTYMODULE\")\n\n\ndef test_install_topological_sort(script: PipTestEnvironment, data: TestData) -> None:\n    res = str(\n        script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"TopoRequires4\",\n            \"--no-index\",\n            \"-f\",\n            data.packages,\n        )\n    )\n    order1 = \"TopoRequires, TopoRequires2, TopoRequires3, TopoRequires4\"\n    order2 = \"TopoRequires, TopoRequires3, TopoRequires2, TopoRequires4\"\n    assert order1 in res or order2 in res, res\n\n\ndef test_install_builds_wheels(script: PipTestEnvironment, data: TestData) -> None:\n    # We need to use a subprocess to get the right value on Windows.\n    res = script.run(\n        \"python\",\n        \"-c\",\n        (\n            \"from pip._internal.utils import appdirs; \"\n            'print(appdirs.user_cache_dir(\"pip\"))'\n        ),\n    )\n    wheels_cache = os.path.join(res.stdout.rstrip(\"\\n\"), \"wheels\")\n    # NB This incidentally tests a local tree + tarball inputs\n    # see test_install_editable_from_git_autobuild_wheel for editable\n    # vcs coverage.\n    to_install = data.packages.joinpath(\"requires_wheelbroken_upper\")\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        to_install,\n        expect_error=True,  # error building wheelbroken\n    )\n    wheels: list[str] = []\n    for _, _, files in os.walk(wheels_cache):\n        wheels.extend(f for f in files if f.endswith(\".whl\"))\n    # Built wheel for upper\n    assert \"Building wheel for upper\" in str(res), str(res)\n    # Built wheel for wheelbroken, but failed\n    assert \"Building wheel for wheelb\" in str(res), str(res)\n    assert \"Failed to build wheelbroken\" in str(res), str(res)\n    # Wheels are built for local directories, but not cached.\n    assert \"Building wheel for require\" in str(res), str(res)\n    # into the cache\n    assert wheels != [], str(res)\n    assert wheels == [\n        f\"upper-2.0-py{sys.version_info[0]}-none-any.whl\",\n    ]\n\n\ndef test_install_no_binary_builds_wheels(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.packages.joinpath(\"requires_wheelbroken_upper\")\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--no-binary=upper\",\n        \"-f\",\n        data.find_links,\n        to_install,\n        expect_error=True,  # error building wheelbroken\n    )\n    # Wheels are built for all requirements\n    assert \"Building wheel for wheelb\" in str(res), str(res)\n    assert \"Building wheel for require\" in str(res), str(res)\n    assert \"Building wheel for upper\" in str(res), str(res)\n    # Wheelbroken failed to build\n    assert \"Failed to build wheelbroken\" in str(res), str(res)\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_install_no_binary_builds_pep_517_wheel(\n    script: PipTestEnvironment, data: TestData, flag: str\n) -> None:\n    res = script.pip_install_local(\n        \"--no-binary=:all:\", data.packages / \"pep517_setup_and_pyproject\", flag\n    )\n    expected = \"Successfully installed pep517-setup-and-pyproject\"\n    # Must have installed the package\n    assert expected in str(res), str(res)\n\n    assert \"Building wheel for pep517-setup\" in str(res), str(res)\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_install_no_binary_uses_local_backend(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path, flag: str\n) -> None:\n    to_install = data.packages.joinpath(\"pep517_wrapper_buildsys\")\n    script.environ[\"PIP_TEST_MARKER_FILE\"] = marker = str(tmpdir / \"marker\")\n    res = script.pip_install_local(\"--no-binary=:all:\", to_install, flag)\n    expected = \"Successfully installed pep517-wrapper-buildsys\"\n    # Must have installed the package\n    assert expected in str(res), str(res)\n\n    assert os.path.isfile(marker), \"Local PEP 517 backend not used\"\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_install_no_binary_uses_cached_wheels(\n    script: PipTestEnvironment, data: TestData, flag: str\n) -> None:\n    # Seed the cache\n    script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", \"-f\", data.find_links, \"upper\"\n    )\n    script.pip(\"uninstall\", \"upper\", \"-y\")\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--no-binary=:all:\",\n        \"-f\",\n        data.find_links,\n        \"upper\",\n        flag,\n        expect_stderr=True,\n    )\n    assert \"Successfully installed upper-2.0\" in str(res), str(res)\n    # upper is built and not obtained from cache\n    assert \"Building wheel for upper\" not in str(res), str(res)\n\n\ndef test_install_editable_with_wrong_egg_name(\n    script: PipTestEnvironment, resolver_variant: ResolverVariant\n) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--editable\",\n        path_to_url(str(pkga_path)) + \"#egg=pkgb\",\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    assert (\n        \"Generating metadata for package pkgb produced metadata \"\n        \"for project name pkga. Fix your #egg=pkgb \"\n        \"fragments.\"\n    ) in result.stderr\n    if resolver_variant == \"resolvelib\":\n        assert \"has inconsistent\" in result.stdout, str(result)\n    else:\n        assert \"Successfully installed pkga\" in str(result), str(result)\n\n\ndef test_install_tar_xz(script: PipTestEnvironment, data: TestData) -> None:\n    try:\n        import lzma  # noqa\n    except ImportError:\n        pytest.skip(\"No lzma support\")\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", data.packages / \"singlemodule-0.0.1.tar.xz\"\n    )\n    assert \"Successfully installed singlemodule-0.0.1\" in res.stdout, res\n\n\ndef test_install_tar_lzma(script: PipTestEnvironment, data: TestData) -> None:\n    try:\n        import lzma  # noqa\n    except ImportError:\n        pytest.skip(\"No lzma support\")\n    res = script.pip(\n        \"install\", \"--no-build-isolation\", data.packages / \"singlemodule-0.0.1.tar.lzma\"\n    )\n    assert \"Successfully installed singlemodule-0.0.1\" in res.stdout, res\n\n\ndef test_double_install(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test double install passing with two same version requirements\n    \"\"\"\n    result = script.pip(\"install\", \"pip\", \"pip\")\n    msg = \"Double requirement given: pip (already in pip, name='pip')\"\n    assert msg not in result.stderr\n\n\ndef test_double_install_fail(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    \"\"\"\n    Test double install failing with two different version requirements\n    \"\"\"\n    # TODO: remove with the legacy resolver\n    result = script.pip_install_local(\n        \"six==1.*\",\n        \"six==1.17.0\",\n        find_links=data.pypi_packages,\n        # The new resolver is perfectly capable of handling this\n        expect_error=(resolver_variant == \"legacy\"),\n    )\n    if resolver_variant == \"legacy\":\n        msg = \"Double requirement given: six==1.17.0 (already in pip==0.*, name='pip')\"\n        assert msg in result.stderr\n\n\ndef _get_expected_error_text() -> str:\n    return (\"Package 'pkga' requires a different Python: {} not in '<1.0'\").format(\n        \".\".join(map(str, sys.version_info[:3]))\n    )\n\n\ndef test_install_incompatible_python_requires(script: PipTestEnvironment) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              python_requires='<1.0',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    result = script.pip(\"install\", \"--no-build-isolation\", pkga_path, expect_error=True)\n    assert _get_expected_error_text() in result.stderr, str(result)\n\n\ndef test_install_incompatible_python_requires_editable(\n    script: PipTestEnvironment,\n) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              python_requires='<1.0',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", f\"--editable={pkga_path}\", expect_error=True\n    )\n    assert _get_expected_error_text() in result.stderr, str(result)\n\n\ndef test_install_incompatible_python_requires_wheel(script: PipTestEnvironment) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              python_requires='<1.0',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    script.run(\n        \"python\",\n        \"setup.py\",\n        \"bdist_wheel\",\n        \"--universal\",\n        cwd=pkga_path,\n    )\n    result = script.pip(\n        \"install\", \"./pkga/dist/pkga-0.1-py2.py3-none-any.whl\", expect_error=True\n    )\n    assert _get_expected_error_text() in result.stderr, str(result)\n\n\ndef test_install_compatible_python_requires(script: PipTestEnvironment) -> None:\n    script.scratch_path.joinpath(\"pkga\").mkdir()\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              python_requires='>1.0',\n              version='0.1')\n    \"\"\"\n        )\n    )\n    res = script.pip(\"install\", \"--no-build-isolation\", pkga_path)\n    assert \"Successfully installed pkga-0.1\" in res.stdout, res\n\n\n@pytest.mark.network\ndef test_install_pep508_with_url(script: PipTestEnvironment) -> None:\n    res = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"packaging@https://files.pythonhosted.org/packages/2f/2b/\"\n        \"c681de3e1dbcd469537aefb15186b800209aa1f299d933d23b48d85c9d56/\"\n        \"packaging-15.3-py2.py3-none-any.whl#sha256=\"\n        \"ce1a869fe039fbf7e217df36c4653d1dbe657778b2d41709593a0003584405f4\",\n    )\n    assert \"Successfully installed packaging-15.3\" in str(res), str(res)\n\n\n@pytest.mark.network\ndef test_install_pep508_with_url_in_install_requires(\n    script: PipTestEnvironment,\n) -> None:\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        install_requires=[\n            \"packaging@https://files.pythonhosted.org/packages/2f/2b/\"\n            \"c681de3e1dbcd469537aefb15186b800209aa1f299d933d23b48d85c9d56/\"\n            \"packaging-15.3-py2.py3-none-any.whl#sha256=\"\n            \"ce1a869fe039fbf7e217df36c4653d1dbe657778b2d41709593a0003584405f4\"\n        ],\n    )\n    res = script.pip(\"install\", pkga_path)\n    assert \"Successfully installed packaging-15.3\" in str(res), str(res)\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\"index\", [PyPI.simple_url, TestPyPI.simple_url])\ndef test_install_from_test_pypi_with_ext_url_dep_is_blocked(\n    script: PipTestEnvironment, index: str\n) -> None:\n    res = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        index,\n        \"pep-508-url-deps\",\n        expect_error=True,\n    )\n    error_message = (\n        \"Packages installed from PyPI cannot depend on packages \"\n        \"which are not also hosted on PyPI.\"\n    )\n    error_cause = (\n        \"pep-508-url-deps depends on sampleproject @ \"\n        \"https://github.com/pypa/sampleproject/archive/master.zip\"\n    )\n    assert res.returncode == 1\n    assert error_message in res.stderr, str(res)\n    assert error_cause in res.stderr, str(res)\n\n\n@pytest.mark.xfail(\n    reason=\"No longer possible to trigger the warning with either --prefix or --target\"\n)\ndef test_installing_scripts_outside_path_prints_warning(\n    script: PipTestEnvironment,\n) -> None:\n    result = script.pip_install_local(\"--prefix\", script.scratch_path, \"script_wheel1\")\n    assert \"Successfully installed script_wheel1\" in result.stdout, str(result)\n    assert \"--no-warn-script-location\" in result.stderr\n\n\ndef test_installing_scripts_outside_path_can_suppress_warning(\n    script: PipTestEnvironment,\n) -> None:\n    result = script.pip_install_local(\n        \"--prefix\", script.scratch_path, \"--no-warn-script-location\", \"script_wheel1\"\n    )\n    assert \"Successfully installed script_wheel1\" in result.stdout, str(result)\n    assert \"--no-warn-script-location\" not in result.stderr\n\n\ndef test_installing_scripts_on_path_does_not_print_warning(\n    script: PipTestEnvironment,\n) -> None:\n    result = script.pip_install_local(\"script_wheel1\")\n    assert \"Successfully installed script_wheel1\" in result.stdout, str(result)\n    assert \"--no-warn-script-location\" not in result.stderr\n\n\ndef test_install_conflict_results_in_warning(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    pkgA_path = create_test_package_with_setup(\n        script,\n        name=\"pkgA\",\n        version=\"1.0\",\n        install_requires=[\"pkgb == 1.0\"],\n    )\n    pkgB_path = create_test_package_with_setup(\n        script,\n        name=\"pkgB\",\n        version=\"2.0\",\n    )\n\n    # Install pkgA without its dependency\n    result1 = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkgA_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkgA-1.0\" in result1.stdout, str(result1)\n\n    # Then install an incorrect version of the dependency\n    result2 = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        pkgB_path,\n        allow_stderr_error=True,\n    )\n    assert \"pkga 1.0 requires pkgb==1.0\" in result2.stderr, str(result2)\n    assert \"Successfully installed pkgB-2.0\" in result2.stdout, str(result2)\n\n\ndef test_install_conflict_warning_can_be_suppressed(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    pkgA_path = create_test_package_with_setup(\n        script,\n        name=\"pkgA\",\n        version=\"1.0\",\n        install_requires=[\"pkgb == 1.0\"],\n    )\n    pkgB_path = create_test_package_with_setup(\n        script,\n        name=\"pkgB\",\n        version=\"2.0\",\n    )\n\n    # Install pkgA without its dependency\n    result1 = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkgA_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkgA-1.0\" in result1.stdout, str(result1)\n\n    # Then install an incorrect version of the dependency; suppressing warning\n    result2 = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        pkgB_path,\n        \"--no-warn-conflicts\",\n    )\n    assert \"Successfully installed pkgB-2.0\" in result2.stdout, str(result2)\n\n\ndef test_target_install_ignores_distutils_config_install_prefix(\n    script: PipTestEnvironment,\n) -> None:\n    prefix = script.scratch_path / \"prefix\"\n    distutils_config = Path.home().joinpath(\n        \"pydistutils.cfg\" if sys.platform == \"win32\" else \".pydistutils.cfg\",\n    )\n    distutils_config.write_text(\n        textwrap.dedent(\n            f\"\"\"\n        [install]\n        prefix={prefix}\n        \"\"\"\n        )\n    )\n    target = script.scratch_path / \"target\"\n    result = script.pip_install_local(\"simplewheel\", \"-t\", target)\n\n    assert \"Successfully installed simplewheel\" in result.stdout\n\n    relative_target = os.path.relpath(target, script.base_path)\n    relative_script_base = os.path.relpath(prefix, script.base_path)\n    result.did_create(relative_target)\n    result.did_not_create(relative_script_base)\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_user_config_accepted(script: PipTestEnvironment) -> None:\n    # user set in the config file is parsed as 0/1 instead of True/False.\n    # Check that this doesn't cause a problem.\n    config_file = script.scratch_path / \"pip.conf\"\n    script.environ[\"PIP_CONFIG_FILE\"] = str(config_file)\n    config_file.write_text(\"[install]\\nuser = true\")\n    result = script.pip_install_local(\"simplewheel\")\n\n    assert \"Successfully installed simplewheel\" in result.stdout\n\n    relative_user = os.path.relpath(script.user_site_path, script.base_path)\n    result.did_create(join(relative_user, \"simplewheel\"))\n\n\n@pytest.mark.parametrize(\n    \"install_args, expected_message\",\n    [\n        ([], \"Requirement already satisfied: pip\"),\n        ([\"--upgrade\"], \"Requirement already {}: pip in\"),\n    ],\n)\n@pytest.mark.parametrize(\"use_module\", [True, False])\ndef test_install_pip_does_not_modify_pip_when_satisfied(\n    script: PipTestEnvironment,\n    install_args: list[str],\n    expected_message: str,\n    use_module: bool,\n    resolver_variant: ResolverVariant,\n) -> None:\n    \"\"\"\n    Test it doesn't upgrade the pip if it already satisfies the requirement.\n    \"\"\"\n    variation = \"satisfied\" if resolver_variant else \"up-to-date\"\n    expected_message = expected_message.format(variation)\n    result = script.pip_install_local(\"pip\", *install_args, use_module=use_module)\n    assert expected_message in result.stdout, str(result)\n\n\ndef test_ignore_yanked_file(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test ignore a \"yanked\" file.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"simple\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        data.index_url(\"yanked\"),\n    )\n    # Make sure a \"yanked\" release is ignored\n    assert \"Successfully installed simple-2.0\\n\" in result.stdout, str(result)\n\n\ndef test_invalid_index_url_argument(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"\n    Test the behaviour of an invalid --index-url argument\n    \"\"\"\n\n    result = script.pip(\n        \"install\",\n        \"--index-url\",\n        \"--user\",\n        shared_data.find_links3,\n        \"Dinner\",\n        expect_error=True,\n    )\n\n    assert (\n        'WARNING: The index url \"--user\" seems invalid, please provide a scheme.'\n    ) in result.stderr, str(result)\n\n\ndef test_valid_index_url_argument(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"\n    Test the behaviour of an valid --index-url argument\n    \"\"\"\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        shared_data.find_links3,\n        \"Dinner\",\n    )\n\n    assert \"Successfully installed Dinner\" in result.stdout, str(result)\n\n\ndef test_install_yanked_file_and_print_warning(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test install a \"yanked\" file and print a warning.\n\n    Yanked files are always ignored, unless they are the only file that\n    matches a version specifier that \"pins\" to an exact version (PEP 592).\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"simple==3.0\",\n        \"--no-build-isolation\",\n        \"--index-url\",\n        data.index_url(\"yanked\"),\n        expect_stderr=True,\n    )\n    expected_warning = \"Reason for being yanked: test reason message\"\n    assert expected_warning in result.stderr, str(result)\n    # Make sure a \"yanked\" release is installed\n    assert \"Successfully installed simple-3.0\\n\" in result.stdout, str(result)\n\n\ndef test_yanked_version_missing_from_available_versions_error_message(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test yanked version is missing from available versions error message.\n\n    Yanked files are always ignored, unless they are the only file that\n    matches a version specifier that \"pins\" to an exact version (PEP 592).\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"simple==0.1\",\n        \"--index-url\",\n        data.index_url(\"yanked\"),\n        expect_error=True,\n    )\n    # the yanked version (3.0) is filtered out from the output:\n    expected_warning = (\n        \"Could not find a version that satisfies the requirement simple==0.1 \"\n        \"(from versions: 1.0, 2.0)\"\n    )\n    assert expected_warning in result.stderr, str(result)\n    # and mentioned in a separate warning:\n    expected_warning = \"Ignored the following yanked versions: 3.0\"\n    assert expected_warning in result.stderr, str(result)\n\n\ndef test_error_all_yanked_files_and_no_pin(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test raising an error if there are only \"yanked\" files available and no pin\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"simple\",\n        \"--index-url\",\n        data.index_url(\"yanked_all\"),\n        expect_error=True,\n    )\n    # Make sure an error is raised\n    assert result.returncode == 1\n    assert \"ERROR: No matching distribution found for simple\\n\" in result.stderr, str(\n        result\n    )\n\n\n@pytest.mark.parametrize(\n    \"install_args\",\n    [\n        (),\n        (\"--trusted-host\", \"localhost\"),\n    ],\n)\ndef test_install_sends_client_cert(\n    install_args: tuple[str, ...],\n    script: PipTestEnvironment,\n    cert_factory: CertFactory,\n    data: TestData,\n) -> None:\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    server = make_mock_server(ssl_context=ctx)\n    server.mock.side_effect = [\n        package_page(\n            {\n                \"simple-3.0.tar.gz\": \"/files/simple-3.0.tar.gz\",\n            }\n        ),\n        file_response(data.packages / \"simple-3.0.tar.gz\"),\n    ]\n\n    url = f\"https://{server.host}:{server.port}/simple\"\n\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"-vvv\",\n        \"--cert\",\n        cert_path,\n        \"--client-cert\",\n        cert_path,\n    ]\n    args.extend([\"--index-url\", url])\n    args.extend(install_args)\n    args.append(\"simple\")\n\n    with server_running(server):\n        script.pip(*args)\n\n    assert server.mock.call_count == 2\n    for call_args in server.mock.call_args_list:\n        # Legacy: replace call_args[0] with call_args.args\n        # when pip drops support for python3.7\n        environ, _ = call_args[0]\n        assert \"SSL_CLIENT_CERT\" in environ\n        assert environ[\"SSL_CLIENT_CERT\"]\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_install_sends_certs_for_pep518_deps(\n    script: PipTestEnvironment,\n    cert_factory: CertFactory,\n    data: TestData,\n    common_wheels: Path,\n    flag: str,\n) -> None:\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    setuptools_pkg = next(common_wheels.glob(\"setuptools*\")).name\n    server = make_mock_server(ssl_context=ctx)\n    server.mock.side_effect = [\n        package_page({setuptools_pkg: f\"/files/{setuptools_pkg}\"}),\n        file_response(common_wheels / setuptools_pkg),\n    ]\n    url = f\"https://{server.host}:{server.port}/simple\"\n\n    args = [\"install\", str(data.packages / \"pep517_setup_and_pyproject\"), flag]\n    args.extend([\"--index-url\", url])\n    args.extend([\"--cert\", cert_path, \"--client-cert\", cert_path])\n\n    with server_running(server):\n        script.pip(*args)\n\n    for call_args in server.mock.call_args_list:\n        environ, _ = call_args.args\n        assert environ.get(\"SSL_CLIENT_CERT\", \"\")\n\n\ndef test_install_skip_work_dir_pkg(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that install of a package in working directory\n    should pass on the second attempt after an install\n    and an uninstall\n    \"\"\"\n\n    # Create a test package, install it and then uninstall it\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.pip_install_local(\"-e\", \".\", expect_stderr=True, cwd=pkg_path)\n\n    script.pip(\"uninstall\", \"simple\", \"-y\")\n\n    # Running the install command again from the working directory\n    # will install the package as it was uninstalled earlier\n    result = script.pip_install_local(\n        \"simple\",\n        expect_stderr=True,\n        cwd=pkg_path,\n    )\n\n    assert \"Requirement already satisfied: simple\" not in result.stdout\n    assert \"Successfully installed simple\" in result.stdout\n\n\n@pytest.mark.parametrize(\n    \"package_name\", [\"simple-package\", \"simple_package\", \"simple.package\"]\n)\ndef test_install_verify_package_name_normalization(\n    script: PipTestEnvironment, package_name: str\n) -> None:\n    \"\"\"\n    Test that install of a package again using a name which\n    normalizes to the original package name, is a no-op\n    since the package is already installed\n    \"\"\"\n    pkg_path = create_test_package_with_setup(\n        script, name=\"simple-package\", version=\"1.0\"\n    )\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"-e\", \".\", expect_stderr=True, cwd=pkg_path\n    )\n    assert \"Successfully installed simple-package\" in result.stdout\n\n    result = script.pip(\"install\", package_name)\n    assert f\"Requirement already satisfied: {package_name}\" in result.stdout\n\n\ndef test_install_logs_pip_version_in_debug(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    fake_package = shared_data.packages / \"simple-2.0.tar.gz\"\n    result = script.pip(\"install\", \"--no-build-isolation\", \"-v\", fake_package)\n    pattern = \"Using pip .* from .*\"\n    assert_re_match(pattern, result.stdout)\n\n\ndef install_find_links(\n    script: PipTestEnvironment,\n    data: TestData,\n    args: Iterable[str],\n    *,\n    dry_run: bool,\n    target_dir: Path | None,\n) -> TestPipResult:\n    return script.pip(\n        \"install\",\n        *(\n            (\n                \"--target\",\n                str(target_dir),\n            )\n            if target_dir is not None\n            else ()\n        ),\n        *((\"--dry-run\",) if dry_run else ()),\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        data.find_links,\n        *args,\n    )\n\n\n@pytest.mark.parametrize(\n    \"with_target_dir\",\n    [True, False],\n)\ndef test_install_dry_run_nothing_installed(\n    script: PipTestEnvironment,\n    data: TestData,\n    tmpdir: Path,\n    with_target_dir: bool,\n) -> None:\n    \"\"\"Test that pip install --dry-run logs what it would install, but doesn't actually\n    install anything.\"\"\"\n    if with_target_dir:\n        install_dir = tmpdir / \"fake-install\"\n        install_dir.mkdir()\n    else:\n        install_dir = None\n\n    result = install_find_links(\n        script, data, [\"simple\"], dry_run=True, target_dir=install_dir\n    )\n    assert \"Would install simple-3.0\" in result.stdout\n    assert \"Successfully installed\" not in result.stdout\n\n    script.assert_not_installed(\"simple\")\n    if with_target_dir:\n        assert not os.listdir(install_dir)\n\n    # Ensure that the same install command would normally have worked if not for\n    # --dry-run.\n    install_find_links(script, data, [\"simple\"], dry_run=False, target_dir=install_dir)\n    if with_target_dir:\n        assert os.listdir(install_dir)\n    else:\n        script.assert_installed(simple=\"3.0\")\n\n\n@pytest.mark.skipif(\n    sys.version_info < (3, 11),\n    reason=\"3.11 required to find distributions via importlib metadata\",\n)\ndef test_install_existing_memory_distribution(script: PipTestEnvironment) -> None:\n    sitecustomize_text = textwrap.dedent(\n        \"\"\"\n        import sys\n        from importlib.metadata import Distribution, DistributionFinder\n\n\n        EXAMPLE_METADATA = '''Metadata-Version: 2.1\n        Name: example\n        Version: 1.0.0\n\n        '''\n\n        class ExampleDistribution(Distribution):\n            def locate_file(self, path):\n                return path\n\n            def read_text(self, filename):\n                if filename == 'METADATA':\n                    return EXAMPLE_METADATA\n\n\n        class CustomFinder(DistributionFinder):\n            def find_distributions(self, context=None):\n                return [ExampleDistribution()]\n\n\n        sys.meta_path.append(CustomFinder())\n        \"\"\"\n    )\n    with open(script.site_packages_path / \"sitecustomize.py\", \"w\") as sitecustomize:\n        sitecustomize.write(sitecustomize_text)\n\n    result = script.pip(\"install\", \"example\")\n\n    assert \"Requirement already satisfied: example in <memory>\" in result.stdout\n\n\ndef test_install_pip_prints_req_chain_local(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a local package with a dependency and check that the\n    dependency chain is reported.\n    \"\"\"\n\n    req_path = script.scratch_path.joinpath(\"requirements.txt\")\n    req_path.write_text(\"base==0.1.0\")\n\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    dep_path = create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-r\",\n        req_path,\n    )\n    assert_re_match(\n        rf\"Processing .*{re.escape(os.path.basename(dep_path))} \"\n        rf\"\\(from base==0.1.0->-r {re.escape(str(req_path))} \\(line 1\\)\\)\",\n        result.stdout,\n    )\n\n\ndef test_install_dist_restriction_without_target(script: PipTestEnvironment) -> None:\n    result = script.pip(\n        \"install\", \"--python-version=3.1\", \"--only-binary=:all:\", expect_error=True\n    )\n    assert (\n        \"Can not use any platform or abi specific options unless installing \"\n        \"via '--target'\" in result.stderr\n    ), str(result)\n\n\ndef test_install_dist_restriction_dry_run_doesnt_require_target(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--python-version=3.1\",\n        \"--only-binary=:all:\",\n        \"--dry-run\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n\n    assert not result.stderr, str(result)\n\n\n@pytest.mark.network\ndef test_install_pip_prints_req_chain_pypi(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a package with a dependency from PyPI and check that the\n    dependency chain is reported.\n    \"\"\"\n    req_path = script.scratch_path.joinpath(\"requirements.txt\")\n    req_path.write_text(\"Paste[openid]==1.7.5.1\")\n\n    result = script.pip(\n        \"install\",\n        \"-r\",\n        req_path,\n    )\n\n    assert (\n        f\"Collecting python-openid \"\n        f\"(from Paste[openid]==1.7.5.1->-r {req_path} (line 1))\" in result.stdout\n    )\n\n\n@pytest.mark.parametrize(\"common_prefix\", [\"\", \"linktest-1.0/\"])\ndef test_install_sdist_links(\n    script: PipTestEnvironment, data: TestData, common_prefix: str\n) -> None:\n    \"\"\"\n    Test installing an sdist with hard and symbolic links.\n    \"\"\"\n\n    # Build an unpack an sdist that contains data files:\n    # - root.dat\n    # - sub/inner.dat\n    # and links (symbolic and hard) to both of those, both in the top-level\n    # and 'sub/' directories. That's 8 links total.\n\n    # We build the sdist from in-memory data, since the filesystem\n    # might not support both kinds of links.\n\n    sdist_path = script.scratch_path.joinpath(\"linktest-1.0.tar.gz\")\n\n    def add_file(tar: tarfile.TarFile, name: str, content: str) -> None:\n        info = tarfile.TarInfo(common_prefix + name)\n        content_bytes = content.encode(\"utf-8\")\n        info.size = len(content_bytes)\n        tar.addfile(info, io.BytesIO(content_bytes))\n\n    def add_link(tar: tarfile.TarFile, name: str, linktype: str, target: str) -> None:\n        info = tarfile.TarInfo(common_prefix + name)\n        info.type = {\"sym\": tarfile.SYMTYPE, \"hard\": tarfile.LNKTYPE}[linktype]\n        info.linkname = target\n        tar.addfile(info)\n\n    with tarfile.open(sdist_path, \"w:gz\") as sdist_tar:\n        add_file(\n            sdist_tar,\n            \"PKG-INFO\",\n            textwrap.dedent(\n                \"\"\"\n                    Metadata-Version: 2.1\n                    Name: linktest\n                    Version: 1.0\n                \"\"\"\n            ),\n        )\n\n        add_file(sdist_tar, \"src/linktest/__init__.py\", \"\")\n        add_file(sdist_tar, \"src/linktest/root.dat\", \"Data\")\n        add_file(sdist_tar, \"src/linktest/sub/__init__.py\", \"\")\n        add_file(sdist_tar, \"src/linktest/sub/inner.dat\", \"Data\")\n        linknames = []\n\n        # Windows requires native path separators in symlink targets.\n        # (see https://github.com/python/cpython/issues/57911)\n        # (This is not needed for hardlinks, nor for the workaround tarfile\n        # uses if symlinking is disabled.)\n        SEP = os.path.sep\n\n        pkg_root = f\"{common_prefix}src/linktest\"\n        for prefix, target_tag, linktype, target in [\n            (\"\", \"root\", \"sym\", \"root.dat\"),\n            (\"\", \"root\", \"hard\", f\"{pkg_root}/root.dat\"),\n            (\"\", \"inner\", \"sym\", f\"sub{SEP}inner.dat\"),\n            (\"\", \"inner\", \"hard\", f\"{pkg_root}/sub/inner.dat\"),\n            (\"sub/\", \"root\", \"sym\", f\"..{SEP}root.dat\"),\n            (\"sub/\", \"root\", \"hard\", f\"{pkg_root}/root.dat\"),\n            (\"sub/\", \"inner\", \"sym\", \"inner.dat\"),\n            (\"sub/\", \"inner\", \"hard\", f\"{pkg_root}/sub/inner.dat\"),\n        ]:\n            name = f\"{prefix}link.{target_tag}.{linktype}.dat\"\n            add_link(sdist_tar, \"src/linktest/\" + name, linktype, target)\n            linknames.append(name)\n\n        add_file(\n            sdist_tar,\n            \"pyproject.toml\",\n            textwrap.dedent(\n                \"\"\"\n                    [build-system]\n                    requires = [\"setuptools\"]\n                    build-backend = \"setuptools.build_meta\"\n                    [project]\n                    name = \"linktest\"\n                    version = \"1.0\"\n                    [tool.setuptools]\n                    include-package-data = true\n                    [tool.setuptools.packages.find]\n                    where = [\"src\"]\n                    [tool.setuptools.package-data]\n                    \"*\" = [\"*.dat\"]\n                \"\"\"\n            ),\n        )\n\n        add_file(\n            sdist_tar,\n            \"src/linktest/__main__.py\",\n            textwrap.dedent(\n                f\"\"\"\n                    from pathlib import Path\n                    linknames = {linknames!r}\n\n                    # we could use importlib.resources here once\n                    # it has stable convenient API across supported versions\n                    res_path = Path(__file__).parent\n\n                    for name in linknames:\n                        data_text = res_path.joinpath(name).read_text()\n                        assert data_text == \"Data\"\n                    print(str(len(linknames)) + ' files checked')\n                \"\"\"\n            ),\n        )\n\n    # Show sdist content, for debugging the test\n    result = script.run(\"python\", \"-m\", \"tarfile\", \"-vl\", str(sdist_path))\n    print(result)\n\n    # Install the package\n    result = script.pip_install_local(sdist_path)\n    print(result)\n\n    # Show installed content, for debugging the test\n    result = script.pip(\"show\", \"-f\", \"linktest\")\n    print(result)\n\n    # Run the internal test\n    result = script.run(\"python\", \"-m\", \"linktest\")\n    assert result.stdout.strip() == \"8 files checked\"\n"
  },
  {
    "path": "tests/functional/test_install_check.py",
    "content": "from collections.abc import Iterable\n\nfrom tests.lib import PipTestEnvironment, create_test_package_with_setup\n\n\ndef assert_contains_expected_lines(string: str, expected_lines: Iterable[str]) -> None:\n    for expected_line in expected_lines:\n        assert (expected_line + \"\\n\") in string\n\n\ndef test_check_install_canonicalization(script: PipTestEnvironment) -> None:\n    pkga_path = create_test_package_with_setup(\n        script,\n        name=\"pkgA\",\n        version=\"1.0\",\n        install_requires=[\"normal-missing\", \"SPECIAL.missing\"],\n    )\n    normal_path = create_test_package_with_setup(\n        script,\n        name=\"normal-missing\",\n        version=\"0.1\",\n    )\n    special_path = create_test_package_with_setup(\n        script,\n        name=\"SPECIAL.missing\",\n        version=\"0.1\",\n    )\n\n    # Let's install pkgA without its dependency\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga_path, \"--no-deps\"\n    )\n    assert \"Successfully installed pkgA-1.0\" in result.stdout, str(result)\n\n    # Install the first missing dependency. Only an error for the\n    # second dependency should remain.\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        normal_path,\n        \"--quiet\",\n        allow_stderr_error=True,\n    )\n    expected_lines = [\n        \"pkga 1.0 requires SPECIAL.missing, which is not installed.\",\n    ]\n    # Deprecated python versions produce an extra warning on stderr\n    assert_contains_expected_lines(result.stderr, expected_lines)\n    assert result.returncode == 0\n\n    # Install the second missing package and expect that there is no warning\n    # during the installation. This is special as the package name requires\n    # name normalization (as in https://github.com/pypa/pip/issues/5134)\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        special_path,\n        \"--quiet\",\n    )\n    assert \"requires\" not in result.stderr\n    assert result.returncode == 0\n\n    # Double check that all errors are resolved in the end\n    result = script.pip(\"check\")\n    expected_lines = [\n        \"No broken requirements found.\",\n    ]\n    assert_contains_expected_lines(result.stdout, expected_lines)\n    assert result.returncode == 0\n\n\ndef test_check_install_does_not_warn_for_out_of_graph_issues(\n    script: PipTestEnvironment,\n) -> None:\n    pkg_broken_path = create_test_package_with_setup(\n        script,\n        name=\"broken\",\n        version=\"1.0\",\n        install_requires=[\"missing\", \"conflict < 1.0\"],\n    )\n    pkg_unrelated_path = create_test_package_with_setup(\n        script,\n        name=\"unrelated\",\n        version=\"1.0\",\n    )\n    pkg_conflict_path = create_test_package_with_setup(\n        script,\n        name=\"conflict\",\n        version=\"1.0\",\n    )\n\n    # Install a package without it's dependencies\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkg_broken_path, \"--no-deps\"\n    )\n    assert \"requires\" not in result.stderr\n\n    # Install conflict package\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        pkg_conflict_path,\n        allow_stderr_error=True,\n    )\n    assert_contains_expected_lines(\n        result.stderr,\n        [\n            \"broken 1.0 requires missing, which is not installed.\",\n            \"broken 1.0 requires conflict<1.0, \"\n            \"but you have conflict 1.0 which is incompatible.\",\n        ],\n    )\n\n    # Install unrelated package\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        pkg_unrelated_path,\n        \"--quiet\",\n    )\n    # should not warn about broken's deps when installing unrelated package\n    assert \"requires\" not in result.stderr\n\n    result = script.pip(\"check\", expect_error=True)\n    expected_lines = [\n        \"broken 1.0 requires missing, which is not installed.\",\n        \"broken 1.0 has requirement conflict<1.0, but you have conflict 1.0.\",\n    ]\n    assert_contains_expected_lines(result.stdout, expected_lines)\n"
  },
  {
    "path": "tests/functional/test_install_cleanup.py",
    "content": "from os.path import exists\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, TestData\n\n\n@pytest.mark.network\n@pytest.mark.xfail(reason=\"The --build option was removed\")\ndef test_no_clean_option_blocks_cleaning_after_install(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test --no-clean option blocks cleaning after install\n    \"\"\"\n    build = script.base_path / \"pip-build\"\n    script.pip(\n        \"install\",\n        \"--no-clean\",\n        \"--no-index\",\n        \"--build\",\n        build,\n        f\"--find-links={data.find_links}\",\n        \"simple\",\n        expect_temp=True,\n        # TODO: allow_stderr_warning is used for the --build deprecation,\n        #       remove it when removing support for --build\n        allow_stderr_warning=True,\n    )\n    assert exists(build)\n"
  },
  {
    "path": "tests/functional/test_install_compat.py",
    "content": "\"\"\"\nTests for compatibility workarounds.\n\n\"\"\"\n\nimport os\nfrom pathlib import Path\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    assert_all_changes,\n    pyversion,\n)\n\n\ndef test_debian_egg_name_workaround(\n    script: PipTestEnvironment,\n    shared_data: TestData,\n    tmp_path: Path,\n) -> None:\n    \"\"\"\n    We can uninstall packages installed with the pyversion removed from the\n    egg-info metadata directory name.\n\n    Refs:\n    http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=618367\n    https://bugs.launchpad.net/ubuntu/+source/distribute/+bug/725178\n    https://bitbucket.org/ianb/pip/issue/104/pip-uninstall-on-ubuntu-linux\n\n    \"\"\"\n    result = script.run(\n        \"python\",\n        \"setup.py\",\n        \"install\",\n        \"--single-version-externally-managed\",\n        f\"--record={tmp_path / 'record'}\",\n        cwd=shared_data.src / \"simplewheel-2.0\",\n    )\n\n    egg_info = os.path.join(\n        script.site_packages, f\"simplewheel-2.0-py{pyversion}.egg-info\"\n    )\n\n    # Debian only removes pyversion for global installs, not inside a venv\n    # so even if this test runs on a Debian/Ubuntu system with broken\n    # setuptools, since our test runs inside a venv we'll still have the normal\n    # .egg-info\n    result.did_create(egg_info, message=f\"Couldn't find {egg_info}\")\n\n    # The Debian no-pyversion version of the .egg-info\n    mangled = os.path.join(script.site_packages, \"simplewheel-2.0.egg-info\")\n    result.did_not_create(mangled, message=f\"Found unexpected {mangled}\")\n\n    # Simulate a Debian install by copying the .egg-info to their name for it\n    full_egg_info = os.path.join(script.base_path, egg_info)\n    assert os.path.isdir(full_egg_info)\n    full_mangled = os.path.join(script.base_path, mangled)\n    os.renames(full_egg_info, full_mangled)\n    assert os.path.isdir(full_mangled)\n\n    # Try the uninstall and verify that everything is removed.\n    result2 = script.pip(\"uninstall\", \"simplewheel\", \"-y\")\n    assert_all_changes(result, result2, [script.venv / \"build\", \"cache\"])\n\n\ndef test_setup_py_with_dos_line_endings(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    It doesn't choke on a setup.py file that uses DOS line endings (\\\\r\\\\n).\n\n    Refs https://github.com/pypa/pip/issues/237\n    \"\"\"\n    to_install = data.packages.joinpath(\"LineEndings\")\n    script.pip(\"install\", \"--no-build-isolation\", to_install)\n"
  },
  {
    "path": "tests/functional/test_install_config.py",
    "content": "import os\nimport ssl\nimport tempfile\nimport textwrap\nfrom pathlib import Path\nfrom typing import Callable\n\nimport pytest\n\nfrom tests.lib import CertFactory, PipTestEnvironment, ScriptFactory, TestData\nfrom tests.lib.server import (\n    MockServer,\n    authorization_response,\n    file_response,\n    make_mock_server,\n    package_page,\n    server_running,\n)\nfrom tests.lib.venv import VirtualEnvironment\n\nTEST_PYPI_INITOOLS = \"https://test.pypi.org/simple/initools/\"\n\n\ndef test_options_from_env_vars(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test if ConfigOptionParser reads env vars (e.g. not using PyPI here)\n\n    \"\"\"\n    script.environ[\"PIP_NO_INDEX\"] = \"1\"\n    result = script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    assert \"Ignoring indexes:\" in result.stdout, str(result)\n    msg = \"DistributionNotFound: No matching distribution found for INITools\"\n    # Case insensitive as the new resolver canonicalizes the project name\n    assert msg.lower() in result.stdout.lower(), str(result)\n\n\ndef test_command_line_options_override_env_vars(\n    script: PipTestEnvironment, virtualenv: VirtualEnvironment\n) -> None:\n    \"\"\"\n    Test that command line options override environmental variables.\n\n    \"\"\"\n    script.environ[\"PIP_INDEX_URL\"] = \"https://example.com/simple/\"\n    result = script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    assert \"Getting page https://example.com/simple/initools\" in result.stdout\n    virtualenv.clear()\n    result = script.pip(\n        \"install\",\n        \"-vvv\",\n        \"--index-url\",\n        \"https://download.zope.org/ppix\",\n        \"INITools\",\n        expect_error=True,\n    )\n    assert \"example.com\" not in result.stdout\n    assert \"Getting page https://download.zope.org/ppix\" in result.stdout\n\n\n@pytest.mark.network\ndef test_env_vars_override_config_file(\n    script: PipTestEnvironment, virtualenv: VirtualEnvironment\n) -> None:\n    \"\"\"\n    Test that environmental variables override settings in config files.\n    \"\"\"\n    config_file = script.scratch_path / \"test-pip.cfg\"\n    # set this to make pip load it\n    script.environ[\"PIP_CONFIG_FILE\"] = str(config_file)\n    # It's important that we test this particular config value ('no-index')\n    # because there is/was a bug which only shows up in cases in which\n    # 'config-item' and 'config_item' hash to the same value modulo the size\n    # of the config dictionary.\n    config_file.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        [global]\n        no-index = 1\n        \"\"\"\n        )\n    )\n    result = script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    msg = \"DistributionNotFound: No matching distribution found for INITools\"\n    # Case insensitive as the new resolver canonicalizes the project name\n    assert msg.lower() in result.stdout.lower(), str(result)\n    script.environ[\"PIP_NO_INDEX\"] = \"0\"\n    virtualenv.clear()\n    result = script.pip(\"install\", \"-vvv\", \"INITools\")\n    assert \"Successfully installed INITools\" in result.stdout\n\n\n@pytest.mark.network\ndef test_command_line_append_flags(\n    script: PipTestEnvironment, virtualenv: VirtualEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test command line flags that append to defaults set by environmental\n    variables.\n\n    \"\"\"\n    script.environ[\"PIP_FIND_LINKS\"] = TEST_PYPI_INITOOLS\n    result = script.pip(\n        \"install\",\n        \"-vvv\",\n        \"INITools\",\n        \"--trusted-host\",\n        \"test.pypi.org\",\n    )\n    assert (\n        \"Fetching project page and analyzing links: https://test.pypi.org\"\n        in result.stdout\n    ), str(result)\n    virtualenv.clear()\n    result = script.pip(\n        \"install\",\n        \"-vvv\",\n        \"--find-links\",\n        data.find_links,\n        \"INITools\",\n        \"--trusted-host\",\n        \"test.pypi.org\",\n    )\n    assert (\n        \"Fetching project page and analyzing links: https://test.pypi.org\"\n        in result.stdout\n    )\n\n\n@pytest.mark.network\ndef test_command_line_appends_correctly(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test multiple appending options set by environmental variables.\n\n    \"\"\"\n    script.environ[\"PIP_FIND_LINKS\"] = f\"{TEST_PYPI_INITOOLS} {data.find_links}\"\n    result = script.pip(\n        \"install\",\n        \"-vvv\",\n        \"INITools\",\n        \"--trusted-host\",\n        \"test.pypi.org\",\n    )\n\n    assert (\n        \"Fetching project page and analyzing links: https://test.pypi.org\"\n        in result.stdout\n    ), result.stdout\n\n\ndef test_config_file_override_stack(\n    script: PipTestEnvironment,\n    virtualenv: VirtualEnvironment,\n    mock_server: MockServer,\n    shared_data: TestData,\n) -> None:\n    \"\"\"\n    Test config files (global, overriding a global config with a\n    local, overriding all with a command line flag).\n    \"\"\"\n    mock_server.set_responses(\n        [\n            package_page({}),\n            package_page({}),\n            package_page({\"INITools-0.2.tar.gz\": \"/files/INITools-0.2.tar.gz\"}),\n            file_response(shared_data.packages.joinpath(\"INITools-0.2.tar.gz\")),\n        ]\n    )\n    mock_server.start()\n    base_address = f\"http://{mock_server.host}:{mock_server.port}\"\n\n    config_file = script.scratch_path / \"test-pip.cfg\"\n\n    # set this to make pip load it\n    script.environ[\"PIP_CONFIG_FILE\"] = str(config_file)\n\n    config_file.write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n        [global]\n        index-url = {base_address}/simple1\n        \"\"\"\n        )\n    )\n    script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    virtualenv.clear()\n\n    config_file.write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n        [global]\n        index-url = {base_address}/simple1\n        [install]\n        index-url = {base_address}/simple2\n        \"\"\"\n        )\n    )\n    script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-vvv\",\n        \"--index-url\",\n        f\"{base_address}/simple3\",\n        \"INITools\",\n    )\n\n    mock_server.stop()\n    requests = mock_server.get_requests()\n    assert len(requests) == 4\n    assert requests[0][\"PATH_INFO\"] == \"/simple1/initools/\"\n    assert requests[1][\"PATH_INFO\"] == \"/simple2/initools/\"\n    assert requests[2][\"PATH_INFO\"] == \"/simple3/initools/\"\n    assert requests[3][\"PATH_INFO\"] == \"/files/INITools-0.2.tar.gz\"\n\n\ndef test_options_from_venv_config(\n    script: PipTestEnvironment, virtualenv: VirtualEnvironment\n) -> None:\n    \"\"\"\n    Test if ConfigOptionParser reads a virtualenv-local config file\n\n    \"\"\"\n    from pip._internal.configuration import CONFIG_BASENAME\n\n    conf = \"[global]\\nno-index = true\"\n    ini = virtualenv.location / CONFIG_BASENAME\n    with open(ini, \"w\") as f:\n        f.write(conf)\n    result = script.pip(\"install\", \"-vvv\", \"INITools\", expect_error=True)\n    assert \"Ignoring indexes:\" in result.stdout, str(result)\n    msg = \"DistributionNotFound: No matching distribution found for INITools\"\n    # Case insensitive as the new resolver canonicalizes the project name\n    assert msg.lower() in result.stdout.lower(), str(result)\n\n\ndef test_install_no_binary_via_config_disables_cached_wheels(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    config_file = tempfile.NamedTemporaryFile(mode=\"wt\", delete=False)\n    try:\n        script.environ[\"PIP_CONFIG_FILE\"] = config_file.name\n        config_file.write(\n            textwrap.dedent(\n                \"\"\"\\\n            [global]\n            no-binary = :all:\n            \"\"\"\n            )\n        )\n        config_file.close()\n        res = script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--no-index\",\n            \"-f\",\n            data.find_links,\n            \"upper\",\n            expect_stderr=True,\n        )\n    finally:\n        os.unlink(config_file.name)\n    assert \"Successfully installed upper-2.0\" in str(res), str(res)\n    # upper is built and not obtained from cache\n    assert \"Building wheel for upper\" in str(res), str(res)\n\n\ndef test_prompt_for_authentication(\n    script: PipTestEnvironment, data: TestData, cert_factory: CertFactory\n) -> None:\n    \"\"\"Test behaviour while installing from a index url\n    requiring authentication\n    \"\"\"\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    server = make_mock_server(ssl_context=ctx)\n    server.mock.side_effect = [\n        package_page(\n            {\n                \"simple-3.0.tar.gz\": \"/files/simple-3.0.tar.gz\",\n            }\n        ),\n        authorization_response(data.packages / \"simple-3.0.tar.gz\"),\n    ]\n\n    url = f\"https://{server.host}:{server.port}/simple\"\n\n    with server_running(server):\n        result = script.pip(\n            \"install\",\n            \"--index-url\",\n            url,\n            \"--cert\",\n            cert_path,\n            \"--client-cert\",\n            cert_path,\n            \"simple\",\n            expect_error=True,\n        )\n\n    assert f\"User for {server.host}:{server.port}\" in result.stdout, str(result)\n\n\ndef test_do_not_prompt_for_authentication(\n    script: PipTestEnvironment, data: TestData, cert_factory: CertFactory\n) -> None:\n    \"\"\"Test behaviour if --no-input option is given while installing\n    from a index url requiring authentication\n    \"\"\"\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    server = make_mock_server(ssl_context=ctx)\n\n    server.mock.side_effect = [\n        package_page(\n            {\n                \"simple-3.0.tar.gz\": \"/files/simple-3.0.tar.gz\",\n            }\n        ),\n        authorization_response(data.packages / \"simple-3.0.tar.gz\"),\n    ]\n\n    url = f\"https://{server.host}:{server.port}/simple\"\n\n    with server_running(server):\n        result = script.pip(\n            \"install\",\n            \"--index-url\",\n            url,\n            \"--cert\",\n            cert_path,\n            \"--client-cert\",\n            cert_path,\n            \"--no-input\",\n            \"simple\",\n            expect_error=True,\n        )\n\n    assert \"ERROR: HTTP error 401\" in result.stderr\n\n\ndef test_do_not_prompt_for_authentication_git(\n    script: PipTestEnvironment, data: TestData, cert_factory: CertFactory\n) -> None:\n    \"\"\"Test behaviour if --no-input option is given while installing\n    from a git http url requiring authentication\n    \"\"\"\n    server = make_mock_server()\n    # Disable vscode user/password prompt, will make tests fail inside vscode\n    script.environ[\"GIT_ASKPASS\"] = \"\"\n\n    # Return 401 on all URLs\n    server.mock.side_effect = lambda _, __: authorization_response(\n        data.packages / \"simple-3.0.tar.gz\"\n    )\n\n    url = f\"git+http://{server.host}:{server.port}/simple\"\n\n    with server_running(server):\n        result = script.pip(\n            \"install\",\n            url,\n            \"--no-input\",\n            expect_error=True,\n        )\n\n    assert \"terminal prompts disabled\" in result.stderr\n\n\n@pytest.fixture(params=(True, False), ids=(\"interactive\", \"noninteractive\"))\ndef interactive(request: pytest.FixtureRequest) -> bool:\n    return request.param\n\n\n@pytest.fixture(params=(True, False), ids=(\"auth_needed\", \"auth_not_needed\"))\ndef auth_needed(request: pytest.FixtureRequest) -> bool:\n    return request.param\n\n\n@pytest.fixture(params=(None, \"disabled\", \"import\", \"subprocess\", \"auto\"))\ndef keyring_provider(request: pytest.FixtureRequest) -> str:\n    return request.param\n\n\n@pytest.fixture(params=(\"disabled\", \"import\", \"subprocess\"))\ndef keyring_provider_implementation(request: pytest.FixtureRequest) -> str:\n    return request.param\n\n\n@pytest.fixture\ndef flags(\n    request: pytest.FixtureRequest,\n    interactive: bool,\n    auth_needed: bool,\n    keyring_provider: str,\n    keyring_provider_implementation: str,\n) -> list[str]:\n    if (\n        keyring_provider not in [None, \"auto\"]\n        and keyring_provider_implementation != keyring_provider\n    ):\n        pytest.skip()\n\n    flags = []\n    if keyring_provider is not None:\n        flags.append(\"--keyring-provider\")\n        flags.append(keyring_provider)\n    if not interactive:\n        flags.append(\"--no-input\")\n    if auth_needed:\n        if keyring_provider_implementation == \"disabled\" or (\n            not interactive and keyring_provider in [None, \"auto\"]\n        ):\n            request.applymarker(pytest.mark.xfail())\n    return flags\n\n\ndef test_prompt_for_keyring_if_needed(\n    data: TestData,\n    cert_factory: CertFactory,\n    auth_needed: bool,\n    flags: list[str],\n    keyring_provider: str,\n    keyring_provider_implementation: str,\n    tmpdir: Path,\n    script_factory: ScriptFactory,\n    virtualenv_factory: Callable[[Path], VirtualEnvironment],\n) -> None:\n    \"\"\"Test behaviour while installing from an index url\n    requiring authentication and keyring is possible.\n    \"\"\"\n    environ = os.environ.copy()\n    workspace = tmpdir.joinpath(\"workspace\")\n\n    if keyring_provider_implementation == \"subprocess\":\n        keyring_virtualenv = virtualenv_factory(workspace.joinpath(\"keyring\"))\n        keyring_script = script_factory(\n            workspace.joinpath(\"keyring\"), keyring_virtualenv\n        )\n        keyring_script.pip_install_local(\"keyring\", \"-f\", data.common_wheels)\n\n        environ[\"PATH\"] = str(keyring_script.bin_path) + os.pathsep + environ[\"PATH\"]\n\n    virtualenv = virtualenv_factory(workspace.joinpath(\"venv\"))\n    script = script_factory(workspace.joinpath(\"venv\"), virtualenv, environ=environ)\n\n    if (\n        keyring_provider not in [None, \"auto\"]\n        or keyring_provider_implementation != \"subprocess\"\n    ):\n        script.pip_install_local(\"keyring\", \"-f\", data.common_wheels)\n\n    if keyring_provider_implementation != \"subprocess\":\n        keyring_script = script\n\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    response = authorization_response if auth_needed else file_response\n\n    server = make_mock_server(ssl_context=ctx)\n    server.mock.side_effect = [\n        package_page(\n            {\n                \"simple-3.0.tar.gz\": \"/files/simple-3.0.tar.gz\",\n            }\n        ),\n        response(data.packages / \"simple-3.0.tar.gz\"),\n        response(data.packages / \"simple-3.0.tar.gz\"),\n    ]\n\n    url = f\"https://USERNAME@{server.host}:{server.port}/simple\"\n\n    keyring_content = textwrap.dedent(\n        \"\"\"\\\n        import os\n        import sys\n        import keyring\n        from keyring.backend import KeyringBackend\n        from keyring.credentials import SimpleCredential\n\n        class TestBackend(KeyringBackend):\n            priority = 1\n\n            def get_credential(self, url, username):\n                sys.stderr.write(\"get_credential was called\" + os.linesep)\n                return SimpleCredential(username=\"USERNAME\", password=\"PASSWORD\")\n\n            def get_password(self, url, username):\n                sys.stderr.write(\"get_password was called\" + os.linesep)\n                return \"PASSWORD\"\n\n            def set_password(self, url, username):\n                pass\n    \"\"\"\n    )\n    keyring_path = keyring_script.site_packages_path / \"keyring_test.py\"\n    keyring_path.write_text(keyring_content)\n\n    keyring_content = (\n        \"import keyring_test;\"\n        \" import keyring;\"\n        \" keyring.set_keyring(keyring_test.TestBackend())\" + os.linesep\n    )\n    keyring_path = keyring_path.with_suffix(\".pth\")\n    keyring_path.write_text(keyring_content)\n\n    with server_running(server):\n        result = script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--index-url\",\n            url,\n            \"--cert\",\n            cert_path,\n            \"--client-cert\",\n            cert_path,\n            *flags,\n            \"simple\",\n        )\n\n    function_name = (\n        \"get_credential\"\n        if keyring_provider_implementation == \"import\"\n        else \"get_password\"\n    )\n    if auth_needed:\n        assert function_name + \" was called\" in result.stderr\n    else:\n        assert function_name + \" was called\" not in result.stderr\n\n\n@pytest.mark.network\ndef test_install_quiet_log(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test suppressing the progress bar with --quiet and --log.\n    \"\"\"\n    logfile = script.scratch_path / \"log\"\n    result = script.pip(\"install\", \"-qqq\", \"setuptools==62.0.0\", \"--log\", logfile)\n    assert result.stdout == \"\"\n    assert result.stderr == \"\"\n"
  },
  {
    "path": "tests/functional/test_install_direct_url.py",
    "content": "import pytest\n\nfrom pip._internal.models.direct_url import VcsInfo\n\nfrom tests.lib import PipTestEnvironment, TestData, _create_test_package\n\n\ndef test_install_find_links_no_direct_url(script: PipTestEnvironment) -> None:\n    result = script.pip_install_local(\"simple\")\n    assert not result.get_created_direct_url(\"simple\")\n\n\ndef test_install_vcs_non_editable_direct_url(script: PipTestEnvironment) -> None:\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpkg\")\n    url = pkg_path.as_uri()\n    args = [\"install\", \"--no-build-isolation\", f\"git+{url}#egg=testpkg\"]\n    result = script.pip(*args)\n    direct_url = result.get_created_direct_url(\"testpkg\")\n    assert direct_url\n    assert direct_url.url == url\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.vcs == \"git\"\n\n\ndef test_install_archive_direct_url(script: PipTestEnvironment, data: TestData) -> None:\n    req = \"simple @ \" + data.packages.joinpath(\"simple-2.0.tar.gz\").as_uri()\n    assert req.startswith(\"simple @ file://\")\n    result = script.pip(\"install\", \"--no-build-isolation\", req)\n    assert result.get_created_direct_url(\"simple\")\n\n\n@pytest.mark.network\ndef test_install_vcs_constraint_direct_url(script: PipTestEnvironment) -> None:\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\n        \"git+https://github.com/pypa/pip-test-package\"\n        \"@5547fa909e83df8bd743d3978d6667497983a4b7\"\n        \"#egg=pip-test-package\"\n    )\n    result = script.pip(\"install\", \"pip-test-package\", \"-c\", constraints_file)\n    assert result.get_created_direct_url(\"pip_test_package\")\n\n\ndef test_install_vcs_constraint_direct_file_url(script: PipTestEnvironment) -> None:\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpkg\")\n    url = pkg_path.as_uri()\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"git+{url}#egg=testpkg\")\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"testpkg\", \"-c\", constraints_file\n    )\n    assert result.get_created_direct_url(\"testpkg\")\n"
  },
  {
    "path": "tests/functional/test_install_extras.py",
    "content": "import re\nimport textwrap\nfrom os.path import join\nfrom pathlib import Path\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    ResolverVariant,\n    TestData,\n    create_basic_wheel_for_package,\n)\n\n\n@pytest.mark.network\ndef test_simple_extras_install_from_pypi(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a package from PyPI using extras dependency Paste[openid].\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"Paste[openid]==1.7.5.1\",\n        expect_stderr=True,\n    )\n    initools_folder = script.site_packages / \"openid\"\n    result.did_create(initools_folder)\n\n\ndef test_extras_after_wheel(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing a package with extras after installing from a wheel.\n    \"\"\"\n    simple = script.site_packages / \"simple\"\n\n    no_extra = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"requires_simple_extra\",\n        expect_stderr=True,\n    )\n    no_extra.did_not_create(simple)\n\n    extra = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"requires_simple_extra[extra]\",\n        expect_stderr=True,\n    )\n    extra.did_create(simple)\n\n\n@pytest.mark.network\ndef test_no_extras_uninstall(script: PipTestEnvironment) -> None:\n    \"\"\"\n    No extras dependency gets uninstalled when the root package is uninstalled\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"Paste[openid]==1.7.5.1\",\n        expect_stderr=True,\n    )\n    result.did_create(join(script.site_packages, \"paste\"))\n    result.did_create(join(script.site_packages, \"openid\"))\n    result2 = script.pip(\"uninstall\", \"Paste\", \"-y\")\n    # openid should not be uninstalled\n    initools_folder = script.site_packages / \"openid\"\n    assert initools_folder not in result2.files_deleted, result.files_deleted\n\n\ndef test_nonexistent_extra_warns_user_no_wheel(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    A warning is logged telling the user that the extra option they requested\n    does not exist in the project they are wishing to install.\n\n    This exercises source installs.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-binary=:all:\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links=\" + data.find_links,\n        \"simple[nonexistent]\",\n        expect_stderr=True,\n    )\n    assert \"simple 3.0 does not provide the extra 'nonexistent'\" in result.stderr, str(\n        result\n    )\n\n\ndef test_nonexistent_extra_warns_user_with_wheel(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    A warning is logged telling the user that the extra option they requested\n    does not exist in the project they are wishing to install.\n\n    This exercises wheel installs.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links=\" + data.find_links,\n        \"simplewheel[nonexistent]\",\n        expect_stderr=True,\n    )\n    assert \"simplewheel 2.0 does not provide the extra 'nonexistent'\" in result.stderr\n\n\ndef test_nonexistent_options_listed_in_order(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Warn the user for each extra that doesn't exist.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links=\" + data.find_links,\n        \"simplewheel[nonexistent, nope]\",\n        expect_stderr=True,\n    )\n    matches = re.findall(\n        \"WARNING: simplewheel 2.0 does not provide the extra '([a-z]*)'\", result.stderr\n    )\n    assert matches == [\"nonexistent\", \"nope\"]\n\n\ndef test_install_fails_if_extra_at_end(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Fail if order of specifiers and extras is incorrect.\n\n    Test uses a requirements file to avoid a testing issue where\n    the specifier gets interpreted as shell redirect.\n    \"\"\"\n    script.scratch_path.joinpath(\"requirements.txt\").write_text(\n        \"requires_simple_extra>=0.1[extra]\"\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links=\" + data.find_links,\n        \"-r\",\n        script.scratch_path / \"requirements.txt\",\n        expect_error=True,\n    )\n    assert \"Invalid requirement: 'requires_simple_extra>=0.1[extra]'\" in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"specified_extra, requested_extra\",\n    [\n        (\"Hop_hOp-hoP\", \"Hop_hOp-hoP\"),\n        (\"Hop_hOp-hoP\", \"hop-hop-hop\"),\n        (\"hop-hop-hop\", \"Hop_hOp-hoP\"),\n    ],\n)\ndef test_install_special_extra(\n    script: PipTestEnvironment,\n    specified_extra: str,\n    requested_extra: str,\n) -> None:\n    \"\"\"Check extra normalization is implemented according to specification.\"\"\"\n    pkga_path = create_basic_wheel_for_package(\n        script,\n        name=\"pkga\",\n        version=\"0.1\",\n        extras={specified_extra: [\"missing_pkg\"]},\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        f\"pkga[{requested_extra}] @ {pkga_path.as_uri()}\",\n        expect_error=True,\n    )\n    assert (\n        \"Could not find a version that satisfies the requirement missing_pkg\"\n    ) in result.stderr, str(result)\n\n\n@pytest.mark.network\ndef test_install_requirements_no_r_flag(script: PipTestEnvironment) -> None:\n    \"\"\"Beginners sometimes forget the -r and this leads to confusion\"\"\"\n    result = script.pip(\"install\", \"requirements.txt\", expect_error=True)\n    assert 'literally named \"requirements.txt\"' in result.stdout, str(result)\n\n\n@pytest.mark.parametrize(\n    \"extra_to_install, simple_version, fails_on_legacy\",\n    [\n        (\"\", \"3.0\", False),\n        (\"[extra1]\", \"2.0\", True),\n        (\"[extra2]\", \"1.0\", True),\n        (\"[extra1,extra2]\", \"1.0\", True),\n    ],\n)\n@pytest.mark.usefixtures(\"data\")\ndef test_install_extra_merging(\n    script: PipTestEnvironment,\n    resolver_variant: ResolverVariant,\n    extra_to_install: str,\n    simple_version: str,\n    fails_on_legacy: bool,\n) -> None:\n    # Check that extra specifications in the extras section are honoured.\n    pkga_path = script.scratch_path / \"pkga\"\n    pkga_path.mkdir()\n    pkga_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from setuptools import setup\n        setup(name='pkga',\n              version='0.1',\n              install_requires=['simple'],\n              extras_require={'extra1': ['simple<3'],\n                              'extra2': ['simple==1.*']},\n        )\n    \"\"\"\n        )\n    )\n\n    result = script.pip_install_local(\n        f\"{pkga_path}{extra_to_install}\",\n        expect_error=(fails_on_legacy and resolver_variant == \"legacy\"),\n    )\n\n    if not fails_on_legacy or resolver_variant == \"resolvelib\":\n        expected = f\"Successfully installed pkga-0.1 simple-{simple_version}\"\n        assert expected in result.stdout\n\n\ndef test_install_extras(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"a\", \"1\", depends=[\"b\", \"dep[x-y]\"])\n    create_basic_wheel_for_package(script, \"b\", \"1\", depends=[\"dep[x_y]\"])\n    create_basic_wheel_for_package(script, \"dep\", \"1\", extras={\"x-y\": [\"meh\"]})\n    create_basic_wheel_for_package(script, \"meh\", \"1\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"a\",\n    )\n    script.assert_installed(a=\"1\", b=\"1\", dep=\"1\", meh=\"1\")\n\n\ndef test_install_setuptools_extras_inconsistency(\n    script: PipTestEnvironment, tmp_path: Path\n) -> None:\n    test_project_path = tmp_path.joinpath(\"test\")\n    test_project_path.mkdir()\n    test_project_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n                from setuptools import setup\n                setup(\n                    name='test',\n                    version='0.1',\n                    extras_require={'extra_underscored': ['packaging']},\n                )\n            \"\"\"\n        )\n    )\n    script.pip(\"install\", \"--no-build-isolation\", \"--dry-run\", test_project_path)\n"
  },
  {
    "path": "tests/functional/test_install_force_reinstall.py",
    "content": "import os\n\nfrom tests.lib import PipTestEnvironment, assert_all_changes\n\n\ndef check_installed_version(\n    script: PipTestEnvironment, package: str, expected: str\n) -> None:\n    result = script.pip(\"show\", package)\n    lines = result.stdout.splitlines()\n    version = None\n    for line in lines:\n        if line.startswith(\"Version: \"):\n            version = line.split()[-1]\n            break\n    assert version == expected, f\"version {version} != {expected}\"\n\n\ndef check_force_reinstall(\n    script: PipTestEnvironment, specifier: str, expected: str\n) -> None:\n    \"\"\"\n    Args:\n      specifier: the requirement specifier to force-reinstall.\n      expected: the expected version after force-reinstalling.\n    \"\"\"\n    result = script.pip_install_local(\"simplewheel==1.0\")\n    check_installed_version(script, \"simplewheel\", \"1.0\")\n\n    # Remove an installed file to test whether --force-reinstall fixes it.\n    to_fix = script.site_packages_path.joinpath(\"simplewheel\", \"__init__.py\")\n    to_fix.unlink()\n\n    result2 = script.pip_install_local(\"--force-reinstall\", specifier)\n    check_installed_version(script, \"simplewheel\", expected)\n\n    # site_packages_path is absolute, but files_created mapping uses\n    # relative paths as key.\n    fixed_key = os.path.relpath(to_fix, script.base_path)\n    result2.did_create(fixed_key, message=\"force-reinstall failed\")\n\n    result3 = script.pip(\"uninstall\", \"simplewheel\", \"-y\")\n    assert_all_changes(result, result3, [script.venv / \"build\", \"cache\"])\n\n\ndef test_force_reinstall_with_no_version_specifier(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Check --force-reinstall when there is no version specifier and the\n    installed version is not the newest version.\n    \"\"\"\n    check_force_reinstall(script, \"simplewheel\", \"2.0\")\n\n\ndef test_force_reinstall_with_same_version_specifier(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Check --force-reinstall when the version specifier equals the installed\n    version and the installed version is not the newest version.\n    \"\"\"\n    check_force_reinstall(script, \"simplewheel==1.0\", \"1.0\")\n"
  },
  {
    "path": "tests/functional/test_install_format_control.py",
    "content": "\"\"\"Tests for --only-binary and --no-binary format control flags.\n\nThese tests verify edge case CLI and requirements file interaction behavior,\nmatching the pattern established by --all-releases and --only-final tests.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    create_basic_sdist_for_package,\n    create_basic_wheel_for_package,\n)\n\n\ndef test_order_no_binary_then_only_binary(script: PipTestEnvironment) -> None:\n    \"\"\"Test --no-binary=:all: --only-binary=<package>.\n\n    When the user specifies --no-binary=:all: --only-binary=simple, they\n    expect 'simple' to allow wheels (later flag overrides).\n    \"\"\"\n    wheel_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    # This should allow wheels for 'simple' because --only-binary comes after\n    result = script.pip_install_local(\n        \"--no-binary=:all:\",\n        \"--only-binary=simple\",\n        \"simple==1.0\",\n        find_links=[wheel_path.parent],\n    )\n    script.assert_installed(simple=\"1.0\")\n    # Should NOT be building from source\n    assert \"Building wheel for simple\" not in result.stdout\n\n\ndef test_order_only_binary_then_no_binary(script: PipTestEnvironment) -> None:\n    \"\"\"Test --only-binary=:all: --no-binary=<package>.\n\n    When the user specifies --only-binary=:all: --no-binary=simple,\n    'simple' should be built from source (later flag overrides).\n    \"\"\"\n    wheel_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n    create_basic_sdist_for_package(script, \"simple\", \"1.0\")\n\n    # This should build from source for 'simple' because --no-binary comes after\n    result = script.pip_install_local(\n        \"--only-binary=:all:\",\n        \"--no-binary=simple\",\n        \"simple==1.0\",\n        find_links=[wheel_path.parent],\n    )\n    script.assert_installed(simple=\"1.0\")\n    assert \"Building wheel for simple\" in result.stdout\n\n\ndef test_reqfile_no_binary_overrides_cmdline_only_binary(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test requirements file --no-binary overrides command line --only-binary.\"\"\"\n    wheel_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n    create_basic_sdist_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {wheel_path.parent.as_posix()}\\n\"\n        \"--no-binary :all:\\nsimple==1.0\\n\",\n    )\n\n    result = script.pip_install_local(\n        \"--only-binary=:all:\", \"-r\", req_file, find_links=[]\n    )\n    script.assert_installed(simple=\"1.0\")\n    # Requirements file --no-binary should override CLI --only-binary\n    assert \"Building wheel for simple\" in result.stdout\n\n\ndef test_reqfile_only_binary_overrides_cmdline_no_binary(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test requirements file --only-binary overrides command line --no-binary.\"\"\"\n    # Create only a wheel, no sdist\n    wheel_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {wheel_path.parent.as_posix()}\\n\"\n        \"--only-binary :all:\\nsimple==1.0\\n\",\n    )\n\n    result = script.pip_install_local(\n        \"--no-binary=:all:\", \"-r\", req_file, find_links=[]\n    )\n    result.assert_installed(\"simple\", editable=False)\n    # Requirements file --only-binary should override CLI --no-binary\n    assert \"Building wheel for simple\" not in result.stdout\n\n\ndef test_package_specific_overrides_all_in_requirements_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test package-specific setting overrides :all: in requirements file.\"\"\"\n    wheel_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {wheel_path.parent.as_posix()}\\n--no-binary :all:\\n\"\n        \"--only-binary simple\\nsimple==1.0\\n\",\n    )\n\n    result = script.pip_install_local(\"-r\", req_file, find_links=[])\n    result.assert_installed(\"simple\", editable=False)\n    # Package-specific --only-binary should override --no-binary :all:\n    assert \"Building wheel for simple\" not in result.stdout\n"
  },
  {
    "path": "tests/functional/test_install_index.py",
    "content": "import shutil\nimport textwrap\n\nfrom tests.lib import PipTestEnvironment, TestData\n\n\ndef test_find_links_relative_path(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"Test find-links as a relative path.\"\"\"\n    result = script.pip(\n        \"install\",\n        \"parent==0.1\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        \"packages/\",\n        cwd=data.root,\n    )\n    dist_info_folder = script.site_packages / \"parent-0.1.dist-info\"\n    initools_folder = script.site_packages / \"parent\"\n    result.did_create(dist_info_folder)\n    result.did_create(initools_folder)\n\n\ndef test_find_links_no_doctype(script: PipTestEnvironment, data: TestData) -> None:\n    shutil.copy(data.packages / \"simple-1.0.tar.gz\", script.scratch_path)\n    html = script.scratch_path.joinpath(\"index.html\")\n    html.write_text('<a href=\"simple-1.0.tar.gz\"></a>')\n    result = script.pip(\n        \"install\",\n        \"simple==1.0\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        expect_stderr=True,\n    )\n    assert not result.stderr\n\n\ndef test_find_links_requirements_file_relative_path(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Test find-links as a relative path to a reqs file.\"\"\"\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            f\"\"\"\n        --no-index\n        --find-links={data.packages.as_posix()}\n        parent==0.1\n        \"\"\"\n        )\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-r\",\n        script.scratch_path / \"test-req.txt\",\n        cwd=data.root,\n    )\n    dist_info_folder = script.site_packages / \"parent-0.1.dist-info\"\n    initools_folder = script.site_packages / \"parent\"\n    result.did_create(dist_info_folder)\n    result.did_create(initools_folder)\n\n\ndef test_install_from_file_index_hash_link(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that a pkg can be installed from a file:// index using a link with a\n    hash\n    \"\"\"\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"-i\", data.index_url(), \"simple==1.0\"\n    )\n    dist_info_folder = script.site_packages / \"simple-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_file_index_url_quoting(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test url quoting of file index url with a space\n    \"\"\"\n    index_url = data.index_url(\"in dex\")\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"-vvv\", \"--index-url\", index_url, \"simple\"\n    )\n    result.did_create(script.site_packages / \"simple\")\n    result.did_create(script.site_packages / \"simple-1.0.dist-info\")\n"
  },
  {
    "path": "tests/functional/test_install_release_control.py",
    "content": "\"\"\"Tests for --all-releases and --only-final release control flags.\"\"\"\n\nfrom __future__ import annotations\n\nfrom tests.lib import PipTestEnvironment, create_basic_wheel_for_package\n\n\ndef test_all_releases_allows_prereleases(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --all-releases :all: allows installing pre-release versions.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    result = script.pip_install_local(\n        \"--all-releases=:all:\", \"simple==1.0a1\", find_links=[pkg_path.parent]\n    )\n    result.assert_installed(\"simple\", editable=False)\n\n\ndef test_all_releases_package_specific(script: PipTestEnvironment) -> None:\n    \"\"\"Test --all-releases with package allows pre-releases for that package.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    result = script.pip_install_local(\n        \"--all-releases=simple\", \"simple==1.0a1\", find_links=[pkg_path.parent]\n    )\n    result.assert_installed(\"simple\", editable=False)\n\n\ndef test_only_final_blocks_prereleases(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --only-final :all: blocks pre-release versions.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    result = script.pip_install_local(\n        \"--only-final=:all:\",\n        \"simple==1.0a1\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert (\n        \"Could not find a final version that satisfies the requirement\" in result.stderr\n    )\n\n\ndef test_only_final_package_specific(script: PipTestEnvironment) -> None:\n    \"\"\"Test --only-final with package blocks pre-releases for that package.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    result = script.pip_install_local(\n        \"--only-final=simple\",\n        \"simple==1.0a1\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert (\n        \"Could not find a final version that satisfies the requirement\" in result.stderr\n    )\n\n\ndef test_pre_transforms_to_all_releases(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --pre is equivalent to --all-releases :all:.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    result = script.pip_install_local(\n        \"--pre\", \"simple==1.0a1\", find_links=[pkg_path.parent]\n    )\n    result.assert_installed(\"simple\", editable=False)\n\n\ndef test_pre_with_all_releases_fails(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --pre cannot be used with --all-releases.\"\"\"\n    result = script.pip(\n        \"install\",\n        \"--pre\",\n        \"--all-releases=pkg1\",\n        \"dummy\",\n        expect_error=True,\n    )\n    assert \"--pre cannot be used with --all-releases or --only-final\" in result.stderr\n\n\ndef test_pre_with_only_final_fails(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --pre cannot be used with --only-final.\"\"\"\n    result = script.pip(\n        \"install\",\n        \"--pre\",\n        \"--only-final=pkg1\",\n        \"dummy\",\n        expect_error=True,\n    )\n    assert \"--pre cannot be used with --all-releases or --only-final\" in result.stderr\n\n\ndef test_all_releases_none(script: PipTestEnvironment) -> None:\n    \"\"\"Test that --all-releases :none: empties the set.\"\"\"\n    # Create both a prerelease and a final version\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    # Without specifying exact version, it should install the final version\n    # because :none: cleared the :all: setting\n    script.pip_install_local(\n        \"--all-releases=:all:\",\n        \"--all-releases=:none:\",\n        \"simple\",\n        find_links=[pre_pkg.parent],\n    )\n    script.assert_installed(simple=\"1.0\")\n\n\ndef test_package_specific_overrides_all(script: PipTestEnvironment) -> None:\n    \"\"\"Test that package-specific --only-final overrides :all: --all-releases.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    # Allow pre-releases for all packages\n    result = script.pip_install_local(\n        \"--all-releases=:all:\",\n        \"--only-final=simple\",  # But not for 'simple'\n        \"simple==1.0a1\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert (\n        \"Could not find a final version that satisfies the requirement\" in result.stderr\n    )\n\n\ndef test_requirements_file_all_releases(script: PipTestEnvironment) -> None:\n    \"\"\"Test --all-releases in requirements file.\"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    req_file = script.temporary_file(\n        \"reqs.txt\", \"--all-releases :all:\\nsimple==1.0a1\\n\"\n    )\n\n    result = script.pip_install_local(\"-r\", req_file, find_links=[pkg_path.parent])\n    result.assert_installed(\"simple\", editable=False)\n\n\ndef test_requirements_file_only_final(script: PipTestEnvironment) -> None:\n    \"\"\"Test --only-final in requirements file.\"\"\"\n    # Create both a prerelease and a final version\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    # No specific version\n    req_file = script.temporary_file(\"reqs.txt\", \"--only-final :all:\\nsimple\\n\")\n\n    script.pip_install_local(\"-r\", req_file, find_links=[pre_pkg.parent])\n    # Should install final version, not prerelease\n    script.assert_installed(simple=\"1.0\")\n\n\ndef test_order_only_final_then_all_releases(script: PipTestEnvironment) -> None:\n    \"\"\"Test critical case: --only-final=:all: --all-releases=<package>.\n\n    This tests that argument order is preserved when passed to build backends.\n    When the user specifies --only-final=:all: --all-releases=simple, they\n    expect 'simple' to allow prereleases (later flag overrides).\n    \"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    # This should allow prereleases for 'simple' because --all-releases comes after\n    result = script.pip_install_local(\n        \"--only-final=:all:\",\n        \"--all-releases=simple\",\n        \"simple==1.0a1\",\n        find_links=[pkg_path.parent],\n    )\n    result.assert_installed(\"simple\", editable=False)\n\n\ndef test_order_all_releases_then_only_final(script: PipTestEnvironment) -> None:\n    \"\"\"Test reverse case: --all-releases=:all: --only-final=<package>.\n\n    This tests that when the user specifies --all-releases=:all: --only-final=simple,\n    'simple' should only allow final releases (later flag overrides).\n    \"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0a1\")\n\n    # This should block prereleases for 'simple' because --only-final comes after\n    result = script.pip_install_local(\n        \"--all-releases=:all:\",\n        \"--only-final=simple\",\n        \"simple==1.0a1\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert (\n        \"Could not find a final version that satisfies the requirement\" in result.stderr\n    )\n\n\ndef test_no_matching_version_without_release_control(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test error message when no version matches without release control flags.\n\n    This verifies the generic \"Could not find a version\" message is shown\n    when release control isn't restricting to final versions only.\n    \"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    # Request a version that doesn't exist, without any release control flags\n    result = script.pip_install_local(\n        \"simple==2.0\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert \"Could not find a version that satisfies the requirement\" in result.stderr\n    # Ensure it's NOT saying \"final version\"\n    assert \"Could not find a final version\" not in result.stderr\n\n\ndef test_no_matching_version_with_all_releases(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test error message when no version matches with --all-releases.\n\n    This verifies the generic \"Could not find a version\" message is shown\n    when --all-releases is used (not restricting to final versions).\n    \"\"\"\n    pkg_path = create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    # Request a version that doesn't exist, with --all-releases\n    result = script.pip_install_local(\n        \"--all-releases=:all:\",\n        \"simple==2.0\",\n        find_links=[pkg_path.parent],\n        expect_error=True,\n    )\n    assert \"Could not find a version that satisfies the requirement\" in result.stderr\n\n\ndef test_pre_flag_with_requirements_file_containing_options(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test --pre on command line works with requirements file options.\n\n    Requirements file options overwrote command-line release control.\n    \"\"\"\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"2.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {pre_pkg.parent.as_posix()}\\nsimple\\n\",\n    )\n\n    report = script.pip_install_local_report(\"-r\", req_file, find_links=[])\n    assert len(report[\"install\"]) == 1\n    assert report[\"install\"][0][\"metadata\"][\"version\"] == \"1.0\"\n\n    report = script.pip_install_local_report(\"--pre\", \"-r\", req_file, find_links=[])\n    assert len(report[\"install\"]) == 1\n    assert report[\"install\"][0][\"metadata\"][\"version\"] == \"2.0a1\"\n\n\ndef test_reqfile_all_releases_overrides_cmdline_only_final(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test requirements file --all-releases overrides command line --only-final.\"\"\"\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"2.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {pre_pkg.parent.as_posix()}\\n--all-releases :all:\\nsimple\\n\",\n    )\n\n    report = script.pip_install_local_report(\n        \"--only-final=:all:\", \"-r\", req_file, find_links=[]\n    )\n    assert len(report[\"install\"]) == 1\n    assert report[\"install\"][0][\"metadata\"][\"version\"] == \"2.0a1\"\n\n\ndef test_reqfile_only_final_overrides_cmdline_all_releases(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test requirements file --only-final overrides command line --all-releases.\"\"\"\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"2.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {pre_pkg.parent.as_posix()}\\n--only-final :all:\\nsimple\\n\",\n    )\n\n    report = script.pip_install_local_report(\n        \"--all-releases=:all:\", \"-r\", req_file, find_links=[]\n    )\n    assert len(report[\"install\"]) == 1\n    assert report[\"install\"][0][\"metadata\"][\"version\"] == \"1.0\"\n\n\ndef test_package_specific_overrides_all_in_requirements_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"Test package-specific setting overrides :all: in requirements file.\"\"\"\n    pre_pkg = create_basic_wheel_for_package(script, \"simple\", \"2.0a1\")\n    create_basic_wheel_for_package(script, \"simple\", \"1.0\")\n\n    req_file = script.temporary_file(\n        \"requirements.txt\",\n        f\"--find-links {pre_pkg.parent.as_posix()}\\n--all-releases :all:\\n\"\n        \"--only-final simple\\nsimple\\n\",\n    )\n\n    report = script.pip_install_local_report(\"-r\", req_file, find_links=[])\n    assert len(report[\"install\"]) == 1\n    assert report[\"install\"][0][\"metadata\"][\"version\"] == \"1.0\"\n"
  },
  {
    "path": "tests/functional/test_install_report.py",
    "content": "import json\nimport textwrap\nfrom pathlib import Path\nfrom typing import Any\n\nimport pytest\nfrom packaging.utils import canonicalize_name\n\nfrom ..lib import PipTestEnvironment, TestData\n\n\ndef _install_dict(report: dict[str, Any]) -> dict[str, Any]:\n    return {canonicalize_name(i[\"metadata\"][\"name\"]): i for i in report[\"install\"]}\n\n\ndef test_install_report_basic(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"simplewheel\",\n        \"--dry-run\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert \"install\" in report\n    assert len(report[\"install\"]) == 1\n    simplewheel_report = _install_dict(report)[\"simplewheel\"]\n    assert simplewheel_report[\"metadata\"][\"name\"] == \"simplewheel\"\n    assert simplewheel_report[\"requested\"] is True\n    assert simplewheel_report[\"is_direct\"] is False\n    url = simplewheel_report[\"download_info\"][\"url\"]\n    assert url.startswith(\"file://\")\n    assert url.endswith(\"/packages/simplewheel-2.0-1-py2.py3-none-any.whl\")\n    assert (\n        simplewheel_report[\"download_info\"][\"archive_info\"][\"hash\"]\n        == \"sha256=71e1ca6b16ae3382a698c284013f66504f2581099b2ce4801f60e9536236ceee\"\n    )\n\n\ndef test_install_report_dep(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    \"\"\"Test dependencies are present in the install report with requested=False.\"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"require_simple\",\n        \"--dry-run\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 2\n    assert _install_dict(report)[\"require-simple\"][\"requested\"] is True\n    assert _install_dict(report)[\"simple\"][\"requested\"] is False\n\n\ndef test_yanked_version(\n    script: PipTestEnvironment, data: TestData, tmp_path: Path\n) -> None:\n    \"\"\"\n    Test is_yanked is True when explicitly requesting a yanked package.\n    Yanked files are always ignored, unless they are the only file that\n    matches a version specifier that \"pins\" to an exact version (PEP 592).\n    \"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"simple==3.0\",\n        \"--index-url\",\n        data.index_url(\"yanked\"),\n        \"--dry-run\",\n        \"--report\",\n        str(report_path),\n        allow_stderr_warning=True,\n    )\n    report = json.loads(report_path.read_text())\n    simple_report = _install_dict(report)[\"simple\"]\n    assert simple_report[\"requested\"] is True\n    assert simple_report[\"is_direct\"] is False\n    assert simple_report[\"is_yanked\"] is True\n    assert simple_report[\"metadata\"][\"version\"] == \"3.0\"\n\n\ndef test_skipped_yanked_version(\n    script: PipTestEnvironment, data: TestData, tmp_path: Path\n) -> None:\n    \"\"\"\n    Test is_yanked is False when not explicitly requesting a yanked package.\n    Yanked files are always ignored, unless they are the only file that\n    matches a version specifier that \"pins\" to an exact version (PEP 592).\n    \"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"simple\",\n        \"--index-url\",\n        data.index_url(\"yanked\"),\n        \"--dry-run\",\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    simple_report = _install_dict(report)[\"simple\"]\n    assert simple_report[\"requested\"] is True\n    assert simple_report[\"is_direct\"] is False\n    assert simple_report[\"is_yanked\"] is False\n    assert simple_report[\"metadata\"][\"version\"] == \"2.0\"\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\n    \"specifiers\",\n    [\n        # result should be the same regardless of the method and order in which\n        # extras are specified\n        (\"Paste[openid]==1.7.5.1\",),\n        (\"Paste==1.7.5.1\", \"Paste[openid]==1.7.5.1\"),\n        (\"Paste[openid]==1.7.5.1\", \"Paste==1.7.5.1\"),\n    ],\n)\ndef test_install_report_index(\n    script: PipTestEnvironment, tmp_path: Path, specifiers: tuple[str, ...]\n) -> None:\n    \"\"\"Test report for sdist obtained from index.\"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--dry-run\",\n        *specifiers,\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 2\n    install_dict = _install_dict(report)\n    assert install_dict[\"paste\"][\"requested\"] is True\n    assert install_dict[\"python-openid\"][\"requested\"] is False\n    paste_report = install_dict[\"paste\"]\n    assert paste_report[\"download_info\"][\"url\"].startswith(\n        \"https://files.pythonhosted.org/\"\n    )\n    assert paste_report[\"download_info\"][\"url\"].endswith(\"/Paste-1.7.5.1.tar.gz\")\n    assert (\n        paste_report[\"download_info\"][\"archive_info\"][\"hash\"]\n        == \"sha256=11645842ba8ec986ae8cfbe4c6cacff5c35f0f4527abf4f5581ae8b4ad49c0b6\"\n    )\n    assert paste_report[\"requested_extras\"] == [\"openid\"]\n    assert \"requires_dist\" in paste_report[\"metadata\"]\n\n\n@pytest.mark.network\ndef test_install_report_index_multiple_extras(\n    script: PipTestEnvironment, tmp_path: Path\n) -> None:\n    \"\"\"Test report for sdist obtained from index, with multiple extras requested.\"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--dry-run\",\n        \"Paste[openid]\",\n        \"Paste[subprocess]\",\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    install_dict = _install_dict(report)\n    assert \"paste\" in install_dict\n    assert install_dict[\"paste\"][\"requested_extras\"] == [\"openid\", \"subprocess\"]\n\n\ndef test_install_report_direct_archive(\n    script: PipTestEnvironment, tmp_path: Path, shared_data: TestData\n) -> None:\n    \"\"\"Test report for direct URL archive.\"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        str(shared_data.root / \"packages\" / \"simplewheel-1.0-py2.py3-none-any.whl\"),\n        \"--dry-run\",\n        \"--no-index\",\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert \"install\" in report\n    assert len(report[\"install\"]) == 1\n    simplewheel_report = _install_dict(report)[\"simplewheel\"]\n    assert simplewheel_report[\"metadata\"][\"name\"] == \"simplewheel\"\n    assert simplewheel_report[\"requested\"] is True\n    assert simplewheel_report[\"is_direct\"] is True\n    url = simplewheel_report[\"download_info\"][\"url\"]\n    assert url.startswith(\"file://\")\n    assert url.endswith(\"/packages/simplewheel-1.0-py2.py3-none-any.whl\")\n    assert (\n        simplewheel_report[\"download_info\"][\"archive_info\"][\"hash\"]\n        == \"sha256=e63aa139caee941ec7f33f057a5b987708c2128238357cf905429846a2008718\"\n    )\n    assert simplewheel_report[\"download_info\"][\"archive_info\"][\"hashes\"] == {\n        \"sha256\": \"e63aa139caee941ec7f33f057a5b987708c2128238357cf905429846a2008718\"\n    }\n\n\n@pytest.mark.network\ndef test_install_report_vcs_and_wheel_cache(\n    script: PipTestEnvironment, tmp_path: Path\n) -> None:\n    \"\"\"Test report for VCS reference, and interactions with the wheel cache.\"\"\"\n    cache_dir = tmp_path / \"cache\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"git+https://github.com/pypa/pip-test-package\"\n        \"@5547fa909e83df8bd743d3978d6667497983a4b7\",\n        \"--cache-dir\",\n        str(cache_dir),\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 1\n    pip_test_package_report = report[\"install\"][0]\n    assert pip_test_package_report[\"is_direct\"] is True\n    assert pip_test_package_report[\"requested\"] is True\n    assert (\n        pip_test_package_report[\"download_info\"][\"url\"]\n        == \"https://github.com/pypa/pip-test-package\"\n    )\n    assert pip_test_package_report[\"download_info\"][\"vcs_info\"][\"vcs\"] == \"git\"\n    assert (\n        pip_test_package_report[\"download_info\"][\"vcs_info\"][\"commit_id\"]\n        == \"5547fa909e83df8bd743d3978d6667497983a4b7\"\n    )\n    # Now do it again to make sure the cache is used and that the report still contains\n    # the original VCS url.\n    report_path.unlink()\n    result = script.pip(\n        \"install\",\n        \"pip-test-package @ git+https://github.com/pypa/pip-test-package\"\n        \"@5547fa909e83df8bd743d3978d6667497983a4b7\",\n        \"--ignore-installed\",\n        \"--cache-dir\",\n        str(cache_dir),\n        \"--report\",\n        str(report_path),\n    )\n    assert \"Using cached pip_test_package\" in result.stdout\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 1\n    pip_test_package_report = report[\"install\"][0]\n    assert pip_test_package_report[\"is_direct\"] is True\n    assert pip_test_package_report[\"requested\"] is True\n    assert (\n        pip_test_package_report[\"download_info\"][\"url\"]\n        == \"https://github.com/pypa/pip-test-package\"\n    )\n    assert pip_test_package_report[\"download_info\"][\"vcs_info\"][\"vcs\"] == \"git\"\n    assert (\n        pip_test_package_report[\"download_info\"][\"vcs_info\"][\"commit_id\"]\n        == \"5547fa909e83df8bd743d3978d6667497983a4b7\"\n    )\n\n\n@pytest.mark.network\ndef test_install_report_vcs_editable(\n    script: PipTestEnvironment, tmp_path: Path\n) -> None:\n    \"\"\"Test report remote editable.\"\"\"\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--editable\",\n        \"git+https://github.com/pypa/pip-test-package\"\n        \"@5547fa909e83df8bd743d3978d6667497983a4b7\"\n        \"#egg=pip-test-package\",\n        \"--report\",\n        str(report_path),\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 1\n    pip_test_package_report = report[\"install\"][0]\n    assert pip_test_package_report[\"is_direct\"] is True\n    assert pip_test_package_report[\"download_info\"][\"url\"].startswith(\"file://\")\n    assert pip_test_package_report[\"download_info\"][\"url\"].endswith(\n        \"/src/pip-test-package\"\n    )\n    assert pip_test_package_report[\"download_info\"][\"dir_info\"][\"editable\"] is True\n\n\ndef test_install_report_local_path_with_extras(\n    script: PipTestEnvironment, tmp_path: Path, shared_data: TestData\n) -> None:\n    \"\"\"Test report remote editable.\"\"\"\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n\n            [project.optional-dependencies]\n            test = [\"simple\"]\n            \"\"\"\n        )\n    )\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--dry-run\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        \"--report\",\n        str(report_path),\n        str(project_path) + \"[test]\",\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 2\n    pkga_report = report[\"install\"][0]\n    assert pkga_report[\"metadata\"][\"name\"] == \"pkga\"\n    assert pkga_report[\"is_direct\"] is True\n    assert pkga_report[\"requested\"] is True\n    assert pkga_report[\"requested_extras\"] == [\"test\"]\n    simple_report = report[\"install\"][1]\n    assert simple_report[\"metadata\"][\"name\"] == \"simple\"\n    assert simple_report[\"is_direct\"] is False\n    assert simple_report[\"requested\"] is False\n    assert \"requested_extras\" not in simple_report\n\n\ndef test_install_report_editable_local_path_with_extras(\n    script: PipTestEnvironment, tmp_path: Path, shared_data: TestData\n) -> None:\n    \"\"\"Test report remote editable.\"\"\"\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n\n            [project.optional-dependencies]\n            test = [\"simple\"]\n            \"\"\"\n        )\n    )\n    report_path = tmp_path / \"report.json\"\n    script.pip(\n        \"install\",\n        \"--dry-run\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        \"--report\",\n        str(report_path),\n        \"--editable\",\n        str(project_path) + \"[test]\",\n    )\n    report = json.loads(report_path.read_text())\n    assert len(report[\"install\"]) == 2\n    pkga_report = report[\"install\"][0]\n    assert pkga_report[\"metadata\"][\"name\"] == \"pkga\"\n    assert pkga_report[\"is_direct\"] is True\n    assert pkga_report[\"requested\"] is True\n    assert pkga_report[\"requested_extras\"] == [\"test\"]\n    simple_report = report[\"install\"][1]\n    assert simple_report[\"metadata\"][\"name\"] == \"simple\"\n    assert simple_report[\"is_direct\"] is False\n    assert simple_report[\"requested\"] is False\n    assert \"requested_extras\" not in simple_report\n\n\ndef test_install_report_to_stdout(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    result = script.pip(\n        \"install\",\n        \"simplewheel\",\n        \"--quiet\",\n        \"--dry-run\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        \"--report\",\n        \"-\",\n    )\n    report = json.loads(result.stdout)\n    assert \"install\" in report\n    assert len(report[\"install\"]) == 1\n"
  },
  {
    "path": "tests/functional/test_install_reqs.py",
    "content": "import json\nimport os\nimport textwrap\nfrom pathlib import Path\nfrom typing import Any, Protocol\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    ResolverVariant,\n    TestData,\n    _create_test_package,\n    _create_test_package_with_subdirectory,\n    create_basic_sdist_for_package,\n    create_basic_wheel_for_package,\n    need_svn,\n    requirements_file,\n)\nfrom tests.lib.local_repos import local_checkout\n\n\nclass ArgRecordingSdist:\n    def __init__(self, sdist_path: Path, args_path: Path) -> None:\n        self.sdist_path = sdist_path\n        self._args_path = args_path\n\n    def args(self) -> Any:\n        return json.loads(self._args_path.read_text())\n\n\nclass ArgRecordingSdistMaker(Protocol):\n    def __call__(self, name: str, **kwargs: Any) -> ArgRecordingSdist: ...\n\n\n@pytest.fixture\ndef arg_recording_sdist_maker(\n    script: PipTestEnvironment,\n) -> ArgRecordingSdistMaker:\n    arg_writing_setup_py_prelude = textwrap.dedent(\n        \"\"\"\n        import io\n        import json\n        import os\n        import sys\n\n        args_path = os.path.join(os.environ[\"OUTPUT_DIR\"], \"{name}.json\")\n        with open(args_path, 'w') as f:\n            json.dump(sys.argv, f)\n        \"\"\"\n    )\n    output_dir = script.scratch_path.joinpath(\"args_recording_sdist_maker_output\")\n    output_dir.mkdir(parents=True)\n    script.environ[\"OUTPUT_DIR\"] = str(output_dir)\n\n    def _arg_recording_sdist_maker(\n        name: str,\n        **kwargs: Any,\n    ) -> ArgRecordingSdist:\n        sdist_path = create_basic_sdist_for_package(\n            script,\n            name,\n            \"0.1.0\",\n            setup_py_prelude=arg_writing_setup_py_prelude.format(name=name),\n            **kwargs,\n        )\n        args_path = output_dir / f\"{name}.json\"\n        return ArgRecordingSdist(sdist_path, args_path)\n\n    return _arg_recording_sdist_maker\n\n\ndef test_requirements_file(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test installing from a requirements file.\n\n    \"\"\"\n    file = script.temporary_multiline_file(\n        \"initools-req.txt\",\n        \"\"\"\\\n        INITools==0.2\n        # and something else to test out:\n        six>=1.0.0\n        \"\"\",\n    )\n    script.pip_install_local(\n        \"-r\", file, find_links=[data.pypi_packages, data.common_wheels]\n    )\n    script.assert_installed(initools=\"0.2\", six=\"1.17.0\")\n\n\n@pytest.mark.parametrize(\n    \"path, groupname\",\n    [\n        (None, \"reqs\"),\n        (\"pyproject.toml\", \"reqs\"),\n        (\"./pyproject.toml\", \"reqs\"),\n        (lambda path: path.absolute(), \"reqs\"),\n    ],\n)\ndef test_dependency_group(\n    script: PipTestEnvironment,\n    path: Any,\n    groupname: str,\n) -> None:\n    \"\"\"\n    Test installing from a dependency group.\n    \"\"\"\n    pyproject = script.temporary_multiline_file(\n        \"pyproject.toml\",\n        \"\"\"\\\n            [dependency-groups]\n            reqs = [\n                \"simple.dist==0.1\",\n                \"simplewheel<2\",\n            ]\n            \"\"\",\n    )\n    if path is None:\n        arg = groupname\n    else:\n        if callable(path):\n            path = path(pyproject)\n        arg = f\"{path}:{groupname}\"\n    script.pip_install_local(\"--group\", arg)\n    script.assert_installed(**{\"simple.dist\": \"0.1\", \"simplewheel\": \"1.0\"})\n\n\ndef test_multiple_dependency_groups(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from two dependency groups simultaneously.\n    \"\"\"\n    script.temporary_multiline_file(\n        \"pyproject.toml\",\n        \"\"\"\\\n            [dependency-groups]\n            simple = [\"simple.dist==0.1\"]\n            othersimple = [\"simplewheel<2\"]\n            \"\"\",\n    )\n    script.pip_install_local(\"--group\", \"simple\", \"--group\", \"othersimple\")\n    script.assert_installed(**{\"simple.dist\": \"0.1\", \"simplewheel\": \"1.0\"})\n\n\ndef test_dependency_group_with_non_normalized_name(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a dependency group with a non-normalized name, verifying that\n    the pyproject.toml content and CLI arg are normalized to match.\n    \"\"\"\n    script.temporary_multiline_file(\n        \"pyproject.toml\",\n        \"\"\"\\\n            [dependency-groups]\n            INITOOLS = [\"simplewheel==1.0\"]\n            \"\"\",\n    )\n    script.pip_install_local(\"--group\", \"IniTools\")\n    script.assert_installed(simplewheel=\"1.0\")\n\n\ndef test_schema_check_in_requirements_file(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a requirements file with an invalid vcs schema..\n\n    \"\"\"\n    script.scratch_path.joinpath(\"file-egg-req.txt\").write_text(\n        \"\\n{}\\n\".format(\n            \"git://github.com/alex/django-fixture-generator.git#egg=fixture_generator\"\n        )\n    )\n\n    with pytest.raises(AssertionError):\n        script.pip(\"install\", \"-vvv\", \"-r\", script.scratch_path / \"file-egg-req.txt\")\n\n\n@pytest.mark.parametrize(\n    \"test_type,editable\",\n    [\n        (\"rel_path\", False),\n        (\"rel_path\", True),\n        (\"rel_url\", False),\n        (\"rel_url\", True),\n        (\"embedded_rel_path\", False),\n        (\"embedded_rel_path\", True),\n    ],\n)\ndef test_relative_requirements_file(\n    script: PipTestEnvironment, data: TestData, test_type: str, editable: bool\n) -> None:\n    \"\"\"\n    Test installing from a requirements file with a relative path. For path\n    URLs, use an egg= definition.\n\n    \"\"\"\n    dist_info_folder = script.site_packages / \"fspkg-0.1.dev0.dist-info\"\n    package_folder = script.site_packages / \"fspkg\"\n\n    # Compute relative install path to FSPkg from scratch path.\n    full_rel_path = os.path.relpath(\n        data.packages.joinpath(\"FSPkg\"), script.scratch_path\n    )\n    full_rel_url = \"file:\" + full_rel_path + \"#egg=FSPkg\"\n    embedded_rel_path = script.scratch_path.joinpath(full_rel_path)\n\n    req_path = {\n        \"rel_path\": full_rel_path,\n        \"rel_url\": full_rel_url,\n        \"embedded_rel_path\": os.fspath(embedded_rel_path),\n    }[test_type]\n\n    req_path = req_path.replace(os.path.sep, \"/\")\n    # Install as either editable or not.\n    if not editable:\n        with requirements_file(req_path + \"\\n\", script.scratch_path) as reqs_file:\n            result = script.pip(\n                \"install\",\n                \"--no-build-isolation\",\n                \"-vvv\",\n                \"-r\",\n                reqs_file.name,\n                cwd=script.scratch_path,\n            )\n            result.did_create(dist_info_folder)\n            result.did_create(package_folder)\n    else:\n        with requirements_file(\n            \"-e \" + req_path + \"\\n\", script.scratch_path\n        ) as reqs_file:\n            result = script.pip(\n                \"install\",\n                \"--no-build-isolation\",\n                \"-vvv\",\n                \"-r\",\n                reqs_file.name,\n                cwd=script.scratch_path,\n            )\n            direct_url = result.get_created_direct_url(\"fspkg\")\n            assert direct_url\n            assert direct_url.is_local_editable()\n\n\n@pytest.mark.xfail\n@pytest.mark.network\n@need_svn\ndef test_multiple_requirements_files(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"\n    Test installing from multiple nested requirements files.\n\n    \"\"\"\n    other_lib_name, other_lib_version = \"six\", \"1.16.0\"\n    script.scratch_path.joinpath(\"initools-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            -e {}@10#egg=INITools\n            -r {}-req.txt\n        \"\"\"\n        ).format(\n            local_checkout(\"svn+http://svn.colorstudy.com/INITools\", tmpdir),\n            other_lib_name,\n        ),\n    )\n    script.scratch_path.joinpath(f\"{other_lib_name}-req.txt\").write_text(\n        f\"{other_lib_name}<={other_lib_version}\"\n    )\n    result = script.pip(\"install\", \"-r\", script.scratch_path / \"initools-req.txt\")\n    assert result.files_created[script.site_packages / other_lib_name].dir\n    fn = f\"{other_lib_name}-{other_lib_version}.dist-info\"\n    assert result.files_created[script.site_packages / fn].dir\n    result.did_create(script.venv / \"src\" / \"initools\")\n\n\ndef test_package_in_constraints_and_dependencies(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\n        \"TopoRequires2==0.0.1\\nTopoRequires==0.0.1\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"TopoRequires2\",\n    )\n    assert \"installed TopoRequires-0.0.1\" in result.stdout\n\n\ndef test_constraints_apply_to_dependency_groups(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"TopoRequires==0.0.1\")\n    pyproject = script.scratch_path / \"pyproject.toml\"\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups]\n            mylibs = [\"TopoRequires2\"]\n            \"\"\"\n        )\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"--group\",\n        \"mylibs\",\n    )\n    assert \"installed TopoRequires-0.0.1\" in result.stdout\n\n\ndef test_multiple_constraints_files(script: PipTestEnvironment, data: TestData) -> None:\n    script.scratch_path.joinpath(\"outer.txt\").write_text(\"-c inner.txt\")\n    script.scratch_path.joinpath(\"inner.txt\").write_text(\"Upper==1.0\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"outer.txt\",\n        \"Upper\",\n    )\n    assert \"installed Upper-1.0\" in result.stdout\n\n\n# FIXME: Unclear what this guarantee is for.\ndef test_respect_order_in_requirements_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"frameworks-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        parent\n        child\n        simple\n        \"\"\"\n        )\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-r\",\n        script.scratch_path / \"frameworks-req.txt\",\n    )\n\n    downloaded = [line for line in result.stdout.split(\"\\n\") if \"Processing\" in line]\n\n    assert (\n        \"parent\" in downloaded[0]\n    ), f'First download should be \"parent\" but was \"{downloaded[0]}\"'\n    assert (\n        \"child\" in downloaded[1]\n    ), f'Second download should be \"child\" but was \"{downloaded[1]}\"'\n    assert (\n        \"simple\" in downloaded[2]\n    ), f'Third download should be \"simple\" but was \"{downloaded[2]}\"'\n\n\ndef test_install_local_editable_with_extras(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    res = script.pip_install_local(\n        \"-e\", f\"{to_install}[bar]\", allow_stderr_warning=True\n    )\n    res.assert_installed(\"LocalExtras\", editable=True, editable_vcs=False)\n    res.assert_installed(\"simple\", editable=False)\n\n\ndef test_install_collected_dependencies_first(script: PipTestEnvironment) -> None:\n    result = script.pip_install_local(\n        \"toporequires2\",\n    )\n    text = [line for line in result.stdout.split(\"\\n\") if \"Installing\" in line][0]\n    assert text.endswith(\"toporequires2\")\n\n\n@pytest.mark.network\ndef test_install_local_editable_with_subdirectory(script: PipTestEnvironment) -> None:\n    version_pkg_path = _create_test_package_with_subdirectory(script, \"version_subdir\")\n    result = script.pip(\n        \"install\",\n        \"-e\",\n        \"{uri}#egg=version_subpkg&subdirectory=version_subdir\".format(\n            uri=f\"git+{version_pkg_path.as_uri()}\",\n        ),\n    )\n\n    result.assert_installed(\"version_subpkg\", sub_dir=\"version_subdir\")\n\n\n@pytest.mark.network\ndef test_install_local_with_subdirectory(script: PipTestEnvironment) -> None:\n    version_pkg_path = _create_test_package_with_subdirectory(script, \"version_subdir\")\n    result = script.pip(\n        \"install\",\n        \"{uri}#egg=version_subpkg&subdirectory=version_subdir\".format(\n            uri=f\"git+{version_pkg_path.as_uri()}\",\n        ),\n    )\n\n    result.assert_installed(\"version_subpkg.py\", editable=False)\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_wheel_user_with_prefix_in_pydistutils_cfg(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    if os.name == \"posix\":\n        user_filename = \".pydistutils.cfg\"\n    else:\n        user_filename = \"pydistutils.cfg\"\n    user_cfg = os.path.join(os.path.expanduser(\"~\"), user_filename)\n    script.scratch_path.joinpath(\"bin\").mkdir()\n    with open(user_cfg, \"w\") as cfg:\n        cfg.write(\n            textwrap.dedent(\n                f\"\"\"\n            [install]\n            prefix={script.scratch_path}\"\"\"\n            )\n        )\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--user\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"requiresupper\",\n    )\n    # Check that we are really installing a wheel\n    assert \"installed requiresupper\" in result.stdout\n\n\ndef test_constraints_not_installed_by_default(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"c.txt\").write_text(\"requiresupper\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"c.txt\",\n        \"Upper\",\n    )\n    assert \"requiresupper\" not in result.stdout\n\n\ndef test_constraints_only_causes_error(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"c.txt\").write_text(\"requiresupper\")\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"c.txt\",\n        expect_error=True,\n    )\n    assert \"installed requiresupper\" not in result.stdout\n\n\ndef test_constraints_local_editable_install_causes_error(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"singlemodule==0.0.0\")\n    to_install = data.src.joinpath(\"singlemodule\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"-e\",\n        to_install,\n        expect_error=True,\n    )\n    # Because singlemodule only has 0.0.1 available.\n    assert \"Cannot install singlemodule 0.0.1\" in result.stderr, str(result)\n\n\n@pytest.mark.network\ndef test_constraints_local_editable_install_pep518(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.src.joinpath(\"pep518-3.0\")\n\n    script.pip(\"download\", \"setuptools\", \"-d\", data.packages)\n    script.pip(\"install\", \"--no-index\", \"-f\", data.find_links, \"-e\", to_install)\n\n\ndef test_constraints_local_install_causes_error(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"singlemodule==0.0.0\")\n    to_install = data.src.joinpath(\"singlemodule\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        to_install,\n        expect_error=True,\n    )\n    # Because singlemodule only has 0.0.1 available.\n    assert \"Cannot install singlemodule 0.0.1\" in result.stderr, str(result)\n\n\ndef test_constraints_constrain_to_local_editable(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    to_install = data.src.joinpath(\"singlemodule\")\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\n        f\"-e {to_install.as_uri()}#egg=singlemodule\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"singlemodule\",\n        allow_stderr_warning=True,\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert \"Editable requirements are not allowed as constraints\" in result.stderr\n    else:\n        assert \"Running setup.py develop for singlemodule\" in result.stdout\n\n\ndef test_constraints_constrain_to_local(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    to_install = data.src.joinpath(\"singlemodule\")\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\n        f\"{to_install.as_uri()}#egg=singlemodule\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"singlemodule\",\n        allow_stderr_warning=True,\n    )\n    assert \"Building wheel for singlemodule\" in result.stdout\n\n\ndef test_constrained_to_url_install_same_url(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.src.joinpath(\"singlemodule\")\n    constraints = f\"{to_install.as_uri()}#egg=singlemodule\"\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(constraints)\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        to_install,\n        allow_stderr_warning=True,\n    )\n    assert \"Building wheel for singlemodule\" in result.stdout, str(result)\n\n\ndef test_double_install_spurious_hash_mismatch(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData\n) -> None:\n    \"\"\"Make sure installing the same hashed sdist twice doesn't throw hash\n    mismatch errors.\n\n    Really, this is a test that we disable reads from the wheel cache in\n    hash-checking mode. Locally, implicitly built wheels of sdists obviously\n    have different hashes from the original archives. Comparing against those\n    causes spurious mismatch errors.\n\n    \"\"\"\n    # Install wheel package, otherwise, it won't try to build wheels.\n    with requirements_file(\n        \"simple==1.0 --hash=sha256:393043e672415891885c9a2a\"\n        \"0929b1af95fb866d6ca016b42d2e6ce53619b653\",\n        tmpdir,\n    ) as reqs_file:\n        # Install a package (and build its wheel):\n        result = script.pip_install_local(\n            \"--find-links\",\n            data.find_links,\n            \"-r\",\n            reqs_file.resolve(),\n        )\n        assert \"Successfully installed simple-1.0\" in str(result)\n\n        # Uninstall it:\n        script.pip(\"uninstall\", \"-y\", \"simple\")\n\n        # Then install it again. We should not hit a hash mismatch, and the\n        # package should install happily.\n        result = script.pip_install_local(\n            \"--find-links\",\n            data.find_links,\n            \"-r\",\n            reqs_file.resolve(),\n        )\n        assert \"Successfully installed simple-1.0\" in str(result)\n\n\ndef test_install_with_extras_from_constraints(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    file = script.temporary_file(\n        \"constraints.txt\", f\"LocalExtras[bar] @ {to_install.as_uri()}\"\n    )\n    result = script.pip_install_local(\n        \"-c\",\n        file,\n        \"LocalExtras\",\n        allow_stderr_warning=True,\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert \"Constraints cannot have extras\" in result.stderr\n    else:\n        result.did_create(script.site_packages / \"simple\")\n\n\ndef test_install_with_extras_from_install(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        name=\"LocalExtras\",\n        version=\"0.0.1\",\n        extras={\"bar\": [\"simple\"], \"baz\": [\"singlemodule\"]},\n    )\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"LocalExtras\")\n    result = script.pip_install_local(\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"LocalExtras[baz]\",\n    )\n    result.did_create(script.site_packages / \"singlemodule.py\")\n\n\ndef test_install_with_extras_joined(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    file = script.temporary_file(\n        \"constraints.txt\", f\"LocalExtras[bar] @ {to_install.as_uri()}\"\n    )\n    result = script.pip_install_local(\n        \"-c\",\n        file,\n        \"LocalExtras[baz]\",\n        allow_stderr_warning=True,\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert \"Constraints cannot have extras\" in result.stderr\n    else:\n        result.did_create(script.site_packages / \"simple\")\n        result.did_create(script.site_packages / \"singlemodule.py\")\n\n\ndef test_install_with_extras_editable_joined(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    file = script.temporary_file(\n        \"constraints.txt\", f\"-e LocalExtras[bar] @ {to_install.as_uri()}\"\n    )\n    result = script.pip_install_local(\n        \"-c\",\n        file,\n        \"LocalExtras[baz]\",\n        allow_stderr_warning=True,\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert \"Editable requirements are not allowed as constraints\" in result.stderr\n    else:\n        result.did_create(script.site_packages / \"simple\")\n        result.did_create(script.site_packages / \"singlemodule.py\")\n\n\ndef test_install_distribution_full_union(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    result = script.pip_install_local(\n        to_install, f\"{to_install}[bar]\", f\"{to_install}[baz]\"\n    )\n    assert \"Building wheel for LocalExtras\" in result.stdout\n    result.did_create(script.site_packages / \"simple\")\n    result.did_create(script.site_packages / \"singlemodule.py\")\n\n\ndef test_install_distribution_duplicate_extras(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    package_name = f\"{to_install}[bar]\"\n    result = script.pip_install_local(package_name, package_name)\n    unexpected = f\"Double requirement given: {package_name}\"\n    assert unexpected not in result.stderr\n\n\ndef test_install_distribution_union_with_constraints(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    to_install = data.packages.joinpath(\"LocalExtras\")\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(f\"{to_install}[bar]\")\n    result = script.pip_install_local(\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        f\"{to_install}[baz]\",\n        allow_stderr_warning=True,\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        msg = \"Unnamed requirements are not allowed as constraints\"\n        assert msg in result.stderr\n    else:\n        assert \"Building wheel for LocalExtras\" in result.stdout\n        result.did_create(script.site_packages / \"singlemodule.py\")\n\n\ndef test_install_distribution_union_with_versions(\n    script: PipTestEnvironment,\n    data: TestData,\n    resolver_variant: ResolverVariant,\n) -> None:\n    to_install_001 = data.packages.joinpath(\"LocalExtras\")\n    to_install_002 = data.packages.joinpath(\"LocalExtras-0.0.2\")\n    result = script.pip_install_local(\n        f\"{to_install_001}[bar]\",\n        f\"{to_install_002}[baz]\",\n        expect_error=(resolver_variant == \"resolvelib\"),\n    )\n    if resolver_variant == \"resolvelib\":\n        assert \"Cannot install localextras\" in result.stderr\n        assert (\"The user requested localextras 0.0.1\") in result.stdout\n        assert (\"The user requested localextras 0.0.2\") in result.stdout\n    else:\n        assert (\n            \"Successfully installed LocalExtras-0.0.1 simple-3.0 singlemodule-0.0.1\"\n        ) in result.stdout\n\n\n@pytest.mark.xfail\ndef test_install_distribution_union_conflicting_extras(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    # LocalExtras requires simple==1.0, LocalExtras[bar] requires simple==2.0;\n    # without a resolver, pip does not detect the conflict between simple==1.0\n    # and simple==2.0. Once a resolver is added, this conflict should be\n    # detected.\n    to_install = data.packages.joinpath(\"LocalExtras-0.0.2\")\n    result = script.pip_install_local(\n        to_install, f\"{to_install}[bar]\", expect_error=True\n    )\n    assert \"installed\" not in result.stdout\n    assert \"Conflict\" in result.stderr\n\n\ndef test_install_unsupported_wheel_link_with_marker(script: PipTestEnvironment) -> None:\n    script.scratch_path.joinpath(\"with-marker.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            {url}; {req}\n        \"\"\"\n        ).format(\n            url=\"https://github.com/a/b/c/asdf-1.5.2-cp27-none-xyz.whl\",\n            req='sys_platform == \"xyz\"',\n        )\n    )\n    result = script.pip(\"install\", \"-r\", script.scratch_path / \"with-marker.txt\")\n\n    assert (\n        \"Ignoring asdf: markers 'sys_platform == \\\"xyz\\\"' don't match your environment\"\n    ) in result.stdout\n    assert len(result.files_created) == 0\n\n\ndef test_install_unsupported_wheel_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    # Trying to install a local wheel with an incompatible version/type\n    # should fail.\n    path = data.packages.joinpath(\"simple.dist-0.1-py1-none-invalid.whl\")\n    script.scratch_path.joinpath(\"wheel-file.txt\").write_text(f\"{path}\\n\")\n    result = script.pip(\n        \"install\",\n        \"-r\",\n        script.scratch_path / \"wheel-file.txt\",\n        expect_error=True,\n        expect_stderr=True,\n    )\n    assert (\n        \"simple.dist-0.1-py1-none-invalid.whl is not a supported wheel on this platform\"\n        in result.stderr\n    )\n    assert len(result.files_created) == 0\n\n\ndef test_config_settings_local_to_package(\n    script: PipTestEnvironment,\n    common_wheels: Path,\n    arg_recording_sdist_maker: ArgRecordingSdistMaker,\n) -> None:\n    pyproject_toml = textwrap.dedent(\n        \"\"\"\n        [build-system]\n        requires = [\"setuptools\"]\n        build-backend = \"setuptools.build_meta\"\n        \"\"\"\n    )\n    simple0_sdist = arg_recording_sdist_maker(\n        \"simple0\",\n        extra_files={\"pyproject.toml\": pyproject_toml},\n        depends=[\"foo\"],\n    )\n    foo_sdist = arg_recording_sdist_maker(\n        \"foo\",\n        extra_files={\"pyproject.toml\": pyproject_toml},\n    )\n    simple1_sdist = arg_recording_sdist_maker(\n        \"simple1\",\n        extra_files={\"pyproject.toml\": pyproject_toml},\n        depends=[\"bar\"],\n    )\n    bar_sdist = arg_recording_sdist_maker(\n        \"bar\",\n        extra_files={\"pyproject.toml\": pyproject_toml},\n        depends=[\"simple3\"],\n    )\n    simple3_sdist = arg_recording_sdist_maker(\n        \"simple3\", extra_files={\"pyproject.toml\": pyproject_toml}\n    )\n    simple2_sdist = arg_recording_sdist_maker(\n        \"simple2\",\n        extra_files={\"pyproject.toml\": pyproject_toml},\n    )\n\n    reqs_file = script.scratch_path.joinpath(\"reqs.txt\")\n    reqs_file.write_text(\n        textwrap.dedent(\n            \"\"\"\n            simple0 --config-settings \"--build-option=--verbose\"\n            foo --config-settings \"--build-option=--quiet\"\n            simple1 --config-settings \"--build-option=--verbose\"\n            simple2\n            \"\"\"\n        )\n    )\n\n    script.pip_install_local(\n        \"--no-build-isolation\",\n        \"-r\",\n        reqs_file,\n        find_links=[script.scratch_path, common_wheels],\n    )\n\n    simple0_args = simple0_sdist.args()\n    assert \"--verbose\" in simple0_args\n    foo_args = foo_sdist.args()\n    assert \"--quiet\" in foo_args\n    simple1_args = simple1_sdist.args()\n    assert \"--verbose\" in simple1_args\n    bar_args = bar_sdist.args()\n    assert \"--verbose\" not in bar_args\n    simple3_args = simple3_sdist.args()\n    assert \"--verbose\" not in simple3_args\n    simple2_args = simple2_sdist.args()\n    assert \"--verbose\" not in simple2_args\n\n\nclass TestEditableDirectURL:\n    def test_install_local_project(\n        self, script: PipTestEnvironment, data: TestData, common_wheels: Path\n    ) -> None:\n        uri = (data.src / \"simplewheel-2.0\").as_uri()\n        script.pip(\n            \"install\", \"--no-index\", \"-e\", f\"simplewheel @ {uri}\", \"-f\", common_wheels\n        )\n        script.assert_installed(simplewheel=\"2.0\")\n\n    def test_install_local_project_with_extra(\n        self, script: PipTestEnvironment, data: TestData, common_wheels: Path\n    ) -> None:\n        uri = (data.src / \"requires_simple_extra\").as_uri()\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"-e\",\n            f\"requires-simple-extra[extra] @ {uri}\",\n            \"-f\",\n            common_wheels,\n            \"-f\",\n            data.packages,\n        )\n        script.assert_installed(requires_simple_extra=\"0.1\")\n        script.assert_installed(simple=\"1.0\")\n\n    def test_install_local_git_repo(\n        self, script: PipTestEnvironment, common_wheels: Path\n    ) -> None:\n        repo_path = _create_test_package(script.scratch_path, \"simple\")\n        url = \"git+\" + repo_path.as_uri()\n        script.pip(\n            \"install\", \"--no-index\", \"-e\", f\"simple @ {url}\", \"-f\", common_wheels\n        )\n        script.assert_installed(simple=\"0.1\")\n\n    @pytest.mark.network\n    def test_install_remote_git_repo_with_extra(\n        self, script: PipTestEnvironment, data: TestData, common_wheels: Path\n    ) -> None:\n        req = \"pip-test-package[extra] @ git+https://github.com/pypa/pip-test-package\"\n        script.pip(\n            \"install\", \"--no-index\", \"-e\", req, \"-f\", common_wheels, \"-f\", data.packages\n        )\n        script.assert_installed(pip_test_package=\"0.1.1\")\n        script.assert_installed(simple=\"3.0\")\n"
  },
  {
    "path": "tests/functional/test_install_requested.py",
    "content": "import pytest\n\nfrom tests.lib import PipTestEnvironment, TestData, TestPipResult\n\n\ndef _assert_requested_present(\n    script: PipTestEnvironment, result: TestPipResult, name: str, version: str\n) -> None:\n    dist_info = script.site_packages / f\"{name}-{version}.dist-info\"\n    requested = dist_info / \"REQUESTED\"\n    assert dist_info in result.files_created\n    assert requested in result.files_created\n\n\ndef _assert_requested_absent(\n    script: PipTestEnvironment, result: TestPipResult, name: str, version: str\n) -> None:\n    dist_info = script.site_packages / f\"{name}-{version}.dist-info\"\n    requested = dist_info / \"REQUESTED\"\n    assert dist_info in result.files_created\n    assert requested not in result.files_created\n\n\ndef test_install_requested_basic(script: PipTestEnvironment, data: TestData) -> None:\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"require_simple\",\n    )\n    _assert_requested_present(script, result, \"require_simple\", \"1.0\")\n    # dependency is not REQUESTED\n    _assert_requested_absent(script, result, \"simple\", \"3.0\")\n\n\ndef test_install_requested_requirements(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"requirements.txt\").write_text(\"require_simple\\n\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-r\",\n        script.scratch_path / \"requirements.txt\",\n    )\n    _assert_requested_present(script, result, \"require_simple\", \"1.0\")\n    _assert_requested_absent(script, result, \"simple\", \"3.0\")\n\n\ndef test_install_requested_dep_in_requirements(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"requirements.txt\").write_text(\n        \"require_simple\\nsimple<3\\n\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-r\",\n        script.scratch_path / \"requirements.txt\",\n    )\n    _assert_requested_present(script, result, \"require_simple\", \"1.0\")\n    # simple must have REQUESTED because it is in requirements.txt\n    _assert_requested_present(script, result, \"simple\", \"2.0\")\n\n\ndef test_install_requested_reqs_and_constraints(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"requirements.txt\").write_text(\"require_simple\\n\")\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"simple<3\\n\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-r\",\n        script.scratch_path / \"requirements.txt\",\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n    )\n    _assert_requested_present(script, result, \"require_simple\", \"1.0\")\n    # simple must not have REQUESTED because it is merely a constraint\n    _assert_requested_absent(script, result, \"simple\", \"2.0\")\n\n\ndef test_install_requested_in_reqs_and_constraints(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"requirements.txt\").write_text(\n        \"require_simple\\nsimple\\n\"\n    )\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"simple<3\\n\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-r\",\n        script.scratch_path / \"requirements.txt\",\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n    )\n    _assert_requested_present(script, result, \"require_simple\", \"1.0\")\n    # simple must have REQUESTED because it is in requirements.txt\n    _assert_requested_present(script, result, \"simple\", \"2.0\")\n\n\ndef test_install_requested_from_cli_with_constraint(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\"simple<3\\n\")\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"simple\",\n    )\n    # simple must have REQUESTED because it was provided on the command line\n    _assert_requested_present(script, result, \"simple\", \"2.0\")\n\n\n@pytest.mark.network\ndef test_install_requested_from_cli_with_url_constraint(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.scratch_path.joinpath(\"constraints.txt\").write_text(\n        \"pip-test-package @ git+https://github.com/pypa/pip-test-package@0.1.1\\n\"\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-c\",\n        script.scratch_path / \"constraints.txt\",\n        \"pip-test-package\",\n    )\n    # pip-test-package must have REQUESTED because it was provided on the command line\n    _assert_requested_present(script, result, \"pip_test_package\", \"0.1.1\")\n"
  },
  {
    "path": "tests/functional/test_install_script.py",
    "content": "import sys\nimport textwrap\n\nfrom tests.lib import PipTestEnvironment\n\n\ndef test_script_file(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a script with inline metadata (PEP 723).\n    \"\"\"\n\n    script_path = script.scratch_path.joinpath(\"script.py\")\n    script_path.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            # /// script\n            # dependencies = [\n            #   \"INITools==0.2\",\n            #   \"simple==1.0\",\n            # ]\n            # ///\n\n            print(\"Hello world from a dummy program\")\n            \"\"\"\n        )\n    )\n    script.pip_install_local(\"--requirements-from-script\", script_path)\n    script.assert_installed(initools=\"0.2\", simple=\"1.0\")\n\n\ndef test_multiple_scripts(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that --requirements-from-script can only be given once in an install command.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--requirements-from-script\",\n        \"does_not_exist.py\",\n        \"--requirements-from-script\",\n        \"also_does_not_exist.py\",\n        allow_stderr_error=True,\n        expect_error=True,\n    )\n\n    assert (\n        \"ERROR: --requirements-from-script can only be given once\" in result.stderr\n    ), (\"multiple script did not fail as expected -- \" + result.stderr)\n\n\ndef test_script_file_python_version(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a script with an incompatible `requires-python`\n    \"\"\"\n\n    script_path = script.scratch_path.joinpath(\"script.py\")\n\n    script_path.write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n            # /// script\n            # requires-python = \"!={sys.version_info.major}.{sys.version_info.minor}.*\"\n            # dependencies = [\n            #   \"INITools==0.2\",\n            #   \"simple==1.0\",\n            # ]\n            # ///\n\n            print(\"Hello world from a dummy program\")\n            \"\"\"\n        )\n    )\n\n    result = script.pip_install_local(\n        \"--requirements-from-script\",\n        script_path,\n        expect_stderr=True,\n        expect_error=True,\n    )\n\n    assert \"requires a different Python\" in result.stderr, (\n        \"Script with incompatible requires-python did not fail as expected -- \"\n        + result.stderr\n    )\n\n\ndef test_script_invalid_TOML(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a script with invalid TOML in its 'script' metadata\n    \"\"\"\n\n    script_path = script.scratch_path.joinpath(\"script.py\")\n\n    script_path.write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n            # /// script\n            # requires-python = \"!={sys.version_info.major}.{sys.version_info.minor}.*\"\n            # dependencies = [\n            # ///\n\n            print(\"Hello world from a dummy program\")\n            \"\"\"\n        )\n    )\n\n    result = script.pip_install_local(\n        \"--requirements-from-script\",\n        script_path,\n        expect_stderr=True,\n        expect_error=True,\n    )\n\n    assert \"Failed to parse TOML\" in result.stderr, (\n        \"Script with invalid TOML metadata did not fail as expected -- \" + result.stderr\n    )\n\n\ndef test_script_multiple_blocks(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a script with multiple metadata blocks\n    \"\"\"\n\n    script_path = script.scratch_path.joinpath(\"script.py\")\n\n    script_path.write_text(\n        textwrap.dedent(\n            f\"\"\"\\\n            # /// script\n            # requires-python = \"!={sys.version_info.major}.{sys.version_info.minor}.*\"\n            # dependencies = [\n            #   \"INITools==0.2\",\n            #   \"simple==1.0\",\n            # ]\n            # ///\n\n            # /// script\n            # requires-python = \"!={sys.version_info.major}.{sys.version_info.minor}.*\"\n            # dependencies = [\n            #   \"INITools==0.2\",\n            #   \"simple==1.0\",\n            # ]\n            # ///\n\n            print(\"Hello world from a dummy program\")\n            \"\"\"\n        )\n    )\n\n    result = script.pip_install_local(\n        \"--requirements-from-script\",\n        script_path,\n        expect_stderr=True,\n        expect_error=True,\n    )\n\n    assert \"Multiple 'script' blocks\" in result.stderr, (\n        \"Script with multiple metadata blocks did not fail as expected -- \"\n        + result.stderr\n    )\n"
  },
  {
    "path": "tests/functional/test_install_upgrade.py",
    "content": "import itertools\nimport os\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    ResolverVariant,\n    TestData,\n    assert_all_changes,\n    pyversion,  # noqa: F401\n)\nfrom tests.lib.local_repos import local_checkout\nfrom tests.lib.wheel import make_wheel\n\n\ndef test_no_upgrade_unless_requested(script: PipTestEnvironment) -> None:\n    \"\"\"\n    No upgrade if not specifically requested.\n\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    result = script.pip_install_local(\"simplewheel\")\n    assert (\n        not result.files_created\n    ), \"pip install INITools upgraded when it should not have\"\n\n\ndef test_invalid_upgrade_strategy_causes_error(script: PipTestEnvironment) -> None:\n    \"\"\"\n    It errors out when the upgrade-strategy is an invalid/unrecognised one\n\n    \"\"\"\n    result = script.pip_install_local(\n        \"--upgrade\", \"--upgrade-strategy=bazinga\", \"simple\", expect_error=True\n    )\n\n    assert result.returncode\n    assert \"invalid choice\" in result.stderr\n\n\ndef test_only_if_needed_does_not_upgrade_deps_when_satisfied(\n    script: PipTestEnvironment, resolver_variant: ResolverVariant\n) -> None:\n    \"\"\"\n    It doesn't upgrade a dependency if it already satisfies the requirements.\n\n    \"\"\"\n    script.pip_install_local(\"simple==2.0\")\n    result = script.pip_install_local(\n        \"--upgrade\", \"--upgrade-strategy=only-if-needed\", \"require_simple\"\n    )\n\n    assert (\n        script.site_packages / \"require_simple-1.0.dist-info\"\n    ) not in result.files_deleted, \"should have installed require_simple==1.0\"\n    assert (\n        script.site_packages / \"simple-2.0.dist-info\"\n    ) not in result.files_deleted, \"should not have uninstalled simple==2.0\"\n\n    msg = \"Requirement already satisfied\"\n    if resolver_variant == \"legacy\":\n        msg = msg + \", skipping upgrade: simple\"\n    assert (\n        msg in result.stdout\n    ), \"did not print correct message for not-upgraded requirement\"\n\n\ndef test_only_if_needed_does_upgrade_deps_when_no_longer_satisfied(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    It does upgrade a dependency if it no longer satisfies the requirements.\n\n    \"\"\"\n    script.pip_install_local(\"simple==1.0\")\n    result = script.pip_install_local(\n        \"--upgrade\", \"--upgrade-strategy=only-if-needed\", \"require_simple\"\n    )\n\n    assert (\n        script.site_packages / \"require_simple-1.0.dist-info\"\n    ) not in result.files_deleted, \"should have installed require_simple==1.0\"\n    expected = script.site_packages / \"simple-3.0.dist-info\"\n    result.did_create(expected, message=\"should have installed simple==3.0\")\n    expected = script.site_packages / \"simple-1.0.dist-info\"\n    assert expected in result.files_deleted, \"should have uninstalled simple==1.0\"\n\n\ndef test_eager_does_upgrade_dependencies_when_currently_satisfied(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    It does upgrade a dependency even if it already satisfies the requirements.\n\n    \"\"\"\n    script.pip_install_local(\"simple==2.0\")\n    result = script.pip_install_local(\n        \"--upgrade\", \"--upgrade-strategy=eager\", \"require_simple\"\n    )\n\n    assert (\n        script.site_packages / \"require_simple-1.0.dist-info\"\n    ) not in result.files_deleted, \"should have installed require_simple==1.0\"\n    assert (\n        script.site_packages / \"simple-2.0.dist-info\"\n    ) in result.files_deleted, \"should have uninstalled simple==2.0\"\n\n\ndef test_eager_does_upgrade_dependencies_when_no_longer_satisfied(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    It does upgrade a dependency if it no longer satisfies the requirements.\n\n    \"\"\"\n    script.pip_install_local(\"simple==1.0\")\n    result = script.pip_install_local(\n        \"--upgrade\", \"--upgrade-strategy=eager\", \"require_simple\"\n    )\n\n    assert (\n        script.site_packages / \"require_simple-1.0.dist-info\"\n    ) not in result.files_deleted, \"should have installed require_simple==1.0\"\n    result.did_create(\n        script.site_packages / \"simple-3.0.dist-info\",\n        message=\"should have installed simple==3.0\",\n    )\n    assert (\n        script.site_packages / \"simple-1.0.dist-info\" in result.files_deleted\n    ), \"should have uninstalled simple==1.0\"\n\n\ndef test_upgrade_to_specific_version(script: PipTestEnvironment) -> None:\n    \"\"\"\n    It does upgrade to specific version requested.\n\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    result = script.pip_install_local(\"simplewheel==2.0\")\n    assert result.files_created, \"pip install with specific version did not upgrade\"\n    assert script.site_packages / \"simplewheel-1.0.dist-info\" in result.files_deleted\n    result.did_create(script.site_packages / \"simplewheel-2.0.dist-info\")\n\n\ndef test_upgrade_if_requested(script: PipTestEnvironment) -> None:\n    \"\"\"\n    And it does upgrade if requested.\n\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    result = script.pip_install_local(\"--upgrade\", \"simplewheel\")\n    assert result.files_created, \"pip install --upgrade did not upgrade\"\n    result.did_not_create(script.site_packages / \"simplewheel-1.0.dist-info\")\n\n\ndef test_upgrade_with_newest_already_installed(\n    script: PipTestEnvironment, data: TestData, resolver_variant: ResolverVariant\n) -> None:\n    \"\"\"\n    If the newest version of a package is already installed, the package should\n    not be reinstalled and the user should be informed.\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--upgrade\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple\",\n    )\n    assert not result.files_created, \"simple upgraded when it should not have\"\n    if resolver_variant == \"resolvelib\":\n        msg = \"Requirement already satisfied\"\n    else:\n        msg = \"already up-to-date\"\n    assert msg in result.stdout, result.stdout\n\n\ndef test_upgrade_force_reinstall_newest(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Force reinstallation of a package even if it is already at its newest\n    version if --force-reinstall is supplied.\n    \"\"\"\n    result = script.pip_install_local(\"simplewheel\")\n    result.did_create(script.site_packages / \"simplewheel\")\n    result2 = script.pip_install_local(\"--upgrade\", \"--force-reinstall\", \"simplewheel\")\n    assert result2.files_updated, \"upgrade to simplewheel 2.0 failed\"\n    result3 = script.pip(\"uninstall\", \"simplewheel\", \"-y\")\n    assert_all_changes(result, result3, [script.venv / \"build\", \"cache\"])\n\n\ndef test_uninstall_before_upgrade(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Automatic uninstall-before-upgrade.\n\n    \"\"\"\n    result = script.pip_install_local(\"simplewheel==1.0\")\n    result.did_create(script.site_packages / \"simplewheel\")\n    result2 = script.pip_install_local(\"simplewheel==2.0\")\n    assert result2.files_created, \"upgrade to simplewheel 2.0 failed\"\n    result3 = script.pip(\"uninstall\", \"simplewheel\", \"-y\")\n    assert_all_changes(result, result3, [script.venv / \"build\", \"cache\"])\n\n\n@pytest.mark.network\ndef test_uninstall_before_upgrade_from_url(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Automatic uninstall-before-upgrade from URL.\n\n    \"\"\"\n    result = script.pip(\"install\", \"INITools==0.2\")\n    result.did_create(script.site_packages / \"initools\")\n    result2 = script.pip(\n        \"install\",\n        \"https://files.pythonhosted.org/packages/source/I/INITools/INITools-0.3.tar.gz\",\n    )\n    assert result2.files_created, \"upgrade to INITools 0.3 failed\"\n    result3 = script.pip(\"uninstall\", \"initools\", \"-y\")\n    assert_all_changes(result, result3, [script.venv / \"build\", \"cache\"])\n\n\n@pytest.mark.network\ndef test_upgrade_to_same_version_from_url(script: PipTestEnvironment) -> None:\n    \"\"\"\n    When installing from a URL the same version that is already installed, no\n    need to uninstall and reinstall if --upgrade is not specified.\n\n    \"\"\"\n    result = script.pip(\"install\", \"INITools==0.3\")\n    result.did_create(script.site_packages / \"initools\")\n    result2 = script.pip(\n        \"install\",\n        \"https://files.pythonhosted.org/packages/source/I/INITools/INITools-0.3.tar.gz\",\n    )\n    assert (\n        script.site_packages / \"initools\" not in result2.files_updated\n    ), \"INITools 0.3 reinstalled same version\"\n    result3 = script.pip(\"uninstall\", \"initools\", \"-y\")\n    assert_all_changes(result, result3, [script.venv / \"build\", \"cache\"])\n\n\ndef test_upgrade_from_reqs_file(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Upgrade from a requirements file.\n\n    \"\"\"\n    req_file = script.temporary_multiline_file(\n        \"test-req.txt\",\n        \"\"\"\\\n        simplewheel<2\n        # and something else to test out:\n        license.dist==0.2\n        \"\"\",\n    )\n    install_result = script.pip_install_local(\"-r\", req_file)\n    script.temporary_multiline_file(\n        \"test-req.txt\",\n        \"\"\"\\\n        simplewheel\n        # and something else to test out:\n        license.dist\n        \"\"\",\n    )\n    script.pip_install_local(\"--upgrade\", \"-r\", req_file)\n    uninstall_result = script.pip(\"uninstall\", \"-r\", req_file, \"-y\")\n    assert_all_changes(\n        install_result,\n        uninstall_result,\n        [script.venv / \"build\", \"cache\", script.scratch / \"test-req.txt\"],\n    )\n\n\ndef test_uninstall_rollback(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test uninstall-rollback (using test package with a setup.py\n    crafted to fail on install).\n\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"broken==0.1\",\n    )\n    result.did_create(script.site_packages / \"broken.py\")\n    result2 = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"broken===0.2+broken\",\n        expect_error=True,\n    )\n    assert result2.returncode == 1, str(result2)\n    assert (\n        script.run(\"python\", \"-c\", \"import broken; print(broken.VERSION)\").stdout\n        == \"0.1\\n\"\n    )\n    assert_all_changes(\n        result.files_after,\n        result2,\n        [script.venv / \"build\"],\n    )\n\n\ndef test_should_not_install_always_from_cache(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    If there is an old cached package, pip should download the newer version\n    Related to issue #175\n    \"\"\"\n    script.pip_install_local(\"simplewheel==2.0\")\n    script.pip(\"uninstall\", \"-y\", \"simplewheel\")\n    result = script.pip_install_local(\"simplewheel==1.0\")\n    result.did_not_create(script.site_packages / \"simplewheel-2.0.dist-info\")\n    result.did_create(script.site_packages / \"simplewheel-1.0.dist-info\")\n\n\ndef test_install_with_ignoreinstalled_requested(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test old conflicting package is completely ignored\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    result = script.pip_install_local(\"-I\", \"simplewheel==2.0\")\n    assert result.files_created, \"pip install -I did not install\"\n    # both the old and new metadata should be present.\n    assert os.path.exists(script.site_packages_path / \"simplewheel-1.0.dist-info\")\n    assert os.path.exists(script.site_packages_path / \"simplewheel-2.0.dist-info\")\n\n\n@pytest.mark.network\ndef test_upgrade_vcs_req_with_no_dists_found(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"It can upgrade a VCS requirement that has no distributions otherwise.\"\"\"\n    req = \"{checkout}#egg=pip-test-package\".format(\n        checkout=local_checkout(\n            \"git+https://github.com/pypa/pip-test-package.git\",\n            tmpdir,\n        )\n    )\n    script.pip(\"install\", req)\n    result = script.pip(\"install\", \"-U\", req)\n    assert not result.returncode\n\n\n@pytest.mark.network\ndef test_upgrade_vcs_req_with_dist_found(script: PipTestEnvironment) -> None:\n    \"\"\"It can upgrade a VCS requirement that has distributions on the index.\"\"\"\n    # TODO(pnasrat) Using local_checkout fails on windows - oddness with the\n    # test path urls/git.\n    req = \"{url}#egg=pretend\".format(\n        url=(\n            \"git+https://github.com/alex/pretend@e7f26ad7dbcb4a02a4995aade4\"\n            \"743aad47656b27\"\n        ),\n    )\n    script.pip(\"install\", req, expect_stderr=True)\n    result = script.pip(\"install\", \"-U\", req, expect_stderr=True)\n    assert \"pypi.org\" not in result.stdout, result.stdout\n\n\n@pytest.mark.parametrize(\n    \"req1, req2\",\n    list(\n        itertools.product(\n            [\"foo.bar\", \"foo_bar\", \"foo-bar\"],\n            [\"foo.bar\", \"foo_bar\", \"foo-bar\"],\n        )\n    ),\n)\ndef test_install_find_existing_package_canonicalize(\n    script: PipTestEnvironment, req1: str, req2: str\n) -> None:\n    \"\"\"Ensure an already-installed dist is found no matter how the dist name\n    was normalized on installation. (pypa/pip#8645)\n    \"\"\"\n    # Create and install a package that's not available in the later stage.\n    req_container = script.scratch_path.joinpath(\"foo-bar\")\n    req_container.mkdir()\n    req_path = make_wheel(\"foo_bar\", \"1.0\").save_to_dir(req_container)\n    script.pip(\"install\", \"--no-index\", req_path)\n\n    # Depend on the previously installed, but now unavailable package.\n    pkg_container = script.scratch_path.joinpath(\"pkg\")\n    pkg_container.mkdir()\n    make_wheel(\n        \"pkg\",\n        \"1.0\",\n        metadata_updates={\"Requires-Dist\": req2},\n    ).save_to_dir(pkg_container)\n\n    # Ensure the previously installed package can be correctly used to match\n    # the dependency.\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links\",\n        pkg_container,\n        \"pkg\",\n    )\n    satisfied_message = f\"Requirement already satisfied: {req2}\"\n    assert satisfied_message in result.stdout, str(result)\n\n\n@pytest.mark.network\n@pytest.mark.skipif(sys.platform != \"win32\", reason=\"Windows-only test\")\ndef test_modifying_pip_presents_error(script: PipTestEnvironment) -> None:\n    result = script.pip(\n        \"install\", \"pip\", \"--force-reinstall\", use_module=False, expect_error=True\n    )\n\n    assert \"python.exe\" in result.stderr or \"python.EXE\" in result.stderr, str(result)\n    assert \" -m \" in result.stderr, str(result)\n"
  },
  {
    "path": "tests/functional/test_install_user.py",
    "content": "\"\"\"\ntests specific to \"pip install --user\"\n\"\"\"\n\nimport os\nimport textwrap\nfrom os.path import curdir, isdir, isfile\nfrom pathlib import Path\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    create_basic_wheel_for_package,\n    need_svn,\n    pyversion,  # noqa: F401\n)\nfrom tests.lib.local_repos import local_checkout\nfrom tests.lib.venv import VirtualEnvironment\n\n\ndef _patch_dist_in_site_packages(virtualenv: VirtualEnvironment) -> None:\n    # Since the tests are run from a virtualenv, and to avoid the \"Will not\n    # install to the usersite because it will lack sys.path precedence...\"\n    # error: Monkey patch the Distribution class so it's possible to install a\n    # conflicting distribution in the user site.\n    virtualenv.sitecustomize = textwrap.dedent(\n        \"\"\"\n        def dist_in_site_packages(dist):\n            return False\n\n        from pip._internal.metadata.base import BaseDistribution\n        BaseDistribution.in_site_packages = property(dist_in_site_packages)\n    \"\"\"\n    )\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\nclass Tests_UserSite:\n    def test_reset_env_system_site_packages_usersite(\n        self,\n        script: PipTestEnvironment,\n        data: TestData,\n    ) -> None:\n        \"\"\"\n        Check user site works as expected.\n        \"\"\"\n        script.pip_install_local(\"--user\", \"INITools==0.2\", \"-f\", data.pypi_packages)\n        result = script.run(\n            \"python\",\n            \"-c\",\n            \"import pkg_resources; print(pkg_resources.get_distribution\"\n            \"('initools').project_name)\",\n        )\n        project_name = result.stdout.strip()\n        assert \"initools\" == project_name, project_name\n\n    @pytest.mark.xfail\n    @pytest.mark.network\n    @need_svn\n    def test_install_subversion_usersite_editable_with_distribute(\n        self, script: PipTestEnvironment, tmpdir: Path\n    ) -> None:\n        \"\"\"\n        Test installing current directory ('.') into usersite after installing\n        distribute\n        \"\"\"\n        result = script.pip(\n            \"install\",\n            \"--user\",\n            \"-e\",\n            \"{checkout}#egg=initools\".format(\n                checkout=local_checkout(\n                    \"svn+http://svn.colorstudy.com/INITools\", tmpdir\n                )\n            ),\n        )\n        result.assert_installed(\"INITools\")\n\n    def test_install_from_current_directory_into_usersite(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"\n        Test installing current directory ('.') into usersite\n        \"\"\"\n        run_from = data.packages.joinpath(\"FSPkg\")\n        result = script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"-vvv\",\n            \"--user\",\n            curdir,\n            cwd=run_from,\n        )\n\n        fspkg_folder = script.user_site / \"fspkg\"\n        result.did_create(fspkg_folder)\n\n        dist_info_folder = script.user_site / \"fspkg-0.1.dev0.dist-info\"\n        result.did_create(dist_info_folder)\n\n    def test_install_user_venv_nositepkgs_fails(\n        self, virtualenv: VirtualEnvironment, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"\n        user install in virtualenv (with no system packages) fails with message\n        \"\"\"\n        # We can't use PYTHONNOUSERSITE, as it's not\n        # honoured by virtualenv's custom site.py.\n        virtualenv.user_site_packages = False\n        run_from = data.packages.joinpath(\"FSPkg\")\n        result = script.pip(\n            \"install\",\n            \"--user\",\n            curdir,\n            cwd=run_from,\n            expect_error=True,\n        )\n        assert (\n            \"Can not perform a '--user' install. User site-packages are not \"\n            \"visible in this virtualenv.\" in result.stderr\n        )\n\n    def test_install_user_conflict_in_usersite(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"\n        Test user install with conflict in usersite updates usersite.\n        \"\"\"\n\n        script.pip_install_local(\"--user\", \"INITools==0.2\", \"-f\", data.pypi_packages)\n\n        result2 = script.pip_install_local(\n            \"--user\", \"INITools==0.1\", \"-f\", data.pypi_packages\n        )\n\n        # usersite has 0.1\n        dist_info_folder = script.user_site / \"initools-0.1.dist-info\"\n        initools_v2_file = (\n            # file only in 0.2\n            script.base_path\n            / script.user_site\n            / \"initools\"\n            / \"configparser.py\"\n        )\n        result2.did_create(dist_info_folder)\n        assert not isfile(initools_v2_file), initools_v2_file\n\n    def test_install_user_conflict_in_globalsite(\n        self, virtualenv: VirtualEnvironment, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test user install with conflict in global site ignores site and\n        installs to usersite\n        \"\"\"\n        create_basic_wheel_for_package(script, \"initools\", \"0.1\")\n        create_basic_wheel_for_package(script, \"initools\", \"0.2\")\n\n        _patch_dist_in_site_packages(virtualenv)\n\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"initools==0.2\",\n        )\n        result2 = script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--user\",\n            \"initools==0.1\",\n        )\n\n        # usersite has 0.1\n        dist_info_folder = script.user_site / \"initools-0.1.dist-info\"\n        initools_folder = script.user_site / \"initools\"\n        result2.did_create(dist_info_folder)\n        result2.did_create(initools_folder)\n\n        # site still has 0.2 (can't look in result1; have to check)\n        dist_info_folder = (\n            script.base_path / script.site_packages / \"initools-0.2.dist-info\"\n        )\n        initools_folder = script.base_path / script.site_packages / \"initools\"\n        assert isdir(dist_info_folder)\n        assert isdir(initools_folder)\n\n    def test_upgrade_user_conflict_in_globalsite(\n        self, virtualenv: VirtualEnvironment, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test user install/upgrade with conflict in global site ignores site and\n        installs to usersite\n        \"\"\"\n        create_basic_wheel_for_package(script, \"initools\", \"0.2\")\n        create_basic_wheel_for_package(script, \"initools\", \"0.3.1\")\n\n        _patch_dist_in_site_packages(virtualenv)\n\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"initools==0.2\",\n        )\n        result2 = script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--user\",\n            \"--upgrade\",\n            \"initools\",\n        )\n\n        # usersite has 0.3.1\n        dist_info_folder = script.user_site / \"initools-0.3.1.dist-info\"\n        initools_folder = script.user_site / \"initools\"\n        result2.did_create(dist_info_folder)\n        result2.did_create(initools_folder)\n\n        # site still has 0.2 (can't look in result1; have to check)\n        dist_info_folder = (\n            script.base_path / script.site_packages / \"initools-0.2.dist-info\"\n        )\n        initools_folder = script.base_path / script.site_packages / \"initools\"\n        assert isdir(dist_info_folder), result2.stdout\n        assert isdir(initools_folder)\n\n    def test_install_user_conflict_in_globalsite_and_usersite(\n        self, virtualenv: VirtualEnvironment, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test user install with conflict in globalsite and usersite ignores\n        global site and updates usersite.\n        \"\"\"\n        initools_v3_file_name = os.path.join(\"initools\", \"configparser.py\")\n        create_basic_wheel_for_package(script, \"initools\", \"0.1\")\n        create_basic_wheel_for_package(script, \"initools\", \"0.2\")\n        create_basic_wheel_for_package(\n            script,\n            \"initools\",\n            \"0.3\",\n            extra_files={initools_v3_file_name: \"# Hi!\"},\n        )\n\n        _patch_dist_in_site_packages(virtualenv)\n\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"initools==0.2\",\n        )\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--user\",\n            \"initools==0.3\",\n        )\n        result3 = script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--user\",\n            \"initools==0.1\",\n        )\n\n        # usersite has 0.1\n        dist_info_folder = script.user_site / \"initools-0.1.dist-info\"\n        result3.did_create(dist_info_folder)\n        initools_v3_file = script.base_path / script.user_site / initools_v3_file_name\n        assert not isfile(initools_v3_file), initools_v3_file\n\n        # site still has 0.2 (can't just look in result1; have to check)\n        dist_info_folder = (\n            script.base_path / script.site_packages / \"initools-0.2.dist-info\"\n        )\n        initools_folder = script.base_path / script.site_packages / \"initools\"\n        assert isdir(dist_info_folder)\n        assert isdir(initools_folder)\n\n    def test_install_user_in_global_virtualenv_with_conflict_fails(\n        self, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test user install in --system-site-packages virtualenv with conflict in\n        site fails.\n        \"\"\"\n        create_basic_wheel_for_package(script, \"pkg\", \"0.1\")\n        create_basic_wheel_for_package(script, \"pkg\", \"0.2\")\n\n        script.pip(\n            \"install\",\n            \"--no-cache-dir\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"pkg==0.2\",\n        )\n\n        result2 = script.pip(\n            \"install\",\n            \"--no-cache-dir\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--user\",\n            \"pkg==0.1\",\n            expect_error=True,\n        )\n        resultp = script.run(\n            \"python\",\n            \"-c\",\n            \"from pip._internal.metadata import get_default_environment; \"\n            \"print(get_default_environment().get_distribution('pkg').location)\",\n        )\n        dist_location = resultp.stdout.strip()\n\n        assert (\n            f\"Will not install to the user site because it will lack sys.path \"\n            f\"precedence to pkg in {dist_location}\"\n        ) in result2.stderr\n\n    def test_install_user_nositepkgs_fails(\n        self,\n        script: PipTestEnvironment,\n        data: TestData,\n    ) -> None:\n        \"\"\"\n        Test that --user install fails when user site-packages are disabled.\n        \"\"\"\n        create_basic_wheel_for_package(script, \"pkg\", \"0.1\")\n\n        # Create a custom Python script that disables user site and runs pip via exec\n        test_script = script.scratch_path / \"test_disable_user_site.py\"\n        test_script.write_text(\n            textwrap.dedent(\n                f\"\"\"\n            import site\n            import sys\n\n            # Make sys.base_prefix equal to sys.prefix to simulate not being in a venv\n            # This ensures virtualenv_no_global() returns False, so we test the\n            # site.ENABLE_USER_SITE path\n            sys.base_prefix = sys.prefix\n            site.ENABLE_USER_SITE = False\n\n            # Set up sys.argv to simulate running pip install --user\n            sys.argv = [\n                \"pip\", \"install\",\n                \"--no-cache-dir\",\n                \"--no-index\",\n                \"--find-links\",\n                r\"{script.scratch_path}\",\n                \"pkg\",\n                \"--user\"\n            ]\n\n            # Import and run pip's main\n            from pip._internal.cli.main import main\n            sys.exit(main())\n            \"\"\"\n            )\n        )\n\n        result = script.run(\"python\", str(test_script), expect_error=True)\n        assert (\n            \"Can not perform a '--user' install. User site-packages are \"\n            \"disabled for this Python.\" in result.stderr\n        )\n"
  },
  {
    "path": "tests/functional/test_install_vcs_git.py",
    "content": "from __future__ import annotations\n\nfrom pathlib import Path\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    _change_test_package_version,\n    _create_test_package,\n    pyversion,  # noqa: F401\n)\nfrom tests.lib.git_submodule_helpers import (\n    _change_test_package_submodule,\n    _create_test_package_with_submodule,\n    _pull_in_submodule_changes_to_module,\n)\nfrom tests.lib.local_repos import local_checkout\n\n\ndef _get_editable_repo_dir(script: PipTestEnvironment, package_name: str) -> Path:\n    \"\"\"\n    Return the repository directory for an editable install.\n    \"\"\"\n    return script.venv_path / \"src\" / package_name\n\n\ndef _get_editable_branch(script: PipTestEnvironment, package_name: str) -> str:\n    \"\"\"\n    Return the current branch of an editable install.\n    \"\"\"\n    repo_dir = _get_editable_repo_dir(script, package_name)\n    result = script.run(\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\", cwd=repo_dir)\n    return result.stdout.strip()\n\n\ndef _get_branch_remote(\n    script: PipTestEnvironment, package_name: str, branch: str\n) -> str:\n    \"\"\" \"\"\"\n    repo_dir = _get_editable_repo_dir(script, package_name)\n    result = script.run(\"git\", \"config\", f\"branch.{branch}.remote\", cwd=repo_dir)\n    return result.stdout.strip()\n\n\ndef _github_checkout(\n    url_path: str,\n    tmpdir: Path,\n    rev: str | None = None,\n    egg: str | None = None,\n    scheme: str | None = None,\n) -> str:\n    \"\"\"\n    Call local_checkout() with a GitHub URL, and return the resulting URL.\n\n    Args:\n      url_path: the string used to create the package URL by filling in the\n        format string \"git+{scheme}://github.com/{url_path}\".\n      temp_dir: the pytest tmpdir value.\n      egg: an optional project name to append to the URL as the egg fragment,\n        prior to returning.\n      scheme: the scheme without the \"git+\" prefix. Defaults to \"https\".\n    \"\"\"\n    if scheme is None:\n        scheme = \"https\"\n    url = f\"git+{scheme}://github.com/{url_path}\"\n    local_url = local_checkout(url, tmpdir)\n    if rev is not None:\n        local_url += f\"@{rev}\"\n    if egg is not None:\n        local_url += f\"#egg={egg}\"\n\n    return local_url\n\n\ndef _make_version_pkg_url(\n    path: Path, rev: str | None = None, name: str = \"version_pkg\"\n) -> str:\n    \"\"\"\n    Return a \"git+file://\" URL to the version_pkg test package.\n\n    Args:\n      path: a pathlib.Path object pointing to a Git repository\n        containing the version_pkg package.\n      rev: an optional revision to install like a branch name, tag, or SHA.\n    \"\"\"\n    file_url = path.as_uri()\n    url_rev = \"\" if rev is None else f\"@{rev}\"\n    url = f\"git+{file_url}{url_rev}#egg={name}\"\n\n    return url\n\n\ndef _install_version_pkg_only(\n    script: PipTestEnvironment,\n    path: Path,\n    rev: str | None = None,\n    allow_stderr_warning: bool = False,\n) -> None:\n    \"\"\"\n    Install the version_pkg package in editable mode (without returning\n    the version).\n\n    Args:\n      path: a pathlib.Path object pointing to a Git repository\n        containing the package.\n      rev: an optional revision to install like a branch name or tag.\n    \"\"\"\n    version_pkg_url = _make_version_pkg_url(path, rev=rev)\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        version_pkg_url,\n        allow_stderr_warning=allow_stderr_warning,\n    )\n\n\ndef _install_version_pkg(\n    script: PipTestEnvironment,\n    path: Path,\n    rev: str | None = None,\n    allow_stderr_warning: bool = False,\n) -> str:\n    \"\"\"\n    Install the version_pkg package in editable mode, and return the version\n    installed.\n\n    Args:\n      path: a pathlib.Path object pointing to a Git repository\n        containing the package.\n      rev: an optional revision to install like a branch name or tag.\n    \"\"\"\n    _install_version_pkg_only(\n        script,\n        path,\n        rev=rev,\n        allow_stderr_warning=allow_stderr_warning,\n    )\n    result = script.run(\"version_pkg\")\n    version = result.stdout.strip()\n\n    return version\n\n\ndef test_git_install_again_after_changes(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing a repository a second time without specifying a revision,\n    and after updates to the remote repository.\n\n    This test also checks that no warning message like the following gets\n    logged on the update: \"Did not find branch or tag ..., assuming ref or\n    revision.\"\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    version = _install_version_pkg(script, version_pkg_path)\n    assert version == \"0.1\"\n\n    _change_test_package_version(script, version_pkg_path)\n    version = _install_version_pkg(script, version_pkg_path)\n    assert version == \"some different version\"\n\n\ndef test_git_install_branch_again_after_branch_changes(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test installing a branch again after the branch is updated in the remote\n    repository.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    version = _install_version_pkg(script, version_pkg_path, rev=\"master\")\n    assert version == \"0.1\"\n\n    _change_test_package_version(script, version_pkg_path)\n    version = _install_version_pkg(script, version_pkg_path, rev=\"master\")\n    assert version == \"some different version\"\n\n\n@pytest.mark.network\ndef test_install_editable_from_git_with_https(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test cloning from Git with https.\n    \"\"\"\n    url_path = \"pypa/pip-test-package.git\"\n    local_url = _github_checkout(url_path, tmpdir, egg=\"pip-test-package\")\n    result = script.pip(\"install\", \"-e\", local_url)\n    result.assert_installed(\n        \"piptestpackage\", dist_name=\"pip-test-package\", with_files=[\".git\"]\n    )\n\n\n@pytest.mark.network\ndef test_install_noneditable_git(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a non-editable git URL with a given tag.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"git+https://github.com/pypa/pip-test-package.git@0.1.1#egg=pip-test-package\",\n    )\n    dist_info_folder = script.site_packages / \"pip_test_package-0.1.1.dist-info\"\n    result.assert_installed(\n        \"piptestpackage\", dist_name=\"pip-test-package\", editable=False\n    )\n    result.did_create(dist_info_folder)\n\n\ndef test_git_with_sha1_revisions(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Git backend should be able to install from SHA1 revisions\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    _change_test_package_version(script, version_pkg_path)\n    sha1 = script.run(\n        \"git\",\n        \"rev-parse\",\n        \"HEAD~1\",\n        cwd=version_pkg_path,\n    ).stdout.strip()\n    version = _install_version_pkg(script, version_pkg_path, rev=sha1)\n    assert \"0.1\" == version\n\n\ndef test_git_with_short_sha1_revisions(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Git backend should be able to install from SHA1 revisions\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    _change_test_package_version(script, version_pkg_path)\n    sha1 = script.run(\n        \"git\",\n        \"rev-parse\",\n        \"HEAD~1\",\n        cwd=version_pkg_path,\n    ).stdout.strip()[:7]\n    version = _install_version_pkg(\n        script,\n        version_pkg_path,\n        rev=sha1,\n        # WARNING: Did not find branch or tag ..., assuming revision or ref.\n        allow_stderr_warning=True,\n    )\n    assert \"0.1\" == version\n\n\ndef test_git_with_branch_name_as_revision(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Git backend should be able to install from branch names\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    branch = \"test_branch\"\n    script.run(\"git\", \"checkout\", \"-b\", branch, cwd=version_pkg_path)\n    _change_test_package_version(script, version_pkg_path)\n    version = _install_version_pkg(script, version_pkg_path, rev=branch)\n    assert \"some different version\" == version\n\n\ndef test_git_with_tag_name_as_revision(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Git backend should be able to install from tag names\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    script.run(\"git\", \"tag\", \"test_tag\", cwd=version_pkg_path)\n    _change_test_package_version(script, version_pkg_path)\n    version = _install_version_pkg(script, version_pkg_path, rev=\"test_tag\")\n    assert \"0.1\" == version\n\n\ndef _add_ref(script: PipTestEnvironment, path: Path, ref: str) -> None:\n    \"\"\"\n    Add a new ref to a repository at the given path.\n    \"\"\"\n    script.run(\"git\", \"update-ref\", ref, \"HEAD\", cwd=path)\n\n\ndef test_git_install_ref(script: PipTestEnvironment) -> None:\n    \"\"\"\n    The Git backend should be able to install a ref with the first install.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    _add_ref(script, version_pkg_path, \"refs/foo/bar\")\n    _change_test_package_version(script, version_pkg_path)\n\n    version = _install_version_pkg(\n        script,\n        version_pkg_path,\n        rev=\"refs/foo/bar\",\n        # WARNING: Did not find branch or tag ..., assuming revision or ref.\n        allow_stderr_warning=True,\n    )\n    assert \"0.1\" == version\n\n\ndef test_git_install_then_install_ref(script: PipTestEnvironment) -> None:\n    \"\"\"\n    The Git backend should be able to install a ref after a package has\n    already been installed.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    _add_ref(script, version_pkg_path, \"refs/foo/bar\")\n    _change_test_package_version(script, version_pkg_path)\n\n    version = _install_version_pkg(script, version_pkg_path)\n    assert \"some different version\" == version\n\n    # Now install the ref.\n    version = _install_version_pkg(\n        script,\n        version_pkg_path,\n        rev=\"refs/foo/bar\",\n        # WARNING: Did not find branch or tag ..., assuming revision or ref.\n        allow_stderr_warning=True,\n    )\n    assert \"0.1\" == version\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\n    \"rev, expected_sha\",\n    [\n        # Clone the default branch\n        (\"\", \"96d6d72ac54132aecbdd5adac88bc8d1f8fb986b\"),\n        # Clone a specific tag\n        (\"@0.1.1\", \"7d654e66c8fa7149c165ddeffa5b56bc06619458\"),\n        # Clone a specific commit\n        (\n            \"@65cf0a5bdd906ecf48a0ac241c17d656d2071d56\",\n            \"65cf0a5bdd906ecf48a0ac241c17d656d2071d56\",\n        ),\n    ],\n)\ndef test_install_git_logs_commit_sha(\n    script: PipTestEnvironment, rev: str, expected_sha: str, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing from a git repository logs a commit SHA.\n    \"\"\"\n    url_path = \"pypa/pip-test-package.git\"\n    base_local_url = _github_checkout(url_path, tmpdir)\n    local_url = f\"{base_local_url}{rev}#egg=pip-test-package\"\n    result = script.pip(\"install\", local_url)\n    # `[4:]` removes a 'git+' prefix\n    assert f\"Resolved {base_local_url[4:]} to commit {expected_sha}\" in result.stdout\n\n\n@pytest.mark.network\ndef test_git_branch_should_not_be_changed(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Editable installations should not change branch\n    related to issue #32 and #161\n    \"\"\"\n    url_path = \"pypa/pip-test-package.git\"\n    local_url = _github_checkout(url_path, tmpdir, egg=\"pip-test-package\")\n    script.pip(\"install\", \"-e\", local_url)\n    branch = _get_editable_branch(script, \"pip-test-package\")\n    assert \"master\" == branch\n\n\n@pytest.mark.network\ndef test_git_with_non_editable_unpacking(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test cloning a git repository from a non-editable URL with a given tag.\n    \"\"\"\n    url_path = \"pypa/pip-test-package.git\"\n    local_url = _github_checkout(\n        url_path,\n        tmpdir,\n        rev=\"0.1.2\",\n        egg=\"pip-test-package\",\n    )\n    result = script.pip(\n        \"install\",\n        local_url,\n        allow_stderr_warning=True,\n    )\n    assert \"0.1.2\" in result.stdout\n\n\n@pytest.mark.network\ndef test_git_with_editable_where_egg_contains_dev_string(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test cloning a git repository from an editable url which contains \"dev\"\n    string\n    \"\"\"\n    url_path = \"dcramer/django-devserver.git\"\n    local_url = _github_checkout(\n        url_path,\n        tmpdir,\n        egg=\"django-devserver\",\n        scheme=\"https\",\n    )\n    result = script.pip(\"install\", \"-e\", local_url)\n    result.assert_installed(\"django-devserver\", with_files=[\".git\"])\n\n\n@pytest.mark.network\ndef test_git_with_non_editable_where_egg_contains_dev_string(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test cloning a git repository from a non-editable url which contains \"dev\"\n    string\n    \"\"\"\n    url_path = \"dcramer/django-devserver.git\"\n    local_url = _github_checkout(\n        url_path,\n        tmpdir,\n        egg=\"django-devserver\",\n        scheme=\"https\",\n    )\n    result = script.pip(\"install\", local_url)\n    devserver_folder = script.site_packages / \"devserver\"\n    result.did_create(devserver_folder)\n\n\ndef test_git_with_ambiguous_revs(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test git with two \"names\" (tag/branch) pointing to the same commit\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    version_pkg_url = _make_version_pkg_url(version_pkg_path, rev=\"0.1\")\n    script.run(\"git\", \"tag\", \"0.1\", cwd=version_pkg_path)\n    result = script.pip(\"install\", \"--no-build-isolation\", \"-e\", version_pkg_url)\n    assert \"Could not find a tag or branch\" not in result.stdout\n    # it is 'version-pkg' instead of 'version_pkg' because\n    # egg-link name is version-pkg.egg-link because it is a single .py module\n    result.assert_installed(\"version_pkg\", with_files=[\".git\"])\n\n\ndef test_editable__no_revision(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test a basic install in editable mode specifying no revision.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    _install_version_pkg_only(script, version_pkg_path)\n\n    branch = _get_editable_branch(script, \"version-pkg\")\n    assert branch == \"master\"\n\n    remote = _get_branch_remote(script, \"version-pkg\", \"master\")\n    assert remote == \"origin\"\n\n\ndef test_editable__branch_with_sha_same_as_default(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing in editable mode a branch whose sha matches the sha\n    of the default branch, but is different from the default branch.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    # Create a second branch with the same SHA.\n    script.run(\"git\", \"branch\", \"develop\", cwd=version_pkg_path)\n    _install_version_pkg_only(script, version_pkg_path, rev=\"develop\")\n\n    branch = _get_editable_branch(script, \"version-pkg\")\n    assert branch == \"develop\"\n\n    remote = _get_branch_remote(script, \"version-pkg\", \"develop\")\n    assert remote == \"origin\"\n\n\ndef test_editable__branch_with_sha_different_from_default(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test installing in editable mode a branch whose sha is different from\n    the sha of the default branch.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    # Create a second branch.\n    script.run(\"git\", \"branch\", \"develop\", cwd=version_pkg_path)\n    # Add another commit to the master branch to give it a different sha.\n    _change_test_package_version(script, version_pkg_path)\n\n    version = _install_version_pkg(script, version_pkg_path, rev=\"develop\")\n    assert version == \"0.1\"\n\n    branch = _get_editable_branch(script, \"version-pkg\")\n    assert branch == \"develop\"\n\n    remote = _get_branch_remote(script, \"version-pkg\", \"develop\")\n    assert remote == \"origin\"\n\n\ndef test_editable__non_master_default_branch(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the branch you get after an editable install from a remote repo\n    with a non-master default branch.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n    # Change the default branch of the remote repo to a name that is\n    # alphabetically after \"master\".\n    script.run(\"git\", \"checkout\", \"-b\", \"release\", cwd=version_pkg_path)\n    _install_version_pkg_only(script, version_pkg_path)\n\n    branch = _get_editable_branch(script, \"version-pkg\")\n    assert branch == \"release\"\n\n\ndef test_reinstalling_works_with_editable_non_master_branch(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Reinstalling an editable installation should not assume that the \"master\"\n    branch exists. See https://github.com/pypa/pip/issues/4448.\n    \"\"\"\n    version_pkg_path = _create_test_package(script.scratch_path)\n\n    # Switch the default branch to something other than 'master'\n    script.run(\"git\", \"branch\", \"-m\", \"foobar\", cwd=version_pkg_path)\n\n    version = _install_version_pkg(script, version_pkg_path)\n    assert \"0.1\" == version\n\n    _change_test_package_version(script, version_pkg_path)\n    version = _install_version_pkg(script, version_pkg_path)\n    assert \"some different version\" == version\n\n\n# TODO(pnasrat) fix all helpers to do right things with paths on windows.\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\n@pytest.mark.xfail(\n    condition=True,\n    reason=\"Git submodule against file: is not working; waiting for a good solution\",\n    run=True,\n)\ndef test_check_submodule_addition(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Submodules are pulled in on install and updated on upgrade.\n    \"\"\"\n    module_path, submodule_path = _create_test_package_with_submodule(\n        script, rel_path=\"testpkg/static\"\n    )\n\n    install_result = script.pip(\n        \"install\", \"-e\", f\"git+{module_path.as_uri()}#egg=version_pkg\"\n    )\n    install_result.did_create(script.venv / \"src/version-pkg/testpkg/static/testfile\")\n\n    _change_test_package_submodule(script, submodule_path)\n    _pull_in_submodule_changes_to_module(\n        script,\n        module_path,\n        rel_path=\"testpkg/static\",\n    )\n\n    # expect error because git may write to stderr\n    update_result = script.pip(\n        \"install\",\n        \"-e\",\n        f\"git+{module_path.as_uri()}#egg=version_pkg\",\n        \"--upgrade\",\n    )\n\n    update_result.did_create(script.venv / \"src/version-pkg/testpkg/static/testfile2\")\n\n\ndef test_install_git_branch_not_cached(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Installing git urls with a branch revision does not cause wheel caching.\n    \"\"\"\n    PKG = \"gitbranchnotcached\"\n    repo_dir = _create_test_package(script.scratch_path, name=PKG)\n    url = _make_version_pkg_url(repo_dir, rev=\"master\", name=PKG)\n    result = script.pip(\"install\", \"--no-build-isolation\", url, \"--only-binary=:all:\")\n    assert f\"Successfully built {PKG}\" in result.stdout, result.stdout\n    script.pip(\"uninstall\", \"-y\", PKG)\n    # build occurs on the second install too because it is not cached\n    result = script.pip(\"install\", \"--no-build-isolation\", url)\n    assert f\"Successfully built {PKG}\" in result.stdout, result.stdout\n\n\ndef test_install_git_sha_cached(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Installing git urls with a sha revision does cause wheel caching.\n    \"\"\"\n    PKG = \"gitshacached\"\n    repo_dir = _create_test_package(script.scratch_path, name=PKG)\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=repo_dir).stdout.strip()\n    url = _make_version_pkg_url(repo_dir, rev=commit, name=PKG)\n    result = script.pip(\"install\", \"--no-build-isolation\", url)\n    assert f\"Successfully built {PKG}\" in result.stdout, result.stdout\n    script.pip(\"uninstall\", \"-y\", PKG)\n    # build does not occur on the second install because it is cached\n    result = script.pip(\"install\", \"--no-build-isolation\", url)\n    assert f\"Successfully built {PKG}\" not in result.stdout, result.stdout\n"
  },
  {
    "path": "tests/functional/test_install_wheel.py",
    "content": "import base64\nimport csv\nimport hashlib\nimport os\nimport shutil\nimport sysconfig\nfrom pathlib import Path\nfrom typing import Any\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, TestData, create_basic_wheel_for_package\nfrom tests.lib.wheel import WheelBuilder, make_wheel\n\n\n# assert_installed expects a package subdirectory, so give it to them\ndef make_wheel_with_file(name: str, version: str, **kwargs: Any) -> WheelBuilder:\n    extra_files = kwargs.setdefault(\"extra_files\", {})\n    extra_files[f\"{name}/__init__.py\"] = \"# example\"\n    return make_wheel(name=name, version=version, **kwargs)\n\n\ndef test_install_from_future_wheel_version(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing a wheel with a WHEEL metadata version that is:\n    - a major version ahead of what we expect (not ok), and\n    - a minor version ahead of what we expect (ok)\n    \"\"\"\n    from tests.lib import TestFailure\n\n    package = make_wheel_with_file(\n        name=\"futurewheel\",\n        version=\"3.0\",\n        wheel_metadata_updates={\"Wheel-Version\": \"3.0\"},\n    ).save_to_dir(tmpdir)\n\n    result = script.pip(\"install\", package, \"--no-index\", expect_error=True)\n    with pytest.raises(TestFailure):\n        result.assert_installed(\"futurewheel\", editable=False)\n\n    package = make_wheel_with_file(\n        name=\"futurewheel\",\n        version=\"1.9\",\n        wheel_metadata_updates={\"Wheel-Version\": \"1.9\"},\n    ).save_to_dir(tmpdir)\n    result = script.pip(\"install\", package, \"--no-index\", expect_stderr=True)\n    result.assert_installed(\"futurewheel\", editable=False)\n\n\n@pytest.mark.parametrize(\n    \"wheel_name\",\n    [\n        \"brokenwheel-1.0-py2.py3-none-any.whl\",\n        \"corruptwheel-1.0-py2.py3-none-any.whl\",\n    ],\n)\ndef test_install_from_broken_wheel(\n    script: PipTestEnvironment, data: TestData, wheel_name: str\n) -> None:\n    \"\"\"\n    Test that installing a broken wheel fails properly\n    \"\"\"\n    from tests.lib import TestFailure\n\n    package = data.packages.joinpath(wheel_name)\n    result = script.pip(\"install\", package, \"--no-index\", expect_error=True)\n    with pytest.raises(TestFailure):\n        result.assert_installed(\"futurewheel\", editable=False)\n\n\ndef test_basic_install_from_wheel(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing from a wheel (that has a script)\n    \"\"\"\n    shutil.copy(shared_data.packages / \"has.script-1.0-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"has.script==1.0\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    dist_info_folder = script.site_packages / \"has.script-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n    script_file = script.bin / \"script.py\"\n    result.did_create(script_file)\n\n\ndef test_basic_install_from_wheel_with_extras(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing from a wheel with extras.\n    \"\"\"\n    shutil.copy(shared_data.packages / \"complex_dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"complex-dist[simple]\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    dist_info_folder = script.site_packages / \"complex_dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"simple.dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n\ndef test_basic_install_from_wheel_file(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing directly from a wheel file.\n    \"\"\"\n    package = data.packages.joinpath(\"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"--no-index\")\n    dist_info_folder = script.site_packages / \"simple.dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n    installer = dist_info_folder / \"INSTALLER\"\n    result.did_create(installer)\n    with open(script.base_path / installer, \"rb\") as installer_file:\n        installer_details = installer_file.read()\n        assert installer_details == b\"pip\\n\"\n    installer_temp = dist_info_folder / \"INSTALLER.pip\"\n    result.did_not_create(installer_temp)\n\n\n# Installation seems to work, but scripttest fails to check.\n# I really don't care now since we're desupporting it soon anyway.\ndef test_basic_install_from_unicode_wheel(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test installing from a wheel (that has a script)\n    \"\"\"\n    make_wheel(\n        \"unicode_package\",\n        \"1.0\",\n        extra_files={\n            \"வணக்கம்/__init__.py\": b\"\",\n            \"வணக்கம்/નમસ્તે.py\": b\"\",\n        },\n    ).save_to_dir(script.scratch_path)\n\n    result = script.pip(\n        \"install\",\n        \"unicode_package==1.0\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n    )\n    dist_info_folder = script.site_packages / \"unicode_package-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n\n    file1 = script.site_packages.joinpath(\"வணக்கம்\", \"__init__.py\")\n    result.did_create(file1)\n\n    file2 = script.site_packages.joinpath(\"வணக்கம்\", \"નમસ્તે.py\")\n    result.did_create(file2)\n\n\ndef get_header_scheme_path_for_script(\n    script: PipTestEnvironment, dist_name: str\n) -> Path:\n    command = (\n        \"from pip._internal.locations import get_scheme;\"\n        f\"scheme = get_scheme({dist_name!r});\"\n        \"print(scheme.headers);\"\n    )\n    result = script.run(\"python\", \"-c\", command).stdout\n    return Path(result.strip())\n\n\ndef test_install_from_wheel_with_headers(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test installing from a wheel file with headers\n    \"\"\"\n    header_text = \"/* hello world */\\n\"\n    package = make_wheel(\n        \"headers.dist\",\n        \"0.1\",\n        extra_data_files={\"headers/header.h\": header_text},\n    ).save_to_dir(script.scratch_path)\n    result = script.pip(\"install\", package, \"--no-index\")\n    dist_info_folder = script.site_packages / \"headers.dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n    header_scheme_path = get_header_scheme_path_for_script(script, \"headers-dist\")\n    header_path = header_scheme_path / \"header.h\"\n    assert header_path.read_text() == header_text\n\n\ndef test_install_wheel_with_target(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing a wheel using pip install --target\n    \"\"\"\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    target_dir = script.scratch_path / \"target\"\n    result = script.pip(\n        \"install\",\n        \"simple.dist==0.1\",\n        \"-t\",\n        target_dir,\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    result.did_create(Path(\"scratch\") / \"target\" / \"simpledist\")\n\n\ndef test_install_wheel_with_target_and_data_files(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test for issue #4092. It will be checked that a data_files specification in\n    setup.py is handled correctly when a wheel is installed with the --target\n    option.\n\n    The setup() for the wheel 'prjwithdatafile-1.0-py2.py3-none-any.whl' is as\n    follows ::\n\n        setup(\n            name='prjwithdatafile',\n            version='1.0',\n            packages=['prjwithdatafile'],\n            data_files=[\n                (r'packages1', ['prjwithdatafile/README.txt']),\n                (r'packages2', ['prjwithdatafile/README.txt'])\n            ]\n        )\n    \"\"\"\n    target_dir = script.scratch_path / \"prjwithdatafile\"\n    package = data.packages.joinpath(\"prjwithdatafile-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"-t\", target_dir, \"--no-index\")\n    project_path = Path(\"scratch\") / \"prjwithdatafile\"\n    result.did_create(project_path / \"packages1\" / \"README.txt\")\n    result.did_create(project_path / \"packages2\" / \"README.txt\")\n    result.did_not_create(project_path / \"lib\" / \"python\")\n\n\ndef test_install_wheel_with_root(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing a wheel using pip install --root\n    \"\"\"\n    root_dir = script.scratch_path / \"root\"\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"simple.dist==0.1\",\n        \"--root\",\n        root_dir,\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    result.did_create(Path(\"scratch\") / \"root\")\n\n\ndef test_install_wheel_with_prefix(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing a wheel using pip install --prefix\n    \"\"\"\n    prefix_dir = script.scratch_path / \"prefix\"\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"simple.dist==0.1\",\n        \"--prefix\",\n        prefix_dir,\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    lib = sysconfig.get_path(\n        \"purelib\", vars={\"base\": os.path.join(\"scratch\", \"prefix\")}\n    )\n    result.did_create(lib)\n\n\ndef test_install_from_wheel_installs_deps(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test can install dependencies of wheels\n    \"\"\"\n    # 'requires_source' depends on the 'source' project\n    package = data.packages.joinpath(\"requires_source-1.0-py2.py3-none-any.whl\")\n    shutil.copy(data.packages / \"source-1.0.tar.gz\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n        package,\n    )\n    result.assert_installed(\"source\", editable=False)\n\n\ndef test_install_from_wheel_no_deps(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test --no-deps works with wheel installs\n    \"\"\"\n    # 'requires_source' depends on the 'source' project\n    package = data.packages.joinpath(\"requires_source-1.0-py2.py3-none-any.whl\")\n    shutil.copy(data.packages / \"source-1.0.tar.gz\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n        \"--no-deps\",\n        package,\n    )\n    pkg_folder = script.site_packages / \"source\"\n    result.did_not_create(pkg_folder)\n\n\ndef test_wheel_record_lines_in_deterministic_order(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    to_install = data.packages.joinpath(\"simplewheel-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", to_install)\n\n    dist_info_folder = script.site_packages / \"simplewheel-1.0.dist-info\"\n    record_path = dist_info_folder / \"RECORD\"\n\n    result.did_create(dist_info_folder)\n    result.did_create(record_path)\n\n    record_path = result.files_created[record_path].full\n    record_lines = [p for p in Path(record_path).read_text().split(\"\\n\") if p]\n    assert record_lines == sorted(record_lines)\n\n\ndef test_wheel_record_lines_have_hash_for_data_files(\n    script: PipTestEnvironment,\n) -> None:\n    package = make_wheel(\n        \"simple\",\n        \"0.1.0\",\n        extra_data_files={\n            \"purelib/info.txt\": \"c\",\n        },\n    ).save_to_dir(script.scratch_path)\n    script.pip(\"install\", package)\n    record_file = script.site_packages_path / \"simple-0.1.0.dist-info\" / \"RECORD\"\n    record_text = record_file.read_text()\n    record_rows = list(csv.reader(record_text.splitlines()))\n    records = {r[0]: r[1:] for r in record_rows}\n    assert records[\"info.txt\"] == [\n        \"sha256=Ln0sA6lQeuJl7PW1NWiFpTOTogKdJBOUmXJloaJa78Y\",\n        \"1\",\n    ]\n\n\ndef test_wheel_record_lines_have_updated_hash_for_scripts(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    pip rewrites \"#!python\" shebang lines in scripts when it installs them;\n    make sure it updates the RECORD file correspondingly.\n    \"\"\"\n    package = make_wheel(\n        \"simple\",\n        \"0.1.0\",\n        extra_data_files={\n            \"scripts/dostuff\": \"#!python\\n\",\n        },\n    ).save_to_dir(script.scratch_path)\n    script.pip(\"install\", package)\n    record_file = script.site_packages_path / \"simple-0.1.0.dist-info\" / \"RECORD\"\n    record_text = record_file.read_text()\n    record_rows = list(csv.reader(record_text.splitlines()))\n    records = {r[0]: r[1:] for r in record_rows}\n\n    script_path = script.bin_path / \"dostuff\"\n    script_contents = script_path.read_bytes()\n    assert not script_contents.startswith(b\"#!python\\n\")\n\n    script_digest = hashlib.sha256(script_contents).digest()\n    script_digest_b64 = (\n        base64.urlsafe_b64encode(script_digest).decode(\"US-ASCII\").rstrip(\"=\")\n    )\n\n    script_record_path = os.path.relpath(\n        script_path, script.site_packages_path\n    ).replace(os.path.sep, \"/\")\n    assert records[script_record_path] == [\n        f\"sha256={script_digest_b64}\",\n        str(len(script_contents)),\n    ]\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_install_user_wheel(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test user install from wheel (that has a script)\n    \"\"\"\n    shutil.copy(shared_data.packages / \"has.script-1.0-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"has.script==1.0\",\n        \"--user\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    dist_info_folder = script.user_site / \"has.script-1.0.dist-info\"\n    result.did_create(dist_info_folder)\n    script_file = script.user_bin / \"script.py\"\n    result.did_create(script_file)\n\n\ndef test_install_from_wheel_gen_entrypoint(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing scripts (entry points are generated)\n    \"\"\"\n    shutil.copy(\n        shared_data.packages / \"script.wheel1a-0.1-py2.py3-none-any.whl\",\n        tmpdir,\n    )\n    result = script.pip(\n        \"install\",\n        \"script.wheel1a==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    if os.name == \"nt\":\n        wrapper_file = script.bin / \"t1.exe\"\n    else:\n        wrapper_file = script.bin / \"t1\"\n    result.did_create(wrapper_file)\n\n    if os.name != \"nt\":\n        assert bool(os.access(script.base_path / wrapper_file, os.X_OK))\n\n\ndef test_install_from_wheel_gen_uppercase_entrypoint(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing scripts with uppercase letters in entry point names\n    \"\"\"\n    shutil.copy(\n        shared_data.packages / \"console_scripts_uppercase-1.0-py2.py3-none-any.whl\",\n        tmpdir,\n    )\n    result = script.pip(\n        \"install\",\n        \"console-scripts-uppercase==1.0\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    if os.name == \"nt\":\n        # Case probably doesn't make any difference on NT\n        wrapper_file = script.bin / \"cmdName.exe\"\n    else:\n        wrapper_file = script.bin / \"cmdName\"\n    result.did_create(wrapper_file)\n\n    if os.name != \"nt\":\n        assert bool(os.access(script.base_path / wrapper_file, os.X_OK))\n\n\ndef test_install_from_wheel_gen_unicode_entrypoint(script: PipTestEnvironment) -> None:\n    make_wheel(\n        \"script_wheel_unicode\",\n        \"1.0\",\n        console_scripts=[\"進入點 = 模組:函式\"],\n    ).save_to_dir(script.scratch_path)\n\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"script_wheel_unicode\",\n    )\n    if os.name == \"nt\":\n        result.did_create(script.bin.joinpath(\"進入點.exe\"))\n    else:\n        result.did_create(script.bin.joinpath(\"進入點\"))\n\n\ndef test_install_from_wheel_with_legacy(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing scripts (legacy scripts are preserved)\n    \"\"\"\n    shutil.copy(\n        shared_data.packages / \"script.wheel2a-0.1-py2.py3-none-any.whl\",\n        tmpdir,\n    )\n    result = script.pip(\n        \"install\",\n        \"script.wheel2a==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n\n    legacy_file1 = script.bin / \"testscript1.bat\"\n    legacy_file2 = script.bin / \"testscript2\"\n\n    result.did_create(legacy_file1)\n    result.did_create(legacy_file2)\n\n\ndef test_install_from_wheel_no_setuptools_entrypoint(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that when we generate scripts, any existing setuptools wrappers in\n    the wheel are skipped.\n    \"\"\"\n    shutil.copy(shared_data.packages / \"script.wheel1-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"script.wheel1==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    if os.name == \"nt\":\n        wrapper_file = script.bin / \"t1.exe\"\n    else:\n        wrapper_file = script.bin / \"t1\"\n    wrapper_helper = script.bin / \"t1-script.py\"\n\n    # The wheel has t1.exe and t1-script.py. We will be generating t1 or\n    # t1.exe depending on the platform. So we check that the correct wrapper\n    # is present and that the -script.py helper has been skipped. We can't\n    # easily test that the wrapper from the wheel has been skipped /\n    # overwritten without getting very platform-dependent, so omit that.\n    result.did_create(wrapper_file)\n    result.did_not_create(wrapper_helper)\n\n\ndef test_skipping_setuptools_doesnt_skip_legacy(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing scripts (legacy scripts are preserved even when we skip\n    setuptools wrappers)\n    \"\"\"\n    shutil.copy(shared_data.packages / \"script.wheel2-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"script.wheel2==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n\n    legacy_file1 = script.bin / \"testscript1.bat\"\n    legacy_file2 = script.bin / \"testscript2\"\n    wrapper_helper = script.bin / \"t1-script.py\"\n\n    result.did_create(legacy_file1)\n    result.did_create(legacy_file2)\n    result.did_not_create(wrapper_helper)\n\n\ndef test_install_from_wheel_gui_entrypoint(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing scripts (gui entry points are generated)\n    \"\"\"\n    shutil.copy(shared_data.packages / \"script.wheel3-0.1-py2.py3-none-any.whl\", tmpdir)\n    result = script.pip(\n        \"install\",\n        \"script.wheel3==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    if os.name == \"nt\":\n        wrapper_file = script.bin / \"t1.exe\"\n    else:\n        wrapper_file = script.bin / \"t1\"\n    result.did_create(wrapper_file)\n\n\ndef test_wheel_compiles_pyc(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing from wheel with --compile on\n    \"\"\"\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    script.pip(\n        \"install\",\n        \"--compile\",\n        \"simple.dist==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    # There are many locations for the __init__.pyc file so attempt to find\n    #   any of them\n    exists = [\n        os.path.exists(script.site_packages_path / \"simpledist/__init__.pyc\"),\n        *script.site_packages_path.glob(\"simpledist/__pycache__/__init__*.pyc\"),\n    ]\n    assert any(exists)\n\n\ndef test_wheel_no_compiles_pyc(\n    script: PipTestEnvironment, shared_data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test installing from wheel with --compile on\n    \"\"\"\n    shutil.copy(shared_data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\", tmpdir)\n    script.pip(\n        \"install\",\n        \"--no-compile\",\n        \"simple.dist==0.1\",\n        \"--no-index\",\n        \"--find-links\",\n        tmpdir,\n    )\n    # There are many locations for the __init__.pyc file so attempt to find\n    #   any of them\n    exists = [\n        os.path.exists(script.site_packages_path / \"simpledist/__init__.pyc\"),\n        *script.site_packages_path.glob(\"simpledist/__pycache__/__init__*.pyc\"),\n    ]\n\n    assert not any(exists)\n\n\ndef test_install_from_wheel_uninstalls_old_version(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    # regression test for https://github.com/pypa/pip/issues/1825\n    package = data.packages.joinpath(\"simplewheel-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"--no-index\")\n    package = data.packages.joinpath(\"simplewheel-2.0-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"--no-index\")\n    dist_info_folder = script.site_packages / \"simplewheel-2.0.dist-info\"\n    result.did_create(dist_info_folder)\n    dist_info_folder = script.site_packages / \"simplewheel-1.0.dist-info\"\n    result.did_not_create(dist_info_folder)\n\n\ndef test_wheel_compile_syntax_error(script: PipTestEnvironment, data: TestData) -> None:\n    package = data.packages.joinpath(\"compilewheel-1.0-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", \"--compile\", package, \"--no-index\")\n    assert \"yield from\" not in result.stdout\n    assert \"SyntaxError: \" not in result.stdout\n\n\ndef test_wheel_install_with_no_cache_dir(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Check wheel installations work, even with no cache.\"\"\"\n    package = data.packages.joinpath(\"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", \"--no-cache-dir\", \"--no-index\", package)\n    result.assert_installed(\"simpledist\", editable=False)\n\n\ndef test_wheel_install_fails_with_extra_dist_info(script: PipTestEnvironment) -> None:\n    package = create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n        extra_files={\n            \"unrelated-2.0.0.dist-info/WHEEL\": \"Wheel-Version: 1.0\",\n            \"unrelated-2.0.0.dist-info/METADATA\": (\"Name: unrelated\\nVersion: 2.0.0\\n\"),\n        },\n    )\n    result = script.pip(\n        \"install\", \"--no-cache-dir\", \"--no-index\", package, expect_error=True\n    )\n    assert \"multiple .dist-info directories\" in result.stderr\n\n\ndef test_wheel_install_fails_with_unrelated_dist_info(\n    script: PipTestEnvironment,\n) -> None:\n    package = create_basic_wheel_for_package(script, \"simple\", \"0.1.0\")\n    new_name = \"unrelated-2.0.0-py2.py3-none-any.whl\"\n    new_package = os.path.join(os.path.dirname(package), new_name)\n    shutil.move(os.fspath(package), new_package)\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        new_package,\n        expect_error=True,\n    )\n\n    assert \"'simple-0.1.0.dist-info' does not start with 'unrelated'\" in result.stderr\n\n\ndef test_wheel_installs_ok_with_nested_dist_info(script: PipTestEnvironment) -> None:\n    package = create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n        extra_files={\n            \"subdir/unrelated-2.0.0.dist-info/WHEEL\": \"Wheel-Version: 1.0\",\n            \"subdir/unrelated-2.0.0.dist-info/METADATA\": (\n                \"Name: unrelated\\nVersion: 2.0.0\\n\"\n            ),\n        },\n    )\n    script.pip(\"install\", \"--no-cache-dir\", \"--no-index\", package)\n\n\ndef test_wheel_installs_ok_with_badly_encoded_irrelevant_dist_info_file(\n    script: PipTestEnvironment,\n) -> None:\n    package = create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n        extra_files={\"simple-0.1.0.dist-info/AUTHORS.txt\": b\"\\xff\"},\n    )\n    script.pip(\"install\", \"--no-cache-dir\", \"--no-index\", package)\n\n\ndef test_wheel_install_fails_with_badly_encoded_metadata(\n    script: PipTestEnvironment,\n) -> None:\n    package = make_wheel(\"simple\", \"0.1.0\", metadata=b\"\\xff\").save_to_dir(\n        script.scratch_path\n    )\n    result = script.pip(\n        \"install\", \"--no-cache-dir\", \"--no-index\", package, expect_error=True\n    )\n    assert \"Error decoding metadata for\" in result.stderr\n    assert \"simple-0.1.0-py2.py3-none-any.whl\" in result.stderr\n    assert \"METADATA\" in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"package_name\",\n    [\"simple-package\", \"simple_package\"],\n)\ndef test_correct_package_name_while_creating_wheel_bug(\n    script: PipTestEnvironment, package_name: str\n) -> None:\n    \"\"\"Check that the package name is correctly named while creating\n    a .whl file with a given format\n    \"\"\"\n    package = create_basic_wheel_for_package(script, package_name, \"1.0\")\n    wheel_name = os.path.basename(package)\n    assert wheel_name == \"simple_package-1.0-py2.py3-none-any.whl\"\n\n\n@pytest.mark.parametrize(\"name\", [\"purelib\", \"abc\"])\ndef test_wheel_with_file_in_data_dir_has_reasonable_error(\n    script: PipTestEnvironment, tmpdir: Path, name: str\n) -> None:\n    \"\"\"Normally we expect entities in the .data directory to be in a\n    subdirectory, but if they are not then we should show a reasonable error\n    message that includes the path.\n    \"\"\"\n    wheel_path = make_wheel(\n        \"simple\", \"0.1.0\", extra_data_files={name: \"hello world\"}\n    ).save_to_dir(tmpdir)\n\n    result = script.pip(\"install\", \"--no-index\", str(wheel_path), expect_error=True)\n    assert f\"simple-0.1.0.data/{name}\" in result.stderr\n\n\ndef test_wheel_with_unknown_subdir_in_data_dir_has_reasonable_error(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    wheel_path = make_wheel(\n        \"simple\", \"0.1.0\", extra_data_files={\"unknown/hello.txt\": \"hello world\"}\n    ).save_to_dir(tmpdir)\n\n    result = script.pip(\"install\", \"--no-index\", str(wheel_path), expect_error=True)\n    assert \"simple-0.1.0.data/unknown/hello.txt\" in result.stderr\n"
  },
  {
    "path": "tests/functional/test_invalid_versions_and_specifiers.py",
    "content": "import zipfile\n\nimport pytest\n\nfrom pip._internal.metadata import select_backend\n\nfrom tests.lib import PipTestEnvironment, TestData\n\n\ndef test_install_from_index_with_invalid_version(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that pip does not crash when installing a package from an index with\n    an invalid version. It ignores invalid versions.\n    \"\"\"\n    index_url = data.index_url(\"invalid-version\")\n    result = script.pip(\n        \"install\", \"--dry-run\", \"--index-url\", index_url, \"invalid-version\"\n    )\n    assert \"Would install invalid-version-1.0\" in result.stdout\n\n\ndef test_install_from_index_with_invalid_specifier(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that pip does not crash when installing a package with an invalid\n    version specifier in its dependencies.\n    \"\"\"\n    index_url = data.index_url(\"require-invalid-version\")\n    result = script.pip(\n        \"install\",\n        \"--dry-run\",\n        \"--index-url\",\n        index_url,\n        \"require-invalid-version\",\n        allow_stderr_warning=True,\n    )\n    assert (\n        \"WARNING: Ignoring version 1.0 of require-invalid-version \"\n        \"since it has invalid metadata\"\n    ) in result.stderr\n    assert \"Would install require-invalid-version-0.1\" in result.stdout\n\n\ndef _install_invalid_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Install a package with an invalid version.\n    \"\"\"\n    with zipfile.ZipFile(\n        data.packages.joinpath(\"invalid_version-2010i-py3-none-any.whl\")\n    ) as zf:\n        zf.extractall(script.site_packages_path)\n\n\ndef _install_require_invalid_version(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Install a package with an invalid version.\n    \"\"\"\n    with zipfile.ZipFile(\n        data.packages.joinpath(\"require_invalid_version-1.0-py3-none-any.whl\")\n    ) as zf:\n        zf.extractall(script.site_packages_path)\n\n\ndef test_uninstall_invalid_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that it is possible to uninstall a distribution with an invalid version.\n    \"\"\"\n    _install_invalid_version(script, data)\n    script.pip(\"uninstall\", \"-y\", \"invalid-version\")\n\n\n@pytest.mark.xfail\ndef test_upgrade_invalid_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that it is possible to upgrade a distribution with an invalid version.\n    \"\"\"\n    _install_invalid_version(script, data)\n    index_url = data.index_url(\"invalid-version\")\n    script.pip(\"install\", \"--index-url\", index_url, \"invalid-version\")\n\n\n@pytest.mark.xfail\ndef test_upgrade_require_invalid_version(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that it is possible to upgrade a distribution with an invalid metadata.\n    \"\"\"\n    _install_require_invalid_version(script, data)\n    index_url = data.index_url(\"require-invalid-version\")\n    script.pip(\"install\", \"--index-url\", index_url, \"require-invalid-version\")\n\n\n@pytest.mark.parametrize(\"format\", [\"columns\", \"freeze\", \"json\"])\ndef test_list_invalid_version(\n    script: PipTestEnvironment, data: TestData, format: str\n) -> None:\n    \"\"\"\n    Test that pip can list an environment containing a package with a legacy version.\n    \"\"\"\n    _install_invalid_version(script, data)\n    script.pip(\"list\", f\"--format={format}\")\n\n\ndef test_freeze_invalid_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that pip can freeze an environment containing a package with a legacy version.\n    \"\"\"\n    _install_invalid_version(script, data)\n    result = script.pip(\"freeze\")\n    assert \"invalid-version===2010i\\n\" in result.stdout\n\n\ndef test_show_invalid_version(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that pip can show an installed distribution with a legacy version.\n    \"\"\"\n    _install_invalid_version(script, data)\n    result = script.pip(\"show\", \"invalid-version\")\n    assert \"Name: invalid-version\\nVersion: 2010i\\n\" in result.stdout\n\n\ndef test_show_require_invalid_version(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that pip can show an installed distribution with a legacy specifier.\n    \"\"\"\n    _install_require_invalid_version(script, data)\n    result = script.pip(\"show\", \"require-invalid-version\")\n    assert \"Name: require-invalid-version\\nVersion: 1.0\\n\" in result.stdout\n    assert \"Requires: invalid-version ==2010i\\n\" in result.stdout\n    if select_backend().NAME == \"importlib\":\n        assert \"Required-by: #N/A\\n\" in result.stdout\n    elif select_backend().NAME == \"pkg_resources\":\n        assert \"Required-by: \\n\" in result.stdout\n    else:\n        pytest.fail(\"Unknown metadata backend\")\n"
  },
  {
    "path": "tests/functional/test_list.py",
    "content": "import json\nimport os\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.models.direct_url import DirectUrl, DirInfo\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    ScriptFactory,\n    TestData,\n    _create_test_package,\n    create_test_package_with_setup,\n    make_wheel,\n    wheel,\n)\n\n\n@pytest.fixture(scope=\"session\")\ndef simple_script(\n    tmpdir_factory: pytest.TempPathFactory,\n    script_factory: ScriptFactory,\n    shared_data: TestData,\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"pip_test_package\")\n    script = script_factory(tmpdir.joinpath(\"workspace\"))\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        shared_data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n        \"simple2==3.0\",\n    )\n    return script\n\n\ndef test_basic_list(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test default behavior of list command without format specifier.\n\n    \"\"\"\n    result = simple_script.pip(\"list\")\n    assert \"simple     1.0\" in result.stdout, str(result)\n    assert \"simple2    3.0\" in result.stdout, str(result)\n\n\ndef test_verbose_flag(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the list command with the '-v' option\n    \"\"\"\n    result = simple_script.pip(\"list\", \"-v\", \"--format=columns\")\n    assert \"Package\" in result.stdout, str(result)\n    assert \"Version\" in result.stdout, str(result)\n    assert \"Location\" in result.stdout, str(result)\n    assert \"Installer\" in result.stdout, str(result)\n    assert \"simple     1.0\" in result.stdout, str(result)\n    assert \"simple2    3.0\" in result.stdout, str(result)\n\n\ndef test_columns_flag(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the list command with the '--format=columns' option\n    \"\"\"\n    result = simple_script.pip(\"list\", \"--format=columns\")\n    assert \"Package\" in result.stdout, str(result)\n    assert \"Version\" in result.stdout, str(result)\n    assert \"simple (1.0)\" not in result.stdout, str(result)\n    assert \"simple     1.0\" in result.stdout, str(result)\n    assert \"simple2    3.0\" in result.stdout, str(result)\n\n\ndef test_format_priority(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that latest format has priority over previous ones.\n    \"\"\"\n    result = simple_script.pip(\n        \"list\", \"--format=columns\", \"--format=freeze\", expect_stderr=True\n    )\n    assert \"simple==1.0\" in result.stdout, str(result)\n    assert \"simple2==3.0\" in result.stdout, str(result)\n    assert \"simple     1.0\" not in result.stdout, str(result)\n    assert \"simple2    3.0\" not in result.stdout, str(result)\n\n    result = simple_script.pip(\"list\", \"--format=freeze\", \"--format=columns\")\n    assert \"Package\" in result.stdout, str(result)\n    assert \"Version\" in result.stdout, str(result)\n    assert \"simple==1.0\" not in result.stdout, str(result)\n    assert \"simple2==3.0\" not in result.stdout, str(result)\n    assert \"simple     1.0\" in result.stdout, str(result)\n    assert \"simple2    3.0\" in result.stdout, str(result)\n\n\ndef test_local_flag(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the behavior of --local flag in the list command\n\n    \"\"\"\n    result = simple_script.pip(\"list\", \"--local\", \"--format=json\")\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in json.loads(result.stdout)\n\n\ndef test_local_columns_flag(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the behavior of --local --format=columns flags in the list command\n\n    \"\"\"\n    result = simple_script.pip(\"list\", \"--local\", \"--format=columns\")\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"simple (1.0)\" not in result.stdout\n    assert \"simple  1.0\" in result.stdout, str(result)\n\n\ndef test_multiple_exclude_and_normalization(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    req_path = wheel.make_wheel(name=\"Normalizable_Name\", version=\"1.0\").save_to_dir(\n        tmpdir\n    )\n    script.pip(\"install\", \"--no-index\", req_path)\n    result = script.pip(\"list\")\n    print(result.stdout)\n    assert \"Normalizable_Name\" in result.stdout\n    assert \"pip\" in result.stdout\n    result = script.pip(\"list\", \"--exclude\", \"normalizablE-namE\", \"--exclude\", \"pIp\")\n    assert \"Normalizable_Name\" not in result.stdout\n    assert \"pip\" not in result.stdout\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_user_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --user flag in the list command\n\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    script.pip_install_local(\"--user\", \"simple.dist==0.1\")\n    result = script.pip(\"list\", \"--user\", \"--format=json\")\n    assert {\"name\": \"simplewheel\", \"version\": \"1.0\"} not in json.loads(result.stdout)\n    assert {\"name\": \"simple.dist\", \"version\": \"0.1\"} in json.loads(result.stdout)\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_user_columns_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --user --format=columns flags in the list command\n\n    \"\"\"\n    script.pip_install_local(\"simplewheel==1.0\")\n    script.pip_install_local(\"--user\", \"simple.dist==0.1\")\n    result = script.pip(\"list\", \"--user\", \"--format=columns\")\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"simple.dist (2.0)\" not in result.stdout\n    assert \"simple.dist 0.1\" in result.stdout, str(result)\n\n\n@pytest.mark.network\ndef test_uptodate_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --uptodate flag in the list command\n\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n        \"simple2==3.0\",\n    )\n    script.pip(\n        \"install\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--uptodate\",\n        \"--format=json\",\n    )\n    json_output = json.loads(result.stdout)\n    for item in json_output:\n        if \"editable_project_location\" in item:\n            item[\"editable_project_location\"] = \"<location>\"\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} not in json_output  # 3.0 is latest\n    assert {\n        \"name\": \"pip-test-package\",\n        \"version\": \"0.1.1\",\n        \"editable_project_location\": \"<location>\",\n    } in json_output  # editables included\n    assert {\"name\": \"simple2\", \"version\": \"3.0\"} in json_output\n\n\n@pytest.mark.network\ndef test_uptodate_columns_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --uptodate --format=columns flag in the list command\n\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n        \"simple2==3.0\",\n    )\n    script.pip(\n        \"install\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--uptodate\",\n        \"--format=columns\",\n    )\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"Editable project location\" in result.stdout  # editables included\n    assert \"pip-test-package (0.1.1,\" not in result.stdout\n    assert \"pip-test-package 0.1.1\" in result.stdout, str(result)\n    assert \"simple2          3.0\" in result.stdout, str(result)\n\n\n@pytest.mark.network\ndef test_outdated_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --outdated flag in the list command\n\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n        \"simple2==3.0\",\n        \"simplewheel==1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git@0.1#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--outdated\",\n        \"--format=json\",\n    )\n    json_output = json.loads(result.stdout)\n    for item in json_output:\n        if \"editable_project_location\" in item:\n            item[\"editable_project_location\"] = \"<location>\"\n    assert {\n        \"name\": \"simple\",\n        \"version\": \"1.0\",\n        \"latest_version\": \"3.0\",\n        \"latest_filetype\": \"sdist\",\n    } in json_output\n    assert {\n        \"name\": \"simplewheel\",\n        \"version\": \"1.0\",\n        \"latest_version\": \"2.0\",\n        \"latest_filetype\": \"wheel\",\n    } in json_output\n    assert {\n        \"name\": \"pip-test-package\",\n        \"version\": \"0.1\",\n        \"latest_version\": \"0.1.1\",\n        \"latest_filetype\": \"sdist\",\n        \"editable_project_location\": \"<location>\",\n    } in json_output\n    assert \"simple2\" not in {p[\"name\"] for p in json_output}\n\n\n@pytest.mark.network\ndef test_outdated_columns_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test the behavior of --outdated --format=columns flag in the list command\n\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n        \"simple2==3.0\",\n        \"simplewheel==1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git@0.1#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--outdated\",\n        \"--format=columns\",\n    )\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"Latest\" in result.stdout\n    assert \"Type\" in result.stdout\n    assert \"simple (1.0) - Latest: 3.0 [sdist]\" not in result.stdout\n    assert \"simplewheel (1.0) - Latest: 2.0 [wheel]\" not in result.stdout\n    assert \"simple           1.0     3.0    sdist\" in result.stdout, str(result)\n    assert \"simplewheel      1.0     2.0    wheel\" in result.stdout, str(result)\n    assert \"simple2\" not in result.stdout, str(result)  # 3.0 is latest\n\n\n@pytest.fixture(scope=\"session\")\ndef pip_test_package_script(\n    tmpdir_factory: pytest.TempPathFactory,\n    script_factory: ScriptFactory,\n    shared_data: TestData,\n) -> PipTestEnvironment:\n    tmpdir = tmpdir_factory.mktemp(\"pip_test_package\")\n    script = script_factory(tmpdir.joinpath(\"workspace\"))\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        shared_data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package\",\n    )\n    return script\n\n\n@pytest.mark.network\ndef test_editables_flag(pip_test_package_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the behavior of --editables flag in the list command\n    \"\"\"\n    result = pip_test_package_script.pip(\"list\", \"--editable\", \"--format=json\")\n    result2 = pip_test_package_script.pip(\"list\", \"--editable\")\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} not in json.loads(result.stdout)\n    assert os.path.join(\"src\", \"pip-test-package\") in result2.stdout\n\n\n@pytest.mark.network\ndef test_exclude_editable_flag(pip_test_package_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the behavior of --editables flag in the list command\n    \"\"\"\n    result = pip_test_package_script.pip(\"list\", \"--exclude-editable\", \"--format=json\")\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in json.loads(result.stdout)\n    assert \"pip-test-package\" not in {p[\"name\"] for p in json.loads(result.stdout)}\n\n\n@pytest.mark.network\ndef test_editables_columns_flag(pip_test_package_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test the behavior of --editables flag in the list command\n    \"\"\"\n    result = pip_test_package_script.pip(\"list\", \"--editable\", \"--format=columns\")\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"Editable project location\" in result.stdout\n    assert os.path.join(\"src\", \"pip-test-package\") in result.stdout, str(result)\n\n\n@pytest.mark.network\ndef test_uptodate_editables_flag(\n    pip_test_package_script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    test the behavior of --editable --uptodate flag in the list command\n    \"\"\"\n    result = pip_test_package_script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--editable\",\n        \"--uptodate\",\n    )\n    assert \"simple\" not in result.stdout\n    assert os.path.join(\"src\", \"pip-test-package\") in result.stdout, str(result)\n\n\n@pytest.mark.network\ndef test_uptodate_editables_columns_flag(\n    pip_test_package_script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    test the behavior of --editable --uptodate --format=columns flag in the\n    list command\n    \"\"\"\n    result = pip_test_package_script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--editable\",\n        \"--uptodate\",\n        \"--format=columns\",\n    )\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"Editable project location\" in result.stdout\n    assert os.path.join(\"src\", \"pip-test-package\") in result.stdout, str(result)\n\n\n@pytest.mark.network\ndef test_outdated_editables_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    test the behavior of --editable --outdated flag in the list command\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git@0.1#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--editable\",\n        \"--outdated\",\n    )\n    assert \"simple\" not in result.stdout\n    assert os.path.join(\"src\", \"pip-test-package\") in result.stdout\n\n\n@pytest.mark.network\ndef test_outdated_editables_columns_flag(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    test the behavior of --editable --outdated flag in the list command\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package.git@0.1#egg=pip-test-package\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--editable\",\n        \"--outdated\",\n        \"--format=columns\",\n    )\n    assert \"Package\" in result.stdout\n    assert \"Version\" in result.stdout\n    assert \"Editable project location\" in result.stdout\n    assert os.path.join(\"src\", \"pip-test-package\") in result.stdout, str(result)\n\n\ndef test_outdated_not_required_flag(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    test the behavior of --outdated --not-required flag in the list command\n    \"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==2.0\",\n        \"require_simple==1.0\",\n    )\n    result = script.pip(\n        \"list\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"--outdated\",\n        \"--not-required\",\n        \"--format=json\",\n    )\n    assert [] == json.loads(result.stdout)\n\n\ndef test_outdated_pre(script: PipTestEnvironment, data: TestData) -> None:\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n\n    # Let's build a fake wheelhouse\n    script.scratch_path.joinpath(\"wheelhouse\").mkdir()\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.joinpath(\"simple-1.1-py2.py3-none-any.whl\").write_text(\"\")\n    wheelhouse_path.joinpath(\"simple-2.0.dev0-py2.py3-none-any.whl\").write_text(\"\")\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--format=json\",\n    )\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in json.loads(result.stdout)\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--format=json\",\n    )\n    assert {\n        \"name\": \"simple\",\n        \"version\": \"1.0\",\n        \"latest_version\": \"1.1\",\n        \"latest_filetype\": \"wheel\",\n    } in json.loads(result.stdout)\n    result_pre = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--pre\",\n        \"--format=json\",\n    )\n    assert {\n        \"name\": \"simple\",\n        \"version\": \"1.0\",\n        \"latest_version\": \"2.0.dev0\",\n        \"latest_filetype\": \"wheel\",\n    } in json.loads(result_pre.stdout)\n\n\ndef test_outdated_formats(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"Test of different outdated formats\"\"\"\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"simple==1.0\",\n    )\n\n    # Let's build a fake wheelhouse\n    script.scratch_path.joinpath(\"wheelhouse\").mkdir()\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.joinpath(\"simple-1.1-py2.py3-none-any.whl\").write_text(\"\")\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--format=freeze\",\n    )\n    assert \"simple==1.0\" in result.stdout\n\n    # Check columns\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--format=columns\",\n    )\n    assert \"Package Version Latest Type\" in result.stdout\n    assert \"simple  1.0     1.1    wheel\" in result.stdout\n\n    # Check that freeze is not allowed\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--format=freeze\",\n        expect_error=True,\n    )\n    assert (\n        \"List format 'freeze' cannot be used with the --outdated option.\"\n        in result.stderr\n    )\n\n    # Check json\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--format=json\",\n    )\n    assert json.loads(result.stdout) == [\n        {\n            \"name\": \"simple\",\n            \"version\": \"1.0\",\n            \"latest_version\": \"1.1\",\n            \"latest_filetype\": \"wheel\",\n        }\n    ]\n\n\ndef test_not_required_flag(script: PipTestEnvironment, data: TestData) -> None:\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"-f\",\n        data.find_links,\n        \"--no-index\",\n        \"TopoRequires4\",\n    )\n    result = script.pip(\"list\", \"--not-required\", expect_stderr=True)\n    assert \"TopoRequires4 \" in result.stdout, str(result)\n    assert \"TopoRequires \" not in result.stdout\n    assert \"TopoRequires2 \" not in result.stdout\n    assert \"TopoRequires3 \" not in result.stdout\n\n\ndef test_list_freeze(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test freeze formatting of list command\n\n    \"\"\"\n    result = simple_script.pip(\"list\", \"--format=freeze\")\n    assert \"simple==1.0\" in result.stdout, str(result)\n    assert \"simple2==3.0\" in result.stdout, str(result)\n\n\ndef test_list_json(simple_script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test json formatting of list command\n\n    \"\"\"\n    result = simple_script.pip(\"list\", \"--format=json\")\n    data = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in data\n    assert {\"name\": \"simple2\", \"version\": \"3.0\"} in data\n\n\ndef test_list_path(tmpdir: Path, script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test list with --path.\n    \"\"\"\n    result = script.pip(\"list\", \"--path\", tmpdir, \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"2.0\"} not in json_result\n\n    script.pip_install_local(\"--target\", tmpdir, \"simple==2.0\")\n    result = script.pip(\"list\", \"--path\", tmpdir, \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"2.0\"} in json_result\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_list_path_exclude_user(\n    tmpdir: Path, script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test list with --path and make sure packages from --user are not picked\n    up.\n    \"\"\"\n    script.pip_install_local(\"--user\", \"simple2\")\n    script.pip_install_local(\"--target\", tmpdir, \"simple==1.0\")\n\n    result = script.pip(\"list\", \"--user\", \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple2\", \"version\": \"3.0\"} in json_result\n\n    result = script.pip(\"list\", \"--path\", tmpdir, \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in json_result\n\n\ndef test_list_path_multiple(\n    tmpdir: Path, script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test list with multiple --path arguments.\n    \"\"\"\n    path1 = tmpdir / \"path1\"\n    os.mkdir(path1)\n    path2 = tmpdir / \"path2\"\n    os.mkdir(path2)\n\n    script.pip_install_local(\"--target\", path1, \"simple==2.0\")\n    script.pip_install_local(\"--target\", path2, \"simple2==3.0\")\n\n    result = script.pip(\"list\", \"--path\", path1, \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"2.0\"} in json_result\n\n    result = script.pip(\"list\", \"--path\", path1, \"--path\", path2, \"--format=json\")\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"2.0\"} in json_result\n    assert {\"name\": \"simple2\", \"version\": \"3.0\"} in json_result\n\n\ndef test_list_skip_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that list should not include package in working directory\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    # List should not include package simple when run from package directory\n    result = script.pip(\"list\", \"--format=json\", cwd=pkg_path)\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} not in json_result\n\n\ndef test_list_include_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that list should include package in working directory\n    if working directory is added in PYTHONPATH\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    # List should include package simple when run from package directory\n    # when the package directory is in PYTHONPATH\n    result = script.pip(\"list\", \"--format=json\", cwd=pkg_path)\n    json_result = json.loads(result.stdout)\n    assert {\"name\": \"simple\", \"version\": \"1.0\"} in json_result\n\n\ndef test_list_pep610_editable(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that a package installed with a direct_url.json with editable=true\n    is correctly listed as editable.\n    \"\"\"\n    pkg_path = _create_test_package(script.scratch_path, name=\"testpkg\")\n    result = script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    direct_url_path = result.get_created_direct_url_path(\"testpkg\")\n    assert direct_url_path\n    # patch direct_url.json to simulate an editable install\n    with open(direct_url_path) as f:\n        direct_url = DirectUrl.from_json(f.read())\n    assert isinstance(direct_url.info, DirInfo)\n    direct_url.info.editable = True\n    with open(direct_url_path, \"w\") as f:\n        f.write(direct_url.to_json())\n    result = script.pip(\"list\", \"--format=json\")\n    for item in json.loads(result.stdout):\n        if item[\"name\"] == \"testpkg\":\n            assert item[\"editable_project_location\"]\n            break\n    else:\n        pytest.fail(\"package 'testpkg' not found in pip list result\")\n\n\ndef test_list_wheel_build(script: PipTestEnvironment) -> None:\n    package = make_wheel(\n        name=\"package\",\n        version=\"3.0\",\n        wheel_metadata_updates={\"Build\": \"123\"},\n    ).save_to_dir(script.scratch_path)\n    script.pip(\"install\", package, \"--no-index\")\n\n    result = script.pip(\"list\")\n    assert \"Build\" in result.stdout, str(result)\n    assert \"123\" in result.stdout, str(result)\n\n\ndef test_outdated_only_final_for_specific_package(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Test that --only-final filters prereleases for specific package.\"\"\"\n    script.pip_install_local(\"simple==1.0\")\n\n    # Create fake wheelhouse with prerelease\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.mkdir()\n    make_wheel(\"simple\", \"1.1\").save_to_dir(wheelhouse_path)\n    make_wheel(\"simple\", \"2.0a1\").save_to_dir(wheelhouse_path)\n\n    # Without --only-final, should show 1.1 (highest stable)\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--format=json\",\n    )\n    outdated = json.loads(result.stdout)\n    assert len(outdated) == 1\n    assert outdated[0][\"name\"] == \"simple\"\n    assert outdated[0][\"latest_version\"] == \"1.1\"\n\n    # With --only-final for simple, should still show 1.1\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--only-final=simple\",\n        \"--format=json\",\n    )\n    outdated = json.loads(result.stdout)\n    assert len(outdated) == 1\n    assert outdated[0][\"name\"] == \"simple\"\n    assert outdated[0][\"latest_version\"] == \"1.1\"\n\n\ndef test_outdated_all_releases_for_specific_package(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Test that --all-releases allows prereleases for specific package.\"\"\"\n    script.pip_install_local(\"simple==1.0\")\n\n    # Create fake wheelhouse with prerelease\n    wheelhouse_path = script.scratch_path / \"wheelhouse\"\n    wheelhouse_path.mkdir()\n    make_wheel(\"simple\", \"1.1\").save_to_dir(wheelhouse_path)\n    make_wheel(\"simple\", \"2.0a1\").save_to_dir(wheelhouse_path)\n\n    # With --all-releases for simple, should show 2.0a1 (highest including prereleases)\n    result = script.pip(\n        \"list\",\n        \"--no-index\",\n        \"--find-links\",\n        wheelhouse_path,\n        \"--outdated\",\n        \"--all-releases=simple\",\n        \"--format=json\",\n    )\n    outdated = json.loads(result.stdout)\n    assert len(outdated) == 1\n    assert outdated[0][\"name\"] == \"simple\"\n    assert outdated[0][\"latest_version\"] == \"2.0a1\"\n"
  },
  {
    "path": "tests/functional/test_lock.py",
    "content": "import textwrap\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.utils.compat import tomllib\nfrom pip._internal.utils.urls import path_to_url\n\nfrom ..lib import PipTestEnvironment, TestData\n\n\ndef test_lock_wheel_from_findlinks(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    \"\"\"Test locking a simple wheel package, to the default pylock.toml.\"\"\"\n    result = script.pip(\n        \"lock\",\n        \"simplewheel==2.0\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        expect_stderr=True,  # for the experimental warning\n    )\n    result.did_create(Path(\"scratch\") / \"pylock.toml\")\n    pylock = tomllib.loads(script.scratch_path.joinpath(\"pylock.toml\").read_text())\n    assert pylock == {\n        \"created-by\": \"pip\",\n        \"lock-version\": \"1.0\",\n        \"packages\": [\n            {\n                \"name\": \"simplewheel\",\n                \"version\": \"2.0\",\n                \"wheels\": [\n                    {\n                        \"name\": \"simplewheel-2.0-1-py2.py3-none-any.whl\",\n                        \"url\": path_to_url(\n                            str(\n                                shared_data.root\n                                / \"packages\"\n                                / \"simplewheel-2.0-1-py2.py3-none-any.whl\"\n                            )\n                        ),\n                        \"hashes\": {\n                            \"sha256\": (\n                                \"71e1ca6b16ae3382a698c284013f6650\"\n                                \"4f2581099b2ce4801f60e9536236ceee\"\n                            )\n                        },\n                    }\n                ],\n            },\n        ],\n    }\n\n\ndef test_lock_sdist_from_findlinks(\n    script: PipTestEnvironment, shared_data: TestData\n) -> None:\n    \"\"\"Test locking a simple wheel package, to the default pylock.toml.\"\"\"\n    result = script.pip(\n        \"lock\",\n        \"--no-build-isolation\",\n        \"simple==2.0\",\n        \"--no-binary=simple\",\n        \"--quiet\",\n        \"--output=-\",\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        expect_stderr=True,  # for the experimental warning\n    )\n    pylock = tomllib.loads(result.stdout)\n    assert pylock[\"packages\"] == [\n        {\n            \"name\": \"simple\",\n            \"sdist\": {\n                \"hashes\": {\n                    \"sha256\": (\n                        \"3a084929238d13bcd3bb928af04f3bac\"\n                        \"7ca2357d419e29f01459dc848e2d69a4\"\n                    ),\n                },\n                \"name\": \"simple-2.0.tar.gz\",\n                \"url\": path_to_url(\n                    str(shared_data.root / \"packages\" / \"simple-2.0.tar.gz\")\n                ),\n            },\n            \"version\": \"2.0\",\n        },\n    ]\n\n\ndef test_lock_local_directory(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n            \"\"\"\n        )\n    )\n    result = script.pip(\n        \"lock\",\n        \".\",\n        \"--quiet\",\n        \"--output=-\",\n        \"--no-build-isolation\",  # to use the pre-installed setuptools\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        cwd=project_path,\n        expect_stderr=True,  # for the experimental warning\n    )\n    pylock = tomllib.loads(result.stdout)\n    assert pylock[\"packages\"] == [\n        {\n            \"name\": \"pkga\",\n            \"directory\": {\"path\": \".\"},\n        },\n    ]\n\n\ndef test_lock_local_editable_with_dep(\n    script: PipTestEnvironment, shared_data: TestData, tmp_path: Path\n) -> None:\n    project_path = tmp_path / \"pkga\"\n    project_path.mkdir()\n    project_path.joinpath(\"pyproject.toml\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [project]\n            name = \"pkga\"\n            version = \"1.0\"\n            dependencies = [\"simplewheel==2.0\"]\n            \"\"\"\n        )\n    )\n    result = script.pip(\n        \"lock\",\n        \"-e\",\n        \".\",\n        \"--quiet\",\n        \"--output=-\",\n        \"--no-build-isolation\",  # to use the pre-installed setuptools\n        \"--no-index\",\n        \"--find-links\",\n        str(shared_data.root / \"packages/\"),\n        cwd=project_path,\n        expect_stderr=True,  # for the experimental warning\n    )\n    pylock = tomllib.loads(result.stdout)\n    assert pylock[\"packages\"] == [\n        {\n            \"name\": \"pkga\",\n            \"directory\": {\"editable\": True, \"path\": \".\"},\n        },\n        {\n            \"name\": \"simplewheel\",\n            \"version\": \"2.0\",\n            \"wheels\": [\n                {\n                    \"name\": \"simplewheel-2.0-1-py2.py3-none-any.whl\",\n                    \"url\": path_to_url(\n                        str(\n                            shared_data.root\n                            / \"packages\"\n                            / \"simplewheel-2.0-1-py2.py3-none-any.whl\"\n                        )\n                    ),\n                    \"hashes\": {\n                        \"sha256\": (\n                            \"71e1ca6b16ae3382a698c284013f6650\"\n                            \"4f2581099b2ce4801f60e9536236ceee\"\n                        )\n                    },\n                }\n            ],\n        },\n    ]\n\n\n@pytest.mark.network\ndef test_lock_vcs(script: PipTestEnvironment, shared_data: TestData) -> None:\n    result = script.pip(\n        \"lock\",\n        \"git+https://github.com/pypa/pip-test-package@0.1.2\",\n        \"--quiet\",\n        \"--output=-\",\n        \"--no-build-isolation\",  # to use the pre-installed setuptools\n        \"--no-index\",\n        expect_stderr=True,  # for the experimental warning\n    )\n    pylock = tomllib.loads(result.stdout)\n    assert pylock[\"packages\"] == [\n        {\n            \"name\": \"pip-test-package\",\n            \"vcs\": {\n                \"type\": \"git\",\n                \"url\": \"https://github.com/pypa/pip-test-package\",\n                \"requested-revision\": \"0.1.2\",\n                \"commit-id\": \"f1c1020ebac81f9aeb5c766ff7a772f709e696ee\",\n            },\n        },\n    ]\n\n\n@pytest.mark.network\ndef test_lock_archive(script: PipTestEnvironment, shared_data: TestData) -> None:\n    result = script.pip(\n        \"lock\",\n        \"https://github.com/pypa/pip-test-package/tarball/0.1.2\",\n        \"--quiet\",\n        \"--output=-\",\n        \"--no-build-isolation\",  # to use the pre-installed setuptools\n        \"--no-index\",\n        expect_stderr=True,  # for the experimental warning\n    )\n    pylock = tomllib.loads(result.stdout)\n    assert pylock[\"packages\"] == [\n        {\n            \"name\": \"pip-test-package\",\n            \"archive\": {\n                \"url\": \"https://github.com/pypa/pip-test-package/tarball/0.1.2\",\n                \"hashes\": {\n                    \"sha256\": (\n                        \"1b176298e5ecd007da367bfda91aad3c\"\n                        \"4a6534227faceda087b00e5b14d596bf\"\n                    ),\n                },\n            },\n        },\n    ]\n"
  },
  {
    "path": "tests/functional/test_new_resolver.py",
    "content": "import os\nimport pathlib\nimport sys\nimport textwrap\nfrom typing import TYPE_CHECKING, Callable, Protocol\n\nimport pytest\n\nfrom tests.conftest import ScriptFactory\nfrom tests.lib import (\n    PipTestEnvironment,\n    create_basic_sdist_for_package,\n    create_basic_wheel_for_package,\n    create_test_package_with_setup,\n)\nfrom tests.lib.venv import VirtualEnvironment\nfrom tests.lib.wheel import make_wheel\n\nMakeFakeWheel = Callable[[str, str, str], pathlib.Path]\n\n\n@pytest.fixture\ndef make_fake_wheel(script: PipTestEnvironment) -> MakeFakeWheel:\n    def _make_fake_wheel(name: str, version: str, wheel_tag: str) -> pathlib.Path:\n        wheel_house = script.scratch_path.joinpath(\"wheelhouse\")\n        wheel_house.mkdir()\n        wheel_builder = make_wheel(\n            name=name,\n            version=version,\n            wheel_metadata_updates={\"Tag\": []},\n        )\n        wheel_path = wheel_house.joinpath(f\"{name}-{version}-{wheel_tag}.whl\")\n        wheel_builder.save_to(wheel_path)\n        return wheel_path\n\n    return _make_fake_wheel\n\n\ndef test_new_resolver_can_install(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    script.assert_installed(simple=\"0.1.0\")\n\n\ndef test_new_resolver_can_install_with_version(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple==0.1.0\",\n    )\n    script.assert_installed(simple=\"0.1.0\")\n\n\ndef test_new_resolver_picks_latest_version(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.2.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    script.assert_installed(simple=\"0.2.0\")\n\n\ndef test_new_resolver_picks_installed_version(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.2.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple==0.1.0\",\n    )\n    script.assert_installed(simple=\"0.1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    assert \"Collecting\" not in result.stdout, \"Should not fetch new version\"\n    script.assert_installed(simple=\"0.1.0\")\n\n\ndef test_new_resolver_picks_installed_version_if_no_match_found(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"simple\",\n        \"0.2.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple==0.1.0\",\n    )\n    script.assert_installed(simple=\"0.1.0\")\n\n    result = script.pip(\"install\", \"--no-cache-dir\", \"--no-index\", \"simple\")\n    assert \"Collecting\" not in result.stdout, \"Should not fetch new version\"\n    script.assert_installed(simple=\"0.1.0\")\n\n\ndef test_new_resolver_installs_dependencies(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    script.assert_installed(base=\"0.1.0\", dep=\"0.1.0\")\n\n\ndef test_new_resolver_ignore_dependencies(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--no-deps\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    script.assert_installed(base=\"0.1.0\")\n    script.assert_not_installed(\"dep\")\n\n\n@pytest.mark.parametrize(\n    \"root_dep\",\n    [\n        \"base[add]\",\n        \"base[add] >= 0.1.0\",\n    ],\n)\ndef test_new_resolver_installs_extras(\n    tmpdir: pathlib.Path, script: PipTestEnvironment, root_dep: str\n) -> None:\n    req_file = tmpdir.joinpath(\"requirements.txt\")\n    req_file.write_text(root_dep)\n\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        extras={\"add\": [\"dep\"]},\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-r\",\n        req_file,\n    )\n    script.assert_installed(base=\"0.1.0\", dep=\"0.1.0\")\n\n\ndef test_new_resolver_installs_extras_warn_missing(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        extras={\"add\": [\"dep\"]},\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base[add,missing]\",\n        expect_stderr=True,\n    )\n    assert \"does not provide the extra\" in result.stderr, str(result)\n    assert \"missing\" in result.stderr, str(result)\n    script.assert_installed(base=\"0.1.0\", dep=\"0.1.0\")\n\n\ndef test_new_resolver_installed_message(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"A\", \"1.0\")\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"A\",\n        expect_stderr=False,\n    )\n    assert \"Successfully installed A-1.0\" in result.stdout, str(result)\n\n\ndef test_new_resolver_no_dist_message(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"A\", \"1.0\")\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"B\",\n        expect_error=True,\n        expect_stderr=True,\n    )\n\n    # Full messages from old resolver:\n    # ERROR: Could not find a version that satisfies the\n    #        requirement xxx (from versions: none)\n    # ERROR: No matching distribution found for xxx\n\n    assert (\n        \"Could not find a version that satisfies the requirement B\" in result.stderr\n    ), str(result)\n    assert \"No matching distribution found for B\" in result.stderr, str(result)\n\n\ndef test_new_resolver_installs_editable(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    source_dir = create_test_package_with_setup(\n        script,\n        name=\"dep\",\n        version=\"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n        \"--editable\",\n        source_dir,\n    )\n    script.assert_installed(base=\"0.1.0\", dep=\"0.1.0\")\n    script.assert_installed_editable(\"dep\")\n\n\n@pytest.mark.parametrize(\n    \"requires_python, ignore_requires_python, dep_version\",\n    [\n        # Something impossible to satisfy.\n        (\"<2\", False, \"0.1.0\"),\n        (\"<2\", True, \"0.2.0\"),\n        # Something guaranteed to satisfy.\n        (\">=2\", False, \"0.2.0\"),\n        (\">=2\", True, \"0.2.0\"),\n    ],\n)\ndef test_new_resolver_requires_python(\n    script: PipTestEnvironment,\n    requires_python: str,\n    ignore_requires_python: bool,\n    dep_version: str,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.2.0\",\n        requires_python=requires_python,\n    )\n\n    args = [\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        os.fspath(script.scratch_path),\n    ]\n    if ignore_requires_python:\n        args.append(\"--ignore-requires-python\")\n    args.append(\"base\")\n\n    script.pip(*args)\n\n    script.assert_installed(base=\"0.1.0\", dep=dep_version)\n\n\ndef test_new_resolver_requires_python_error(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        requires_python=\"<2\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n        expect_error=True,\n    )\n\n    message = (\n        \"Package 'base' requires a different Python: \"\n        \"{}.{}.{} not in '<2'\".format(*sys.version_info[:3])\n    )\n    assert message in result.stderr, str(result)\n\n\ndef test_new_resolver_requires_python_ok_with_python_version_flag(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        requires_python=\"<3\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--dry-run\",\n        \"--python-version=2\",\n        \"--only-binary=:all:\",\n        \"base\",\n    )\n\n    assert not result.stderr, str(result)\n\n\ndef test_new_resolver_installed(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    assert \"Requirement already satisfied\" not in result.stdout, str(result)\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base~=0.1.0\",\n    )\n    assert \"Requirement already satisfied: base~=0.1.0\" in result.stdout, str(result)\n    result.did_not_update(\n        script.site_packages / \"base\", message=\"base 0.1.0 reinstalled\"\n    )\n\n\ndef test_new_resolver_ignore_installed(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n    )\n    satisfied_output = \"Requirement already satisfied\"\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    assert satisfied_output not in result.stdout, str(result)\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--ignore-installed\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    assert satisfied_output not in result.stdout, str(result)\n    result.did_update(\n        script.site_packages / \"base\", message=\"base 0.1.0 not reinstalled\"\n    )\n\n\ndef test_new_resolver_only_builds_sdists_when_needed(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n    )\n    create_basic_sdist_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n        # Replace setup.py with something that fails\n        extra_files={\"setup.py\": \"assert False\"},\n    )\n    create_basic_sdist_for_package(\n        script,\n        \"dep\",\n        \"0.2.0\",\n    )\n    # We only ever need to check dep 0.2.0 as it's the latest version\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n    script.assert_installed(base=\"0.1.0\", dep=\"0.2.0\")\n\n    # We merge criteria here, as we have two \"dep\" requirements\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n        \"dep\",\n    )\n    script.assert_installed(base=\"0.1.0\", dep=\"0.2.0\")\n\n\ndef test_new_resolver_install_different_version(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n    create_basic_wheel_for_package(script, \"base\", \"0.2.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==0.1.0\",\n    )\n\n    # This should trigger an uninstallation of base.\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==0.2.0\",\n    )\n\n    assert \"Uninstalling base-0.1.0\" in result.stdout, str(result)\n    assert \"Successfully uninstalled base-0.1.0\" in result.stdout, str(result)\n    result.did_update(script.site_packages / \"base\", message=\"base not upgraded\")\n    script.assert_installed(base=\"0.2.0\")\n\n\ndef test_new_resolver_force_reinstall(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==0.1.0\",\n    )\n\n    # This should trigger an uninstallation of base due to --force-reinstall,\n    # even though the installed version matches.\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--force-reinstall\",\n        \"base==0.1.0\",\n    )\n\n    assert \"Uninstalling base-0.1.0\" in result.stdout, str(result)\n    assert \"Successfully uninstalled base-0.1.0\" in result.stdout, str(result)\n    result.did_update(script.site_packages / \"base\", message=\"base not reinstalled\")\n    script.assert_installed(base=\"0.1.0\")\n\n\n@pytest.mark.parametrize(\n    \"available_versions, pip_args, expected_version\",\n    [\n        # Choose the latest non-prerelease by default.\n        ([\"1.0\", \"2.0a1\"], [\"pkg\"], \"1.0\"),\n        # Choose the prerelease if the specifier spells out a prerelease.\n        ([\"1.0\", \"2.0a1\"], [\"pkg==2.0a1\"], \"2.0a1\"),\n        # Choose the prerelease if explicitly allowed by the user.\n        ([\"1.0\", \"2.0a1\"], [\"pkg\", \"--pre\"], \"2.0a1\"),\n        # Choose the prerelease if no stable releases are available.\n        ([\"2.0a1\"], [\"pkg\"], \"2.0a1\"),\n    ],\n    ids=[\"default\", \"exact-pre\", \"explicit-pre\", \"no-stable\"],\n)\ndef test_new_resolver_handles_prerelease(\n    script: PipTestEnvironment,\n    available_versions: list[str],\n    pip_args: list[str],\n    expected_version: str,\n) -> None:\n    for version in available_versions:\n        create_basic_wheel_for_package(script, \"pkg\", version)\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        *pip_args,\n    )\n    script.assert_installed(pkg=expected_version)\n\n\n@pytest.mark.parametrize(\n    \"pkg_deps, root_deps\",\n    [\n        # This tests the marker is picked up from a transitive dependency.\n        ([\"dep; os_name == 'nonexist_os'\"], [\"pkg\"]),\n        # This tests the marker is picked up from a root dependency.\n        ([], [\"pkg\", \"dep; os_name == 'nonexist_os'\"]),\n    ],\n)\ndef test_new_resolver_skips_marker(\n    script: PipTestEnvironment, pkg_deps: list[str], root_deps: list[str]\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\", depends=pkg_deps)\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        *root_deps,\n    )\n    script.assert_installed(pkg=\"1.0\")\n    script.assert_not_installed(\"dep\")\n\n\n@pytest.mark.parametrize(\n    \"constraints\",\n    [\n        [\"pkg<2.0\", \"constraint_only<1.0\"],\n        # This also tests the pkg constraint don't get merged with the\n        # requirement prematurely. (pypa/pip#8134)\n        [\"pkg<2.0\"],\n    ],\n)\ndef test_new_resolver_constraints(\n    script: PipTestEnvironment, constraints: list[str]\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"2.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"3.0\")\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"\\n\".join(constraints))\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"1.0\")\n    script.assert_not_installed(\"constraint_only\")\n\n\ndef test_new_resolver_constraint_no_specifier(script: PipTestEnvironment) -> None:\n    \"It's allowed (but useless...) for a constraint to have no specifier\"\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"pkg\")\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"1.0\")\n\n\n@pytest.mark.parametrize(\n    \"constraint, error\",\n    [\n        (\n            \"dist.zip\",\n            \"Unnamed requirements are not allowed as constraints\",\n        ),\n        (\n            \"-e git+https://example.com/dist.git#egg=req\",\n            \"Editable requirements are not allowed as constraints\",\n        ),\n        (\n            \"pkg[extra]\",\n            \"Constraints cannot have extras\",\n        ),\n    ],\n)\ndef test_new_resolver_constraint_reject_invalid(\n    script: PipTestEnvironment, constraint: str, error: str\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(constraint)\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"pkg\",\n        expect_error=True,\n        expect_stderr=True,\n    )\n    assert error in result.stderr, str(result)\n\n\ndef test_new_resolver_constraint_on_dependency(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"1.0\", depends=[\"dep\"])\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n    create_basic_wheel_for_package(script, \"dep\", \"2.0\")\n    create_basic_wheel_for_package(script, \"dep\", \"3.0\")\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"dep==2.0\")\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"base\",\n    )\n    script.assert_installed(base=\"1.0\")\n    script.assert_installed(dep=\"2.0\")\n\n\n@pytest.mark.parametrize(\n    \"constraint_version, expect_error, message\",\n    [\n        (\"1.0\", True, \"Cannot install foo 2.0\"),\n        (\"2.0\", False, \"Successfully installed foo-2.0\"),\n    ],\n)\ndef test_new_resolver_constraint_on_path_empty(\n    script: PipTestEnvironment,\n    constraint_version: str,\n    expect_error: bool,\n    message: str,\n) -> None:\n    \"\"\"A path requirement can be filtered by a constraint.\"\"\"\n    setup_py = script.scratch_path / \"setup.py\"\n    text = \"from setuptools import setup\\nsetup(name='foo', version='2.0')\"\n    setup_py.write_text(text)\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraints_txt.write_text(f\"foo=={constraint_version}\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_txt,\n        str(script.scratch_path),\n        expect_error=expect_error,\n    )\n\n    if expect_error:\n        assert message in result.stderr, str(result)\n    else:\n        assert message in result.stdout, str(result)\n\n\ndef test_new_resolver_constraint_only_marker_match(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"2.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"3.0\")\n\n    constraints_content = textwrap.dedent(\n        \"\"\"\n        pkg==1.0; python_version == \"{ver[0]}.{ver[1]}\"  # Always satisfies.\n        pkg==2.0; python_version < \"0\"  # Never satisfies.\n        \"\"\"\n    ).format(ver=sys.version_info)\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraints_txt.write_text(constraints_content)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_txt,\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"1.0\")\n\n\ndef test_new_resolver_upgrade_needs_option(script: PipTestEnvironment) -> None:\n    # Install pkg 1.0.0\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0.0\")\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg\",\n    )\n\n    # Now release a new version\n    create_basic_wheel_for_package(script, \"pkg\", \"2.0.0\")\n\n    # This should not upgrade because we don't specify --upgrade\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg\",\n    )\n\n    assert \"Requirement already satisfied\" in result.stdout, str(result)\n    script.assert_installed(pkg=\"1.0.0\")\n\n    # This should upgrade\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"PKG\",  # Deliberately uppercase to check canonicalization\n    )\n\n    assert \"Uninstalling pkg-1.0.0\" in result.stdout, str(result)\n    assert \"Successfully uninstalled pkg-1.0.0\" in result.stdout, str(result)\n    result.did_update(script.site_packages / \"pkg\", message=\"pkg not upgraded\")\n    script.assert_installed(pkg=\"2.0.0\")\n\n\ndef test_new_resolver_upgrade_strategy(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\", depends=[\"dep\"])\n    create_basic_wheel_for_package(script, \"dep\", \"1.0.0\")\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n    )\n\n    script.assert_installed(base=\"1.0.0\")\n    script.assert_installed(dep=\"1.0.0\")\n\n    # Now release new versions\n    create_basic_wheel_for_package(script, \"base\", \"2.0.0\", depends=[\"dep\"])\n    create_basic_wheel_for_package(script, \"dep\", \"2.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"base\",\n    )\n\n    # With upgrade strategy \"only-if-needed\" (the default), dep should not\n    # be upgraded.\n    script.assert_installed(base=\"2.0.0\")\n    script.assert_installed(dep=\"1.0.0\")\n\n    create_basic_wheel_for_package(script, \"base\", \"3.0.0\", depends=[\"dep\"])\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"--upgrade-strategy=eager\",\n        \"base\",\n    )\n\n    # With upgrade strategy \"eager\", dep should be upgraded.\n    script.assert_installed(base=\"3.0.0\")\n    script.assert_installed(dep=\"2.0.0\")\n\n\nif TYPE_CHECKING:\n\n    class PackageBuilder(Protocol):\n        def __call__(\n            self,\n            script: PipTestEnvironment,\n            name: str,\n            version: str,\n            requires: list[str],\n            extras: dict[str, list[str]],\n        ) -> str: ...\n\n\ndef _local_with_setup(\n    script: PipTestEnvironment,\n    name: str,\n    version: str,\n    requires: list[str],\n    extras: dict[str, list[str]],\n) -> str:\n    \"\"\"Create the package as a local source directory to install from path.\"\"\"\n    path = create_test_package_with_setup(\n        script,\n        name=name,\n        version=version,\n        install_requires=requires,\n        extras_require=extras,\n    )\n    return str(path)\n\n\ndef _direct_wheel(\n    script: PipTestEnvironment,\n    name: str,\n    version: str,\n    requires: list[str],\n    extras: dict[str, list[str]],\n) -> str:\n    \"\"\"Create the package as a wheel to install from path directly.\"\"\"\n    path = create_basic_wheel_for_package(\n        script,\n        name=name,\n        version=version,\n        depends=requires,\n        extras=extras,\n    )\n    return str(path)\n\n\ndef _wheel_from_index(\n    script: PipTestEnvironment,\n    name: str,\n    version: str,\n    requires: list[str],\n    extras: dict[str, list[str]],\n) -> str:\n    \"\"\"Create the package as a wheel to install from index.\"\"\"\n    create_basic_wheel_for_package(\n        script,\n        name=name,\n        version=version,\n        depends=requires,\n        extras=extras,\n    )\n    return name\n\n\nclass TestExtraMerge:\n    \"\"\"\n    Test installing a package that depends the same package with different\n    extras, one listed as required and the other as in extra.\n    \"\"\"\n\n    @pytest.mark.parametrize(\n        \"pkg_builder\",\n        [\n            _local_with_setup,\n            _direct_wheel,\n            _wheel_from_index,\n        ],\n    )\n    def test_new_resolver_extra_merge_in_package(\n        self, script: PipTestEnvironment, pkg_builder: \"PackageBuilder\"\n    ) -> None:\n        create_basic_wheel_for_package(script, \"depdev\", \"1.0.0\")\n        create_basic_wheel_for_package(\n            script,\n            \"dep\",\n            \"1.0.0\",\n            extras={\"dev\": [\"depdev\"]},\n        )\n        requirement = pkg_builder(\n            script,\n            name=\"pkg\",\n            version=\"1.0.0\",\n            requires=[\"dep\"],\n            extras={\"dev\": [\"dep[dev]\"]},\n        )\n\n        script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--no-cache-dir\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            requirement + \"[dev]\",\n        )\n        script.assert_installed(pkg=\"1.0.0\", dep=\"1.0.0\", depdev=\"1.0.0\")\n\n\ndef test_new_resolver_build_directory_error_zazo_19(script: PipTestEnvironment) -> None:\n    \"\"\"https://github.com/pradyunsg/zazo/issues/19#issuecomment-631615674\n\n    This will first resolve like this:\n\n    1. Pin pkg-b==2.0.0 (since pkg-b has fewer choices)\n    2. Pin pkg-a==3.0.0 -> Conflict due to dependency pkg-b<2\n    3. Pin pkg-b==1.0.0\n\n    Since pkg-b is only available as sdist, both the first and third steps\n    would trigger building from source. This ensures the preparer can build\n    different versions of a package for the resolver.\n\n    The preparer would fail with the following message if the different\n    versions end up using the same build directory::\n\n        ERROR: pip can't proceed with requirements 'pkg-b ...' due to a\n        pre-existing build directory (...). This is likely due to a previous\n        installation that failed. pip is being responsible and not assuming it\n        can delete this. Please delete it and try again.\n    \"\"\"\n    create_basic_wheel_for_package(\n        script,\n        \"pkg_a\",\n        \"3.0.0\",\n        depends=[\"pkg-b<2\"],\n    )\n    create_basic_wheel_for_package(script, \"pkg_a\", \"2.0.0\")\n    create_basic_wheel_for_package(script, \"pkg_a\", \"1.0.0\")\n\n    create_basic_sdist_for_package(script, \"pkg_b\", \"2.0.0\")\n    create_basic_sdist_for_package(script, \"pkg_b\", \"1.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg-a\",\n        \"pkg-b\",\n    )\n    script.assert_installed(pkg_a=\"3.0.0\", pkg_b=\"1.0.0\")\n\n\ndef test_new_resolver_upgrade_same_version(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"2\")\n    create_basic_wheel_for_package(script, \"pkg\", \"1\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"2\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"2\")\n\n\ndef test_new_resolver_local_and_req(script: PipTestEnvironment) -> None:\n    source_dir = create_test_package_with_setup(\n        script,\n        name=\"pkg\",\n        version=\"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        source_dir,\n        \"pkg!=0.1.0\",\n        expect_error=True,\n    )\n\n\ndef test_new_resolver_no_deps_checks_requires_python(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(\n        script,\n        \"base\",\n        \"0.1.0\",\n        depends=[\"dep\"],\n        requires_python=\"<2\",  # Something that always fails.\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.2.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--no-deps\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base\",\n        expect_error=True,\n    )\n\n    message = (\n        \"Package 'base' requires a different Python: \"\n        \"{}.{}.{} not in '<2'\".format(*sys.version_info[:3])\n    )\n    assert message in result.stderr\n\n\ndef test_new_resolver_prefers_installed_in_upgrade_if_latest(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1\")\n    local_pkg = create_test_package_with_setup(script, name=\"pkg\", version=\"2\")\n\n    # Install the version that's not on the index.\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        local_pkg,\n    )\n\n    # Now --upgrade should still pick the local version because it's \"better\".\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"pkg\",\n    )\n    script.assert_installed(pkg=\"2\")\n\n\n@pytest.mark.parametrize(\"N\", [2, 10, 20])\ndef test_new_resolver_presents_messages_when_backtracking_a_lot(\n    script: PipTestEnvironment, N: int\n) -> None:\n    # Generate a set of wheels that will definitely cause backtracking.\n    for index in range(1, N + 1):\n        A_version = f\"{index}.0.0\"\n        B_version = f\"{index}.0.0\"\n        C_version = f\"{index - 1}.0.0\"\n\n        depends = [\"B == \" + B_version]\n        if index != 1:\n            depends.append(\"C == \" + C_version)\n\n        print(\"A\", A_version, \"B\", B_version, \"C\", C_version)\n        create_basic_wheel_for_package(script, \"A\", A_version, depends=depends)\n\n    for index in range(1, N + 1):\n        B_version = f\"{index}.0.0\"\n        C_version = f\"{index}.0.0\"\n        depends = [\"C == \" + C_version]\n\n        print(\"B\", B_version, \"C\", C_version)\n        create_basic_wheel_for_package(script, \"B\", B_version, depends=depends)\n\n    for index in range(1, N + 1):\n        C_version = f\"{index}.0.0\"\n        print(\"C\", C_version)\n        create_basic_wheel_for_package(script, \"C\", C_version)\n\n    # Install A\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"A\",\n    )\n\n    script.assert_installed(A=\"1.0.0\", B=\"1.0.0\", C=\"1.0.0\")\n    # These numbers are hard-coded in the code.\n    if N >= 1:\n        assert \"This could take a while.\" in result.stdout\n    if N >= 8:\n        assert result.stdout.count(\"This could take a while.\") >= 2\n    if N >= 13:\n        assert \"press Ctrl + C\" in result.stdout\n\n\n@pytest.mark.parametrize(\n    \"metadata_version\",\n    [\n        \"0.1.0+local.1\",  # Normalized form.\n        \"0.1.0+local_1\",  # Non-normalized form containing an underscore.\n        # Non-normalized form containing a dash. This is allowed, installation\n        # works correctly, but assert_installed() fails because pkg_resources\n        # cannot handle it correctly. Nobody is complaining about it right now,\n        # we're probably dropping it for importlib.metadata soon(tm), so let's\n        # ignore it for the time being.\n        pytest.param(\"0.1.0+local-1\", marks=pytest.mark.xfail(strict=False)),\n    ],\n    ids=[\"meta_dot\", \"meta_underscore\", \"meta_dash\"],\n)\n@pytest.mark.parametrize(\n    \"filename_version\",\n    [\n        (\"0.1.0+local.1\"),  # Tools are encouraged to use this.\n        (\"0.1.0+local_1\"),  # But this is allowed (version not normalized).\n    ],\n    ids=[\"file_dot\", \"file_underscore\"],\n)\ndef test_new_resolver_check_wheel_version_normalized(\n    script: PipTestEnvironment,\n    metadata_version: str,\n    filename_version: str,\n) -> None:\n    filename = f\"simple-{filename_version}-py2.py3-none-any.whl\"\n\n    wheel_builder = make_wheel(name=\"simple\", version=metadata_version)\n    wheel_builder.save_to(script.scratch_path / filename)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    script.assert_installed(simple=\"0.1.0+local.1\")\n\n\ndef test_new_resolver_does_reinstall_local_sdists(script: PipTestEnvironment) -> None:\n    archive_path = create_basic_sdist_for_package(\n        script,\n        \"pkg\",\n        \"1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        archive_path,\n    )\n    script.assert_installed(pkg=\"1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        archive_path,\n        expect_stderr=True,\n    )\n    assert \"Installing collected packages: pkg\" in result.stdout, str(result)\n    script.assert_installed(pkg=\"1.0\")\n\n\ndef test_new_resolver_does_reinstall_local_paths(script: PipTestEnvironment) -> None:\n    pkg = create_test_package_with_setup(script, name=\"pkg\", version=\"1.0\")\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        pkg,\n    )\n    script.assert_installed(pkg=\"1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        pkg,\n    )\n    assert \"Installing collected packages: pkg\" in result.stdout, str(result)\n    script.assert_installed(pkg=\"1.0\")\n\n\ndef test_new_resolver_does_not_reinstall_when_from_a_local_index(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_sdist_for_package(\n        script,\n        \"simple\",\n        \"0.1.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    script.assert_installed(simple=\"0.1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"simple\",\n    )\n    # Should not reinstall!\n    assert \"Installing collected packages: simple\" not in result.stdout, str(result)\n    assert \"Requirement already satisfied: simple\" in result.stdout, str(result)\n    script.assert_installed(simple=\"0.1.0\")\n\n\ndef test_new_resolver_skip_inconsistent_metadata(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"A\", \"1\")\n\n    a_2 = create_basic_wheel_for_package(script, \"A\", \"2\")\n    a_2.rename(a_2.parent.joinpath(\"a-3-py2.py3-none-any.whl\"))\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--verbose\",\n        \"A\",\n        allow_stderr_warning=True,\n    )\n\n    assert (\n        \" inconsistent version: expected '3', but metadata has '2'\"\n    ) in result.stdout, str(result)\n    script.assert_installed(a=\"1\")\n\n\n@pytest.mark.parametrize(\n    \"upgrade\",\n    [True, False],\n    ids=[\"upgrade\", \"no-upgrade\"],\n)\ndef test_new_resolver_lazy_fetch_candidates(\n    script: PipTestEnvironment, upgrade: bool\n) -> None:\n    create_basic_wheel_for_package(script, \"myuberpkg\", \"1\")\n    create_basic_wheel_for_package(script, \"myuberpkg\", \"2\")\n    create_basic_wheel_for_package(script, \"myuberpkg\", \"3\")\n\n    # Install an old version first.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"myuberpkg==1\",\n    )\n\n    # Now install the same package again, maybe with the upgrade flag.\n    if upgrade:\n        pip_upgrade_args = [\"--upgrade\"]\n    else:\n        pip_upgrade_args = []\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"myuberpkg\",\n        *pip_upgrade_args,  # Trailing comma fails on Python 2.\n    )\n\n    # pip should install the version preferred by the strategy...\n    if upgrade:\n        script.assert_installed(myuberpkg=\"3\")\n    else:\n        script.assert_installed(myuberpkg=\"1\")\n\n    # But should reach there in the best route possible, without trying\n    # candidates it does not need to.\n    assert \"myuberpkg-2\" not in result.stdout, str(result)\n\n\ndef test_new_resolver_no_fetch_no_satisfying(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"myuberpkg\", \"1\")\n\n    # Install the package. This should emit a \"Processing\" message for\n    # fetching the distribution from the --find-links page.\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"myuberpkg\",\n    )\n    assert \"Processing \" in result.stdout, str(result)\n\n    # Try to upgrade the package. This should NOT emit the \"Processing\"\n    # message because the currently installed version is latest.\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"myuberpkg\",\n    )\n    assert \"Processing \" not in result.stdout, str(result)\n\n\ndef test_new_resolver_does_not_install_unneeded_packages_with_url_constraint(\n    script: PipTestEnvironment,\n) -> None:\n    archive_path = create_basic_wheel_for_package(\n        script,\n        \"installed\",\n        \"0.1.0\",\n    )\n    not_installed_path = create_basic_wheel_for_package(\n        script,\n        \"not_installed\",\n        \"0.1.0\",\n    )\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"not_installed @ {not_installed_path.as_uri()}\")\n\n    (script.scratch_path / \"index\").mkdir()\n    archive_path.rename(script.scratch_path / \"index\" / archive_path.name)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"-c\",\n        constraints_file,\n        \"installed\",\n    )\n\n    script.assert_installed(installed=\"0.1.0\")\n    script.assert_not_installed(\"not_installed\")\n\n\ndef test_new_resolver_installs_packages_with_url_constraint(\n    script: PipTestEnvironment,\n) -> None:\n    installed_path = create_basic_wheel_for_package(\n        script,\n        \"installed\",\n        \"0.1.0\",\n    )\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"installed @ {installed_path.as_uri()}\")\n\n    script.pip(\n        \"install\", \"--no-cache-dir\", \"--no-index\", \"-c\", constraints_file, \"installed\"\n    )\n\n    script.assert_installed(installed=\"0.1.0\")\n\n\ndef test_new_resolver_reinstall_link_requirement_with_constraint(\n    script: PipTestEnvironment,\n) -> None:\n    installed_path = create_basic_wheel_for_package(\n        script,\n        \"installed\",\n        \"0.1.0\",\n    )\n\n    cr_file = script.scratch_path / \"constraints.txt\"\n    cr_file.write_text(f\"installed @ {installed_path.as_uri()}\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-r\",\n        cr_file,\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        cr_file,\n        \"-r\",\n        cr_file,\n    )\n    # TODO: strengthen assertion to \"second invocation does no work\"\n    # I don't think this is true yet, but it should be in the future.\n\n    script.assert_installed(installed=\"0.1.0\")\n\n\ndef test_new_resolver_prefers_url_constraint(script: PipTestEnvironment) -> None:\n    installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    not_installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"test_pkg @ {installed_path.as_uri()}\")\n\n    (script.scratch_path / \"index\").mkdir()\n    not_installed_path.rename(script.scratch_path / \"index\" / not_installed_path.name)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"-c\",\n        constraints_file,\n        \"test_pkg\",\n    )\n\n    script.assert_installed(test_pkg=\"0.1.0\")\n\n\ndef test_new_resolver_prefers_url_constraint_on_update(\n    script: PipTestEnvironment,\n) -> None:\n    installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    not_installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"test_pkg @ {installed_path.as_uri()}\")\n\n    (script.scratch_path / \"index\").mkdir()\n    not_installed_path.rename(script.scratch_path / \"index\" / not_installed_path.name)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"test_pkg\",\n    )\n\n    script.assert_installed(test_pkg=\"0.2.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"-c\",\n        constraints_file,\n        \"test_pkg\",\n    )\n\n    script.assert_installed(test_pkg=\"0.1.0\")\n\n\n@pytest.mark.parametrize(\"version_option\", [\"--constraint\", \"--requirement\"])\ndef test_new_resolver_fails_with_url_constraint_and_incompatible_version(\n    script: PipTestEnvironment,\n    version_option: str,\n) -> None:\n    not_installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    not_installed_path = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n\n    url_constraint = script.scratch_path / \"constraints.txt\"\n    url_constraint.write_text(f\"test_pkg @ {not_installed_path.as_uri()}\")\n\n    version_req = script.scratch_path / \"requirements.txt\"\n    version_req.write_text(\"test_pkg<0.2.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--constraint\",\n        url_constraint,\n        version_option,\n        version_req,\n        \"test_pkg\",\n        expect_error=True,\n    )\n\n    assert \"Cannot install test_pkg\" in result.stderr, str(result)\n    assert (\n        \"because these package versions have conflicting dependencies.\"\n    ) in result.stderr, str(result)\n\n    script.assert_not_installed(\"test_pkg\")\n\n    # Assert that pip works properly in the absence of the constraints file.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        version_option,\n        version_req,\n        \"test_pkg\",\n    )\n\n\ndef test_new_resolver_ignores_unneeded_conflicting_constraints(\n    script: PipTestEnvironment,\n) -> None:\n    version_1 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    version_2 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"installed\",\n        \"0.1.0\",\n    )\n\n    constraints = [\n        f\"test_pkg @ {version_1.as_uri()}\",\n        f\"test_pkg @ {version_2.as_uri()}\",\n    ]\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"\\n\".join(constraints))\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"installed\",\n    )\n\n    script.assert_not_installed(\"test_pkg\")\n    script.assert_installed(installed=\"0.1.0\")\n\n\ndef test_new_resolver_fails_on_needed_conflicting_constraints(\n    script: PipTestEnvironment,\n) -> None:\n    version_1 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    version_2 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n\n    constraints = [\n        f\"test_pkg @ {version_1.as_uri()}\",\n        f\"test_pkg @ {version_2.as_uri()}\",\n    ]\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"\\n\".join(constraints))\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"test_pkg\",\n        expect_error=True,\n    )\n\n    assert (\n        \"Cannot install test_pkg because these package versions have conflicting \"\n        \"dependencies.\"\n    ) in result.stderr, str(result)\n\n    script.assert_not_installed(\"test_pkg\")\n\n    # Assert that pip works properly in the absence of the constraints file.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"test_pkg\",\n    )\n\n\ndef test_new_resolver_fails_on_conflicting_constraint_and_requirement(\n    script: PipTestEnvironment,\n) -> None:\n    version_1 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.1.0\",\n    )\n    version_2 = create_basic_wheel_for_package(\n        script,\n        \"test_pkg\",\n        \"0.2.0\",\n    )\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"test_pkg @ {version_1.as_uri()}\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        f\"test_pkg @ {version_2.as_uri()}\",\n        expect_error=True,\n    )\n\n    assert \"Cannot install test-pkg 0.2.0\" in result.stderr, str(result)\n    assert (\n        \"because these package versions have conflicting dependencies.\"\n    ) in result.stderr, str(result)\n\n    script.assert_not_installed(\"test_pkg\")\n\n    # Assert that pip works properly in the absence of the constraints file.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        f\"test_pkg @ {version_2.as_uri()}\",\n    )\n\n\n@pytest.mark.parametrize(\"editable\", [False, True])\ndef test_new_resolver_succeeds_on_matching_constraint_and_requirement(\n    script: PipTestEnvironment, editable: bool\n) -> None:\n    if editable:\n        source_dir = create_test_package_with_setup(\n            script, name=\"test_pkg\", version=\"0.1.0\"\n        )\n    else:\n        source_dir = create_basic_wheel_for_package(\n            script,\n            \"test_pkg\",\n            \"0.1.0\",\n        )\n\n    req_line = f\"test_pkg @ {source_dir.as_uri()}\"\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(req_line)\n\n    last_args: tuple[str, ...]\n    if editable:\n        last_args = (\"-e\", os.fspath(source_dir))\n    else:\n        last_args = (req_line,)\n\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_file,\n        *last_args,\n    )\n\n    script.assert_installed(test_pkg=\"0.1.0\")\n    if editable:\n        script.assert_installed_editable(\"test_pkg\")\n\n\ndef test_new_resolver_applies_url_constraint_to_dep(script: PipTestEnvironment) -> None:\n    version_1 = create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.1.0\",\n    )\n    version_2 = create_basic_wheel_for_package(\n        script,\n        \"dep\",\n        \"0.2.0\",\n    )\n\n    base = create_basic_wheel_for_package(script, \"base\", \"0.1.0\", depends=[\"dep\"])\n\n    (script.scratch_path / \"index\").mkdir()\n    base.rename(script.scratch_path / \"index\" / base.name)\n    version_2.rename(script.scratch_path / \"index\" / version_2.name)\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"dep @ {version_1.as_uri()}\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_file,\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"base\",\n    )\n\n    script.assert_installed(dep=\"0.1.0\")\n\n\ndef test_new_resolver_handles_compatible_wheel_tags_in_constraint_url(\n    script: PipTestEnvironment, make_fake_wheel: MakeFakeWheel\n) -> None:\n    initial_path = make_fake_wheel(\"base\", \"0.1.0\", \"fakepy1-fakeabi-fakeplat\")\n\n    constrained = script.scratch_path / \"constrained\"\n    constrained.mkdir()\n\n    final_path = constrained / initial_path.name\n\n    initial_path.rename(final_path)\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"base @ {final_path.as_uri()}\")\n\n    result = script.pip(\n        \"install\",\n        \"--implementation\",\n        \"fakepy\",\n        \"--only-binary=:all:\",\n        \"--python-version\",\n        \"1\",\n        \"--abi\",\n        \"fakeabi\",\n        \"--platform\",\n        \"fakeplat\",\n        \"--target\",\n        script.scratch_path / \"target\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_file,\n        \"base\",\n    )\n\n    dist_info = pathlib.Path(\"scratch\", \"target\", \"base-0.1.0.dist-info\")\n    result.did_create(dist_info)\n\n\ndef test_new_resolver_handles_incompatible_wheel_tags_in_constraint_url(\n    script: PipTestEnvironment, make_fake_wheel: MakeFakeWheel\n) -> None:\n    initial_path = make_fake_wheel(\"base\", \"0.1.0\", \"fakepy1-fakeabi-fakeplat\")\n\n    constrained = script.scratch_path / \"constrained\"\n    constrained.mkdir()\n\n    final_path = constrained / initial_path.name\n\n    initial_path.rename(final_path)\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"base @ {final_path.as_uri()}\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_file,\n        \"base\",\n        expect_error=True,\n    )\n\n    assert (\n        \"Cannot install base because these package versions have conflicting \"\n        \"dependencies.\"\n    ) in result.stderr, str(result)\n\n    script.assert_not_installed(\"base\")\n\n\ndef test_new_resolver_avoids_incompatible_wheel_tags_in_constraint_url(\n    script: PipTestEnvironment, make_fake_wheel: MakeFakeWheel\n) -> None:\n    initial_path = make_fake_wheel(\"dep\", \"0.1.0\", \"fakepy1-fakeabi-fakeplat\")\n\n    constrained = script.scratch_path / \"constrained\"\n    constrained.mkdir()\n\n    final_path = constrained / initial_path.name\n\n    initial_path.rename(final_path)\n\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(f\"dep @ {final_path.as_uri()}\")\n\n    index = script.scratch_path / \"index\"\n    index.mkdir()\n\n    index_dep = create_basic_wheel_for_package(script, \"dep\", \"0.2.0\")\n\n    base = create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n    base_2 = create_basic_wheel_for_package(script, \"base\", \"0.2.0\", depends=[\"dep\"])\n\n    index_dep.rename(index / index_dep.name)\n    base.rename(index / base.name)\n    base_2.rename(index / base_2.name)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"-c\",\n        constraints_file,\n        \"--find-links\",\n        script.scratch_path / \"index\",\n        \"base\",\n    )\n\n    script.assert_installed(base=\"0.1.0\")\n    script.assert_not_installed(\"dep\")\n\n\n@pytest.mark.parametrize(\n    \"suffixes_equivalent, depend_suffix, request_suffix\",\n    [\n        pytest.param(\n            True,\n            \"#egg=foo\",\n            \"\",\n            id=\"drop-depend-egg\",\n        ),\n        pytest.param(\n            True,\n            \"\",\n            \"#egg=foo\",\n            id=\"drop-request-egg\",\n        ),\n        pytest.param(\n            True,\n            \"#subdirectory=bar&egg=foo\",\n            \"#subdirectory=bar&egg=bar\",\n            id=\"drop-egg-only\",\n        ),\n        pytest.param(\n            True,\n            \"#subdirectory=bar&egg=foo\",\n            \"#egg=foo&subdirectory=bar\",\n            id=\"fragment-ordering\",\n        ),\n        pytest.param(\n            True,\n            \"?a=1&b=2\",\n            \"?b=2&a=1\",\n            id=\"query-opordering\",\n        ),\n        pytest.param(\n            False,\n            \"#sha512=1234567890abcdef\",\n            \"#sha512=abcdef1234567890\",\n            id=\"different-keys\",\n        ),\n        pytest.param(\n            False,\n            \"#sha512=1234567890abcdef\",\n            \"#md5=1234567890abcdef\",\n            id=\"different-values\",\n        ),\n        pytest.param(\n            False,\n            \"#subdirectory=bar&egg=foo\",\n            \"#subdirectory=rex\",\n            id=\"drop-egg-still-different\",\n        ),\n    ],\n)\ndef test_new_resolver_direct_url_equivalent(\n    tmp_path: pathlib.Path,\n    script: PipTestEnvironment,\n    suffixes_equivalent: bool,\n    depend_suffix: str,\n    request_suffix: str,\n) -> None:\n    pkga = create_basic_wheel_for_package(script, name=\"pkga\", version=\"1\")\n    pkgb = create_basic_wheel_for_package(\n        script,\n        name=\"pkgb\",\n        version=\"1\",\n        depends=[f\"pkga@{pkga.as_uri()}{depend_suffix}\"],\n    )\n\n    # Make pkgb visible via --find-links, but not pkga.\n    find_links = tmp_path.joinpath(\"find_links\")\n    find_links.mkdir()\n    with open(pkgb, \"rb\") as f:\n        find_links.joinpath(pkgb.name).write_bytes(f.read())\n\n    # Install pkgb from --find-links, and pkga directly but from a different\n    # URL suffix as specified in pkgb. This should work!\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        str(find_links),\n        f\"{pkga.as_uri()}{request_suffix}\",\n        \"pkgb\",\n        expect_error=(not suffixes_equivalent),\n    )\n\n    if suffixes_equivalent:\n        script.assert_installed(pkga=\"1\", pkgb=\"1\")\n    else:\n        script.assert_not_installed(\"pkga\", \"pkgb\")\n\n\ndef test_new_resolver_direct_url_with_extras(\n    tmp_path: pathlib.Path, script: PipTestEnvironment\n) -> None:\n    pkg1 = create_basic_wheel_for_package(script, name=\"pkg1\", version=\"1\")\n    pkg2 = create_basic_wheel_for_package(\n        script,\n        name=\"pkg2\",\n        version=\"1\",\n        extras={\"ext\": [\"pkg1\"]},\n    )\n    pkg3 = create_basic_wheel_for_package(\n        script,\n        name=\"pkg3\",\n        version=\"1\",\n        depends=[\"pkg2[ext]\"],\n    )\n\n    # Make pkg1 and pkg3 visible via --find-links, but not pkg2.\n    find_links = tmp_path.joinpath(\"find_links\")\n    find_links.mkdir()\n    with open(pkg1, \"rb\") as f:\n        find_links.joinpath(pkg1.name).write_bytes(f.read())\n    with open(pkg3, \"rb\") as f:\n        find_links.joinpath(pkg3.name).write_bytes(f.read())\n\n    # Install with pkg2 only available with direct URL. The extra-ed direct\n    # URL pkg2 should be able to provide pkg2[ext] required by pkg3.\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        str(find_links),\n        pkg2,\n        \"pkg3\",\n    )\n\n    script.assert_installed(pkg1=\"1\", pkg2=\"1\", pkg3=\"1\")\n    assert not result.get_created_direct_url(\"pkg1\")\n    assert result.get_created_direct_url(\"pkg2\")\n    assert not result.get_created_direct_url(\"pkg3\")\n\n\ndef test_new_resolver_modifies_installed_incompatible(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, name=\"a\", version=\"1\")\n    create_basic_wheel_for_package(script, name=\"a\", version=\"2\")\n    create_basic_wheel_for_package(script, name=\"a\", version=\"3\")\n    create_basic_wheel_for_package(script, name=\"b\", version=\"1\", depends=[\"a==1\"])\n    create_basic_wheel_for_package(script, name=\"b\", version=\"2\", depends=[\"a==2\"])\n    create_basic_wheel_for_package(script, name=\"c\", version=\"1\", depends=[\"a!=1\"])\n    create_basic_wheel_for_package(script, name=\"c\", version=\"2\", depends=[\"a!=1\"])\n    create_basic_wheel_for_package(script, name=\"d\", version=\"1\", depends=[\"b\", \"c\"])\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"b==1\",\n    )\n\n    # d-1 depends on b and c. b-1 is already installed and therefore first\n    # pinned, but later found to be incompatible since the \"a==1\" dependency\n    # makes all c versions impossible to satisfy. The resolver should be able to\n    # discard b-1 and backtrack, so b-2 is selected instead.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"d==1\",\n    )\n    script.assert_installed(d=\"1\", c=\"2\", b=\"2\", a=\"2\")\n\n\ndef test_new_resolver_transitively_depends_on_unnamed_local(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, name=\"certbot-docs\", version=\"1\")\n    certbot = create_test_package_with_setup(\n        script,\n        name=\"certbot\",\n        version=\"99.99.0.dev0\",\n        extras_require={\"docs\": [\"certbot-docs\"]},\n    )\n    certbot_apache = create_test_package_with_setup(\n        script,\n        name=\"certbot-apache\",\n        version=\"99.99.0.dev0\",\n        install_requires=[\"certbot>=99.99.0.dev0\"],\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        f\"{certbot}[docs]\",\n        certbot_apache,\n    )\n    script.assert_installed(\n        certbot=\"99.99.0.dev0\",\n        certbot_apache=\"99.99.0.dev0\",\n        certbot_docs=\"1\",\n    )\n\n\ndef _to_localhost_uri(path: pathlib.Path) -> str:\n    # Something like file://localhost/path/to/package\n    return path.as_uri().replace(\"///\", \"//localhost/\")\n\n\n@pytest.mark.parametrize(\n    \"format_dep\",\n    [\n        pytest.param(pathlib.Path.as_uri, id=\"emptyhost\"),\n        pytest.param(_to_localhost_uri, id=\"localhost\"),\n    ],\n)\n@pytest.mark.parametrize(\n    \"format_input\",\n    [\n        pytest.param(pathlib.Path, id=\"path\"),\n        pytest.param(pathlib.Path.as_uri, id=\"emptyhost\"),\n        pytest.param(_to_localhost_uri, id=\"localhost\"),\n    ],\n)\ndef test_new_resolver_file_url_normalize(\n    script: PipTestEnvironment,\n    format_dep: Callable[[pathlib.Path], str],\n    format_input: Callable[[pathlib.Path], str],\n) -> None:\n    lib_a = create_test_package_with_setup(\n        script,\n        name=\"lib_a\",\n        version=\"1\",\n    )\n    lib_b = create_test_package_with_setup(\n        script,\n        name=\"lib_b\",\n        version=\"1\",\n        install_requires=[f\"lib_a @ {format_dep(lib_a)}\"],\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        format_input(lib_a),\n        lib_b,\n    )\n    script.assert_installed(lib_a=\"1\", lib_b=\"1\")\n\n\ndef test_new_resolver_dont_backtrack_on_extra_if_base_constrained(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\", extras={\"ext\": [\"dep\"]})\n    create_basic_wheel_for_package(script, \"pkg\", \"2.0\", extras={\"ext\": [\"dep\"]})\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"pkg==1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--constraint\",\n        constraints_file,\n        \"pkg[ext]\",\n    )\n    assert \"pkg-2.0\" not in result.stdout, \"Should not try 2.0 due to constraint\"\n    script.assert_installed(pkg=\"1.0\", dep=\"1.0\")\n\n\n@pytest.mark.parametrize(\"swap_order\", [True, False])\n@pytest.mark.parametrize(\"two_extras\", [True, False])\ndef test_new_resolver_dont_backtrack_on_extra_if_base_constrained_in_requirement(\n    script: PipTestEnvironment, swap_order: bool, two_extras: bool\n) -> None:\n    \"\"\"\n    Verify that a requirement with a constraint on a package (either on the base\n    on the base with an extra) causes the resolver to infer the same constraint for\n    any (other) extras with the same base.\n\n    :param swap_order: swap the order the install specifiers appear in\n    :param two_extras: also add an extra for the constrained specifier\n    \"\"\"\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n    create_basic_wheel_for_package(\n        script, \"pkg\", \"1.0\", extras={\"ext1\": [\"dep\"], \"ext2\": [\"dep\"]}\n    )\n    create_basic_wheel_for_package(\n        script, \"pkg\", \"2.0\", extras={\"ext1\": [\"dep\"], \"ext2\": [\"dep\"]}\n    )\n\n    to_install: tuple[str, str] = (\n        \"pkg[ext1]\",\n        \"pkg[ext2]==1.0\" if two_extras else \"pkg==1.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        *(to_install if not swap_order else reversed(to_install)),\n    )\n    assert \"pkg-2.0\" not in result.stdout, \"Should not try 2.0 due to constraint\"\n    script.assert_installed(pkg=\"1.0\", dep=\"1.0\")\n\n\n@pytest.mark.parametrize(\"swap_order\", [True, False])\n@pytest.mark.parametrize(\"two_extras\", [True, False])\ndef test_new_resolver_dont_backtrack_on_conflicting_constraints_on_extras(\n    tmpdir: pathlib.Path,\n    virtualenv: VirtualEnvironment,\n    script_factory: ScriptFactory,\n    swap_order: bool,\n    two_extras: bool,\n) -> None:\n    \"\"\"\n    Verify that conflicting constraints on the same package with different\n    extras cause the resolver to trivially reject the request rather than\n    trying any candidates.\n\n    :param swap_order: swap the order the install specifiers appear in\n    :param two_extras: also add an extra for the second specifier\n    \"\"\"\n    script: PipTestEnvironment = script_factory(\n        tmpdir.joinpath(\"workspace\"),\n        virtualenv,\n        {**os.environ, \"PIP_RESOLVER_DEBUG\": \"1\"},\n    )\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n    create_basic_wheel_for_package(\n        script, \"pkg\", \"1.0\", extras={\"ext1\": [\"dep\"], \"ext2\": [\"dep\"]}\n    )\n    create_basic_wheel_for_package(\n        script, \"pkg\", \"2.0\", extras={\"ext1\": [\"dep\"], \"ext2\": [\"dep\"]}\n    )\n\n    to_install: tuple[str, str] = (\n        \"pkg[ext1]>1\",\n        \"pkg[ext2]==1.0\" if two_extras else \"pkg==1.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        *(to_install if not swap_order else reversed(to_install)),\n        expect_error=True,\n    )\n    assert (\n        \"pkg-2.0\" not in result.stdout or \"pkg-1.0\" not in result.stdout\n    ), \"Should only try one of 1.0, 2.0 depending on order\"\n    assert \"Reporter.starting()\" in result.stdout, (\n        \"This should never fail unless the debug reporting format has changed,\"\n        \" in which case the other assertions in this test need to be reviewed.\"\n    )\n    assert (\n        \"Reporter.rejecting_candidate\" not in result.stdout\n    ), \"Should be able to conclude conflict before even selecting a candidate\"\n    assert (\n        \"conflict is caused by\" in result.stdout\n    ), \"Resolver should be trivially able to find conflict cause\"\n\n\ndef test_new_resolver_respect_user_requested_if_extra_is_installed(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg1\", \"1.0\")\n    create_basic_wheel_for_package(script, \"pkg2\", \"1.0\", extras={\"ext\": [\"pkg1\"]})\n    create_basic_wheel_for_package(script, \"pkg2\", \"2.0\", extras={\"ext\": [\"pkg1\"]})\n    create_basic_wheel_for_package(script, \"pkg3\", \"1.0\", depends=[\"pkg2[ext]\"])\n\n    # Install pkg3 with an older pkg2.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg3\",\n        \"pkg2==1.0\",\n    )\n    script.assert_installed(pkg3=\"1.0\", pkg2=\"1.0\", pkg1=\"1.0\")\n\n    # Now upgrade both pkg3 and pkg2. pkg2 should be upgraded although pkg2[ext]\n    # is not requested by the user.\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--upgrade\",\n        \"pkg3\",\n        \"pkg2\",\n    )\n    script.assert_installed(pkg3=\"1.0\", pkg2=\"2.0\", pkg1=\"1.0\")\n\n\ndef test_new_resolver_constraint_on_link_with_extra(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Verify that installing works from a link with both an extra and a constraint.\n    \"\"\"\n    wheel: pathlib.Path = create_basic_wheel_for_package(\n        script, \"pkg\", \"1.0\", extras={\"ext\": []}\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        # no index, no --find-links: only the explicit path\n        \"--no-index\",\n        f\"{wheel}[ext]\",\n        \"pkg==1\",\n    )\n    script.assert_installed(pkg=\"1.0\")\n\n\ndef test_new_resolver_constraint_on_link_with_extra_indirect(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Verify that installing works from a link with an extra if there is an indirect\n    dependency on that same package with the same extra (#12372).\n    \"\"\"\n    wheel_one: pathlib.Path = create_basic_wheel_for_package(\n        script, \"pkg1\", \"1.0\", extras={\"ext\": []}\n    )\n    wheel_two: pathlib.Path = create_basic_wheel_for_package(\n        script, \"pkg2\", \"1.0\", depends=[\"pkg1[ext]==1.0\"]\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        # no index, no --find-links: only the explicit path\n        wheel_two,\n        f\"{wheel_one}[ext]\",\n    )\n    script.assert_installed(pkg1=\"1.0\", pkg2=\"1.0\")\n\n\ndef test_new_resolver_do_not_backtrack_on_build_failure(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_sdist_for_package(script, \"pkg1\", \"2.0\", fails_build=True)\n    create_basic_wheel_for_package(script, \"pkg1\", \"1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg1\",\n        expect_error=True,\n    )\n\n    assert \"Failed to build 'pkg1'\" in result.stderr\n\n\ndef test_new_resolver_works_when_failing_package_builds_are_disallowed(\n    script: PipTestEnvironment,\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg2\", \"1.0\", depends=[\"pkg1\"])\n    create_basic_sdist_for_package(script, \"pkg1\", \"2.0\", fails_build=True)\n    create_basic_wheel_for_package(script, \"pkg1\", \"1.0\")\n    constraints_file = script.scratch_path / \"constraints.txt\"\n    constraints_file.write_text(\"pkg1 != 2.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"pkg2\",\n    )\n\n    script.assert_installed(pkg2=\"1.0\", pkg1=\"1.0\")\n\n\n@pytest.mark.parametrize(\"swap_order\", [True, False])\ndef test_new_resolver_comes_from_with_extra(\n    script: PipTestEnvironment, swap_order: bool\n) -> None:\n    \"\"\"\n    Verify that reporting where a dependency comes from is accurate when it comes\n    from a package with an extra.\n\n    :param swap_order: swap the order the install specifiers appear in\n    \"\"\"\n    create_basic_wheel_for_package(script, \"dep\", \"1.0\")\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\", extras={\"ext\": [\"dep\"]})\n\n    to_install: tuple[str, str] = (\"pkg\", \"pkg[ext]\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        *(to_install if not swap_order else reversed(to_install)),\n    )\n    assert \"(from pkg[ext])\" in result.stdout\n    assert \"(from pkg)\" not in result.stdout\n    script.assert_installed(pkg=\"1.0\", dep=\"1.0\")\n"
  },
  {
    "path": "tests/functional/test_new_resolver_errors.py",
    "content": "import pathlib\nimport sys\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    create_basic_wheel_for_package,\n    create_test_package_with_setup,\n)\nfrom tests.lib.wheel import make_wheel\n\n\ndef test_new_resolver_conflict_requirements_file(\n    tmpdir: pathlib.Path, script: PipTestEnvironment\n) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"1.0\")\n    create_basic_wheel_for_package(script, \"base\", \"2.0\")\n    create_basic_wheel_for_package(\n        script,\n        \"pkga\",\n        \"1.0\",\n        depends=[\"base==1.0\"],\n    )\n    create_basic_wheel_for_package(\n        script,\n        \"pkgb\",\n        \"1.0\",\n        depends=[\"base==2.0\"],\n    )\n\n    req_file = tmpdir.joinpath(\"requirements.txt\")\n    req_file.write_text(\"pkga\\npkgb\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-r\",\n        req_file,\n        expect_error=True,\n    )\n\n    message = \"package versions have conflicting dependencies\"\n    assert message in result.stderr, str(result)\n\n\ndef test_new_resolver_conflict_constraints_file(\n    tmpdir: pathlib.Path, script: PipTestEnvironment\n) -> None:\n    create_basic_wheel_for_package(script, \"pkg\", \"1.0\")\n\n    constraints_file = tmpdir.joinpath(\"constraints.txt\")\n    constraints_file.write_text(\"pkg!=1.0\")\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"-c\",\n        constraints_file,\n        \"pkg==1.0\",\n        expect_error=True,\n    )\n\n    assert \"ResolutionImpossible\" in result.stderr, str(result)\n\n    message = \"The user requested (constraint) pkg!=1.0\"\n    assert message in result.stdout, str(result)\n\n\ndef test_new_resolver_requires_python_error(script: PipTestEnvironment) -> None:\n    compatible_python = f\">={sys.version_info.major}.{sys.version_info.minor}\"\n    incompatible_python = f\"<{sys.version_info.major}.{sys.version_info.minor}\"\n\n    pkga = create_test_package_with_setup(\n        script,\n        name=\"pkga\",\n        version=\"1.0\",\n        python_requires=compatible_python,\n    )\n    pkgb = create_test_package_with_setup(\n        script,\n        name=\"pkgb\",\n        version=\"1.0\",\n        python_requires=incompatible_python,\n    )\n\n    # This always fails because pkgb can never be satisfied.\n    result = script.pip(\n        \"install\", \"--no-build-isolation\", \"--no-index\", pkga, pkgb, expect_error=True\n    )\n\n    # The error message should mention the Requires-Python: value causing the\n    # conflict, not the compatible one.\n    assert incompatible_python in result.stderr, str(result)\n    assert compatible_python not in result.stderr, str(result)\n\n\ndef test_new_resolver_checks_requires_python_before_dependencies(\n    script: PipTestEnvironment,\n) -> None:\n    incompatible_python = f\"<{sys.version_info.major}.{sys.version_info.minor}\"\n\n    pkg_dep = create_basic_wheel_for_package(\n        script,\n        name=\"pkg-dep\",\n        version=\"1\",\n    )\n    create_basic_wheel_for_package(\n        script,\n        name=\"pkg-root\",\n        version=\"1\",\n        # Refer the dependency by URL to prioritise it as much as possible,\n        # to test that Requires-Python is *still* inspected first.\n        depends=[f\"pkg-dep@{pathlib.Path(pkg_dep).as_uri()}\"],\n        requires_python=incompatible_python,\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"pkg-root\",\n        expect_error=True,\n    )\n\n    # Resolution should fail because of pkg-root's Requires-Python.\n    # This is done before dependencies so pkg-dep should never be pulled.\n    assert incompatible_python in result.stderr, str(result)\n    # Setuptools produces wheels with normalized names.\n    assert \"pkg_dep\" not in result.stderr, str(result)\n    assert \"pkg_dep\" not in result.stdout, str(result)\n\n\ndef test_new_resolver_no_versions_available_hint(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test hint that no package candidate is available at all,\n    when ResolutionImpossible occurs.\n    \"\"\"\n    wheel_house = script.scratch_path.joinpath(\"wheelhouse\")\n    wheel_house.mkdir()\n\n    incompatible_dep_wheel = make_wheel(\n        name=\"incompatible-dep\",\n        version=\"1.0.0\",\n        wheel_metadata_updates={\"Tag\": [\"py3-none-fakeplat\"]},\n    )\n    incompatible_dep_wheel.save_to(\n        wheel_house.joinpath(\"incompatible_dep-1.0.0-py3-none-fakeplat.whl\")\n    )\n\n    # Create multiple versions of a package that depend on the incompatible dependency\n    requesting_pkg_v1 = make_wheel(\n        name=\"requesting-pkg\",\n        version=\"1.0.0\",\n        metadata_updates={\"Requires-Dist\": [\"incompatible-dep==1.0.0\"]},\n    )\n    requesting_pkg_v1.save_to(\n        wheel_house.joinpath(\"requesting_pkg-1.0.0-py2.py3-none-any.whl\")\n    )\n\n    requesting_pkg_v2 = make_wheel(\n        name=\"requesting-pkg\",\n        version=\"2.0.0\",\n        metadata_updates={\"Requires-Dist\": [\"incompatible-dep==1.0.0\"]},\n    )\n    requesting_pkg_v2.save_to(\n        wheel_house.joinpath(\"requesting_pkg-2.0.0-py2.py3-none-any.whl\")\n    )\n\n    # Attempt to install the requesting package\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        str(wheel_house),\n        \"requesting-pkg\",\n        expect_error=True,\n    )\n\n    # Check that ResolutionImpossible error occurred\n    assert \"ResolutionImpossible\" in result.stderr, str(result)\n\n    # Check that the new hint message is present\n    assert (\n        \"Additionally, some packages in these conflicts have no \"\n        \"matching distributions available for your environment:\\n\"\n        \"    incompatible-dep\\n\" in result.stdout\n    ), str(result)\n"
  },
  {
    "path": "tests/functional/test_new_resolver_hashes.py",
    "content": "import collections\nimport hashlib\n\nimport pytest\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    create_basic_sdist_for_package,\n    create_basic_wheel_for_package,\n)\n\n_FindLinks = collections.namedtuple(\n    \"_FindLinks\",\n    \"index_html sdist_hash wheel_hash\",\n)\n\n\ndef _create_find_links(script: PipTestEnvironment) -> _FindLinks:\n    sdist_path = create_basic_sdist_for_package(script, \"base\", \"0.1.0\")\n    wheel_path = create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n\n    sdist_hash = hashlib.sha256(sdist_path.read_bytes()).hexdigest()\n    wheel_hash = hashlib.sha256(wheel_path.read_bytes()).hexdigest()\n\n    index_html = script.scratch_path / \"index.html\"\n    index_html.write_text(\n        f\"\"\"\n        <!DOCTYPE html>\n        <a href=\"{sdist_path.as_uri()}#sha256={sdist_hash}\">{sdist_path.stem}</a>\n        <a href=\"{wheel_path.as_uri()}#sha256={wheel_hash}\">{wheel_path.stem}</a>\n        \"\"\".strip()\n    )\n\n    return _FindLinks(index_html, sdist_hash, wheel_hash)\n\n\n@pytest.mark.parametrize(\n    \"requirements_template, message\",\n    [\n        (\n            \"\"\"\n            base==0.1.0 --hash=sha256:{sdist_hash} --hash=sha256:{wheel_hash}\n            base==0.1.0 --hash=sha256:{sdist_hash} --hash=sha256:{wheel_hash}\n            \"\"\",\n            \"Checked 2 links for project {name!r} against 2 hashes \"\n            \"(2 matches, 0 no digest): discarding no candidates\",\n        ),\n        (\n            # Different hash lists are intersected.\n            \"\"\"\n            base==0.1.0 --hash=sha256:{sdist_hash} --hash=sha256:{wheel_hash}\n            base==0.1.0 --hash=sha256:{sdist_hash}\n            \"\"\",\n            \"Checked 2 links for project {name!r} against 1 hashes \"\n            \"(1 matches, 0 no digest): discarding 1 non-matches\",\n        ),\n    ],\n    ids=[\"identical\", \"intersect\"],\n)\ndef test_new_resolver_hash_intersect(\n    script: PipTestEnvironment, requirements_template: str, message: str\n) -> None:\n    find_links = _create_find_links(script)\n\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        requirements_template.format(\n            sdist_hash=find_links.sdist_hash,\n            wheel_hash=find_links.wheel_hash,\n        ),\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-deps\",\n        \"--no-index\",\n        \"--find-links\",\n        find_links.index_html,\n        \"-vv\",\n        \"--requirement\",\n        requirements_txt,\n    )\n\n    assert message.format(name=\"base\") in result.stdout, str(result)\n\n\ndef test_new_resolver_hash_intersect_from_constraint(\n    script: PipTestEnvironment,\n) -> None:\n    find_links = _create_find_links(script)\n    sdist_hash = find_links.sdist_hash\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraints_txt.write_text(f\"base==0.1.0 --hash=sha256:{sdist_hash}\")\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        f\"\"\"\n        base==0.1.0 --hash=sha256:{sdist_hash} --hash=sha256:{find_links.wheel_hash}\n        \"\"\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-deps\",\n        \"--no-index\",\n        \"--find-links\",\n        find_links.index_html,\n        \"-vv\",\n        \"--constraint\",\n        constraints_txt,\n        \"--requirement\",\n        requirements_txt,\n    )\n\n    message = (\n        \"Checked 2 links for project {name!r} against 1 hashes \"\n        \"(1 matches, 0 no digest): discarding 1 non-matches\"\n    ).format(name=\"base\")\n    assert message in result.stdout, str(result)\n\n\n@pytest.mark.parametrize(\n    \"requirements_template, constraints_template\",\n    [\n        (\n            \"\"\"\n            base==0.1.0 --hash=sha256:{sdist_hash}\n            base==0.1.0 --hash=sha256:{wheel_hash}\n            \"\"\",\n            \"\",\n        ),\n        (\n            \"base==0.1.0 --hash=sha256:{sdist_hash}\",\n            \"base==0.1.0 --hash=sha256:{wheel_hash}\",\n        ),\n    ],\n    ids=[\"both-requirements\", \"one-each\"],\n)\ndef test_new_resolver_hash_intersect_empty(\n    script: PipTestEnvironment,\n    requirements_template: str,\n    constraints_template: str,\n) -> None:\n    find_links = _create_find_links(script)\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraints_txt.write_text(\n        constraints_template.format(\n            sdist_hash=find_links.sdist_hash,\n            wheel_hash=find_links.wheel_hash,\n        ),\n    )\n\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        requirements_template.format(\n            sdist_hash=find_links.sdist_hash,\n            wheel_hash=find_links.wheel_hash,\n        ),\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--no-cache-dir\",\n        \"--no-deps\",\n        \"--no-index\",\n        \"--find-links\",\n        find_links.index_html,\n        \"--constraint\",\n        constraints_txt,\n        \"--requirement\",\n        requirements_txt,\n        expect_error=True,\n    )\n\n    assert (\n        \"THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE.\"\n    ) in result.stderr, str(result)\n\n\ndef test_new_resolver_hash_intersect_empty_from_constraint(\n    script: PipTestEnvironment,\n) -> None:\n    find_links = _create_find_links(script)\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraints_txt.write_text(\n        f\"\"\"\n        base==0.1.0 --hash=sha256:{find_links.sdist_hash}\n        base==0.1.0 --hash=sha256:{find_links.wheel_hash}\n        \"\"\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-deps\",\n        \"--no-index\",\n        \"--find-links\",\n        find_links.index_html,\n        \"--constraint\",\n        constraints_txt,\n        \"base==0.1.0\",\n        expect_error=True,\n    )\n\n    message = (\n        \"Hashes are required in --require-hashes mode, but they are missing \"\n        \"from some requirements.\"\n    )\n    assert message in result.stderr, str(result)\n\n\n@pytest.mark.parametrize(\"constrain_by_hash\", [False, True])\ndef test_new_resolver_hash_requirement_and_url_constraint_can_succeed(\n    script: PipTestEnvironment,\n    constrain_by_hash: bool,\n) -> None:\n    wheel_path = create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n\n    wheel_hash = hashlib.sha256(wheel_path.read_bytes()).hexdigest()\n\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        f\"\"\"\n        base==0.1.0 --hash=sha256:{wheel_hash}\n        \"\"\",\n    )\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraint_text = f\"base @ {wheel_path.as_uri()}\\n\"\n    if constrain_by_hash:\n        constraint_text += f\"base==0.1.0 --hash=sha256:{wheel_hash}\\n\"\n    constraints_txt.write_text(constraint_text)\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--constraint\",\n        constraints_txt,\n        \"--requirement\",\n        requirements_txt,\n    )\n\n    script.assert_installed(base=\"0.1.0\")\n\n\n@pytest.mark.parametrize(\"constrain_by_hash\", [False, True])\ndef test_new_resolver_hash_requirement_and_url_constraint_can_fail(\n    script: PipTestEnvironment,\n    constrain_by_hash: bool,\n) -> None:\n    wheel_path = create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n    other_path = create_basic_wheel_for_package(script, \"other\", \"0.1.0\")\n\n    other_hash = hashlib.sha256(other_path.read_bytes()).hexdigest()\n\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        f\"\"\"\n        base==0.1.0 --hash=sha256:{other_hash}\n        \"\"\",\n    )\n\n    constraints_txt = script.scratch_path / \"constraints.txt\"\n    constraint_text = f\"base @ {wheel_path.as_uri()}\\n\"\n    if constrain_by_hash:\n        constraint_text += f\"base==0.1.0 --hash=sha256:{other_hash}\\n\"\n    constraints_txt.write_text(constraint_text)\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--constraint\",\n        constraints_txt,\n        \"--requirement\",\n        requirements_txt,\n        expect_error=True,\n    )\n\n    assert (\n        \"THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE.\"\n    ) in result.stderr, str(result)\n\n    script.assert_not_installed(\"base\", \"other\")\n\n\ndef test_new_resolver_hash_with_extras(script: PipTestEnvironment) -> None:\n    parent_with_extra_path = create_basic_wheel_for_package(\n        script, \"parent_with_extra\", \"0.1.0\", depends=[\"child[extra]\"]\n    )\n    parent_with_extra_hash = hashlib.sha256(\n        parent_with_extra_path.read_bytes()\n    ).hexdigest()\n\n    parent_without_extra_path = create_basic_wheel_for_package(\n        script, \"parent_without_extra\", \"0.1.0\", depends=[\"child\"]\n    )\n    parent_without_extra_hash = hashlib.sha256(\n        parent_without_extra_path.read_bytes()\n    ).hexdigest()\n\n    child_path = create_basic_wheel_for_package(\n        script, \"child\", \"0.1.0\", extras={\"extra\": [\"extra\"]}\n    )\n    child_hash = hashlib.sha256(child_path.read_bytes()).hexdigest()\n\n    # Newer release\n    create_basic_wheel_for_package(\n        script, \"child\", \"0.2.0\", extras={\"extra\": [\"extra\"]}\n    )\n\n    extra_path = create_basic_wheel_for_package(script, \"extra\", \"0.1.0\")\n    extra_hash = hashlib.sha256(extra_path.read_bytes()).hexdigest()\n\n    requirements_txt = script.scratch_path / \"requirements.txt\"\n    requirements_txt.write_text(\n        f\"\"\"\n        child[extra]==0.1.0 --hash=sha256:{child_hash}\n        parent_with_extra==0.1.0 --hash=sha256:{parent_with_extra_hash}\n        parent_without_extra==0.1.0 --hash=sha256:{parent_without_extra_hash}\n        extra==0.1.0 --hash=sha256:{extra_hash}\n        \"\"\",\n    )\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--requirement\",\n        requirements_txt,\n    )\n\n    script.assert_installed(\n        parent_with_extra=\"0.1.0\",\n        parent_without_extra=\"0.1.0\",\n        child=\"0.1.0\",\n        extra=\"0.1.0\",\n    )\n"
  },
  {
    "path": "tests/functional/test_new_resolver_target.py",
    "content": "from __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Callable\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\n\nfrom tests.lib import PipTestEnvironment\nfrom tests.lib.wheel import make_wheel\n\nMakeFakeWheel = Callable[[str], str]\n\n\n@pytest.fixture\ndef make_fake_wheel(script: PipTestEnvironment) -> MakeFakeWheel:\n    def _make_fake_wheel(wheel_tag: str) -> str:\n        wheel_house = script.scratch_path.joinpath(\"wheelhouse\")\n        wheel_house.mkdir()\n        wheel_builder = make_wheel(\n            name=\"fake\",\n            version=\"1.0\",\n            wheel_metadata_updates={\"Tag\": []},\n        )\n        wheel_path = wheel_house.joinpath(f\"fake-1.0-{wheel_tag}.whl\")\n        wheel_builder.save_to(wheel_path)\n        return str(wheel_path)\n\n    return _make_fake_wheel\n\n\n@pytest.mark.parametrize(\"implementation\", [None, \"fakepy\"])\n@pytest.mark.parametrize(\"python_version\", [None, \"1\"])\n@pytest.mark.parametrize(\"abi\", [None, \"fakeabi\"])\n@pytest.mark.parametrize(\"platform\", [None, \"fakeplat\"])\ndef test_new_resolver_target_checks_compatibility_failure(\n    script: PipTestEnvironment,\n    make_fake_wheel: MakeFakeWheel,\n    implementation: str | None,\n    python_version: str | None,\n    abi: str | None,\n    platform: str | None,\n) -> None:\n    fake_wheel_tag = \"fakepy1-fakeabi-fakeplat\"\n    args = [\n        \"install\",\n        \"--only-binary=:all:\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--target\",\n        str(script.scratch_path.joinpath(\"target\")),\n        make_fake_wheel(fake_wheel_tag),\n    ]\n    if implementation:\n        args += [\"--implementation\", implementation]\n    if python_version:\n        args += [\"--python-version\", python_version]\n    if abi:\n        args += [\"--abi\", abi]\n    if platform:\n        args += [\"--platform\", platform]\n\n    args_tag = f\"{implementation}{python_version}-{abi}-{platform}\"\n    wheel_tag_matches = args_tag == fake_wheel_tag\n\n    result = script.pip(*args, expect_error=(not wheel_tag_matches))\n\n    dist_info = Path(\"scratch\", \"target\", \"fake-1.0.dist-info\")\n    if wheel_tag_matches:\n        assert result.returncode == SUCCESS\n        result.did_create(dist_info)\n    else:\n        assert result.returncode == ERROR\n        result.did_not_create(dist_info)\n"
  },
  {
    "path": "tests/functional/test_new_resolver_user.py",
    "content": "import os\nimport textwrap\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, create_basic_wheel_for_package\nfrom tests.lib.venv import VirtualEnvironment\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_new_resolver_install_user(script: PipTestEnvironment) -> None:\n    create_basic_wheel_for_package(script, \"base\", \"0.1.0\")\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base\",\n    )\n    result.did_create(script.user_site / \"base\")\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_new_resolver_install_user_satisfied_by_global_site(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    An install a matching version to user site should reuse a global site\n    installation if it satisfies.\n    \"\"\"\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==1.0.0\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base==1.0.0\",\n    )\n\n    result.did_not_create(script.user_site / \"base\")\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\ndef test_new_resolver_install_user_conflict_in_user_site(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Installing a different version in user site should uninstall an existing\n    different version in user site.\n    \"\"\"\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\")\n    create_basic_wheel_for_package(script, \"base\", \"2.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base==2.0.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base==1.0.0\",\n    )\n\n    base_1_dist_info = script.user_site / \"base-1.0.0.dist-info\"\n    base_2_dist_info = script.user_site / \"base-2.0.0.dist-info\"\n\n    result.did_create(base_1_dist_info)\n    result.did_not_create(base_2_dist_info)\n\n\n@pytest.fixture\ndef patch_dist_in_site_packages(virtualenv: VirtualEnvironment) -> None:\n    # Since the tests are run from a virtualenv, and to avoid the \"Will not\n    # install to the usersite because it will lack sys.path precedence...\"\n    # error: Monkey patch `pip._internal.utils.misc.dist_in_site_packages`\n    # so it's possible to install a conflicting distribution in the user site.\n    virtualenv.sitecustomize = textwrap.dedent(\n        \"\"\"\n        def dist_in_site_packages(dist):\n            return False\n\n        from pip._internal.metadata.base import BaseDistribution\n        BaseDistribution.in_site_packages = property(dist_in_site_packages)\n    \"\"\"\n    )\n\n\n@pytest.mark.usefixtures(\"enable_user_site\", \"patch_dist_in_site_packages\")\ndef test_new_resolver_install_user_reinstall_global_site(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Specifying --force-reinstall makes a different version in user site,\n    ignoring the matching installation in global site.\n    \"\"\"\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==1.0.0\",\n    )\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"--force-reinstall\",\n        \"base==1.0.0\",\n    )\n\n    result.did_create(script.user_site / \"base\")\n\n    site_packages_content = set(os.listdir(script.site_packages_path))\n    assert \"base\" in site_packages_content\n\n\n@pytest.mark.usefixtures(\"enable_user_site\", \"patch_dist_in_site_packages\")\ndef test_new_resolver_install_user_conflict_in_global_site(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Installing a different version in user site should ignore an existing\n    different version in global site, and simply add to the user site.\n    \"\"\"\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\")\n    create_basic_wheel_for_package(script, \"base\", \"2.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==1.0.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base==2.0.0\",\n    )\n\n    base_2_dist_info = script.user_site / \"base-2.0.0.dist-info\"\n    result.did_create(base_2_dist_info)\n\n    site_packages_content = set(os.listdir(script.site_packages_path))\n    assert \"base-1.0.0.dist-info\" in site_packages_content\n\n\n@pytest.mark.usefixtures(\"enable_user_site\", \"patch_dist_in_site_packages\")\ndef test_new_resolver_install_user_conflict_in_global_and_user_sites(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Installing a different version in user site should ignore an existing\n    different version in global site, but still upgrade the user site.\n    \"\"\"\n    create_basic_wheel_for_package(script, \"base\", \"1.0.0\")\n    create_basic_wheel_for_package(script, \"base\", \"2.0.0\")\n\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"base==2.0.0\",\n    )\n    script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"--force-reinstall\",\n        \"base==2.0.0\",\n    )\n\n    result = script.pip(\n        \"install\",\n        \"--no-cache-dir\",\n        \"--no-index\",\n        \"--find-links\",\n        script.scratch_path,\n        \"--user\",\n        \"base==1.0.0\",\n    )\n\n    base_1_dist_info = script.user_site / \"base-1.0.0.dist-info\"\n    base_2_dist_info = script.user_site / \"base-2.0.0.dist-info\"\n\n    result.did_create(base_1_dist_info)\n    assert base_2_dist_info in result.files_deleted\n\n    site_packages_content = set(os.listdir(script.site_packages_path))\n    assert \"base-2.0.0.dist-info\" in site_packages_content\n"
  },
  {
    "path": "tests/functional/test_no_color.py",
    "content": "\"\"\"\nTest specific for the --no-color option\n\"\"\"\n\nimport os\nimport shutil\nimport subprocess\nimport sys\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment\n\n\n@pytest.mark.network\n@pytest.mark.skipif(shutil.which(\"script\") is None, reason=\"no 'script' executable\")\ndef test_no_color(script: PipTestEnvironment) -> None:\n    \"\"\"Ensure colour output disabled when --no-color is passed.\"\"\"\n    # Using 'script' in this test allows for transparently testing pip's output\n    # since pip is smart enough to disable colour output when piped, which is\n    # not the behaviour we want to be testing here.\n    #\n    # On the other hand, this test is non-portable due to the options passed to\n    # 'script' and well as the mere use of the same.\n    #\n    # This test will stay until someone has the time to rewrite it.\n    pip_command = \"pip download {} setuptools==62.0.0 --no-cache-dir -d /tmp/\"\n    if sys.platform == \"darwin\":\n        command = f\"script -q /tmp/pip-test-no-color.txt {pip_command}\"\n    else:\n        command = f'script -q /tmp/pip-test-no-color.txt --command \"{pip_command}\"'\n\n    def get_run_output(option: str = \"\") -> str:\n        cmd = command.format(option)\n        proc = subprocess.Popen(\n            cmd,\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        proc.communicate()\n\n        try:\n            with open(\"/tmp/pip-test-no-color.txt\") as output_file:\n                retval = output_file.read()\n            return retval\n        finally:\n            os.unlink(\"/tmp/pip-test-no-color.txt\")\n            os.unlink(\"/tmp/setuptools-62.0.0-py3-none-any.whl\")\n\n    assert \"\\x1b[3\" in get_run_output(\"\"), \"Expected color in output\"\n    assert \"\\x1b[3\" not in get_run_output(\"--no-color\"), \"Expected no color in output\"\n"
  },
  {
    "path": "tests/functional/test_pep517.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom pathlib import Path\nfrom typing import Any\n\nimport pytest\nimport tomli_w\n\nfrom pip._internal.build_env import (\n    BuildEnvironment,\n    SubprocessBuildEnvironmentInstaller,\n)\nfrom pip._internal.req import InstallRequirement\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    create_basic_wheel_for_package,\n    make_test_finder,\n)\n\n\ndef make_project(\n    tmpdir: Path,\n    requires: list[str] | None = None,\n    backend: str | None = None,\n    backend_path: list[str] | None = None,\n) -> Path:\n    requires = requires or []\n    project_dir = tmpdir / \"project\"\n    project_dir.mkdir()\n    buildsys: dict[str, Any] = {\"requires\": requires}\n    if backend:\n        buildsys[\"build-backend\"] = backend\n    if backend_path:\n        buildsys[\"backend-path\"] = backend_path\n    data = tomli_w.dumps({\"build-system\": buildsys})\n    project_dir.joinpath(\"pyproject.toml\").write_text(data)\n    return project_dir\n\n\ndef test_backend(tmpdir: Path, data: TestData) -> None:\n    \"\"\"Check we can call a requirement's backend successfully\"\"\"\n    project_dir = make_project(tmpdir, backend=\"dummy_backend\")\n    req = InstallRequirement(None, None)\n    req.source_dir = os.fspath(project_dir)  # make req believe it has been unpacked\n    req.load_pyproject_toml()\n    finder = make_test_finder(find_links=[data.backends])\n    env = BuildEnvironment(SubprocessBuildEnvironmentInstaller(finder))\n    env.install_requirements([\"dummy_backend\"], \"normal\", kind=\"Installing\")\n    conflicting, missing = env.check_requirements([\"dummy_backend\"])\n    assert not conflicting\n    assert not missing\n    assert hasattr(req.pep517_backend, \"build_wheel\")\n    with env:\n        assert req.pep517_backend is not None\n        assert req.pep517_backend.build_wheel(\"dir\") == \"Backend called\"\n\n\ndummy_backend_code = \"\"\"\\\ndef build_wheel(\n    wheel_directory,\n    config_settings=None,\n    metadata_directory=None\n):\n    return \"Backend called\"\n\"\"\"\n\n\ndef test_backend_path(tmpdir: Path, data: TestData) -> None:\n    \"\"\"Check we can call a backend inside the project\"\"\"\n    project_dir = make_project(tmpdir, backend=\"dummy_backend\", backend_path=[\".\"])\n    (project_dir / \"dummy_backend.py\").write_text(dummy_backend_code)\n    req = InstallRequirement(None, None)\n    req.source_dir = os.fspath(project_dir)  # make req believe it has been unpacked\n    req.load_pyproject_toml()\n\n    env = BuildEnvironment(object())  # type: ignore\n    assert hasattr(req.pep517_backend, \"build_wheel\")\n    with env:\n        assert req.pep517_backend is not None\n        assert req.pep517_backend.build_wheel(\"dir\") == \"Backend called\"\n\n\ndef test_backend_path_and_dep(tmpdir: Path, data: TestData) -> None:\n    \"\"\"Check we can call a requirement's backend successfully\"\"\"\n    project_dir = make_project(\n        tmpdir, backend=\"dummy_internal_backend\", backend_path=[\".\"]\n    )\n    (project_dir / \"dummy_internal_backend.py\").write_text(\n        \"from dummy_backend import build_wheel\"\n    )\n    req = InstallRequirement(None, None)\n    req.source_dir = os.fspath(project_dir)  # make req believe it has been unpacked\n    req.load_pyproject_toml()\n    finder = make_test_finder(find_links=[data.backends])\n    env = BuildEnvironment(SubprocessBuildEnvironmentInstaller(finder))\n    env.install_requirements([\"dummy_backend\"], \"normal\", kind=\"Installing\")\n\n    assert hasattr(req.pep517_backend, \"build_wheel\")\n    with env:\n        assert req.pep517_backend is not None\n        assert req.pep517_backend.build_wheel(\"dir\") == \"Backend called\"\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep517_install(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, flag: str\n) -> None:\n    \"\"\"Check we can build with a custom backend\"\"\"\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\"], backend=\"test_backend\"\n    )\n    result = script.pip(\"install\", \"--no-index\", \"-f\", data.backends, project_dir, flag)\n    result.assert_installed(\"project\", editable=False)\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep517_install_with_reqs(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, flag: str\n) -> None:\n    \"\"\"Backend generated requirements are installed in the build env\"\"\"\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\"], backend=\"test_backend\"\n    )\n    project_dir.joinpath(\"backend_reqs.txt\").write_text(\"simplewheel\")\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        data.backends,\n        \"-f\",\n        data.packages,\n        project_dir,\n        flag,\n    )\n    result.assert_installed(\"project\", editable=False)\n\n\ndef test_conflicting_pep517_backend_requirements(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData\n) -> None:\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\", \"simplewheel==1.0\"], backend=\"test_backend\"\n    )\n    project_dir.joinpath(\"backend_reqs.txt\").write_text(\"simplewheel==2.0\")\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        data.backends,\n        \"-f\",\n        data.packages,\n        project_dir,\n        expect_error=True,\n    )\n    msg = (\n        f\"Some build dependencies for {project_dir.as_uri()} conflict with the backend \"\n        \"dependencies: simplewheel==1.0 is incompatible with \"\n        \"simplewheel==2.0.\"\n    )\n    assert result.returncode != 0\n    assert msg in result.stderr, str(result)\n\n\ndef test_no_check_build_deps(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData\n) -> None:\n    project_dir = make_project(\n        tmpdir, requires=[\"simplewheel==2.0\"], backend=\"test_backend\"\n    )\n    script.pip(\n        \"install\",\n        \"simplewheel==1.0\",\n        \"test_backend\",\n        \"--no-index\",\n        \"-f\",\n        data.packages,\n        \"-f\",\n        data.backends,\n    )\n    result = script.pip(\"install\", \"--no-build-isolation\", project_dir)\n    result.assert_installed(\"project\", editable=False)\n\n\ndef test_validate_missing_pep517_backend_requirements(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData\n) -> None:\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\", \"simplewheel==1.0\"], backend=\"test_backend\"\n    )\n    result = script.pip_install_local(\n        \"--no-build-isolation\",\n        \"--check-build-dependencies\",\n        project_dir,\n        find_links=[data.backends, data.packages],\n        expect_error=True,\n    )\n    msg = (\n        f\"Some build dependencies for {project_dir.as_uri()} are missing: \"\n        \"'simplewheel==1.0', 'test_backend'.\"\n    )\n    assert result.returncode != 0\n    assert msg in result.stderr, str(result)\n\n\ndef test_validate_conflicting_pep517_backend_requirements(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData\n) -> None:\n    project_dir = make_project(\n        tmpdir, requires=[\"simplewheel==1.0\"], backend=\"test_backend\"\n    )\n    script.pip(\"install\", \"simplewheel==2.0\", \"--no-index\", \"-f\", data.packages)\n    result = script.pip_install_local(\n        \"--no-build-isolation\",\n        \"--check-build-dependencies\",\n        project_dir,\n        find_links=[data.backends, data.packages],\n        expect_error=True,\n    )\n    msg = (\n        f\"Some build dependencies for {project_dir.as_uri()} conflict with the backend \"\n        \"dependencies: simplewheel==2.0 is incompatible with \"\n        \"simplewheel==1.0.\"\n    )\n    assert result.returncode != 0\n    assert msg in result.stderr, str(result)\n\n\ndef test_pep517_backend_requirements_satisfied_by_prerelease(\n    script: PipTestEnvironment,\n    data: TestData,\n) -> None:\n    create_basic_wheel_for_package(script, \"myreq\", \"1.0a1\")\n    script.pip(\"install\", \"myreq==1.0a1\", \"--no-index\", \"-f\", script.scratch_path)\n    script.pip(\"install\", \"test_backend\", \"--no-index\", \"-f\", data.backends)\n\n    project_dir = make_project(\n        script.scratch_path,\n        requires=[\"test_backend\", \"myreq\"],\n        backend=\"test_backend\",\n    )\n    project_dir.joinpath(\"backend_reqs.txt\").write_text(\"myreq\")\n\n    result = script.pip(\"install\", \"--no-index\", \"--no-build-isolation\", project_dir)\n    assert \"Installing backend dependencies:\" not in result.stdout\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep517_backend_requirements_already_satisfied(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, flag: str\n) -> None:\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\", \"simplewheel==1.0\"], backend=\"test_backend\"\n    )\n    project_dir.joinpath(\"backend_reqs.txt\").write_text(\"simplewheel\")\n    result = script.pip_install_local(\n        project_dir,\n        flag,\n        build_isolation=True,\n        find_links=[data.backends, data.packages],\n    )\n    assert \"Installing backend dependencies:\" not in result.stdout\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_pep517_install_with_no_cache_dir(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, flag: str\n) -> None:\n    \"\"\"Check builds with a custom backends work, even with no cache.\"\"\"\n    project_dir = make_project(\n        tmpdir, requires=[\"test_backend\"], backend=\"test_backend\"\n    )\n    result = script.pip_install_local(\n        \"--no-cache-dir\",\n        project_dir,\n        flag,\n        build_isolation=True,\n        find_links=data.backends,\n    )\n    result.assert_installed(\"project\", editable=False)\n\n\ndef make_pyproject_with_setup(\n    tmpdir: Path, build_system: bool = True, set_backend: bool = True\n) -> tuple[Path, str]:\n    project_dir = tmpdir / \"project\"\n    project_dir.mkdir()\n    setup_script = \"from setuptools import setup\\n\"\n    expect_script_dir_on_path = True\n    if build_system:\n        buildsys: dict[str, Any] = {\n            \"requires\": [\"setuptools\", \"wheel\"],\n        }\n        if set_backend:\n            buildsys[\"build-backend\"] = \"setuptools.build_meta\"\n            expect_script_dir_on_path = False\n        project_data = tomli_w.dumps({\"build-system\": buildsys})\n    else:\n        project_data = \"\"\n\n    if expect_script_dir_on_path:\n        setup_script += \"from pep517_test import __version__\\n\"\n    else:\n        setup_script += (\n            \"try:\\n\"\n            \"    import pep517_test\\n\"\n            \"except ImportError:\\n\"\n            \"    pass\\n\"\n            \"else:\\n\"\n            '    raise RuntimeError(\"Source dir incorrectly on sys.path\")\\n'\n        )\n\n    setup_script += 'setup(name=\"pep517_test\", version=\"0.1\", packages=[\"pep517_test\"])'\n\n    project_dir.joinpath(\"pyproject.toml\").write_text(project_data)\n    project_dir.joinpath(\"setup.py\").write_text(setup_script)\n    package_dir = project_dir / \"pep517_test\"\n    package_dir.mkdir()\n    package_dir.joinpath(\"__init__.py\").write_text('__version__ = \"0.1\"')\n    return project_dir, \"pep517_test\"\n\n\ndef test_no_build_system_section(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, common_wheels: Path\n) -> None:\n    \"\"\"Check builds with setup.py, pyproject.toml, but no build-system section.\"\"\"\n    project_dir, name = make_pyproject_with_setup(tmpdir, build_system=False)\n    result = script.pip_install_local(\n        \"--no-cache-dir\", project_dir, find_links=common_wheels\n    )\n    result.assert_installed(name, editable=False)\n\n\ndef test_no_build_backend_entry(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, common_wheels: Path\n) -> None:\n    \"\"\"Check builds with setup.py, pyproject.toml, but no build-backend entry.\"\"\"\n    project_dir, name = make_pyproject_with_setup(tmpdir, set_backend=False)\n    result = script.pip_install_local(\n        \"--no-cache-dir\", project_dir, find_links=common_wheels\n    )\n    result.assert_installed(name, editable=False)\n\n\ndef test_explicit_setuptools_backend(\n    script: PipTestEnvironment, tmpdir: Path, data: TestData, common_wheels: Path\n) -> None:\n    \"\"\"Check builds with setup.py, pyproject.toml, and a build-backend entry.\"\"\"\n    project_dir, name = make_pyproject_with_setup(tmpdir)\n    result = script.pip_install_local(\n        \"--no-cache-dir\", project_dir, find_links=common_wheels\n    )\n    result.assert_installed(name, editable=False)\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_nested_builds(script: PipTestEnvironment, flag: str, data: TestData) -> None:\n    \"\"\"Smoke test ensuring that nested PEP 517 builds work.\"\"\"\n    # trove-classifiers -> setuptools\n    #                   -> calvar -> setuptools\n    result = script.pip_install_local(\n        \"trove-classifiers\",\n        \"--no-cache\",\n        \"--no-binary\",\n        \"trove-classifiers,calvar\",\n        flag,\n        find_links=[data.pypi_packages, data.common_wheels],\n    )\n    result.assert_installed(\"trove_classifiers\", editable=False)\n"
  },
  {
    "path": "tests/functional/test_pep660.py",
    "content": "import os\nfrom pathlib import Path\nfrom typing import Any\n\nimport pytest\nimport tomli_w\n\nfrom tests.lib import PipTestEnvironment\n\nSETUP_PY = \"\"\"\nfrom setuptools import setup\n\nsetup()\n\"\"\"\n\nSETUP_CFG = \"\"\"\n[metadata]\nname = project\nversion = 1.0.0\n\"\"\"\n\nBACKEND_WITHOUT_PEP660 = \"\"\"\nfrom setuptools.build_meta import (\n    build_wheel as _build_wheel,\n    prepare_metadata_for_build_wheel as _prepare_metadata_for_build_wheel,\n    get_requires_for_build_wheel as _get_requires_for_build_wheel,\n)\n\ndef get_requires_for_build_wheel(config_settings=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(\":get_requires_for_build_wheel called\", file=f)\n    return _get_requires_for_build_wheel(config_settings)\n\ndef prepare_metadata_for_build_wheel(metadata_directory, config_settings=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(\":prepare_metadata_for_build_wheel called\", file=f)\n    return _prepare_metadata_for_build_wheel(metadata_directory, config_settings)\n\ndef build_wheel(wheel_directory, config_settings=None, metadata_directory=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(f\":build_wheel called with config_settings={config_settings}\", file=f)\n    return _build_wheel(wheel_directory, config_settings, metadata_directory)\n\"\"\"\n\n# fmt: off\nBACKEND_WITH_PEP660 = BACKEND_WITHOUT_PEP660 + \"\"\"\ndef get_requires_for_build_editable(config_settings=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(\":get_requires_for_build_editable called\", file=f)\n    return _get_requires_for_build_wheel(config_settings)\n\ndef prepare_metadata_for_build_editable(metadata_directory, config_settings=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(\":prepare_metadata_for_build_editable called\", file=f)\n    return _prepare_metadata_for_build_wheel(metadata_directory, config_settings)\n\ndef build_editable(wheel_directory, config_settings=None, metadata_directory=None):\n    with open(\"log.txt\", \"a\") as f:\n        print(f\":build_editable called with config_settings={config_settings}\", file=f)\n    return _build_wheel(wheel_directory, config_settings, metadata_directory)\n\"\"\"\n# fmt: on\n\n\ndef _make_project(\n    tmpdir: Path, backend_code: str, with_setup_py: bool, with_pyproject: bool = True\n) -> Path:\n    project_dir = tmpdir / \"project\"\n    project_dir.mkdir()\n    project_dir.joinpath(\"setup.cfg\").write_text(SETUP_CFG)\n    if with_setup_py:\n        project_dir.joinpath(\"setup.py\").write_text(SETUP_PY)\n    if backend_code:\n        assert with_pyproject\n        buildsys: dict[str, Any] = {\"requires\": [\"setuptools\"]}\n        buildsys[\"build-backend\"] = \"test_backend\"\n        buildsys[\"backend-path\"] = [\".\"]\n        data = tomli_w.dumps({\"build-system\": buildsys})\n        project_dir.joinpath(\"pyproject.toml\").write_text(data)\n        project_dir.joinpath(\"test_backend.py\").write_text(backend_code)\n    elif with_pyproject:\n        project_dir.joinpath(\"pyproject.toml\").touch()\n    project_dir.joinpath(\"log.txt\").touch()\n    return project_dir\n\n\ndef _assert_hook_called(project_dir: Path, hook: str) -> None:\n    log = project_dir.joinpath(\"log.txt\").read_text()\n    assert f\":{hook} called\" in log, f\"{hook} has not been called\"\n\n\ndef _assert_hook_called_with_config_settings(\n    project_dir: Path, hook: str, config_settings: dict[str, str]\n) -> None:\n    log = project_dir.joinpath(\"log.txt\").read_text()\n    assert f\":{hook} called\" in log, f\"{hook} has not been called\"\n    assert (\n        f\":{hook} called with config_settings={config_settings}\" in log\n    ), f\"{hook} has not been called with the expected config settings:\\n{log}\"\n\n\ndef _assert_hook_not_called(project_dir: Path, hook: str) -> None:\n    log = project_dir.joinpath(\"log.txt\").read_text()\n    assert f\":{hook} called\" not in log, f\"{hook} should not have been called\"\n\n\ndef test_install_pep517_basic(tmpdir: Path, script: PipTestEnvironment) -> None:\n    \"\"\"\n    Check that the test harness we have in this file is sane.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITHOUT_PEP660, with_setup_py=False)\n    script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--no-build-isolation\",\n        project_dir,\n    )\n    _assert_hook_called(project_dir, \"prepare_metadata_for_build_wheel\")\n    _assert_hook_called(project_dir, \"build_wheel\")\n\n\ndef test_install_pep660_basic(tmpdir: Path, script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test with backend that supports build_editable.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITH_PEP660, with_setup_py=False)\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--no-build-isolation\",\n        \"--editable\",\n        project_dir,\n        \"--config-setting\",\n        \"x=y\",\n    )\n    _assert_hook_called(project_dir, \"prepare_metadata_for_build_editable\")\n    _assert_hook_called_with_config_settings(project_dir, \"build_editable\", {\"x\": \"y\"})\n    assert (\n        result.test_env.site_packages.joinpath(\"project.egg-link\")\n        not in result.files_created\n    ), \"a .egg-link file should not have been created\"\n\n\ndef test_install_pep660_from_reqs_file(\n    tmpdir: Path, script: PipTestEnvironment\n) -> None:\n    \"\"\"\n    Test with backend that supports build_editable.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITH_PEP660, with_setup_py=False)\n    reqs_file = tmpdir / \"requirements.txt\"\n    reqs_file.write_text(f\"-e {project_dir.as_uri()} --config-setting x=y\\n\")\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"--no-build-isolation\",\n        \"-r\",\n        reqs_file,\n    )\n    _assert_hook_called(project_dir, \"prepare_metadata_for_build_editable\")\n    _assert_hook_called_with_config_settings(project_dir, \"build_editable\", {\"x\": \"y\"})\n    assert (\n        result.test_env.site_packages.joinpath(\"project.egg-link\")\n        not in result.files_created\n    ), \"a .egg-link file should not have been created\"\n\n\n@pytest.mark.parametrize(\"isolation_arg\", [[], [\"--no-build-isolation\"]])\ndef test_install_no_pep660(\n    isolation_arg: list[str],\n    tmpdir: Path,\n    script: PipTestEnvironment,\n    common_wheels: Path,\n) -> None:\n    \"\"\"\n    Test the error message when the build backend does not support PEP 660.\n\n    The error is the same with and without build isolation.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITHOUT_PEP660, with_setup_py=True)\n    result = script.pip(\n        \"install\",\n        \"--no-index\",\n        \"-f\",\n        common_wheels,\n        *isolation_arg,\n        \"--editable\",\n        project_dir,\n        allow_error=True,\n    )\n    assert result.returncode != 0\n    assert \"missing the 'build_editable' hook\" in result.stderr\n\n\ndef test_wheel_editable_pep660_basic(tmpdir: Path, script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test 'pip wheel' of an editable pep 660 project.\n    It must *not* call prepare_metadata_for_build_editable.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITH_PEP660, with_setup_py=False)\n    wheel_dir = tmpdir / \"dist\"\n    script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"--no-build-isolation\",\n        \"--editable\",\n        project_dir,\n        \"-w\",\n        wheel_dir,\n    )\n    _assert_hook_not_called(project_dir, \"prepare_metadata_for_build_editable\")\n    _assert_hook_not_called(project_dir, \"build_editable\")\n    _assert_hook_called(project_dir, \"prepare_metadata_for_build_wheel\")\n    _assert_hook_called(project_dir, \"build_wheel\")\n    assert len(os.listdir(str(wheel_dir))) == 1, \"a wheel should have been created\"\n\n\ndef test_download_editable_pep660_basic(\n    tmpdir: Path, script: PipTestEnvironment\n) -> None:\n    \"\"\"\n    Test 'pip download' of an editable pep 660 project.\n    It must *not* call prepare_metadata_for_build_editable.\n    \"\"\"\n    project_dir = _make_project(tmpdir, BACKEND_WITH_PEP660, with_setup_py=False)\n    reqs_file = tmpdir / \"requirements.txt\"\n    reqs_file.write_text(f\"-e {project_dir.as_uri()}\\n\")\n    download_dir = tmpdir / \"download\"\n    script.pip(\n        \"download\",\n        \"--no-index\",\n        \"--no-build-isolation\",\n        \"-r\",\n        reqs_file,\n        \"-d\",\n        download_dir,\n    )\n    _assert_hook_not_called(project_dir, \"prepare_metadata_for_build_editable\")\n    _assert_hook_called(project_dir, \"prepare_metadata_for_build_wheel\")\n    assert len(os.listdir(str(download_dir))) == 1, \"a zip should have been created\"\n"
  },
  {
    "path": "tests/functional/test_pep668.py",
    "content": "import json\nimport pathlib\nimport textwrap\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, create_basic_wheel_for_package\nfrom tests.lib.venv import VirtualEnvironment\n\n\n@pytest.fixture\ndef patch_check_externally_managed(virtualenv: VirtualEnvironment) -> None:\n    # Since the tests are run from a virtual environment, and we can't\n    # guarantee access to the actual stdlib location (where EXTERNALLY-MANAGED\n    # needs to go into), we patch the check to always raise a simple message.\n    virtualenv.sitecustomize = textwrap.dedent(\n        \"\"\"\\\n        from pip._internal.exceptions import ExternallyManagedEnvironment\n        from pip._internal.utils import misc\n\n        def check_externally_managed():\n            raise ExternallyManagedEnvironment(\"I am externally managed\")\n\n        misc.check_externally_managed = check_externally_managed\n        \"\"\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"arguments\",\n    [\n        pytest.param([\"install\"], id=\"install\"),\n        pytest.param([\"install\", \"--user\"], id=\"install-user\"),\n        pytest.param([\"install\", \"--dry-run\"], id=\"install-dry-run\"),\n        pytest.param([\"uninstall\", \"-y\"], id=\"uninstall\"),\n    ],\n)\n@pytest.mark.usefixtures(\"patch_check_externally_managed\")\ndef test_fails(script: PipTestEnvironment, arguments: list[str]) -> None:\n    result = script.pip(*arguments, \"pip\", expect_error=True)\n    assert \"I am externally managed\" in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"arguments\",\n    [\n        pytest.param([\"install\"], id=\"install\"),\n        pytest.param([\"install\", \"--dry-run\"], id=\"install-dry-run\"),\n        pytest.param([\"uninstall\", \"-y\"], id=\"uninstall\"),\n    ],\n)\n@pytest.mark.usefixtures(\"patch_check_externally_managed\")\ndef test_succeeds_when_overridden(\n    script: PipTestEnvironment, arguments: list[str]\n) -> None:\n    result = script.pip(*arguments, \"pip\", \"--break-system-packages\")\n    assert \"I am externally managed\" not in result.stderr\n\n\n@pytest.mark.parametrize(\n    \"arguments\",\n    [\n        pytest.param([\"install\", \"--root\"], id=\"install-root\"),\n        pytest.param([\"install\", \"--prefix\"], id=\"install-prefix\"),\n        pytest.param([\"install\", \"--target\"], id=\"install-target\"),\n    ],\n)\n@pytest.mark.usefixtures(\"patch_check_externally_managed\")\ndef test_allows_if_out_of_environment(\n    script: PipTestEnvironment,\n    arguments: list[str],\n) -> None:\n    wheel = create_basic_wheel_for_package(script, \"foo\", \"1.0\")\n    result = script.pip(*arguments, script.scratch_path, wheel.as_uri())\n    assert \"Successfully installed foo-1.0\" in result.stdout\n    assert \"I am externally managed\" not in result.stderr\n\n\n@pytest.mark.usefixtures(\"patch_check_externally_managed\")\ndef test_allows_install_dry_run(\n    script: PipTestEnvironment,\n    tmp_path: pathlib.Path,\n) -> None:\n    output = tmp_path.joinpath(\"out.json\")\n    wheel = create_basic_wheel_for_package(script, \"foo\", \"1.0\")\n    result = script.pip(\n        \"install\",\n        \"--dry-run\",\n        f\"--report={output.as_posix()}\",\n        wheel.as_uri(),\n        expect_stderr=True,\n    )\n    assert \"Would install foo-1.0\" in result.stdout\n    assert \"I am externally managed\" not in result.stderr\n    with output.open(encoding=\"utf8\") as f:\n        assert isinstance(json.load(f), dict)\n"
  },
  {
    "path": "tests/functional/test_pip_runner_script.py",
    "content": "import os\nfrom pathlib import Path\n\nfrom pip import __version__\n\nfrom tests.lib import PipTestEnvironment\n\n\ndef test_runner_work_in_environments_with_no_pip(\n    script: PipTestEnvironment, pip_src: Path\n) -> None:\n    runner = pip_src / \"src\" / \"pip\" / \"__pip-runner__.py\"\n\n    # Ensure there's no pip installed in the environment\n    script.pip(\"uninstall\", \"pip\", \"--yes\", use_module=True)\n    # We don't use script.pip to check here, as when testing a\n    # zipapp, script.pip will run pip from the zipapp.\n    script.run(\"python\", \"-c\", \"import pip\", expect_error=True)\n\n    # The runner script should still invoke a usable pip\n    result = script.run(\"python\", os.fspath(runner), \"--version\")\n\n    assert __version__ in result.stdout\n"
  },
  {
    "path": "tests/functional/test_proxy.py",
    "content": "import ssl\nimport sys\nfrom pathlib import Path\nfrom typing import Any\n\nimport proxy\nimport pytest\nfrom proxy.http.proxy import HttpProxyBasePlugin\n\nfrom tests.conftest import CertFactory\nfrom tests.lib import PipTestEnvironment, TestData\nfrom tests.lib.server import (\n    authorization_response,\n    make_mock_server,\n    package_page,\n    server_running,\n)\n\n\nclass AccessLogPlugin(HttpProxyBasePlugin):\n    def on_access_log(self, context: dict[str, Any]) -> None:\n        print(context)\n\n\n@pytest.mark.network\ndef test_proxy_overrides_env(\n    script: PipTestEnvironment, capfd: pytest.CaptureFixture[str]\n) -> None:\n    with (\n        proxy.Proxy(port=0, num_acceptors=1) as proxy1,\n        proxy.Proxy(plugins=[AccessLogPlugin], port=0, num_acceptors=1) as proxy2,\n    ):\n        script.environ[\"http_proxy\"] = f\"127.0.0.1:{proxy2.flags.port}\"\n        script.environ[\"https_proxy\"] = f\"127.0.0.1:{proxy2.flags.port}\"\n        result = script.pip(\n            \"download\",\n            \"--proxy\",\n            f\"http://127.0.0.1:{proxy1.flags.port}\",\n            \"--trusted-host\",\n            \"127.0.0.1\",\n            \"-d\",\n            \"pip_downloads\",\n            \"INITools==0.1\",\n        )\n        result.did_create(Path(\"scratch\") / \"pip_downloads\" / \"INITools-0.1.tar.gz\")\n        out, _ = capfd.readouterr()\n        assert \"CONNECT\" not in out\n\n\ndef test_proxy_does_not_override_netrc(\n    script: PipTestEnvironment,\n    data: TestData,\n    cert_factory: CertFactory,\n) -> None:\n    cert_path = cert_factory()\n    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cert_path)\n    ctx.load_cert_chain(cert_path, cert_path)\n    ctx.verify_mode = ssl.CERT_REQUIRED\n\n    server = make_mock_server(ssl_context=ctx)\n    server.mock.side_effect = [\n        package_page(\n            {\n                \"simple-3.0.tar.gz\": \"/files/simple-3.0.tar.gz\",\n            }\n        ),\n        authorization_response(data.packages / \"simple-3.0.tar.gz\"),\n        authorization_response(data.packages / \"simple-3.0.tar.gz\"),\n    ]\n\n    url = f\"https://{server.host}:{server.port}/simple\"\n\n    netrc = script.scratch_path / \".netrc\"\n    netrc.write_text(f\"machine {server.host} login USERNAME password PASSWORD\")\n    with proxy.Proxy(port=0, num_acceptors=1) as proxy1, server_running(server):\n        script.environ[\"NETRC\"] = netrc\n        script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--proxy\",\n            f\"http://127.0.0.1:{proxy1.flags.port}\",\n            \"--trusted-host\",\n            \"127.0.0.1\",\n            \"--no-cache-dir\",\n            \"--index-url\",\n            url,\n            \"--cert\",\n            cert_path,\n            \"--client-cert\",\n            cert_path,\n            \"simple\",\n        )\n        script.assert_installed(simple=\"3.0\")\n\n\n@pytest.mark.xfail(\n    sys.version_info >= (3, 14),\n    reason=\"Access logs are blank intermittently on 3.14\",\n    strict=False,\n)\n@pytest.mark.network\n@pytest.mark.parametrize(\"flag\", [\"\", \"--use-feature=inprocess-build-deps\"])\ndef test_build_deps_use_proxy_from_cli(\n    script: PipTestEnvironment,\n    capfd: pytest.CaptureFixture[str],\n    data: TestData,\n    flag: str,\n) -> None:\n    with proxy.Proxy(port=0, num_acceptors=1, plugins=[AccessLogPlugin]) as proxy1:\n        result = script.pip(\n            \"wheel\",\n            \"-v\",\n            str(data.packages / \"pep517_setup_and_pyproject\"),\n            \"--proxy\",\n            f\"http://127.0.0.1:{proxy1.flags.port}\",\n            flag,\n        )\n\n    wheel_path = script.scratch / \"pep517_setup_and_pyproject-1.0-py3-none-any.whl\"\n    result.did_create(wheel_path)\n    access_log, _ = capfd.readouterr()\n    assert \"CONNECT\" in access_log, \"setuptools was not fetched using proxy\"\n"
  },
  {
    "path": "tests/functional/test_python_option.py",
    "content": "import json\nimport os\nfrom pathlib import Path\nfrom venv import EnvBuilder\n\nfrom tests.lib import PipTestEnvironment, TestData\n\n\ndef test_python_interpreter(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n    shared_data: TestData,\n) -> None:\n    env_path = os.fspath(tmpdir / \"venv\")\n    env = EnvBuilder(with_pip=False)\n    env.create(env_path)\n\n    result = script.pip(\"--python\", env_path, \"list\", \"--format=json\")\n    before = json.loads(result.stdout)\n\n    # Ideally we would assert that before==[], but there's a problem in CI\n    # that means this isn't true. See https://github.com/pypa/pip/pull/11326\n    # for details.\n\n    script.pip(\n        \"--python\",\n        env_path,\n        \"install\",\n        \"-f\",\n        shared_data.find_links,\n        \"--no-index\",\n        \"simplewheel==1.0\",\n    )\n\n    result = script.pip(\"--python\", env_path, \"list\", \"--format=json\")\n    installed = json.loads(result.stdout)\n    assert {\"name\": \"simplewheel\", \"version\": \"1.0\"} in installed\n\n    script.pip(\"--python\", env_path, \"uninstall\", \"simplewheel\", \"--yes\")\n    result = script.pip(\"--python\", env_path, \"list\", \"--format=json\")\n    assert json.loads(result.stdout) == before\n\n\ndef test_error_python_option_wrong_location(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n    shared_data: TestData,\n) -> None:\n    env_path = os.fspath(tmpdir / \"venv\")\n    env = EnvBuilder(with_pip=False)\n    env.create(env_path)\n\n    script.pip(\"list\", \"--python\", env_path, \"--format=json\", expect_error=True)\n"
  },
  {
    "path": "tests/functional/test_search.py",
    "content": "import logging\nfrom typing import TYPE_CHECKING\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS\nfrom pip._internal.commands import create_command\nfrom pip._internal.commands.search import highest_version, print_results, transform_hits\n\nfrom tests.lib import PipTestEnvironment\n\nif TYPE_CHECKING:\n    from pip._internal.commands.search import TransformedHit\n\n\ndef test_version_compare() -> None:\n    \"\"\"\n    Test version comparison.\n\n    \"\"\"\n    assert highest_version([\"1.0\", \"2.0\", \"0.1\"]) == \"2.0\"\n    assert highest_version([\"1.0a1\", \"1.0\"]) == \"1.0\"\n\n\ndef test_pypi_xml_transformation() -> None:\n    \"\"\"\n    Test transformation of data structures (PyPI xmlrpc to custom list).\n\n    \"\"\"\n    pypi_hits: list[dict[str, str]] = [\n        {\n            \"name\": \"foo\",\n            \"summary\": \"foo summary\",\n            \"version\": \"1.0\",\n        },\n        {\n            \"name\": \"foo\",\n            \"summary\": \"foo summary v2\",\n            \"version\": \"2.0\",\n        },\n        {\n            \"_pypi_ordering\": 50,  # type: ignore[dict-item]\n            \"name\": \"bar\",\n            \"summary\": \"bar summary\",\n            \"version\": \"1.0\",\n        },\n    ]\n    expected: list[TransformedHit] = [\n        {\n            \"versions\": [\"1.0\", \"2.0\"],\n            \"name\": \"foo\",\n            \"summary\": \"foo summary v2\",\n        },\n        {\n            \"versions\": [\"1.0\"],\n            \"name\": \"bar\",\n            \"summary\": \"bar summary\",\n        },\n    ]\n    assert transform_hits(pypi_hits) == expected\n\n\n@pytest.mark.network\n@pytest.mark.search\ndef test_basic_search(script: PipTestEnvironment) -> None:\n    \"\"\"\n    End to end test of search command.\n\n    \"\"\"\n    output = script.pip(\"search\", \"pip\")\n    assert \"The PyPA recommended tool for installing Python packages.\" in output.stdout\n\n\n@pytest.mark.network\n@pytest.mark.skip(\n    reason=(\n        \"Warehouse search behavior is different and no longer returns \"\n        \"multiple results. See \"\n        \"https://github.com/pypa/warehouse/issues/3717 for more \"\n        \"information.\"\n    ),\n)\n@pytest.mark.search\ndef test_multiple_search(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test searching for multiple packages at once.\n\n    \"\"\"\n    output = script.pip(\"search\", \"pip\", \"INITools\")\n    assert \"The PyPA recommended tool for installing Python packages.\" in output.stdout\n    assert \"Tools for parsing and using INI-style files\" in output.stdout\n\n\n@pytest.mark.search\ndef test_search_missing_argument(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test missing required argument for search\n    \"\"\"\n    result = script.pip(\"search\", expect_error=True)\n    assert \"ERROR: Missing required argument (search query).\" in result.stderr\n\n\n@pytest.mark.network\n@pytest.mark.search\ndef test_run_method_should_return_success_when_find_packages() -> None:\n    \"\"\"\n    Test SearchCommand.run for found package\n    \"\"\"\n    command = create_command(\"search\")\n    cmdline = \"--index=https://pypi.org/pypi pip\"\n    with command.main_context():\n        options, args = command.parse_args(cmdline.split())\n        status = command.run(options, args)\n    assert status == SUCCESS\n\n\n@pytest.mark.network\n@pytest.mark.search\ndef test_run_method_should_return_no_matches_found_when_does_not_find_pkgs() -> None:\n    \"\"\"\n    Test SearchCommand.run for no matches\n    \"\"\"\n    command = create_command(\"search\")\n    cmdline = \"--index=https://pypi.org/pypi nonexistentpackage\"\n    with command.main_context():\n        options, args = command.parse_args(cmdline.split())\n        status = command.run(options, args)\n    assert status == NO_MATCHES_FOUND\n\n\n@pytest.mark.network\n@pytest.mark.search\ndef test_search_should_exit_status_code_zero_when_find_packages(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test search exit status code for package found\n    \"\"\"\n    result = script.pip(\"search\", \"pip\")\n    assert result.returncode == SUCCESS\n\n\n@pytest.mark.network\n@pytest.mark.search\ndef test_search_exit_status_code_when_finds_no_package(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test search exit status code for no matches\n    \"\"\"\n    result = script.pip(\"search\", \"nonexistentpackage\", expect_error=True)\n    assert result.returncode == NO_MATCHES_FOUND, result.returncode\n\n\n@pytest.mark.search\ndef test_latest_prerelease_install_message(\n    caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    \"\"\"\n    Test documentation for installing pre-release packages is displayed\n    \"\"\"\n    hits: list[TransformedHit] = [\n        {\n            \"name\": \"ni\",\n            \"summary\": \"For knights who say Ni!\",\n            \"versions\": [\"1.0.0\", \"1.0.1a\"],\n        }\n    ]\n\n    installed_package = mock.Mock(project_name=\"ni\")\n    monkeypatch.setattr(\"pip._vendor.pkg_resources.working_set\", [installed_package])\n\n    get_dist = mock.Mock()\n    get_dist.return_value = mock.Mock(version=\"1.0.0\")\n    monkeypatch.setattr(\"pip._internal.commands.search.get_distribution\", get_dist)\n    with caplog.at_level(logging.INFO):\n        print_results(hits)\n\n    message = caplog.records[-1].getMessage()\n    assert 'pre-release; install with \"pip install --pre\"' in message\n    assert get_dist.call_args_list == [mock.call(\"ni\")]\n\n\n@pytest.mark.search\ndef test_search_print_results_should_contain_latest_versions(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    \"\"\"\n    Test that printed search results contain the latest package versions\n    \"\"\"\n    hits: list[TransformedHit] = [\n        {\n            \"name\": \"testlib1\",\n            \"summary\": \"Test library 1.\",\n            \"versions\": [\"1.0.5\", \"1.0.3\"],\n        },\n        {\n            \"name\": \"testlib2\",\n            \"summary\": \"Test library 1.\",\n            \"versions\": [\"2.0.1\", \"2.0.3\"],\n        },\n    ]\n\n    with caplog.at_level(logging.INFO):\n        print_results(hits)\n\n    log_messages = sorted([r.getMessage() for r in caplog.records])\n    assert log_messages[0].startswith(\"testlib1 (1.0.5)\")\n    assert log_messages[1].startswith(\"testlib2 (2.0.3)\")\n"
  },
  {
    "path": "tests/functional/test_self_update.py",
    "content": "# Check that pip can update itself correctly\n\nfrom pathlib import Path\nfrom typing import Any\n\n\ndef test_self_update_editable(script: Any, pip_src: Any, common_wheels: Path) -> None:\n    # Test that if we have an environment with pip installed in non-editable\n    # mode, that pip can safely update itself to an editable install.\n    # See https://github.com/pypa/pip/issues/12666 for details.\n\n    # Install flit-core (build backend) since we use --no-build-isolation\n    script.pip(\"install\", \"--no-index\", \"-f\", common_wheels, \"flit-core\")\n\n    # Step 1. Install pip as non-editable. This is expected to succeed as\n    # the existing pip in the environment is installed in editable mode, so\n    # it only places a .pth file in the environment.\n    proc = script.pip(\"install\", \"--no-build-isolation\", pip_src)\n    assert proc.returncode == 0\n    # Step 2. Using the pip we just installed, install pip *again*, but\n    # in editable mode. This could fail, as we'll need to uninstall the running\n    # pip in order to install the new copy, and uninstalling pip while it's\n    # running could fail. This test is specifically to ensure that doesn't\n    # happen...\n    proc = script.pip(\"install\", \"--no-build-isolation\", \"-e\", pip_src)\n    assert proc.returncode == 0\n"
  },
  {
    "path": "tests/functional/test_show.py",
    "content": "import os\nimport pathlib\nimport re\nimport textwrap\n\nimport pytest\n\nfrom pip import __version__\nfrom pip._internal.commands.show import search_packages_info\nfrom pip._internal.utils.unpacking import untar_file\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    create_test_package_with_setup,\n    pyversion,\n)\n\n\ndef test_basic_show(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test end to end test for show command.\n    \"\"\"\n    result = script.pip(\"show\", \"pip\")\n    lines = result.stdout.splitlines()\n    assert len(lines) == 11\n    assert \"Name: pip\" in lines\n    assert f\"Version: {__version__}\" in lines\n    assert any(line.startswith(\"Location: \") for line in lines)\n    assert \"Requires: \" in lines\n\n\ndef test_show_with_files_not_found(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test for show command with installed files listing enabled and\n    installed-files.txt not found.\n    \"\"\"\n    editable = data.packages.joinpath(\"SetupPyUTF8\")\n    script.run(\"python\", \"setup.py\", \"develop\", cwd=editable)\n    result = script.pip(\"show\", \"-f\", \"SetupPyUTF8\")\n    lines = result.stdout.splitlines()\n    assert len(lines) == 13\n    assert \"Name: SetupPyUTF8\" in lines\n    assert \"Version: 0.0.0\" in lines\n    assert any(line.startswith(\"Location: \") for line in lines)\n    assert \"Requires: \" in lines\n    assert \"Files:\" in lines\n    assert \"Cannot locate RECORD or installed-files.txt\" in lines\n\n\ndef test_show_with_files_from_wheel(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that a wheel's files can be listed.\n    \"\"\"\n    script.pip_install_local(data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"show\", \"-f\", \"simple.dist\")\n    lines = result.stdout.splitlines()\n    assert \"Name: simple.dist\" in lines\n    assert \"Cannot locate RECORD or installed-files.txt\" not in lines[6], lines[6]\n    assert re.search(r\"Files:\\n(  .+\\n)+\", result.stdout)\n    assert f\"  simpledist{os.sep}__init__.py\" in lines[6:]\n\n\ndef test_show_with_files_from_legacy(\n    tmp_path: pathlib.Path, script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test listing files in the show command (legacy installed-files.txt).\n    \"\"\"\n    # Since 'pip install' now always tries to build a wheel from sdist, it\n    # cannot properly generate a setup. The legacy code path is basically\n    # 'setup.py install' plus installed-files.txt, which we manually generate.\n    source_dir = tmp_path.joinpath(\"unpacked-sdist\")\n    setuptools_record = tmp_path.joinpath(\"installed-record.txt\")\n    untar_file(os.fspath(data.packages.joinpath(\"simple-1.0.tar.gz\")), str(source_dir))\n    script.run(\n        \"python\",\n        \"setup.py\",\n        \"install\",\n        \"--single-version-externally-managed\",\n        \"--record\",\n        str(setuptools_record),\n        cwd=source_dir,\n    )\n    # Emulate the installed-files.txt generation which previous pip version did\n    # after running setup.py install (write_installed_files_from_setuptools_record).\n    egg_info_dir = script.site_packages_path / f\"simple-1.0-py{pyversion}.egg-info\"\n    egg_info_dir.joinpath(\"installed-files.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n                ../simple/__init__.py\n                PKG-INFO\n                SOURCES.txt\n                dependency_links.txt\n                top_level.txt\n            \"\"\"\n        )\n    )\n\n    result = script.pip(\"show\", \"--files\", \"simple\")\n    lines = result.stdout.splitlines()\n    assert \"Cannot locate RECORD or installed-files.txt\" not in lines[6], lines[6]\n    assert re.search(r\"Files:\\n(  .+\\n)+\", result.stdout)\n    assert f\"  simple{os.sep}__init__.py\" in lines[6:]\n\n\ndef test_missing_argument(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test show command with no arguments.\n    \"\"\"\n    result = script.pip(\"show\", expect_error=True)\n    assert \"ERROR: Please provide a package name or names.\" in result.stderr\n\n\ndef test_find_package_not_found() -> None:\n    \"\"\"\n    Test trying to get info about a nonexistent package.\n    \"\"\"\n    result = search_packages_info([\"abcd3\"])\n    assert len(list(result)) == 0\n\n\ndef test_report_single_not_found(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test passing one name and that isn't found.\n    \"\"\"\n    # We choose a non-canonicalized name to test that the non-canonical\n    # form is logged.\n    # Also, the following should report an error as there are no results\n    # to print. Consequently, there is no need to pass\n    # allow_stderr_warning=True since this is implied by expect_error=True.\n    result = script.pip(\"show\", \"Abcd-3\", expect_error=True)\n    assert \"WARNING: Package(s) not found: Abcd-3\" in result.stderr\n    assert not result.stdout.splitlines()\n\n\ndef test_report_mixed_not_found(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test passing a mixture of found and not-found names.\n    \"\"\"\n    # We test passing non-canonicalized names.\n    result = script.pip(\"show\", \"Abcd3\", \"A-B-C\", \"pip\", allow_stderr_warning=True)\n    assert \"WARNING: Package(s) not found: A-B-C, Abcd3\" in result.stderr\n    lines = result.stdout.splitlines()\n    assert len(lines) == 11\n    assert \"Name: pip\" in lines\n\n\ndef test_search_any_case() -> None:\n    \"\"\"\n    Search for a package in any case.\n\n    \"\"\"\n    result = list(search_packages_info([\"PIP\"]))\n    assert len(result) == 1\n    assert result[0].name == \"pip\"\n\n\ndef test_more_than_one_package() -> None:\n    \"\"\"\n    Search for more than one package.\n\n    \"\"\"\n    result = list(search_packages_info([\"pIp\", \"pytest\", \"Virtualenv\"]))\n    assert len(result) == 3\n\n\ndef test_show_verbose_with_classifiers(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that classifiers can be listed\n    \"\"\"\n    result = script.pip(\"show\", \"pip\", \"--verbose\")\n    lines = result.stdout.splitlines()\n    assert \"Name: pip\" in lines\n    assert re.search(r\"Classifiers:\\n(  .+\\n)+\", result.stdout)\n    assert \"Intended Audience :: Developers\" in result.stdout\n\n\ndef test_show_verbose_installer(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test that the installer is shown (this currently needs a wheel install)\n    \"\"\"\n    script.pip_install_local(data.packages / \"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"show\", \"--verbose\", \"simple.dist\")\n    lines = result.stdout.splitlines()\n    assert \"Name: simple.dist\" in lines\n    assert \"Installer: pip\" in lines\n\n\ndef test_show_verbose_project_urls(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that project urls can be listed\n    \"\"\"\n    result = script.pip(\"show\", \"pip\", \"--verbose\")\n    lines = result.stdout.splitlines()\n    assert \"Name: pip\" in lines\n    assert re.search(r\"Project-URLs:\\n(  .+\\n)+\", result.stdout)\n    assert \"Source, https://github.com/pypa/pip\" in result.stdout\n\n\ndef test_show_verbose(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test end to end test for verbose show command.\n    \"\"\"\n    result = script.pip(\"show\", \"--verbose\", \"pip\")\n    lines = result.stdout.splitlines()\n    assert any(line.startswith(\"Metadata-Version: \") for line in lines)\n    assert any(line.startswith(\"Installer: \") for line in lines)\n    assert \"Entry-points:\" in lines\n    assert \"Classifiers:\" in lines\n    assert \"Project-URLs:\" in lines\n\n\ndef test_all_fields(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that all the fields are present\n    \"\"\"\n    # future-compat: once pip adopts PEP 639 in pyproject.toml and\n    # its build backend produces metadata 2.4 or greater,\n    # it will display \"License-Expression\" rather than License\n    verbose = script.pip(\"show\", \"--verbose\", \"pip\").stdout\n    match = re.search(r\"Metadata-Version:\\s(\\d+\\.\\d+)\", verbose)\n    if match is not None:\n        metadata_version = match.group(1)\n        metadata_version_tuple = tuple(map(int, metadata_version.split(\".\")))\n        if metadata_version_tuple >= (2, 4) and \"License-Expression\" in verbose:\n            license_str = \"License-Expression\"\n        else:\n            license_str = \"License\"\n    else:\n        license_str = \"License\"\n\n    result = script.pip(\"show\", \"pip\")\n    lines = result.stdout.splitlines()\n    expected = {\n        \"Name\",\n        \"Version\",\n        \"Summary\",\n        \"Home-page\",\n        \"Author\",\n        \"Author-email\",\n        f\"{license_str}\",\n        \"Location\",\n        \"Editable project location\",\n        \"Requires\",\n        \"Required-by\",\n    }\n    actual = {re.sub(\":.*$\", \"\", line) for line in lines}\n    assert actual == expected\n\n\ndef test_pip_show_is_short(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that pip show stays short\n    \"\"\"\n    result = script.pip(\"show\", \"pip\")\n    lines = result.stdout.splitlines()\n    assert len(lines) <= 11\n\n\ndef test_pip_show_divider(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Expect a divider between packages\n    \"\"\"\n    script.pip_install_local(\"--no-build-isolation\", \"pip-test-package\")\n    result = script.pip(\"show\", \"pip\", \"pip-test-package\")\n    lines = result.stdout.splitlines()\n    assert \"---\" in lines\n\n\ndef test_package_name_is_canonicalized(script: PipTestEnvironment) -> None:\n    script.pip_install_local(\"--no-build-isolation\", \"pip-test-package\")\n\n    dash_show_result = script.pip(\"show\", \"pip-test-package\")\n    underscore_upper_show_result = script.pip(\"show\", \"pip-test_Package\")\n\n    assert underscore_upper_show_result.returncode == 0\n    assert underscore_upper_show_result.stdout == dash_show_result.stdout\n\n\ndef test_show_required_by_packages_basic(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that installed packages that depend on this package are shown\n    \"\"\"\n    script.pip_install_local(\"--no-build-isolation\", data.src / \"requires_simple\")\n\n    result = script.pip(\"show\", \"simple\")\n    lines = result.stdout.splitlines()\n\n    assert \"Name: simple\" in lines\n    assert (\n        \"Required-by: requires_simple\" in lines\n        or \"Required-by: requires-simple\" in lines\n    )\n\n\ndef test_show_required_by_packages_capitalized(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that the installed packages which depend on a package are shown\n    where the package has a capital letter\n    \"\"\"\n    script.pip_install_local(\"--no-build-isolation\", data.src / \"requires_capitalized\")\n\n    result = script.pip(\"show\", \"simple\")\n    lines = result.stdout.splitlines()\n\n    assert \"Name: simple\" in lines\n    assert (\n        \"Required-by: Requires_Capitalized\" in lines\n        or \"Required-by: Requires-Capitalized\" in lines\n    )\n\n\ndef test_show_required_by_packages_requiring_capitalized(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test that the installed packages which depend on a package are shown\n    where the package has a name with a mix of\n    lower and upper case letters\n    \"\"\"\n    script.pip_install_local(\"--no-build-isolation\", data.src / \"requires_capitalized\")\n    script.pip_install_local(\n        \"--no-build-isolation\", data.src / \"requires_requires_capitalized\"\n    )\n\n    result = script.pip(\"show\", \"Requires_Capitalized\")\n    lines = result.stdout.splitlines()\n    print(lines)\n\n    assert (\n        \"Name: Requires_Capitalized\" in lines or \"Name: Requires-Capitalized\" in lines\n    )\n    assert (\n        \"Required-by: requires_requires_capitalized\" in lines\n        or \"Required-by: requires-requires-capitalized\" in lines\n    )\n\n\ndef test_show_skip_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that show should not include package\n    present in working directory\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    # Show should not include package simple when run from package directory\n    result = script.pip(\"show\", \"simple\", expect_error=True, cwd=pkg_path)\n    assert \"WARNING: Package(s) not found: simple\" in result.stderr\n\n\ndef test_show_include_work_dir_pkg(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that show should include package in working directory\n    if working directory is added in PYTHONPATH\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(script, name=\"simple\", version=\"1.0\")\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    # Show should include package simple when run from package directory,\n    # when package directory is in PYTHONPATH\n    result = script.pip(\"show\", \"simple\", cwd=pkg_path)\n    lines = result.stdout.splitlines()\n    assert \"Name: simple\" in lines\n\n\ndef test_show_deduplicate_requirements(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that show should deduplicate requirements\n    for a package\n    \"\"\"\n\n    # Create a test package and create .egg-info dir\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=\"simple\",\n        version=\"1.0\",\n        install_requires=[\n            \"pip >= 19.0.1\",\n            'pip >= 19.3.1; python_version < \"3.8\"',\n            'pip >= 23.0.1; python_version < \"3.9\"',\n        ],\n    )\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    result = script.pip(\"show\", \"simple\", cwd=pkg_path)\n    lines = result.stdout.splitlines()\n    assert \"Requires: pip\" in lines\n\n\n@pytest.mark.parametrize(\n    \"project_url\",\n    [\"Home-page\", \"home-page\", \"Homepage\", \"homepage\", \"home_PAGE\", \"home page\"],\n)\ndef test_show_populate_homepage_from_project_urls(\n    script: PipTestEnvironment, project_url: str\n) -> None:\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=\"simple\",\n        version=\"1.0\",\n        project_urls={project_url: \"https://example.com\"},\n    )\n    script.run(\"python\", \"setup.py\", \"egg_info\", expect_stderr=True, cwd=pkg_path)\n    script.environ.update({\"PYTHONPATH\": pkg_path})\n\n    result = script.pip(\"show\", \"simple\", cwd=pkg_path)\n    lines = result.stdout.splitlines()\n    assert \"Home-page: https://example.com\" in lines\n\n\ndef test_show_license_expression(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Show License-Expression if present in metadata >= 2.4.\n    \"\"\"\n    script.pip_install_local(data.packages / \"license.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"show\", \"license.dist\")\n    lines = result.stdout.splitlines()\n    assert \"License-Expression: MIT AND MIT-0\" in lines\n    assert \"License: The legacy license declaration\" not in lines\n\n\ndef test_show_license_for_metadata_24(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Show License if License-Expression is not there for metadata >= 2.4.\n    \"\"\"\n    script.pip_install_local(data.packages / \"license.dist-0.2-py2.py3-none-any.whl\")\n    result = script.pip(\"show\", \"license.dist\")\n    lines = result.stdout.splitlines()\n    assert \"License-Expression: \" not in lines\n    assert \"License: The legacy license declaration\" in lines\n"
  },
  {
    "path": "tests/functional/test_truststore.py",
    "content": "from typing import Any, Callable\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, TestPipResult\n\nPipRunner = Callable[..., TestPipResult]\n\n\n@pytest.fixture\ndef pip_no_truststore(script: PipTestEnvironment) -> PipRunner:\n    def pip(*args: str, **kwargs: Any) -> TestPipResult:\n        return script.pip(*args, \"--use-deprecated=legacy-certs\", **kwargs)\n\n    return pip\n\n\n@pytest.mark.network\n@pytest.mark.parametrize(\n    \"package\",\n    [\n        \"INITools\",\n        \"https://github.com/pypa/pip-test-package/archive/refs/heads/master.zip\",\n    ],\n    ids=[\"PyPI\", \"GitHub\"],\n)\ndef test_no_truststore_can_install(\n    script: PipTestEnvironment,\n    pip_no_truststore: PipRunner,\n    package: str,\n) -> None:\n    result = pip_no_truststore(\"install\", package)\n    assert \"Successfully installed\" in result.stdout\n"
  },
  {
    "path": "tests/functional/test_uninstall.py",
    "content": "import logging\nimport os\nimport sys\nimport textwrap\nfrom collections.abc import Iterator\nfrom os.path import join, normpath\nfrom pathlib import Path\nfrom tempfile import mkdtemp\nfrom typing import Any\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._internal.req.constructors import install_req_from_line\nfrom pip._internal.utils.misc import rmtree\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    assert_all_changes,\n    create_test_package_with_setup,\n    need_svn,\n)\nfrom tests.lib.local_repos import local_checkout, local_repo\n\n\ndef test_basic_uninstall(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test basic install and uninstall.\n    \"\"\"\n    result = script.pip_install_local(\"six\", \"-f\", data.pypi_packages)\n    result.did_create(join(script.site_packages, \"six.py\"))\n    # the import forces the generation of __pycache__ if the version of python\n    # supports it\n    script.run(\"python\", \"-c\", \"import six\")\n    result2 = script.pip(\"uninstall\", \"six\", \"-y\")\n    assert_all_changes(result, result2, [script.venv / \"build\", \"cache\"])\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 12),\n    reason=\"distutils is no longer available in Python 3.12+\",\n)\ndef test_basic_uninstall_distutils(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test basic install and uninstall.\n\n    \"\"\"\n    script.scratch_path.joinpath(\"distutils_install\").mkdir()\n    pkg_path = script.scratch_path / \"distutils_install\"\n    pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        from distutils.core import setup\n        setup(\n            name='distutils-install',\n            version='0.1',\n        )\n    \"\"\"\n        )\n    )\n    result = script.run(\"python\", os.fspath(pkg_path / \"setup.py\"), \"install\")\n    result = script.pip(\"list\", \"--format=json\")\n    script.assert_installed(distutils_install=\"0.1\")\n    result = script.pip(\n        \"uninstall\", \"distutils_install\", \"-y\", expect_stderr=True, expect_error=True\n    )\n    assert \"Cannot uninstall distutils-install 0.1\" in result.stderr\n    assert (\n        \"It is a distutils installed project and thus we cannot accurately determine \"\n        \"which files belong to it which would lead to only a partial uninstall.\"\n    ) in result.stderr\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 12),\n    reason=\"Setuptools<64 does not support Python 3.12+\",\n)\n@pytest.mark.network\ndef test_basic_uninstall_with_scripts(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Uninstall an easy_installed package with scripts.\n\n    \"\"\"\n    # setuptools 52 removed easy_install.\n    script.pip(\"install\", \"setuptools==51.3.3\", use_module=True)\n\n    result = script.easy_install(\"PyLogo\", expect_stderr=True)\n    easy_install_pth = script.site_packages / \"easy-install.pth\"\n    pylogo = sys.platform == \"win32\" and \"pylogo\" or \"PyLogo\"\n    assert pylogo in result.files_updated[os.fspath(easy_install_pth)].bytes\n    result2 = script.pip(\"uninstall\", \"pylogo\", \"-y\")\n    assert_all_changes(\n        result,\n        result2,\n        [script.venv / \"build\", \"cache\", easy_install_pth],\n    )\n\n\n@pytest.mark.parametrize(\"name\", [\"GTrolls.tar.gz\", \"https://guyto.com/archives/\"])\ndef test_uninstall_invalid_parameter(\n    script: PipTestEnvironment, caplog: pytest.LogCaptureFixture, name: str\n) -> None:\n    result = script.pip(\"uninstall\", name, \"-y\", expect_error=True)\n    expected_message = (\n        f\"Invalid requirement: '{name}' ignored -\"\n        f\" the uninstall command expects named requirements.\"\n    )\n    assert expected_message in result.stderr\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 12),\n    reason=\"Setuptools<64 does not support Python 3.12+\",\n)\n@pytest.mark.network\ndef test_uninstall_easy_install_after_import(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Uninstall an easy_installed package after it's been imported\n\n    \"\"\"\n    # setuptools 52 removed easy_install.\n    script.pip(\"install\", \"setuptools==51.3.3\", use_module=True)\n\n    result = script.easy_install(\"INITools==0.2\", expect_stderr=True)\n    # the import forces the generation of __pycache__ if the version of python\n    # supports it\n    script.run(\"python\", \"-c\", \"import initools\")\n    result2 = script.pip(\"uninstall\", \"INITools\", \"-y\")\n    assert_all_changes(\n        result,\n        result2,\n        [\n            script.venv / \"build\",\n            \"cache\",\n            script.site_packages / \"easy-install.pth\",\n        ],\n    )\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 12),\n    reason=\"Setuptools<64 does not support Python 3.12+\",\n)\n@pytest.mark.network\ndef test_uninstall_trailing_newline(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Uninstall behaves appropriately if easy-install.pth\n    lacks a trailing newline\n\n    \"\"\"\n    # setuptools 52 removed easy_install.\n    script.pip(\"install\", \"setuptools==51.3.3\", use_module=True)\n\n    script.easy_install(\"INITools==0.2\", expect_stderr=True)\n    script.easy_install(\"PyLogo\", expect_stderr=True)\n    easy_install_pth = script.site_packages_path / \"easy-install.pth\"\n\n    # trim trailing newline from easy-install.pth\n    with open(easy_install_pth) as f:\n        pth_before = f.read()\n\n    with open(easy_install_pth, \"w\") as f:\n        f.write(pth_before.rstrip())\n\n    # uninstall initools\n    script.pip(\"uninstall\", \"INITools\", \"-y\")\n    with open(easy_install_pth) as f:\n        pth_after = f.read()\n\n    # verify that only initools is removed\n    before_without_initools = [\n        line for line in pth_before.splitlines() if \"initools\" not in line.lower()\n    ]\n    lines_after = pth_after.splitlines()\n\n    assert lines_after == before_without_initools\n\n\n@pytest.mark.network\ndef test_basic_uninstall_namespace_package(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Uninstall a distribution with a namespace package without clobbering\n    the namespace and everything in it.\n\n    \"\"\"\n    result = script.pip(\"install\", \"pd.requires==0.0.3\")\n    result.did_create(join(script.site_packages, \"pd\"))\n    result2 = script.pip(\"uninstall\", \"pd.find\", \"-y\")\n    assert join(script.site_packages, \"pd\") not in result2.files_deleted, sorted(\n        result2.files_deleted.keys()\n    )\n    assert join(script.site_packages, \"pd\", \"find\") in result2.files_deleted, sorted(\n        result2.files_deleted.keys()\n    )\n\n\ndef test_uninstall_overlapping_package(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Uninstalling a distribution that adds modules to a pre-existing package\n    should only remove those added modules, not the rest of the existing\n    package.\n\n    See: GitHub issue #355 (pip uninstall removes things it didn't install)\n    \"\"\"\n    parent_pkg = data.packages.joinpath(\"parent-0.1.tar.gz\")\n    child_pkg = data.packages.joinpath(\"child-0.1.tar.gz\")\n\n    result1 = script.pip(\"install\", \"--no-build-isolation\", parent_pkg)\n    result1.did_create(join(script.site_packages, \"parent\"))\n    result2 = script.pip(\"install\", \"--no-build-isolation\", child_pkg)\n    result2.did_create(join(script.site_packages, \"child\"))\n    result2.did_create(\n        normpath(join(script.site_packages, \"parent/plugins/child_plugin.py\"))\n    )\n    # The import forces the generation of __pycache__ if the version of python\n    #  supports it\n    script.run(\"python\", \"-c\", \"import parent.plugins.child_plugin, child\")\n    result3 = script.pip(\"uninstall\", \"-y\", \"child\")\n    assert join(script.site_packages, \"child\") in result3.files_deleted, sorted(\n        result3.files_created.keys()\n    )\n    assert (\n        normpath(join(script.site_packages, \"parent/plugins/child_plugin.py\"))\n        in result3.files_deleted\n    ), sorted(result3.files_deleted.keys())\n    assert join(script.site_packages, \"parent\") not in result3.files_deleted, sorted(\n        result3.files_deleted.keys()\n    )\n    # Additional check: uninstalling 'child' should return things to the\n    # previous state, without unintended side effects.\n    assert_all_changes(result2, result3, [])\n\n\n@pytest.mark.parametrize(\n    \"console_scripts\",\n    [\n        \"test_ = distutils_install:test\",\n        \",test_ = distutils_install:test_test\",\n        \", = distutils_install:test_test\",\n    ],\n)\ndef test_uninstall_entry_point_colon_in_name(\n    script: PipTestEnvironment, console_scripts: str\n) -> None:\n    \"\"\"\n    Test uninstall package with two or more entry points in the same section,\n    whose name contain a colon.\n    \"\"\"\n    pkg_name = \"ep_install\"\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=pkg_name,\n        version=\"0.1\",\n        entry_points={\n            \"console_scripts\": [\n                console_scripts,\n            ],\n            \"pip_test.ep\": [\n                \"ep:name1 = distutils_install\",\n                \"ep:name2 = distutils_install\",\n            ],\n        },\n    )\n    script_name = script.bin_path.joinpath(console_scripts.split(\"=\")[0].strip())\n    if sys.platform == \"win32\":\n        script_name = script_name.with_suffix(\".exe\")\n    script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    assert script_name.exists()\n    script.assert_installed(ep_install=\"0.1\")\n\n    script.pip(\"uninstall\", \"ep_install\", \"-y\")\n    assert not script_name.exists()\n    script.assert_not_installed(\"ep-install\")\n\n\ndef test_uninstall_gui_scripts(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Make sure that uninstall removes gui scripts\n    \"\"\"\n    pkg_name = \"gui_pkg\"\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=pkg_name,\n        version=\"0.1\",\n        entry_points={\n            \"gui_scripts\": [\n                \"test_ = distutils_install:test\",\n            ],\n        },\n    )\n    script_name = script.bin_path.joinpath(\"test_\")\n    if sys.platform == \"win32\":\n        script_name = script_name.with_suffix(\".exe\")\n    script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    assert script_name.exists()\n    script.pip(\"uninstall\", pkg_name, \"-y\")\n    assert not script_name.exists()\n\n\ndef test_uninstall_console_scripts(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test uninstalling a package with more files (console_script entry points,\n    extra directories).\n    \"\"\"\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=\"discover\",\n        version=\"0.1\",\n        entry_points={\"console_scripts\": [\"discover = discover:main\"]},\n    )\n    result = script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    result.did_create(script.bin / f\"discover{script.exe}\")\n    result2 = script.pip(\"uninstall\", \"discover\", \"-y\")\n    assert_all_changes(\n        result,\n        result2,\n        [\n            os.path.join(script.venv, \"build\"),\n            \"cache\",\n            os.path.join(\"scratch\", \"discover\", \"discover.egg-info\"),\n            os.path.join(\"scratch\", \"discover\", \"build\"),\n        ],\n    )\n\n\ndef test_uninstall_console_scripts_uppercase_name(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test uninstalling console script with uppercase character.\n    \"\"\"\n    pkg_path = create_test_package_with_setup(\n        script,\n        name=\"ep_install\",\n        version=\"0.1\",\n        entry_points={\n            \"console_scripts\": [\n                \"Test = distutils_install:Test\",\n            ],\n        },\n    )\n    script_name = script.bin_path.joinpath(\"Test\" + script.exe)\n\n    script.pip(\"install\", \"--no-build-isolation\", pkg_path)\n    assert script_name.exists()\n\n    script.pip(\"uninstall\", \"ep_install\", \"-y\")\n    assert not script_name.exists()\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 12),\n    reason=\"Setuptools<64 does not support Python 3.12+\",\n)\n@pytest.mark.network\ndef test_uninstall_easy_installed_console_scripts(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test uninstalling package with console_scripts that is easy_installed.\n    \"\"\"\n    # setuptools 52 removed easy_install and prints a warning after 42 when\n    # the command is used.\n    script.pip(\"install\", \"setuptools==51.3.3\", use_module=True)\n\n    result = script.easy_install(\"discover\", allow_stderr_warning=True)\n    result.did_create(script.bin / f\"discover{script.exe}\")\n    result2 = script.pip(\"uninstall\", \"discover\", \"-y\")\n    assert_all_changes(\n        result,\n        result2,\n        [\n            script.venv / \"build\",\n            \"cache\",\n            script.site_packages / \"easy-install.pth\",\n        ],\n    )\n\n\n@pytest.mark.xfail\n@pytest.mark.network\n@need_svn\ndef test_uninstall_editable_from_svn(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"\n    Test uninstalling an editable installation from svn.\n    \"\"\"\n    result = script.pip(\n        \"install\",\n        \"-e\",\n        \"{checkout}#egg=initools\".format(\n            checkout=local_checkout(\"svn+http://svn.colorstudy.com/INITools\", tmpdir)\n        ),\n    )\n    result.assert_installed(\"INITools\")\n    result2 = script.pip(\"uninstall\", \"-y\", \"initools\")\n    assert script.venv / \"src\" / \"initools\" in result2.files_after\n    assert_all_changes(\n        result,\n        result2,\n        [\n            script.venv / \"src\",\n            script.venv / \"build\",\n            script.site_packages / \"easy-install.pth\",\n        ],\n    )\n\n\n@pytest.mark.network\ndef test_uninstall_editable_with_source_outside_venv(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test uninstalling editable install from existing source outside the venv.\n    \"\"\"\n    try:\n        temp = mkdtemp()\n        temp_pkg_dir = join(temp, \"pip-test-package\")\n        _test_uninstall_editable_with_source_outside_venv(\n            script,\n            tmpdir,\n            temp_pkg_dir,\n        )\n    finally:\n        rmtree(temp)\n\n\ndef _test_uninstall_editable_with_source_outside_venv(\n    script: PipTestEnvironment,\n    tmpdir: Path,\n    temp_pkg_dir: str,\n) -> None:\n    result = script.run(\n        \"git\",\n        \"clone\",\n        local_repo(\"git+https://github.com/pypa/pip-test-package\", tmpdir),\n        temp_pkg_dir,\n        expect_stderr=True,\n    )\n    result2 = script.run(\"python\", \"setup.py\", \"develop\", cwd=temp_pkg_dir)\n    result2.did_create(join(script.site_packages, \"pip-test-package.egg-link\"))\n    result3 = script.pip(\"uninstall\", \"-y\", \"pip-test-package\")\n    assert_all_changes(\n        result,\n        result3,\n        [script.venv / \"build\", script.site_packages / \"easy-install.pth\"],\n    )\n\n\n@pytest.mark.xfail\n@pytest.mark.network\n@need_svn\ndef test_uninstall_from_reqs_file(script: PipTestEnvironment, tmpdir: Path) -> None:\n    \"\"\"\n    Test uninstall from a requirements file.\n\n    \"\"\"\n    local_svn_url = local_checkout(\n        \"svn+http://svn.colorstudy.com/INITools\",\n        tmpdir,\n    )\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            -e {url}#egg=initools\n            # and something else to test out:\n            PyLogo<0.4\n        \"\"\"\n        ).format(url=local_svn_url)\n    )\n    result = script.pip(\"install\", \"-r\", \"test-req.txt\")\n    script.scratch_path.joinpath(\"test-req.txt\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            # -f, -i, and --extra-index-url should all be ignored by uninstall\n            -f http://www.example.com\n            -i http://www.example.com\n            --extra-index-url http://www.example.com\n\n            -e {url}#egg=initools\n            # and something else to test out:\n            PyLogo<0.4\n        \"\"\"\n        ).format(url=local_svn_url)\n    )\n    result2 = script.pip(\"uninstall\", \"-r\", \"test-req.txt\", \"-y\")\n    assert_all_changes(\n        result,\n        result2,\n        [\n            script.venv / \"build\",\n            script.venv / \"src\",\n            script.scratch / \"test-req.txt\",\n            script.site_packages / \"easy-install.pth\",\n        ],\n    )\n\n\ndef test_uninstallpathset_no_paths(caplog: pytest.LogCaptureFixture) -> None:\n    \"\"\"\n    Test UninstallPathSet logs notification when there are no paths to\n    uninstall\n    \"\"\"\n    from pip._internal.metadata import get_default_environment\n    from pip._internal.req.req_uninstall import UninstallPathSet\n\n    caplog.set_level(logging.INFO)\n\n    test_dist = get_default_environment().get_distribution(\"pip\")\n    assert test_dist is not None, \"pip not installed\"\n\n    uninstall_set = UninstallPathSet(test_dist)\n    uninstall_set.remove()  # with no files added to set\n\n    assert \"Can't uninstall 'pip'. No files were found to uninstall.\" in caplog.text\n\n\ndef test_uninstall_non_local_distutils(\n    caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, tmpdir: Path\n) -> None:\n    einfo = tmpdir.joinpath(\"thing-1.0.egg-info\")\n    with open(einfo, \"wb\"):\n        pass\n\n    get_dist = Mock()\n    get_dist.return_value = Mock(\n        key=\"thing\",\n        project_name=\"thing\",\n        egg_info=einfo,\n        location=einfo,\n    )\n    monkeypatch.setattr(\"pip._vendor.pkg_resources.get_distribution\", get_dist)\n\n    req = install_req_from_line(\"thing\")\n    req.uninstall()\n\n    assert os.path.exists(einfo)\n\n\ndef test_uninstall_wheel(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test uninstalling a wheel\n    \"\"\"\n    package = data.packages.joinpath(\"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"--no-index\")\n    dist_info_folder = script.site_packages / \"simple.dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n    result2 = script.pip(\"uninstall\", \"simple.dist\", \"-y\")\n    assert_all_changes(result, result2, [])\n\n\n@pytest.mark.parametrize(\n    \"installer\",\n    [\n        FileNotFoundError,\n        IsADirectoryError,\n        \"\",\n        os.linesep,\n        b\"\\xc0\\xff\\xee\",\n        \"pip\",\n        \"MegaCorp Cloud Install-O-Matic\",\n    ],\n)\ndef test_uninstall_without_record_fails(\n    script: PipTestEnvironment, data: TestData, installer: Any\n) -> None:\n    \"\"\"\n    Test uninstalling a package installed without RECORD\n    \"\"\"\n    package = data.packages.joinpath(\"simple.dist-0.1-py2.py3-none-any.whl\")\n    result = script.pip(\"install\", package, \"--no-index\")\n    dist_info_folder = script.site_packages / \"simple.dist-0.1.dist-info\"\n    result.did_create(dist_info_folder)\n\n    # Remove RECORD\n    record_path = dist_info_folder / \"RECORD\"\n    (script.base_path / record_path).unlink()\n    ignore_changes = [record_path]\n\n    # Populate, remove or otherwise break INSTALLER\n    installer_path = dist_info_folder / \"INSTALLER\"\n    ignore_changes += [installer_path]\n    installer_path = script.base_path / installer_path\n    if installer in (FileNotFoundError, IsADirectoryError):\n        installer_path.unlink()\n        if installer is IsADirectoryError:\n            installer_path.mkdir()\n    else:\n        if isinstance(installer, bytes):\n            installer_path.write_bytes(installer)\n        else:\n            installer_path.write_text(installer + os.linesep)\n\n    result2 = script.pip(\"uninstall\", \"simple.dist\", \"-y\", expect_error=True)\n    assert \"Cannot uninstall simple.dist 0.1\" in result2.stderr\n    assert \"no RECORD file was found for simple.dist\" in result2.stderr\n    if not isinstance(installer, str) or not installer.strip() or installer == \"pip\":\n        hint = (\n            \"You might be able to recover from this via: \"\n            \"pip install --force-reinstall --no-deps simple.dist==0.1\"\n        )\n    elif installer:\n        hint = f\"The package was installed by {installer}.\"\n    assert f\"hint: {hint}\" in result2.stderr\n    assert_all_changes(result.files_after, result2, ignore_changes)\n\n\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_uninstall_with_symlink(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test uninstalling a wheel, with an additional symlink\n    https://github.com/pypa/pip/issues/6892\n    \"\"\"\n    package = data.packages.joinpath(\"simple.dist-0.1-py2.py3-none-any.whl\")\n    script.pip(\"install\", package, \"--no-index\")\n    symlink_target = tmpdir / \"target\"\n    symlink_target.mkdir()\n    symlink_source = script.site_packages / \"symlink\"\n    (script.base_path / symlink_source).symlink_to(symlink_target)\n    st_mode = symlink_target.stat().st_mode\n    distinfo_path = script.site_packages_path / \"simple.dist-0.1.dist-info\"\n    record_path = distinfo_path / \"RECORD\"\n    with open(record_path, \"a\") as f:\n        f.write(\"symlink,,\\n\")\n    uninstall_result = script.pip(\"uninstall\", \"simple.dist\", \"-y\")\n    assert symlink_source in uninstall_result.files_deleted\n    assert symlink_target.stat().st_mode == st_mode\n\n\ndef test_uninstall_setuptools_develop_install(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Try uninstall after setup.py develop followed of setup.py install\"\"\"\n    pkg_path = data.packages.joinpath(\"FSPkg\")\n    script.run(\"python\", \"setup.py\", \"develop\", expect_stderr=True, cwd=pkg_path)\n    script.run(\"python\", \"setup.py\", \"install\", expect_stderr=True, cwd=pkg_path)\n    script.assert_installed(FSPkg=\"0.1.dev0\")\n    # Uninstall both develop and install\n    uninstall = script.pip(\"uninstall\", \"FSPkg\", \"-y\")\n    uninstall2 = script.pip(\"uninstall\", \"FSPkg\", \"-y\")\n    # Depending on the metadata backend, the egg-link will be uninstalled first\n    # or second, so we use xor in the assertions below.\n    assert (join(script.site_packages, \"FSPkg.egg-link\") in uninstall.files_deleted) ^ (\n        join(script.site_packages, \"FSPkg.egg-link\") in uninstall2.files_deleted\n    )\n    assert any(\n        p.name.startswith(\"FSPkg\") and p.suffix == \".egg\"\n        for p in uninstall.files_deleted\n    ) ^ any(\n        p.name.startswith(\"FSPkg\") and p.suffix == \".egg\"\n        for p in uninstall2.files_deleted\n    )\n    script.assert_not_installed(\"FSPkg\")\n\n\ndef test_uninstall_editable_and_pip_install(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Try uninstall after pip install -e after pip install\"\"\"\n    # SETUPTOOLS_SYS_PATH_TECHNIQUE=raw removes the assumption that `-e`\n    # installs are always higher priority than regular installs.\n    # This becomes the default behavior in setuptools 25.\n    script.environ[\"SETUPTOOLS_SYS_PATH_TECHNIQUE\"] = \"raw\"\n\n    pkg_path = data.packages.joinpath(\"FSPkg\")\n    script.run(\"python\", \"setup.py\", \"develop\", expect_stderr=True, cwd=pkg_path)\n    # ensure both are installed with --ignore-installed:\n    script.pip(\n        \"install\",\n        \"--no-build-isolation\",\n        \"--ignore-installed\",\n        \".\",\n        expect_stderr=True,\n        cwd=pkg_path,\n    )\n    script.assert_installed(FSPkg=\"0.1.dev0\")\n    # Uninstall both develop and install\n    uninstall = script.pip(\"uninstall\", \"FSPkg\", \"-y\")\n    assert not any(p.suffix == \".egg-link\" for p in uninstall.files_deleted)\n    uninstall2 = script.pip(\"uninstall\", \"FSPkg\", \"-y\")\n    assert (\n        join(script.site_packages, \"FSPkg.egg-link\") in uninstall2.files_deleted\n    ), list(uninstall2.files_deleted.keys())\n    script.assert_not_installed(\"FSPkg\")\n\n\n@pytest.fixture\ndef move_easy_install_pth(script: PipTestEnvironment) -> Iterator[None]:\n    \"\"\"Move easy-install.pth out of the way for testing easy_install.\"\"\"\n    easy_install_pth = join(script.site_packages_path, \"easy-install.pth\")\n    pip_test_pth = join(script.site_packages_path, \"pip-test.pth\")\n    os.rename(easy_install_pth, pip_test_pth)\n    yield\n    os.rename(pip_test_pth, easy_install_pth)\n\n\n@pytest.mark.usefixtures(\"move_easy_install_pth\")\ndef test_uninstall_editable_and_pip_install_easy_install_remove(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Try uninstall after pip install -e after pip install\n    and removing easy-install.pth\"\"\"\n    # SETUPTOOLS_SYS_PATH_TECHNIQUE=raw removes the assumption that `-e`\n    # installs are always higher priority than regular installs.\n    # This becomes the default behavior in setuptools 25.\n    script.environ[\"SETUPTOOLS_SYS_PATH_TECHNIQUE\"] = \"raw\"\n\n    # Install FSPkg\n    pkg_path = data.packages.joinpath(\"FSPkg\")\n    script.run(\"python\", \"setup.py\", \"develop\", expect_stderr=True, cwd=pkg_path)\n\n    # Rename easy-install.pth to pip-test-fspkg.pth\n    easy_install_pth = join(script.site_packages_path, \"easy-install.pth\")\n    pip_test_fspkg_pth = join(script.site_packages_path, \"pip-test-fspkg.pth\")\n    os.rename(easy_install_pth, pip_test_fspkg_pth)\n\n    # Confirm that FSPkg is installed\n    script.assert_installed(FSPkg=\"0.1.dev0\")\n\n    # Remove pip-test-fspkg.pth\n    os.remove(pip_test_fspkg_pth)\n\n    # Uninstall will fail with given warning\n    uninstall = script.pip(\"uninstall\", \"FSPkg\", \"-y\", allow_stderr_warning=True)\n    assert \"Cannot remove entries from nonexistent file\" in uninstall.stderr\n\n    assert (\n        join(script.site_packages, \"FSPkg.egg-link\") in uninstall.files_deleted\n    ), list(uninstall.files_deleted.keys())\n\n    # Confirm that FSPkg is uninstalled\n    script.assert_not_installed(\"FSPkg\")\n\n\ndef test_uninstall_ignores_missing_packages(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Uninstall of a non existent package prints a warning and exits cleanly\"\"\"\n    result = script.pip(\n        \"uninstall\",\n        \"-y\",\n        \"non-existent-pkg\",\n        expect_stderr=True,\n    )\n\n    assert \"Skipping non-existent-pkg as it is not installed.\" in result.stderr\n    assert result.returncode == 0, \"Expected clean exit\"\n\n\ndef test_uninstall_ignores_missing_packages_and_uninstalls_rest(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.pip_install_local(\"simple\")\n    result = script.pip(\n        \"uninstall\",\n        \"-y\",\n        \"non-existent-pkg\",\n        \"simple\",\n        expect_stderr=True,\n    )\n\n    assert \"Skipping non-existent-pkg as it is not installed.\" in result.stderr\n    assert \"Successfully uninstalled simple\" in result.stdout\n    assert result.returncode == 0, \"Expected clean exit\"\n"
  },
  {
    "path": "tests/functional/test_uninstall_user.py",
    "content": "\"\"\"\ntests specific to uninstalling --user installs\n\"\"\"\n\nimport platform\nimport sys\nfrom os.path import isdir, isfile, normcase\n\nimport pytest\n\nfrom tests.functional.test_install_user import _patch_dist_in_site_packages\nfrom tests.lib import PipTestEnvironment, TestData, assert_all_changes\nfrom tests.lib.venv import VirtualEnvironment\nfrom tests.lib.wheel import make_wheel\n\n\n@pytest.mark.usefixtures(\"enable_user_site\")\nclass Tests_UninstallUserSite:\n    @pytest.mark.network\n    def test_uninstall_from_usersite(self, script: PipTestEnvironment) -> None:\n        \"\"\"\n        Test uninstall from usersite\n        \"\"\"\n        result1 = script.pip(\"install\", \"--user\", \"INITools==0.3\")\n        result2 = script.pip(\"uninstall\", \"-y\", \"INITools\")\n        assert_all_changes(result1, result2, [script.venv / \"build\", \"cache\"])\n\n    def test_uninstall_from_usersite_with_dist_in_global_site(\n        self, virtualenv: VirtualEnvironment, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test uninstall from usersite (with same dist in global site)\n        \"\"\"\n        entry_points_txt = \"[console_scripts]\\nscript = pkg:func\"\n        make_wheel(\n            \"pkg\",\n            \"0.1\",\n            extra_metadata_files={\"entry_points.txt\": entry_points_txt},\n        ).save_to_dir(script.scratch_path)\n        make_wheel(\n            \"pkg\",\n            \"0.1.1\",\n            extra_metadata_files={\"entry_points.txt\": entry_points_txt},\n        ).save_to_dir(script.scratch_path)\n\n        _patch_dist_in_site_packages(virtualenv)\n\n        script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--no-warn-script-location\",\n            \"pkg==0.1\",\n        )\n\n        result2 = script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--find-links\",\n            script.scratch_path,\n            \"--no-warn-script-location\",\n            \"--user\",\n            \"pkg==0.1.1\",\n        )\n        result3 = script.pip(\"uninstall\", \"-vy\", \"pkg\")\n\n        # uninstall console is mentioning user scripts, but not global scripts\n        assert normcase(script.user_bin_path) in result3.stdout, str(result3)\n        assert normcase(script.bin_path) not in result3.stdout, str(result3)\n\n        # uninstall worked\n        assert_all_changes(result2, result3, [script.venv / \"build\", \"cache\"])\n\n        # site still has 0.2 (can't look in result1; have to check)\n        dist_info_folder = script.base_path / script.site_packages / \"pkg-0.1.dist-info\"\n        assert isdir(dist_info_folder)\n\n    @pytest.mark.xfail(\n        sys.platform == \"darwin\"\n        and platform.machine() == \"arm64\"\n        and sys.version_info[:2] < (3, 10),\n        reason=\"Unexpected egg-link install path\",\n    )\n    def test_uninstall_editable_from_usersite(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"\n        Test uninstall editable local user install\n        \"\"\"\n        assert script.user_site_path.exists()\n\n        # install\n        to_install = data.packages.joinpath(\"FSPkg\")\n        result1 = script.run(\n            \"python\", \"setup.py\", \"develop\", \"--user\", \"--prefix=\", cwd=to_install\n        )\n        egg_link = script.user_site / \"FSPkg.egg-link\"\n        result1.did_create(egg_link)\n\n        # uninstall\n        result2 = script.pip(\"uninstall\", \"-y\", \"FSPkg\")\n        assert not isfile(script.base_path / egg_link)\n\n        assert_all_changes(\n            result1,\n            result2,\n            [\n                script.venv / \"build\",\n                \"cache\",\n                script.user_site / \"easy-install.pth\",\n            ],\n        )\n"
  },
  {
    "path": "tests/functional/test_uploaded_prior_to.py",
    "content": "\"\"\"Tests for pip install --uploaded-prior-to.\"\"\"\n\nfrom __future__ import annotations\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment, TestData\nfrom tests.lib.server import (\n    file_response,\n    make_mock_server,\n    package_page,\n    server_running,\n)\n\n\nclass TestUploadedPriorTo:\n    \"\"\"Test --uploaded-prior-to functionality.\"\"\"\n\n    def test_uploaded_prior_to_invalid_date(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that invalid date format is rejected.\"\"\"\n        result = script.pip_install_local(\n            \"--uploaded-prior-to=invalid-date\", \"simple\", expect_error=True\n        )\n        assert \"invalid\" in result.stderr.lower() or \"error\" in result.stderr.lower()\n\n    def test_uploaded_prior_to_file_index_no_upload_time(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that file:// indexes are exempt from upload-time filtering.\"\"\"\n        result = script.pip(\n            \"install\",\n            \"--no-build-isolation\",\n            \"--index-url\",\n            data.index_url(\"simple\"),\n            \"--uploaded-prior-to=2100-01-01T00:00:00\",\n            \"simple\",\n            expect_error=False,\n        )\n        assert \"Successfully installed simple\" in result.stdout\n\n    def test_uploaded_prior_to_http_index_no_upload_time(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that HTTP index without upload-time causes immediate error.\"\"\"\n        server = make_mock_server()\n        simple_package = data.packages / \"simple-1.0.tar.gz\"\n        server.mock.side_effect = [\n            package_page({\"simple-1.0.tar.gz\": \"/files/simple-1.0.tar.gz\"}),\n            file_response(simple_package),\n        ]\n\n        with server_running(server):\n            result = script.pip(\n                \"install\",\n                \"--index-url\",\n                f\"http://{server.host}:{server.port}\",\n                \"--uploaded-prior-to=2100-01-01T00:00:00\",\n                \"simple\",\n                expect_error=True,\n            )\n\n        assert \"does not provide upload-time metadata\" in result.stderr\n\n    @pytest.mark.network\n    def test_uploaded_prior_to_with_real_pypi(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test filtering against real PyPI with upload-time metadata.\"\"\"\n        # Test with old cutoff date - should find no matching versions\n        result = script.pip(\n            \"install\",\n            \"--dry-run\",\n            \"--no-deps\",\n            \"--uploaded-prior-to=2010-01-01T00:00:00\",\n            \"requests==2.0.0\",\n            expect_error=True,\n        )\n        assert \"Could not find a version that satisfies\" in result.stderr\n\n        # Test with future cutoff date - should find the package\n        result = script.pip(\n            \"install\",\n            \"--dry-run\",\n            \"--no-deps\",\n            \"--uploaded-prior-to=2030-01-01T00:00:00\",\n            \"requests==2.0.0\",\n            expect_error=False,\n        )\n        assert \"Would install requests-2.0.0\" in result.stdout\n\n    @pytest.mark.network\n    def test_uploaded_prior_to_date_formats(self, script: PipTestEnvironment) -> None:\n        \"\"\"Test various date format strings are accepted.\"\"\"\n        formats = [\n            \"2030-01-01\",\n            \"2030-01-01T00:00:00\",\n            \"2030-01-01T00:00:00+00:00\",\n            \"2030-01-01T00:00:00-05:00\",\n        ]\n\n        for date_format in formats:\n            result = script.pip(\n                \"install\",\n                \"--dry-run\",\n                \"--no-deps\",\n                f\"--uploaded-prior-to={date_format}\",\n                \"requests==2.0.0\",\n                expect_error=False,\n            )\n            assert \"Would install requests-2.0.0\" in result.stdout\n\n    def test_uploaded_prior_to_allows_local_files(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that local file installs bypass upload-time filtering.\"\"\"\n        simple_wheel = data.packages / \"simplewheel-1.0-py2.py3-none-any.whl\"\n\n        result = script.pip(\n            \"install\",\n            \"--no-index\",\n            \"--uploaded-prior-to=2000-01-01T00:00:00\",\n            str(simple_wheel),\n            expect_error=False,\n        )\n        assert \"Successfully installed simplewheel-1.0\" in result.stdout\n\n    def test_uploaded_prior_to_allows_find_links(\n        self, script: PipTestEnvironment, data: TestData\n    ) -> None:\n        \"\"\"Test that --find-links bypasses upload-time filtering.\"\"\"\n        result = script.pip_install_local(\n            \"--uploaded-prior-to=2000-01-01T00:00:00\", \"simple==1.0\"\n        )\n        assert \"Successfully installed simple-1.0\" in result.stdout\n"
  },
  {
    "path": "tests/functional/test_vcs_bazaar.py",
    "content": "\"\"\"\nContains functional tests of the Bazaar class.\n\"\"\"\n\nimport os\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.vcs.bazaar import Bazaar\nfrom pip._internal.vcs.versioncontrol import RemoteNotFoundError\n\nfrom tests.lib import PipTestEnvironment, is_bzr_installed, need_bzr\n\n\n@pytest.mark.skipif(\n    sys.platform == \"win32\" or \"CI\" not in os.environ,\n    reason=\"Bazaar is only required under CI\",\n)\ndef test_ensure_bzr_available() -> None:\n    \"\"\"Make sure that bzr is available when running in CI.\"\"\"\n    assert is_bzr_installed()\n\n\n@need_bzr\ndef test_get_remote_url__no_remote(script: PipTestEnvironment, tmpdir: Path) -> None:\n    repo_dir = tmpdir / \"temp-repo\"\n    repo_dir.mkdir()\n\n    script.run(\"bzr\", \"init\", os.fspath(repo_dir))\n\n    with pytest.raises(RemoteNotFoundError):\n        Bazaar().get_remote_url(os.fspath(repo_dir))\n"
  },
  {
    "path": "tests/functional/test_vcs_git.py",
    "content": "\"\"\"\nContains functional tests of the Git class.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport pathlib\nfrom unittest.mock import Mock, patch\n\nimport pytest\n\nfrom pip._internal.utils.misc import HiddenText\nfrom pip._internal.vcs import vcs\nfrom pip._internal.vcs.git import Git, RemoteNotFoundError\n\nfrom tests.lib import PipTestEnvironment, _create_test_package, _git_commit\n\n\ndef test_get_backend_for_scheme() -> None:\n    assert vcs.get_backend_for_scheme(\"git+https\") is vcs.get_backend(\"Git\")\n\n\ndef get_head_sha(script: PipTestEnvironment, dest: str) -> str:\n    \"\"\"Return the HEAD sha.\"\"\"\n    result = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=dest)\n    sha = result.stdout.strip()\n\n    return sha\n\n\ndef checkout_ref(script: PipTestEnvironment, repo_dir: str, ref: str) -> None:\n    script.run(\"git\", \"checkout\", ref, cwd=repo_dir)\n\n\ndef checkout_new_branch(script: PipTestEnvironment, repo_dir: str, branch: str) -> None:\n    script.run(\n        \"git\",\n        \"checkout\",\n        \"-b\",\n        branch,\n        cwd=repo_dir,\n    )\n\n\ndef do_commit(script: PipTestEnvironment, dest: str) -> str:\n    _git_commit(script, dest, message=\"test commit\", allow_empty=True)\n    return get_head_sha(script, dest)\n\n\ndef add_commits(script: PipTestEnvironment, dest: str, count: int) -> list[str]:\n    \"\"\"Return a list of the commit hashes from oldest to newest.\"\"\"\n    shas = []\n    for _ in range(count):\n        sha = do_commit(script, dest)\n        shas.append(sha)\n\n    return shas\n\n\ndef check_rev(repo_dir: str, rev: str, expected: tuple[str | None, bool]) -> None:\n    assert Git.get_revision_sha(repo_dir, rev) == expected\n\n\ndef test_git_dir_ignored(tmpdir: pathlib.Path) -> None:\n    \"\"\"\n    Test that a GIT_DIR environment variable is ignored.\n    \"\"\"\n    repo_path = tmpdir / \"test-repo\"\n    repo_path.mkdir()\n    repo_dir = str(repo_path)\n\n    env = {\"GIT_DIR\": \"foo\"}\n    # If GIT_DIR is not ignored, then os.listdir() will return ['foo'].\n    Git.run_command([\"init\", repo_dir], cwd=repo_dir, extra_environ=env)\n    assert os.listdir(repo_dir) == [\".git\"]\n\n\ndef test_git_work_tree_ignored(tmpdir: pathlib.Path) -> None:\n    \"\"\"\n    Test that a GIT_WORK_TREE environment variable is ignored.\n    \"\"\"\n    repo_path = tmpdir / \"test-repo\"\n    repo_path.mkdir()\n    repo_dir = str(repo_path)\n\n    Git.run_command([\"init\", repo_dir], cwd=repo_dir)\n    # Choose a directory relative to the cwd that does not exist.\n    # If GIT_WORK_TREE is not ignored, then the command will error out\n    # with: \"fatal: This operation must be run in a work tree\".\n    env = {\"GIT_WORK_TREE\": \"foo\"}\n    Git.run_command([\"status\", repo_dir], extra_environ=env, cwd=repo_dir)\n\n\ndef test_get_remote_url(script: PipTestEnvironment, tmpdir: pathlib.Path) -> None:\n    source_path = tmpdir / \"source\"\n    source_path.mkdir()\n    source_url = source_path.as_uri()\n\n    source_dir = str(source_path)\n    script.run(\"git\", \"init\", cwd=source_dir)\n    do_commit(script, source_dir)\n\n    repo_dir = str(tmpdir / \"repo\")\n    script.run(\"git\", \"clone\", source_url, repo_dir)\n\n    remote_url = Git.get_remote_url(repo_dir)\n    assert remote_url == source_url\n\n\ndef test_get_remote_url__no_remote(\n    script: PipTestEnvironment, tmpdir: pathlib.Path\n) -> None:\n    \"\"\"\n    Test a repo with no remote.\n    \"\"\"\n    repo_path = tmpdir / \"temp-repo\"\n    repo_path.mkdir()\n    repo_dir = str(repo_path)\n\n    script.run(\"git\", \"init\", cwd=repo_dir)\n\n    with pytest.raises(RemoteNotFoundError):\n        Git.get_remote_url(repo_dir)\n\n\ndef test_get_current_branch(script: PipTestEnvironment) -> None:\n    repo_dir = str(script.scratch_path)\n\n    script.run(\"git\", \"init\", cwd=repo_dir)\n    sha = do_commit(script, repo_dir)\n\n    assert Git.get_current_branch(repo_dir) == \"master\"\n\n    # Switch to a branch with the same SHA as \"master\" but whose name\n    # is alphabetically after.\n    checkout_new_branch(script, repo_dir, \"release\")\n    assert Git.get_current_branch(repo_dir) == \"release\"\n\n    # Also test the detached HEAD case.\n    checkout_ref(script, repo_dir, sha)\n    assert Git.get_current_branch(repo_dir) is None\n\n\ndef test_get_current_branch__branch_and_tag_same_name(\n    script: PipTestEnvironment, tmpdir: pathlib.Path\n) -> None:\n    \"\"\"\n    Check calling get_current_branch() from a branch or tag when the branch\n    and tag have the same name.\n    \"\"\"\n    repo_dir = str(tmpdir)\n    script.run(\"git\", \"init\", cwd=repo_dir)\n    do_commit(script, repo_dir)\n    checkout_new_branch(script, repo_dir, \"dev\")\n    # Create a tag with the same name as the branch.\n    script.run(\"git\", \"tag\", \"dev\", cwd=repo_dir)\n\n    assert Git.get_current_branch(repo_dir) == \"dev\"\n\n    # Now try with the tag checked out.\n    checkout_ref(script, repo_dir, \"refs/tags/dev\")\n    assert Git.get_current_branch(repo_dir) is None\n\n\ndef test_get_revision_sha(script: PipTestEnvironment) -> None:\n    repo_dir = str(script.scratch_path)\n\n    script.run(\"git\", \"init\", cwd=repo_dir)\n    shas = add_commits(script, repo_dir, count=3)\n\n    tag_sha = shas[0]\n    origin_sha = shas[1]\n    head_sha = shas[2]\n    assert head_sha == shas[-1]\n\n    origin_ref = \"refs/remotes/origin/origin-branch\"\n    generic_ref = \"refs/generic-ref\"\n\n    script.run(\"git\", \"branch\", \"local-branch\", head_sha, cwd=repo_dir)\n    script.run(\"git\", \"tag\", \"v1.0\", tag_sha, cwd=repo_dir)\n    script.run(\"git\", \"update-ref\", origin_ref, origin_sha, cwd=repo_dir)\n    script.run(\n        \"git\",\n        \"update-ref\",\n        \"refs/remotes/upstream/upstream-branch\",\n        head_sha,\n        cwd=repo_dir,\n    )\n    script.run(\"git\", \"update-ref\", generic_ref, head_sha, cwd=repo_dir)\n\n    # Test two tags pointing to the same sha.\n    script.run(\"git\", \"tag\", \"v2.0\", tag_sha, cwd=repo_dir)\n    # Test tags sharing the same suffix as another tag, both before and\n    # after the suffix alphabetically.\n    script.run(\"git\", \"tag\", \"aaa/v1.0\", head_sha, cwd=repo_dir)\n    script.run(\"git\", \"tag\", \"zzz/v1.0\", head_sha, cwd=repo_dir)\n\n    check_rev(repo_dir, \"v1.0\", (tag_sha, False))\n    check_rev(repo_dir, \"v2.0\", (tag_sha, False))\n    check_rev(repo_dir, \"origin-branch\", (origin_sha, True))\n\n    ignored_names = [\n        # Local branches should be ignored.\n        \"local-branch\",\n        # Non-origin remote branches should be ignored.\n        \"upstream-branch\",\n        # Generic refs should be ignored.\n        \"generic-ref\",\n        # Fully spelled-out refs should be ignored.\n        origin_ref,\n        generic_ref,\n        # Test passing a valid commit hash.\n        tag_sha,\n        # Test passing a non-existent name.\n        \"does-not-exist\",\n    ]\n    for name in ignored_names:\n        check_rev(repo_dir, name, (None, False))\n\n\ndef test_is_commit_id_equal(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test Git.is_commit_id_equal().\n    \"\"\"\n    version_pkg_path = os.fspath(_create_test_package(script.scratch_path))\n    script.run(\"git\", \"branch\", \"branch0.1\", cwd=version_pkg_path)\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=version_pkg_path).stdout.strip()\n\n    assert Git.is_commit_id_equal(version_pkg_path, commit)\n    assert not Git.is_commit_id_equal(version_pkg_path, commit[:7])\n    assert not Git.is_commit_id_equal(version_pkg_path, \"branch0.1\")\n    assert not Git.is_commit_id_equal(version_pkg_path, \"abc123\")\n    # Also check passing a None value.\n    assert not Git.is_commit_id_equal(version_pkg_path, None)\n\n\ndef test_is_immutable_rev_checkout(script: PipTestEnvironment) -> None:\n    version_pkg_path = os.fspath(_create_test_package(script.scratch_path))\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=version_pkg_path).stdout.strip()\n    assert Git().is_immutable_rev_checkout(\n        \"git+https://g.c/o/r@\" + commit, version_pkg_path\n    )\n    assert not Git().is_immutable_rev_checkout(\"git+https://g.c/o/r\", version_pkg_path)\n    assert not Git().is_immutable_rev_checkout(\n        \"git+https://g.c/o/r@master\", version_pkg_path\n    )\n\n\ndef test_get_repository_root(script: PipTestEnvironment) -> None:\n    version_pkg_path = _create_test_package(script.scratch_path)\n    tests_path = version_pkg_path.joinpath(\"tests\")\n    tests_path.mkdir()\n\n    root1 = Git.get_repository_root(os.fspath(version_pkg_path))\n    assert root1 is not None\n    assert os.path.normcase(root1) == os.path.normcase(version_pkg_path)\n\n    root2 = Git.get_repository_root(os.fspath(tests_path))\n    assert root2 is not None\n    assert os.path.normcase(root2) == os.path.normcase(version_pkg_path)\n\n\ndef test_resolve_commit_not_on_branch(\n    script: PipTestEnvironment, tmp_path: pathlib.Path\n) -> None:\n    repo_path = tmp_path / \"repo\"\n    repo_file = repo_path / \"file.txt\"\n    clone_path = repo_path / \"clone\"\n    repo_path.mkdir()\n    script.run(\"git\", \"init\", cwd=str(repo_path))\n\n    repo_file.write_text(\".\")\n    script.run(\"git\", \"add\", \"file.txt\", cwd=str(repo_path))\n    script.run(\"git\", \"commit\", \"-m\", \"initial commit\", cwd=str(repo_path))\n    script.run(\"git\", \"checkout\", \"-b\", \"abranch\", cwd=str(repo_path))\n\n    # create a commit\n    repo_file.write_text(\"..\")\n    script.run(\"git\", \"commit\", \"-a\", \"-m\", \"commit 1\", cwd=str(repo_path))\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=str(repo_path)).stdout.strip()\n\n    # make sure our commit is not on a branch\n    script.run(\"git\", \"checkout\", \"master\", cwd=str(repo_path))\n    script.run(\"git\", \"branch\", \"-D\", \"abranch\", cwd=str(repo_path))\n\n    # create a ref that points to our commit\n    (repo_path / \".git\" / \"refs\" / \"myrefs\").mkdir(parents=True)\n    (repo_path / \".git\" / \"refs\" / \"myrefs\" / \"myref\").write_text(commit)\n\n    # check we can fetch our commit\n    rev_options = Git.make_rev_options(commit)\n    Git().fetch_new(\n        str(clone_path),\n        HiddenText(repo_path.as_uri(), redacted=\"*\"),\n        rev_options,\n        verbosity=0,\n    )\n\n\ndef _initialize_clonetest_server(\n    repo_path: pathlib.Path, script: PipTestEnvironment, enable_partial_clone: bool\n) -> pathlib.Path:\n    repo_path.mkdir()\n    script.run(\"git\", \"init\", cwd=str(repo_path))\n    repo_file = repo_path / \"file.txt\"\n    repo_file.write_text(\".\")\n    script.run(\"git\", \"add\", \"file.txt\", cwd=str(repo_path))\n    script.run(\"git\", \"commit\", \"-m\", \"initial commit\", cwd=str(repo_path))\n\n    # Enable filtering support on server\n    if enable_partial_clone:\n        script.run(\"git\", \"config\", \"uploadpack.allowFilter\", \"true\", cwd=repo_path)\n        script.run(\n            \"git\", \"config\", \"uploadpack.allowanysha1inwant\", \"true\", cwd=repo_path\n        )\n\n    return repo_file\n\n\n@pytest.mark.parametrize(\n    \"version_out, expected_message\",\n    [\n        (\"git version -2.25.1\", \"Can't parse git version: git version -2.25.1\"),\n        (\"git version 2.a.1\", \"Can't parse git version: git version 2.a.1\"),\n        (\"git ver. 2.25.1\", \"Can't parse git version: git ver. 2.25.1\"),\n    ],\n)\n@patch(\"pip._internal.vcs.versioncontrol.VersionControl.run_command\")\ndef test_git_parse_fail_warning(\n    mock_run_command: Mock,\n    caplog: pytest.LogCaptureFixture,\n    version_out: str,\n    expected_message: str,\n) -> None:\n    \"\"\"Test invalid git version logs adds an explicit warning log.\"\"\"\n    mock_run_command.return_value = version_out\n\n    caplog.set_level(logging.WARNING)\n\n    git_tuple = Git().get_git_version()\n    # Returns an empty tuple if it is an invalid git version\n    assert git_tuple == ()\n\n    # Check for warning log\n    assert expected_message in caplog.text.strip()\n\n\n@pytest.mark.skipif(Git().get_git_version() < (2, 17), reason=\"git too old\")\ndef test_partial_clone(script: PipTestEnvironment, tmp_path: pathlib.Path) -> None:\n    \"\"\"Test partial clone w/ a git-server that supports it\"\"\"\n    repo_path = tmp_path / \"repo\"\n    repo_file = _initialize_clonetest_server(\n        repo_path, script, enable_partial_clone=True\n    )\n    clone_path1 = repo_path / \"clone1\"\n    clone_path2 = repo_path / \"clone2\"\n\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=str(repo_path)).stdout.strip()\n\n    # Check that we can clone at HEAD\n    Git().fetch_new(\n        str(clone_path1),\n        HiddenText(repo_path.as_uri(), redacted=\"*\"),\n        Git.make_rev_options(),\n        verbosity=0,\n    )\n    # Check that we can clone to commit\n    Git().fetch_new(\n        str(clone_path2),\n        HiddenText(repo_path.as_uri(), redacted=\"*\"),\n        Git.make_rev_options(commit),\n        verbosity=0,\n    )\n\n    # Write some additional stuff to git pull\n    repo_file.write_text(\"..\")\n    script.run(\"git\", \"commit\", \"-am\", \"second commit\", cwd=str(repo_path))\n\n    # Make sure git pull works - with server supporting filtering\n    assert (\n        \"warning: filtering not recognized by server, ignoring\"\n        not in script.run(\"git\", \"pull\", cwd=clone_path1).stderr\n    )\n    assert (\n        \"warning: filtering not recognized by server, ignoring\"\n        not in script.run(\"git\", \"pull\", cwd=clone_path2).stderr\n    )\n\n\n@pytest.mark.skipif(Git().get_git_version() < (2, 17), reason=\"git too old\")\ndef test_partial_clone_without_server_support(\n    script: PipTestEnvironment, tmp_path: pathlib.Path\n) -> None:\n    \"\"\"Test partial clone w/ a git-server that does not support it\"\"\"\n    repo_path = tmp_path / \"repo\"\n    repo_file = _initialize_clonetest_server(\n        repo_path, script, enable_partial_clone=False\n    )\n    clone_path1 = repo_path / \"clone1\"\n    clone_path2 = repo_path / \"clone2\"\n\n    commit = script.run(\"git\", \"rev-parse\", \"HEAD\", cwd=str(repo_path)).stdout.strip()\n\n    # Check that we can clone at HEAD\n    Git().fetch_new(\n        str(clone_path1),\n        HiddenText(repo_path.as_uri(), redacted=\"*\"),\n        Git.make_rev_options(),\n        verbosity=0,\n    )\n    # Check that we can clone to commit\n    Git().fetch_new(\n        str(clone_path2),\n        HiddenText(repo_path.as_uri(), redacted=\"*\"),\n        Git.make_rev_options(commit),\n        verbosity=0,\n    )\n\n    # Write some additional stuff to git pull\n    repo_file.write_text(\"..\")\n    script.run(\"git\", \"commit\", \"-am\", \"second commit\", cwd=str(repo_path))\n\n    # Make sure git pull works - even though server doesn't support filtering\n    assert (\n        \"warning: filtering not recognized by server, ignoring\"\n        in script.run(\"git\", \"pull\", cwd=clone_path1).stderr\n    )\n    assert (\n        \"warning: filtering not recognized by server, ignoring\"\n        in script.run(\"git\", \"pull\", cwd=clone_path2).stderr\n    )\n\n\ndef test_clone_without_partial_clone_support(\n    script: PipTestEnvironment, tmp_path: pathlib.Path\n) -> None:\n    \"\"\"Older git clients don't support partial clone. Test the fallback path\"\"\"\n    repo_path = tmp_path / \"repo\"\n    repo_file = _initialize_clonetest_server(\n        repo_path, script, enable_partial_clone=True\n    )\n    clone_path = repo_path / \"clone1\"\n\n    # Check that we can clone w/ old version of git w/o --filter\n    with patch(\"pip._internal.vcs.git.Git.get_git_version\", return_value=(2, 16)):\n        Git().fetch_new(\n            str(clone_path),\n            HiddenText(repo_path.as_uri(), redacted=\"*\"),\n            Git.make_rev_options(),\n            verbosity=0,\n        )\n\n    repo_file.write_text(\"...\")\n    script.run(\"git\", \"commit\", \"-am\", \"third commit\", cwd=str(repo_path))\n\n    # Should work fine w/o attempting to use `--filter` args\n    assert (\n        \"warning: filtering not recognized by server, ignoring\"\n        not in script.run(\"git\", \"pull\", cwd=clone_path).stderr\n    )\n"
  },
  {
    "path": "tests/functional/test_vcs_mercurial.py",
    "content": "import os\n\nfrom pip._internal.vcs.mercurial import Mercurial\n\nfrom tests.lib import PipTestEnvironment, _create_test_package, need_mercurial\n\n\n@need_mercurial\ndef test_get_repository_root(script: PipTestEnvironment) -> None:\n    version_pkg_path = _create_test_package(script.scratch_path, vcs=\"hg\")\n    tests_path = version_pkg_path.joinpath(\"tests\")\n    tests_path.mkdir()\n\n    root1 = Mercurial.get_repository_root(os.fspath(version_pkg_path))\n    assert root1 is not None\n    assert os.path.normcase(root1) == os.path.normcase(version_pkg_path)\n\n    root2 = Mercurial.get_repository_root(os.fspath(tests_path))\n    assert root2 is not None\n    assert os.path.normcase(root2) == os.path.normcase(version_pkg_path)\n"
  },
  {
    "path": "tests/functional/test_vcs_subversion.py",
    "content": "from pathlib import Path\n\nimport pytest\n\nfrom pip._internal.vcs.subversion import Subversion\nfrom pip._internal.vcs.versioncontrol import RemoteNotFoundError\n\nfrom tests.lib import PipTestEnvironment, _create_svn_repo, need_svn\n\n\n@need_svn\ndef test_get_remote_url__no_remote(script: PipTestEnvironment, tmpdir: Path) -> None:\n    repo_path = tmpdir / \"temp-repo\"\n    repo_path.mkdir()\n    repo_dir = str(repo_path)\n\n    _create_svn_repo(script.scratch_path, repo_dir)\n\n    with pytest.raises(RemoteNotFoundError):\n        Subversion().get_remote_url(repo_dir)\n\n\n@need_svn\ndef test_get_remote_url__no_remote_with_setup(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    repo_path = tmpdir / \"temp-repo\"\n    repo_path.mkdir()\n    setup = repo_path / \"setup.py\"\n    setup.touch()\n    repo_dir = str(repo_path)\n\n    _create_svn_repo(script.scratch_path, repo_dir)\n\n    with pytest.raises(RemoteNotFoundError):\n        Subversion().get_remote_url(repo_dir)\n"
  },
  {
    "path": "tests/functional/test_warning.py",
    "content": "import os\nimport sys\nimport textwrap\nfrom pathlib import Path\n\nimport pytest\n\nfrom tests.lib import PipTestEnvironment\n\n\n@pytest.fixture\ndef warnings_demo(tmpdir: Path) -> Path:\n    demo = tmpdir.joinpath(\"warnings_demo.py\")\n    demo.write_text(\n        textwrap.dedent(\n            \"\"\"\n        from logging import basicConfig\n        from pip._internal.utils import deprecation\n\n        deprecation.install_warning_logger()\n        basicConfig()\n\n        deprecation.deprecated(reason=\"deprecated!\", replacement=None, gone_in=None)\n    \"\"\"\n        )\n    )\n    return demo\n\n\ndef test_deprecation_warnings_are_correct(\n    script: PipTestEnvironment, warnings_demo: Path\n) -> None:\n    result = script.run(\"python\", os.fspath(warnings_demo), expect_stderr=True)\n    expected = \"WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\\n\"\n    assert result.stderr == expected\n\n\ndef test_deprecation_warnings_can_be_silenced(\n    script: PipTestEnvironment, warnings_demo: Path\n) -> None:\n    script.environ[\"PYTHONWARNINGS\"] = \"ignore\"\n    result = script.run(\"python\", os.fspath(warnings_demo))\n    assert result.stderr == \"\"\n\n\nDEPRECATION_TEXT = \"drop support for Python 2.7\"\nCPYTHON_DEPRECATION_TEXT = \"January 1st, 2020\"\n\n\ndef test_version_warning_is_not_shown_if_python_version_is_not_2(\n    script: PipTestEnvironment,\n) -> None:\n    result = script.pip(\"debug\", allow_stderr_warning=True)\n    assert DEPRECATION_TEXT not in result.stderr, str(result)\n    assert CPYTHON_DEPRECATION_TEXT not in result.stderr, str(result)\n\n\ndef test_flag_does_nothing_if_python_version_is_not_2(\n    script: PipTestEnvironment,\n) -> None:\n    script.pip(\"list\", \"--no-python-version-warning\")\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 10), reason=\"distutils is deprecated in 3.10+\"\n)\ndef test_pip_works_with_warnings_as_errors(script: PipTestEnvironment) -> None:\n    script.environ[\"PYTHONWARNINGS\"] = \"error\"\n    script.pip(\"--version\")\n"
  },
  {
    "path": "tests/functional/test_wheel.py",
    "content": "\"\"\"'pip wheel' tests\"\"\"\n\nimport os\nimport re\nimport sys\nimport textwrap\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import ERROR\n\nfrom tests.lib import (\n    PipTestEnvironment,\n    TestData,\n    pyversion,\n)\n\n\ndef add_files_to_dist_directory(folder: Path) -> None:\n    (folder / \"dist\").mkdir(parents=True)\n    (folder / \"dist\" / \"a_name-0.0.1.tar.gz\").write_text(\"hello\")\n    # Not adding a wheel file since that confuses setuptools' backend.\n    # (folder / 'dist' / 'a_name-0.0.1-py2.py3-none-any.whl').write_text(\n    #     \"hello\"\n    # )\n\n\ndef test_wheel_exit_status_code_when_no_requirements(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test wheel exit status code when no requirements specified\n    \"\"\"\n    result = script.pip(\"wheel\", expect_error=True)\n    assert \"You must give at least one requirement to wheel\" in result.stderr\n    assert result.returncode == ERROR\n\n\ndef test_wheel_exit_status_code_when_blank_requirements_file(\n    script: PipTestEnvironment,\n) -> None:\n    \"\"\"\n    Test wheel exit status code when blank requirements file specified\n    \"\"\"\n    script.scratch_path.joinpath(\"blank.txt\").write_text(\"\\n\")\n    script.pip(\"wheel\", \"-r\", \"blank.txt\")\n\n\ndef test_pip_wheel_success(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test 'pip wheel' success.\n    \"\"\"\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"simple==3.0\",\n    )\n    wheel_file_name = f\"simple-3.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    assert re.search(\n        r\"Created wheel for simple: \"\n        rf\"filename={re.escape(wheel_file_name)} size=\\d+ sha256=[A-Fa-f0-9]{{64}}\",\n        result.stdout,\n    )\n    assert re.search(r\"^\\s+Stored in directory: \", result.stdout, re.M)\n    result.did_create(wheel_file_path)\n    assert \"Successfully built simple\" in result.stdout, result.stdout\n\n\ndef test_pip_wheel_success_with_dependency_group(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test 'pip wheel' success.\n    \"\"\"\n    pyproject = script.scratch_path / \"pyproject.toml\"\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups]\n            simple = [\"simple==3.0\"]\n            \"\"\"\n        )\n    )\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"--group\",\n        \"simple\",\n    )\n    wheel_file_name = f\"simple-3.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    assert re.search(\n        r\"Created wheel for simple: \"\n        rf\"filename={re.escape(wheel_file_name)} size=\\d+ sha256=[A-Fa-f0-9]{{64}}\",\n        result.stdout,\n    )\n    assert re.search(r\"^\\s+Stored in directory: \", result.stdout, re.M)\n    result.did_create(wheel_file_path)\n    assert \"Successfully built simple\" in result.stdout, result.stdout\n\n\ndef test_pip_wheel_build_cache(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test 'pip wheel' builds and caches.\n    \"\"\"\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"simple==3.0\",\n    )\n    wheel_file_name = f\"simple-3.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n    assert \"Successfully built simple\" in result.stdout, result.stdout\n    # remove target file\n    (script.scratch_path / wheel_file_name).unlink()\n    # pip wheel again and test that no build occurs since\n    # we get the wheel from cache\n    result = script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"simple==3.0\",\n    )\n    result.did_create(wheel_file_path)\n    assert \"Successfully built simple\" not in result.stdout, result.stdout\n\n\ndef test_basic_pip_wheel_downloads_wheels(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test 'pip wheel' downloads wheels\n    \"\"\"\n    result = script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"simple.dist\",\n    )\n    wheel_file_name = \"simple.dist-0.1-py2.py3-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n    assert \"Saved\" in result.stdout, result.stdout\n\n\ndef test_pip_wheel_build_relative_cachedir(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test 'pip wheel' builds and caches with a non-absolute cache directory.\n    \"\"\"\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"--cache-dir\",\n        \"./cache\",\n        \"simple==3.0\",\n    )\n    assert result.returncode == 0\n\n\ndef test_pip_wheel_builds_when_no_binary_set(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    data.packages.joinpath(\"simple-3.0-py2.py3-none-any.whl\").touch()\n    # Check that the wheel package is ignored\n    res = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"--no-binary\",\n        \":all:\",\n        \"-f\",\n        data.find_links,\n        \"simple==3.0\",\n    )\n    assert \"Building wheel for simple\" in str(res), str(res)\n\n\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_pip_wheel_readonly_cache(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    cache_dir = tmpdir / \"cache\"\n    cache_dir.mkdir()\n    os.chmod(cache_dir, 0o400)  # read-only cache\n    # Check that the wheel package is ignored\n    res = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"--cache-dir\",\n        cache_dir,\n        \"simple==3.0\",\n        allow_stderr_warning=True,\n    )\n    assert res.returncode == 0\n    assert \"The cache has been disabled.\" in str(res), str(res)\n\n\ndef test_pip_wheel_builds_editable_deps(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"\n    Test 'pip wheel' finds and builds dependencies of editables\n    \"\"\"\n    editable_path = os.path.join(data.src, \"requires_simple\")\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-e\",\n        editable_path,\n    )\n    wheel_file_name = f\"simple-1.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n\n\ndef test_pip_wheel_builds_editable(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test 'pip wheel' builds an editable package\n    \"\"\"\n    editable_path = os.path.join(data.src, \"simplewheel-1.0\")\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-e\",\n        editable_path,\n    )\n    wheel_file_name = f\"simplewheel-1.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n\n\n@pytest.mark.network\ndef test_pip_wheel_git_editable_keeps_clone(\n    script: PipTestEnvironment, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that `pip wheel -e giturl` preserves a git clone in src.\n    \"\"\"\n    script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-deps\",\n        \"-e\",\n        \"git+https://github.com/pypa/pip-test-package#egg=pip-test-package\",\n        \"--src\",\n        tmpdir / \"src\",\n        \"--wheel-dir\",\n        tmpdir,\n    )\n    assert (tmpdir / \"src\" / \"pip-test-package\").exists()\n    assert (tmpdir / \"src\" / \"pip-test-package\" / \".git\").exists()\n\n\ndef test_pip_wheel_builds_editable_does_not_create_zip(\n    script: PipTestEnvironment, data: TestData, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test 'pip wheel' of editables does not create zip files\n    (regression test for issue #9122)\n    \"\"\"\n    wheel_dir = tmpdir / \"wheel_dir\"\n    wheel_dir.mkdir()\n    editable_path = os.path.join(data.src, \"simplewheel-1.0\")\n    script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-deps\",\n        \"-e\",\n        editable_path,\n        \"-w\",\n        wheel_dir,\n    )\n    wheels = os.listdir(wheel_dir)\n    assert len(wheels) == 1\n    assert wheels[0].endswith(\".whl\")\n\n\ndef test_pip_wheel_fail(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test 'pip wheel' failure.\n    \"\"\"\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"wheelbroken==0.1\",\n        expect_error=True,\n    )\n    wheel_file_name = f\"wheelbroken-0.1-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_not_create(wheel_file_path)\n    assert \"FakeError\" in result.stderr, result.stderr\n    assert \"Failed to build wheelbroken\" in result.stdout, result.stdout\n    assert result.returncode != 0\n\n\ndef test_pip_wheel_source_deps(script: PipTestEnvironment, data: TestData) -> None:\n    \"\"\"\n    Test 'pip wheel' finds and builds source archive dependencies\n    of wheels\n    \"\"\"\n    # 'requires_source' is a wheel that depends on the 'source' project\n    result = script.pip(\n        \"wheel\",\n        \"--no-build-isolation\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"requires_source\",\n    )\n    wheel_file_name = f\"source-1.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n    assert \"Successfully built source\" in result.stdout, result.stdout\n\n\ndef test_wheel_package_with_latin1_setup(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Create a wheel from a package with latin-1 encoded setup.py.\"\"\"\n\n    pkg_to_wheel = data.packages.joinpath(\"SetupPyLatin1\")\n    result = script.pip(\"wheel\", \"--no-build-isolation\", pkg_to_wheel)\n    assert \"Successfully built SetupPyUTF8\" in result.stdout\n\n\ndef test_pip_wheel_with_pep518_build_reqs(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path\n) -> None:\n    result = script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"-f\",\n        common_wheels,\n        \"pep518==3.0\",\n    )\n    wheel_file_name = f\"pep518-3.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n    assert \"Successfully built pep518\" in result.stdout, result.stdout\n    assert \"Installing build dependencies\" in result.stdout, result.stdout\n\n\ndef test_pip_wheel_with_pep518_build_reqs_no_isolation(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    script.pip_install_local(\"simplewheel==2.0\")\n    result = script.pip(\n        \"wheel\",\n        \"--no-index\",\n        \"-f\",\n        data.find_links,\n        \"--no-build-isolation\",\n        \"pep518==3.0\",\n    )\n    wheel_file_name = f\"pep518-3.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n    assert \"Successfully built pep518\" in result.stdout, result.stdout\n    assert \"Installing build dependencies\" not in result.stdout, result.stdout\n\n\ndef test_pip_wheel_with_user_set_in_config(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path\n) -> None:\n    config_file = script.scratch_path / \"pip.conf\"\n    script.environ[\"PIP_CONFIG_FILE\"] = str(config_file)\n    config_file.write_text(\"[install]\\nuser = true\")\n    result = script.pip(\n        \"wheel\", data.src / \"withpyproject\", \"--no-index\", \"-f\", common_wheels\n    )\n    assert \"Successfully built withpyproject\" in result.stdout, result.stdout\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"win\"),\n    reason=\"The empty extension module does not work on Win\",\n)\ndef test_pip_wheel_ext_module_with_tmpdir_inside(\n    script: PipTestEnvironment, data: TestData, common_wheels: Path\n) -> None:\n    tmpdir = data.src / \"extension/tmp\"\n    tmpdir.mkdir()\n    script.environ[\"TMPDIR\"] = str(tmpdir)\n\n    # To avoid a test dependency on a C compiler, we set the env vars to \"noop\"\n    # The .c source is empty anyway\n    script.environ[\"CC\"] = script.environ[\"LDSHARED\"] = \"true\"\n\n    result = script.pip(\n        \"wheel\", data.src / \"extension\", \"--no-index\", \"-f\", common_wheels\n    )\n    assert \"Successfully built extension\" in result.stdout, result.stdout\n\n\ndef test_pep517_wheels_are_not_confused_with_other_files(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Check correct wheels are copied. (#6196)\"\"\"\n    pkg_to_wheel = data.src / \"withpyproject\"\n    add_files_to_dist_directory(pkg_to_wheel)\n\n    result = script.pip(\n        \"wheel\",\n        pkg_to_wheel,\n        \"-w\",\n        script.scratch_path,\n        \"--no-index\",\n        \"-f\",\n        data.common_wheels,\n    )\n    assert \"Installing build dependencies\" in result.stdout, result.stdout\n\n    wheel_file_name = f\"withpyproject-0.0.1-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n\n\ndef test_legacy_wheels_are_not_confused_with_other_files(\n    script: PipTestEnvironment, data: TestData\n) -> None:\n    \"\"\"Check correct wheels are copied. (#6196)\"\"\"\n    pkg_to_wheel = data.src / \"simplewheel-1.0\"\n    add_files_to_dist_directory(pkg_to_wheel)\n\n    result = script.pip(\n        \"wheel\", \"--no-build-isolation\", pkg_to_wheel, \"-w\", script.scratch_path\n    )\n    assert \"Installing build dependencies\" not in result.stdout, result.stdout\n\n    wheel_file_name = f\"simplewheel-1.0-py{pyversion[0]}-none-any.whl\"\n    wheel_file_path = script.scratch / wheel_file_name\n    result.did_create(wheel_file_path)\n"
  },
  {
    "path": "tests/lib/__init__.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport json\nimport os\nimport pathlib\nimport re\nimport shutil\nimport site\nimport subprocess\nimport sys\nimport textwrap\nfrom base64 import urlsafe_b64encode\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom contextlib import contextmanager\nfrom hashlib import sha256\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom textwrap import dedent\nfrom typing import Any, AnyStr, Callable, Literal, Protocol, Union, cast\nfrom urllib.request import pathname2url\nfrom zipfile import ZipFile\n\nimport pytest\nfrom scripttest import FoundDir, FoundFile, ProcResult, TestFileEnvironment\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli.main import main as pip_entry_point\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.locations import get_major_minor_version\nfrom pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\n\nfrom tests.lib.filesystem import create_file\nfrom tests.lib.venv import VirtualEnvironment\nfrom tests.lib.wheel import make_wheel\n\nResolverVariant = Literal[\"resolvelib\", \"legacy\"]\n\nDATA_DIR = pathlib.Path(__file__).parent.parent.joinpath(\"data\").resolve()\nSRC_DIR = pathlib.Path(__file__).resolve().parent.parent.parent\n\npyversion = get_major_minor_version()\n\nCURRENT_PY_VERSION_INFO = sys.version_info[:3]\n\n_Test = Callable[..., None]\n_FilesState = dict[str, Union[FoundDir, FoundFile]]\n\n\ndef make_test_search_scope(\n    find_links: list[str] | None = None,\n    index_urls: list[str] | None = None,\n) -> SearchScope:\n    if find_links is None:\n        find_links = []\n    if index_urls is None:\n        index_urls = []\n\n    return SearchScope.create(\n        find_links=find_links,\n        index_urls=index_urls,\n        no_index=False,\n    )\n\n\ndef make_test_link_collector(\n    find_links: list[str] | None = None,\n    index_urls: list[str] | None = None,\n    session: PipSession | None = None,\n) -> LinkCollector:\n    \"\"\"\n    Create a LinkCollector object for testing purposes.\n    \"\"\"\n    if session is None:\n        session = PipSession()\n\n    search_scope = make_test_search_scope(\n        find_links=find_links,\n        index_urls=index_urls,\n    )\n\n    return LinkCollector(session=session, search_scope=search_scope)\n\n\ndef make_test_finder(\n    find_links: list[str] | None = None,\n    index_urls: list[str] | None = None,\n    allow_all_prereleases: bool = False,\n    session: PipSession | None = None,\n    target_python: TargetPython | None = None,\n    uploaded_prior_to: datetime.datetime | None = None,\n) -> PackageFinder:\n    \"\"\"\n    Create a PackageFinder for testing purposes.\n    \"\"\"\n    link_collector = make_test_link_collector(\n        find_links=find_links,\n        index_urls=index_urls,\n        session=session,\n    )\n\n    # Convert allow_all_prereleases to release_control\n    release_control = ReleaseControl()\n    if allow_all_prereleases:\n        release_control.all_releases.add(\":all:\")\n\n    selection_prefs = SelectionPreferences(\n        allow_yanked=True,\n        release_control=release_control,\n    )\n\n    return PackageFinder.create(\n        link_collector=link_collector,\n        selection_prefs=selection_prefs,\n        target_python=target_python,\n        uploaded_prior_to=uploaded_prior_to,\n    )\n\n\nclass TestData:\n    \"\"\"\n    Represents a bundle of pre-created test data.\n\n    This copies a pristine set of test data into a root location that is\n    designed to be test specific. The reason for this is when running the tests\n    concurrently errors can be generated because the related tooling uses\n    the directory as a work space. This leads to two concurrent processes\n    trampling over each other. This class gets around that by copying all\n    data into a directory and operating on the copied data.\n    \"\"\"\n\n    __test__ = False\n\n    def __init__(\n        self,\n        root: pathlib.Path,\n        source: pathlib.Path | None = None,\n    ) -> None:\n        self.source = source or DATA_DIR\n        self.root = root.resolve()\n\n    @classmethod\n    def copy(cls, root: pathlib.Path) -> TestData:\n        obj = cls(root)\n        obj.reset()\n        return obj\n\n    def reset(self) -> None:\n        # Check explicitly for the target directory to avoid overly-broad\n        # try/except.\n        if self.root.exists():\n            shutil.rmtree(self.root)\n        shutil.copytree(self.source, self.root, symlinks=True)\n\n    @property\n    def packages(self) -> pathlib.Path:\n        return self.root.joinpath(\"packages\")\n\n    @property\n    def packages2(self) -> pathlib.Path:\n        return self.root.joinpath(\"packages2\")\n\n    @property\n    def packages3(self) -> pathlib.Path:\n        return self.root.joinpath(\"packages3\")\n\n    @property\n    def pypi_packages(self) -> pathlib.Path:\n        return self.root.joinpath(\"pypi_packages\")\n\n    @property\n    def src(self) -> pathlib.Path:\n        return self.root.joinpath(\"src\")\n\n    @property\n    def indexes(self) -> pathlib.Path:\n        return self.root.joinpath(\"indexes\")\n\n    @property\n    def reqfiles(self) -> pathlib.Path:\n        return self.root.joinpath(\"reqfiles\")\n\n    @property\n    def completion_paths(self) -> pathlib.Path:\n        return self.root.joinpath(\"completion_paths\")\n\n    @property\n    def find_links(self) -> str:\n        return self.packages.as_uri()\n\n    @property\n    def find_links2(self) -> str:\n        return self.packages2.as_uri()\n\n    @property\n    def find_links3(self) -> str:\n        return self.packages3.as_uri()\n\n    @property\n    def backends(self) -> str:\n        return self.root.joinpath(\"backends\").as_uri()\n\n    def index_url(self, index: str = \"simple\") -> str:\n        return self.root.joinpath(\"indexes\", index).as_uri()\n\n    @property\n    def common_wheels(self) -> pathlib.Path:\n        # This is logically separate from the rest of the test data, but\n        # it's convenient to include here.\n        return DATA_DIR.joinpath(\"common_wheels\")\n\n\nclass TestFailure(AssertionError):\n    \"\"\"\n    An \"assertion\" failed during testing.\n    \"\"\"\n\n\nStrPath = Union[str, pathlib.Path]\n\n\nclass FoundFiles(Mapping[StrPath, FoundFile]):\n    def __init__(self, paths: Mapping[str, FoundFile]) -> None:\n        self._paths = {pathlib.Path(k): v for k, v in paths.items()}\n\n    def __contains__(self, o: object) -> bool:\n        if isinstance(o, pathlib.Path):\n            return o in self._paths\n        elif isinstance(o, str):\n            return pathlib.Path(o) in self._paths\n        return False\n\n    def __len__(self) -> int:\n        return len(self._paths)\n\n    def __getitem__(self, k: StrPath) -> FoundFile:\n        if isinstance(k, pathlib.Path):\n            return self._paths[k]\n        elif isinstance(k, str):\n            return self._paths[pathlib.Path(k)]\n        raise KeyError(k)\n\n    def __iter__(self) -> Iterator[pathlib.Path]:\n        return iter(self._paths)\n\n\nclass TestPipResult:\n    __test__ = False\n\n    def __init__(self, impl: ProcResult, verbose: bool = False) -> None:\n        self._impl = impl\n\n        if verbose:\n            print(self.stdout)\n            if self.stderr:\n                print(\"======= stderr ========\")\n                print(self.stderr)\n                print(\"=======================\")\n\n    def __getattr__(self, attr: str) -> Any:\n        return getattr(self._impl, attr)\n\n    if sys.platform == \"win32\":\n\n        @property\n        def stdout(self) -> str:\n            return self._impl.stdout.replace(\"\\r\\n\", \"\\n\")\n\n        @property\n        def stderr(self) -> str:\n            return self._impl.stderr.replace(\"\\r\\n\", \"\\n\")\n\n        def __str__(self) -> str:\n            return str(self._impl).replace(\"\\r\\n\", \"\\n\")\n\n    else:\n        # Python doesn't automatically forward __str__ through __getattr__\n\n        def __str__(self) -> str:\n            return str(self._impl)\n\n    @property\n    def files_created(self) -> FoundFiles:\n        return FoundFiles(self._impl.files_created)\n\n    @property\n    def files_updated(self) -> FoundFiles:\n        return FoundFiles(self._impl.files_updated)\n\n    @property\n    def files_deleted(self) -> FoundFiles:\n        return FoundFiles(self._impl.files_deleted)\n\n    def get_created_direct_url_path(self, pkg: str) -> Path | None:\n        dist_info_prefix = canonicalize_name(pkg).replace(\"-\", \"_\") + \"-\"\n        for filename in self.files_created:\n            if (\n                filename.name == DIRECT_URL_METADATA_NAME\n                and filename.parent.name.endswith(\".dist-info\")\n                and filename.parent.name.startswith(dist_info_prefix)\n            ):\n                return self.test_env.base_path / filename\n        return None\n\n    def get_created_direct_url(self, pkg: str) -> DirectUrl | None:\n        direct_url_path = self.get_created_direct_url_path(pkg)\n        if direct_url_path:\n            with open(direct_url_path) as f:\n                return DirectUrl.from_json(f.read())\n        return None\n\n    def assert_installed(\n        self,\n        pkg_name: str,\n        *,\n        dist_name: str | None = None,\n        editable: bool = True,\n        editable_vcs: bool = True,\n        with_files: list[str] | None = None,\n        without_files: list[str] | None = None,\n        sub_dir: str | None = None,\n    ) -> None:\n        if dist_name is None:\n            dist_name = pkg_name\n        with_files = with_files or []\n        without_files = without_files or []\n        e = self.test_env\n\n        if editable and editable_vcs:\n            pkg_dir = e.venv / \"src\" / canonicalize_name(dist_name)\n            # If package was installed in a sub directory\n            if sub_dir:\n                pkg_dir = pkg_dir / sub_dir\n        elif editable and not editable_vcs:\n            pkg_dir = None\n            assert not with_files\n            assert not without_files\n        else:\n            pkg_dir = e.site_packages / pkg_name\n\n        direct_url = self.get_created_direct_url(dist_name)\n        if not editable:\n            if direct_url and direct_url.is_local_editable():\n                raise TestFailure(\n                    \"unexpected editable direct_url.json created: \"\n                    f\"{self.get_created_direct_url_path(dist_name)!r}\\n\"\n                    f\"{self}\"\n                )\n        else:\n            if not direct_url or not direct_url.is_local_editable():\n                raise TestFailure(\n                    f\"{dist_name!r} not installed as editable: direct_url.json \"\n                    \"not found or not editable\\n\"\n                    f\"{self.get_created_direct_url_path(dist_name)!r}\\n\"\n                    f\"{self}\"\n                )\n\n        if pkg_dir and (pkg_dir in self.files_created) == (os.curdir in without_files):\n            maybe = \"not \" if os.curdir in without_files else \"\"\n            files = sorted(p.as_posix() for p in self.files_created)\n            raise TestFailure(\n                textwrap.dedent(\n                    f\"\"\"\n                    expected package directory {pkg_dir!r} {maybe}to be created\n                    actually created:\n                    {files}\n                    \"\"\"\n                )\n            )\n\n        for f in with_files:\n            normalized_path = os.path.normpath(pkg_dir / f)\n            if normalized_path not in self.files_created:\n                raise TestFailure(\n                    f\"Package directory {pkg_dir!r} missing expected content {f!r}\"\n                )\n\n        for f in without_files:\n            normalized_path = os.path.normpath(pkg_dir / f)\n            if normalized_path in self.files_created:\n                raise TestFailure(\n                    f\"Package directory {pkg_dir!r} has unexpected content {f}\"\n                )\n\n    def did_create(self, path: StrPath, message: str | None = None) -> None:\n        assert path in self.files_created, _one_or_both(message, self)\n\n    def did_not_create(self, p: StrPath, message: str | None = None) -> None:\n        assert p not in self.files_created, _one_or_both(message, self)\n\n    def did_update(self, path: StrPath, message: str | None = None) -> None:\n        assert path in self.files_updated, _one_or_both(message, self)\n\n    def did_not_update(self, p: StrPath, message: str | None = None) -> None:\n        assert p not in self.files_updated, _one_or_both(message, self)\n\n\ndef _one_or_both(a: str | None, b: Any) -> str:\n    \"\"\"Returns f\"{a}\\n{b}\" if a is truthy, else returns str(b).\"\"\"\n    if not a:\n        return str(b)\n\n    return f\"{a}\\n{b}\"\n\n\ndef make_check_stderr_message(stderr: str, line: str, reason: str) -> str:\n    \"\"\"\n    Create an exception message to use inside check_stderr().\n    \"\"\"\n    return dedent(\n        \"\"\"\\\n    {reason}:\n     Caused by line: {line!r}\n     Complete stderr: {stderr}\n    \"\"\"\n    ).format(stderr=stderr, line=line, reason=reason)\n\n\ndef _check_stderr(\n    stderr: str,\n    allow_stderr_warning: bool,\n    allow_stderr_error: bool,\n) -> None:\n    \"\"\"\n    Check the given stderr for logged warnings and errors.\n\n    :param stderr: stderr output as a string.\n    :param allow_stderr_warning: whether a logged warning (or deprecation\n        message) is allowed. Must be True if allow_stderr_error is True.\n    :param allow_stderr_error: whether a logged error is allowed.\n    \"\"\"\n    assert not (allow_stderr_error and not allow_stderr_warning)\n\n    lines = stderr.splitlines()\n    for line in lines:\n        line = line.lstrip()\n        # First check for logging errors, which we don't allow during\n        # tests even if allow_stderr_error=True (since a logging error\n        # would signal a bug in pip's code).\n        #    Unlike errors logged with logger.error(), these errors are\n        # sent directly to stderr and so bypass any configured log formatter.\n        # The \"--- Logging error ---\" string is used in Python 3.4+, and\n        # \"Logged from file \" is used in Python 2.\n        if line.startswith((\"--- Logging error ---\", \"Logged from file \")):\n            reason = \"stderr has a logging error, which is never allowed\"\n            msg = make_check_stderr_message(stderr, line=line, reason=reason)\n            raise RuntimeError(msg)\n        if allow_stderr_error:\n            continue\n\n        if line.startswith(\"ERROR: \"):\n            reason = (\n                \"stderr has an unexpected error \"\n                \"(pass allow_stderr_error=True to permit this)\"\n            )\n            msg = make_check_stderr_message(stderr, line=line, reason=reason)\n            raise RuntimeError(msg)\n        if allow_stderr_warning:\n            continue\n\n        if line.startswith(\"WARNING: \"):\n            reason = (\n                \"stderr has an unexpected warning \"\n                \"(pass allow_stderr_warning=True to permit this)\"\n            )\n            msg = make_check_stderr_message(stderr, line=line, reason=reason)\n            raise RuntimeError(msg)\n\n\nclass PipTestEnvironment(TestFileEnvironment):\n    \"\"\"\n    A specialized TestFileEnvironment for testing pip\n    \"\"\"\n\n    #\n    # Attribute naming convention\n    # ---------------------------\n    #\n    # Instances of this class have many attributes representing paths\n    # in the filesystem.  To keep things straight, absolute paths have\n    # a name of the form xxxx_path and relative paths have a name that\n    # does not end in '_path'.\n\n    exe = sys.platform == \"win32\" and \".exe\" or \"\"\n    verbose = False\n\n    def __init__(\n        self,\n        base_path: pathlib.Path,\n        *args: Any,\n        virtualenv: VirtualEnvironment,\n        pip_expect_warning: bool = False,\n        zipapp: str | None = None,\n        **kwargs: Any,\n    ) -> None:\n        # Store paths related to the virtual environment\n        self.venv_path = virtualenv.location\n        self.lib_path = virtualenv.lib\n        self.site_packages_path = virtualenv.site\n        self.bin_path = virtualenv.bin\n\n        assert site.USER_BASE is not None\n        assert site.USER_SITE is not None\n\n        self.user_base_path = self.venv_path.joinpath(\"user\")\n        self.user_site_path = self.venv_path.joinpath(\n            \"user\",\n            site.USER_SITE[len(site.USER_BASE) + 1 :],\n        )\n        if sys.platform == \"win32\":\n            scripts_base = self.user_site_path.joinpath(\"..\").resolve()\n            self.user_bin_path = scripts_base.joinpath(\"Scripts\")\n        else:\n            self.user_bin_path = self.user_base_path.joinpath(\n                os.path.relpath(self.bin_path, self.venv_path)\n            )\n\n        # Create a Directory to use as a scratch pad\n        self.scratch_path = base_path.joinpath(\"scratch\")\n        self.scratch_path.mkdir()\n\n        # Set our default working directory\n        kwargs.setdefault(\"cwd\", self.scratch_path)\n\n        # Setup our environment\n        environ = kwargs.setdefault(\"environ\", os.environ.copy())\n        environ[\"PATH\"] = os.pathsep.join(\n            [os.fspath(self.bin_path), environ.get(\"PATH\", \"\")],\n        )\n        environ[\"PYTHONUSERBASE\"] = self.user_base_path\n        # Writing bytecode can mess up updated file detection\n        environ[\"PYTHONDONTWRITEBYTECODE\"] = \"1\"\n        # Make sure we get UTF-8 on output, even on Windows...\n        environ[\"PYTHONIOENCODING\"] = \"UTF-8\"\n\n        # Whether all pip invocations should expect stderr\n        # (useful for Python version deprecation)\n        self.pip_expect_warning = pip_expect_warning\n\n        # The name of an (optional) zipapp to use when running pip\n        self.zipapp = zipapp\n\n        # Call the TestFileEnvironment __init__\n        super().__init__(base_path, *args, **kwargs)\n\n        # Expand our absolute path directories into relative\n        for name in [\n            \"base\",\n            \"venv\",\n            \"bin\",\n            \"lib\",\n            \"site_packages\",\n            \"user_base\",\n            \"user_site\",\n            \"user_bin\",\n            \"scratch\",\n        ]:\n            real_name = f\"{name}_path\"\n            relative_path = pathlib.Path(\n                os.path.relpath(getattr(self, real_name), self.base_path)\n            )\n            setattr(self, name, relative_path)\n\n        # Make sure temp_path is a Path object\n        self.temp_path: pathlib.Path = pathlib.Path(self.temp_path)\n        # Ensure the tmp dir exists, things break horribly if it doesn't\n        self.temp_path.mkdir()\n\n        # create easy-install.pth in user_site, so we always have it updated\n        #   instead of created\n        self.user_site_path.mkdir(parents=True)\n        self.user_site_path.joinpath(\"easy-install.pth\").touch()\n\n    def _ignore_file(self, fn: str) -> bool:\n        if fn.endswith((\"__pycache__\", \".pyc\")):\n            result = True\n        elif self.zipapp and fn.endswith(\"cacert.pem\"):\n            # Temporary copies of cacert.pem are extracted\n            # when running from a zipapp\n            result = True\n        else:\n            result = super()._ignore_file(fn)\n        return result\n\n    def _find_traverse(self, path: str, result: dict[str, FoundDir]) -> None:\n        # Ignore symlinked directories to avoid duplicates in `run()`\n        # results because of venv `lib64 -> lib/` symlink on Linux.\n        full = os.path.join(self.base_path, path)\n        if os.path.isdir(full) and os.path.islink(full):\n            if not self.temp_path or path != \"tmp\":\n                result[path] = FoundDir(self.base_path, path)\n        else:\n            super()._find_traverse(path, result)\n\n    def run(\n        self,\n        *args: str,\n        cwd: StrPath | None = None,\n        allow_stderr_error: bool | None = None,\n        allow_stderr_warning: bool | None = None,\n        allow_error: bool = False,\n        **kw: Any,\n    ) -> TestPipResult:\n        \"\"\"\n        :param allow_stderr_error: whether a logged error is allowed in\n            stderr.  Passing True for this argument implies\n            `allow_stderr_warning` since warnings are weaker than errors.\n        :param allow_stderr_warning: whether a logged warning (or\n            deprecation message) is allowed in stderr.\n        :param allow_error: if True (default is False) does not raise\n            exception when the command exit value is non-zero.  Implies\n            expect_error, but in contrast to expect_error will not assert\n            that the exit value is zero.\n        :param expect_error: if False (the default), asserts that the command\n            exits with 0.  Otherwise, asserts that the command exits with a\n            non-zero exit code.  Passing True also implies allow_stderr_error\n            and allow_stderr_warning.\n        :param expect_stderr: whether to allow warnings in stderr (equivalent\n            to `allow_stderr_warning`).  This argument is an abbreviated\n            version of `allow_stderr_warning` and is also kept for backwards\n            compatibility.\n        \"\"\"\n        if self.verbose:\n            print(f\">> running {args} {kw}\")\n\n        cwd = cwd or self.cwd\n        if sys.platform == \"win32\":\n            # Partial fix for ScriptTest.run using `shell=True` on Windows.\n            args = tuple(re.sub(\"([&|<>^])\", r\"^\\1\", str(a)) for a in args)\n\n        if allow_error:\n            kw[\"expect_error\"] = True\n\n        # Propagate default values.\n        expect_error = kw.get(\"expect_error\")\n        if expect_error:\n            # Then default to allowing logged errors.\n            if allow_stderr_error is not None and not allow_stderr_error:\n                raise RuntimeError(\n                    \"cannot pass allow_stderr_error=False with expect_error=True\"\n                )\n            allow_stderr_error = True\n\n        elif kw.get(\"expect_stderr\"):\n            # Then default to allowing logged warnings.\n            if allow_stderr_warning is not None and not allow_stderr_warning:\n                raise RuntimeError(\n                    \"cannot pass allow_stderr_warning=False with expect_stderr=True\"\n                )\n            allow_stderr_warning = True\n\n        if allow_stderr_error:\n            if allow_stderr_warning is not None and not allow_stderr_warning:\n                raise RuntimeError(\n                    \"cannot pass allow_stderr_warning=False with \"\n                    \"allow_stderr_error=True\"\n                )\n\n        # Default values if not set.\n        if allow_stderr_error is None:\n            allow_stderr_error = False\n        if allow_stderr_warning is None:\n            allow_stderr_warning = allow_stderr_error\n\n        # Pass expect_stderr=True to allow any stderr.  We do this because\n        # we do our checking of stderr further on in check_stderr().\n        kw[\"expect_stderr\"] = True\n        # Ignore linter check\n        # B026 Star-arg unpacking after a keyword argument is strongly discouraged\n        result = super().run(cwd=cwd, *args, **kw)  # noqa: B026\n\n        if expect_error and not allow_error:\n            if result.returncode == 0:\n                __tracebackhide__ = True\n                raise AssertionError(f\"Script passed unexpectedly:\\n{result}\")\n\n        _check_stderr(\n            result.stderr,\n            allow_stderr_error=allow_stderr_error,\n            allow_stderr_warning=allow_stderr_warning,\n        )\n\n        return TestPipResult(result, verbose=self.verbose)\n\n    def pip(\n        self,\n        *args: StrPath,\n        use_module: bool = True,\n        **kwargs: Any,\n    ) -> TestPipResult:\n        __tracebackhide__ = True\n        if self.pip_expect_warning:\n            kwargs[\"allow_stderr_warning\"] = True\n        if self.zipapp:\n            exe = \"python\"\n            args = (self.zipapp,) + args\n        elif use_module:\n            exe = \"python\"\n            args = (\"-m\", \"pip\") + args\n        else:\n            exe = \"pip\"\n        return self.run(exe, *(os.fspath(a) for a in args), **kwargs)\n\n    def pip_install_local(\n        self,\n        *args: StrPath,\n        find_links: StrPath | list[StrPath] = pathlib.Path(DATA_DIR, \"packages\"),\n        build_isolation: bool = False,\n        **kwargs: Any,\n    ) -> TestPipResult:\n        \"\"\"\n        Invoke pip install without PyPI access. By default, only local\n        packages are included via --find-links.\n        \"\"\"\n        # Convert find links paths to absolute file: URIs\n        if not isinstance(find_links, list):\n            find_links = [find_links]\n        find_links_args: list[StrPath] = []\n        for folder in find_links:\n            # Don't rewrite paths that are already file URIs\n            if isinstance(folder, str) and folder.startswith(\"file:\"):\n                find_links_args.extend((\"--find-links\", folder))\n            else:\n                path = pathlib.Path(folder).resolve()\n                find_links_args.extend((\"--find-links\", path.as_uri()))\n\n        cmd = [\"install\", \"--no-index\", *find_links_args, *args]\n        if not build_isolation:\n            cmd.insert(1, \"--no-build-isolation\")\n        return self.pip(*cmd, **kwargs)\n\n    def pip_install_local_report(\n        self,\n        *args: StrPath,\n        find_links: StrPath | list[StrPath] = pathlib.Path(DATA_DIR, \"packages\"),\n        **kwargs: Any,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Invoke pip install with --dry-run --report and return parsed JSON report.\n        Includes --no-index and --find-links like pip_install_local.\n        \"\"\"\n        result = self.pip_install_local(\n            \"--dry-run\",\n            \"--report\",\n            \"-\",\n            \"--quiet\",\n            *args,\n            find_links=find_links,\n            **kwargs,\n        )\n        return json.loads(result.stdout)\n\n    def easy_install(self, *args: str, **kwargs: Any) -> TestPipResult:\n        args = (\"-m\", \"easy_install\") + args\n        return self.run(\"python\", *args, **kwargs)\n\n    def assert_installed(self, **kwargs: str) -> None:\n        ret = self.pip(\"list\", \"--format=json\")\n        installed = {\n            (canonicalize_name(val[\"name\"]), val[\"version\"])\n            for val in json.loads(ret.stdout)\n        }\n        expected = {(canonicalize_name(k), v) for k, v in kwargs.items()}\n        assert expected <= installed, f\"{expected!r} not all in {installed!r}\"\n\n    def assert_not_installed(self, *args: str) -> None:\n        ret = self.pip(\"list\", \"--format=json\")\n        installed = {canonicalize_name(val[\"name\"]) for val in json.loads(ret.stdout)}\n        # None of the given names should be listed as installed, i.e. their\n        # intersection should be empty.\n        expected = {canonicalize_name(k) for k in args}\n        assert not (expected & installed), f\"{expected!r} contained in {installed!r}\"\n\n    def assert_installed_editable(self, dist_name: str) -> None:\n        dist_name = canonicalize_name(dist_name)\n        ret = self.pip(\"list\", \"--format=json\")\n        installed = json.loads(ret.stdout)\n        assert any(\n            x\n            for x in installed\n            if canonicalize_name(x[\"name\"]) == dist_name\n            and x.get(\"editable_project_location\")\n        )\n\n    def temporary_file(\n        self, filename: str | pathlib.Path, contents: str\n    ) -> pathlib.Path:\n        \"\"\"Create a temporary file with the given filename and contents.\"\"\"\n        path = self.scratch_path.joinpath(filename)\n        create_file(path, contents)\n        return path\n\n    def temporary_multiline_file(\n        self, filename: str | pathlib.Path, contents: str\n    ) -> pathlib.Path:\n        \"\"\"Like temporary_file() but calls textwrap.dedent beforehand.\"\"\"\n        return self.temporary_file(filename, textwrap.dedent(contents))\n\n\n# FIXME ScriptTest does something similar, but only within a single\n# ProcResult; this generalizes it so states can be compared across\n# multiple commands.  Maybe should be rolled into ScriptTest?\ndef diff_states(\n    start: _FilesState, end: _FilesState, ignore: Iterable[StrPath] = ()\n) -> dict[str, _FilesState]:\n    \"\"\"\n    Differences two \"filesystem states\" as represented by dictionaries\n    of FoundFile and FoundDir objects.\n\n    Returns a dictionary with following keys:\n\n    ``deleted``\n        Dictionary of files/directories found only in the start state.\n\n    ``created``\n        Dictionary of files/directories found only in the end state.\n\n    ``updated``\n        Dictionary of files whose size has changed (FIXME not entirely\n        reliable, but comparing contents is not possible because\n        FoundFile.bytes is lazy, and comparing mtime doesn't help if\n        we want to know if a file has been returned to its earlier\n        state).\n\n    Ignores mtime and other file attributes; only presence/absence and\n    size are considered.\n\n    \"\"\"\n\n    def prefix_match(path: str, prefix_path: StrPath) -> bool:\n        prefix = os.fspath(prefix_path)\n        if path == prefix:\n            return True\n        prefix = prefix.rstrip(os.path.sep) + os.path.sep\n        return path.startswith(prefix)\n\n    start_keys = {k for k in start if not any(prefix_match(k, i) for i in ignore)}\n    end_keys = {k for k in end if not any(prefix_match(k, i) for i in ignore)}\n    deleted = {k: start[k] for k in start_keys.difference(end_keys)}\n    created = {k: end[k] for k in end_keys.difference(start_keys)}\n    updated = {}\n    for k in start_keys.intersection(end_keys):\n        if start[k].size != end[k].size:\n            updated[k] = end[k]\n    return {\"deleted\": deleted, \"created\": created, \"updated\": updated}\n\n\ndef assert_all_changes(\n    start_state: _FilesState | TestPipResult,\n    end_state: _FilesState | TestPipResult,\n    expected_changes: list[StrPath],\n) -> dict[str, _FilesState]:\n    \"\"\"\n    Fails if anything changed that isn't listed in the\n    expected_changes.\n\n    start_state is either a dict mapping paths to\n    scripttest.[FoundFile|FoundDir] objects or a TestPipResult whose\n    files_before we'll test.  end_state is either a similar dict or a\n    TestPipResult whose files_after we'll test.\n\n    Note: listing a directory means anything below\n    that directory can be expected to have changed.\n    \"\"\"\n    __tracebackhide__ = True\n\n    start_files = start_state\n    end_files = end_state\n    if isinstance(start_state, TestPipResult):\n        start_files = start_state.files_before\n    if isinstance(end_state, TestPipResult):\n        end_files = end_state.files_after\n    start_files = cast(_FilesState, start_files)\n    end_files = cast(_FilesState, end_files)\n\n    diff = diff_states(start_files, end_files, ignore=expected_changes)\n    if list(diff.values()) != [{}, {}, {}]:\n        raise TestFailure(\n            \"Unexpected changes:\\n\"\n            + \"\\n\".join([k + \": \" + \", \".join(v.keys()) for k, v in diff.items()])\n        )\n\n    # Don't throw away this potentially useful information\n    return diff\n\n\ndef _create_main_file(\n    dir_path: pathlib.Path,\n    name: str | None = None,\n    output: str | None = None,\n) -> None:\n    \"\"\"\n    Create a module with a main() function that prints the given output.\n    \"\"\"\n    if name is None:\n        name = \"version_pkg\"\n    if output is None:\n        output = \"0.1\"\n    text = textwrap.dedent(\n        f\"\"\"\n        def main():\n            print({output!r})\n        \"\"\"\n    )\n    filename = f\"{name}.py\"\n    dir_path.joinpath(filename).write_text(text)\n\n\ndef _git_commit(\n    env_or_script: PipTestEnvironment,\n    repo_dir: StrPath,\n    message: str | None = None,\n    allow_empty: bool = False,\n    stage_modified: bool = False,\n) -> None:\n    \"\"\"\n    Run git-commit.\n\n    Args:\n      env_or_script: pytest's `script` or `env` argument.\n      repo_dir: a path to a Git repository.\n      message: an optional commit message.\n    \"\"\"\n    if message is None:\n        message = \"test commit\"\n\n    args = []\n\n    if allow_empty:\n        args.append(\"--allow-empty\")\n\n    if stage_modified:\n        args.append(\"--all\")\n\n    new_args = [\n        \"git\",\n        \"commit\",\n        \"-q\",\n        \"--author\",\n        \"pip <distutils-sig@python.org>\",\n    ]\n    new_args.extend(args)\n    new_args.extend([\"-m\", message])\n    env_or_script.run(*new_args, cwd=repo_dir)\n\n\ndef _vcs_add(\n    location: pathlib.Path,\n    version_pkg_path: pathlib.Path,\n    vcs: str = \"git\",\n) -> pathlib.Path:\n    if vcs == \"git\":\n        subprocess.check_call([\"git\", \"init\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call([\"git\", \"add\", \".\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call(\n            [\"git\", \"commit\", \"-m\", \"initial version\"], cwd=os.fspath(version_pkg_path)\n        )\n    elif vcs == \"hg\":\n        subprocess.check_call([\"hg\", \"init\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call([\"hg\", \"add\", \".\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call(\n            [\n                \"hg\",\n                \"commit\",\n                \"-q\",\n                \"--user\",\n                \"pip <distutils-sig@python.org>\",\n                \"-m\",\n                \"initial version\",\n            ],\n            cwd=os.fspath(version_pkg_path),\n        )\n    elif vcs == \"svn\":\n        repo_url = _create_svn_repo(location, version_pkg_path)\n        subprocess.check_call(\n            [\"svn\", \"checkout\", repo_url, \"pip-test-package\"], cwd=os.fspath(location)\n        )\n        checkout_path = location / \"pip-test-package\"\n\n        version_pkg_path = checkout_path\n    elif vcs == \"bazaar\":\n        subprocess.check_call([\"bzr\", \"init\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call([\"bzr\", \"add\", \".\"], cwd=os.fspath(version_pkg_path))\n        subprocess.check_call(\n            [\"bzr\", \"whoami\", \"pip <distutils-sig@python.org>\"],\n            cwd=os.fspath(version_pkg_path),\n        )\n        subprocess.check_call(\n            [\n                \"bzr\",\n                \"commit\",\n                \"-q\",\n                \"--author\",\n                \"pip <distutils-sig@python.org>\",\n                \"-m\",\n                \"initial version\",\n            ],\n            cwd=os.fspath(version_pkg_path),\n        )\n    else:\n        raise ValueError(f\"Unknown vcs: {vcs}\")\n    return version_pkg_path\n\n\ndef _create_test_package_with_subdirectory(\n    script: PipTestEnvironment, subdirectory: str\n) -> pathlib.Path:\n    script.scratch_path.joinpath(\"version_pkg\").mkdir()\n    version_pkg_path = script.scratch_path / \"version_pkg\"\n    _create_main_file(version_pkg_path, name=\"version_pkg\", output=\"0.1\")\n    version_pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            from setuptools import setup, find_packages\n\n            setup(\n                name=\"version_pkg\",\n                version=\"0.1\",\n                packages=find_packages(),\n                py_modules=[\"version_pkg\"],\n                entry_points=dict(console_scripts=[\"version_pkg=version_pkg:main\"]),\n            )\n            \"\"\"\n        )\n    )\n\n    subdirectory_path = version_pkg_path.joinpath(subdirectory)\n    subdirectory_path.mkdir()\n    _create_main_file(subdirectory_path, name=\"version_subpkg\", output=\"0.1\")\n\n    subdirectory_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            from setuptools import find_packages, setup\n\n            setup(\n                name=\"version_subpkg\",\n                version=\"0.1\",\n                packages=find_packages(),\n                py_modules=[\"version_subpkg\"],\n                entry_points=dict(console_scripts=[\"version_pkg=version_subpkg:main\"]),\n            )\n            \"\"\"\n        )\n    )\n\n    script.run(\"git\", \"init\", cwd=version_pkg_path)\n    script.run(\"git\", \"add\", \".\", cwd=version_pkg_path)\n    _git_commit(script, version_pkg_path, message=\"initial version\")\n\n    return version_pkg_path\n\n\ndef _create_test_package_with_srcdir(\n    dir_path: pathlib.Path, name: str = \"version_pkg\", vcs: str = \"git\"\n) -> pathlib.Path:\n    dir_path.joinpath(name).mkdir()\n    version_pkg_path = dir_path / name\n    subdir_path = version_pkg_path.joinpath(\"subdir\")\n    subdir_path.mkdir()\n    src_path = subdir_path.joinpath(\"src\")\n    src_path.mkdir()\n    pkg_path = src_path.joinpath(\"pkg\")\n    pkg_path.mkdir()\n    pkg_path.joinpath(\"__init__.py\").write_text(\"\")\n    subdir_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            f\"\"\"\n                from setuptools import setup, find_packages\n                setup(\n                    name=\"{name}\",\n                    version=\"0.1\",\n                    packages=find_packages(),\n                    package_dir={{\"\": \"src\"}},\n                )\n            \"\"\"\n        )\n    )\n    return _vcs_add(dir_path, version_pkg_path, vcs)\n\n\ndef _create_test_package(\n    dir_path: pathlib.Path, name: str = \"version_pkg\", vcs: str = \"git\"\n) -> pathlib.Path:\n    dir_path.joinpath(name).mkdir()\n    version_pkg_path = dir_path / name\n    _create_main_file(version_pkg_path, name=name, output=\"0.1\")\n    version_pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            f\"\"\"\n                from setuptools import setup, find_packages\n                setup(\n                    name=\"{name}\",\n                    version=\"0.1\",\n                    packages=find_packages(),\n                    py_modules=[\"{name}\"],\n                    entry_points=dict(console_scripts=[\"{name}={name}:main\"]),\n                )\n            \"\"\"\n        )\n    )\n    return _vcs_add(dir_path, version_pkg_path, vcs)\n\n\ndef _create_svn_repo(repo_path: pathlib.Path, version_pkg_path: StrPath) -> str:\n    repo_url = repo_path.joinpath(\"pip-test-package-repo\", \"trunk\").as_uri()\n    subprocess.check_call(\n        \"svnadmin create pip-test-package-repo\".split(), cwd=repo_path\n    )\n    subprocess.check_call(\n        [\n            \"svn\",\n            \"import\",\n            os.fspath(version_pkg_path),\n            repo_url,\n            \"-m\",\n            \"Initial import of pip-test-package\",\n        ],\n        cwd=os.fspath(repo_path),\n    )\n    return repo_url\n\n\ndef _change_test_package_version(\n    script: PipTestEnvironment, version_pkg_path: pathlib.Path\n) -> None:\n    _create_main_file(\n        version_pkg_path, name=\"version_pkg\", output=\"some different version\"\n    )\n    # Pass -a to stage the change to the main file.\n    _git_commit(script, version_pkg_path, message=\"messed version\", stage_modified=True)\n\n\n@contextmanager\ndef requirements_file(contents: str, tmpdir: pathlib.Path) -> Iterator[pathlib.Path]:\n    \"\"\"Return a Path to a requirements file of given contents.\n\n    As long as the context manager is open, the requirements file will exist.\n\n    :param tmpdir: A Path to the folder in which to create the file\n\n    \"\"\"\n    path = tmpdir / \"reqs.txt\"\n    path.write_text(contents)\n    yield path\n    path.unlink()\n\n\ndef create_test_package_with_setup(\n    script: PipTestEnvironment, **setup_kwargs: Any\n) -> pathlib.Path:\n    assert \"name\" in setup_kwargs, setup_kwargs\n    pkg_path = script.scratch_path / setup_kwargs[\"name\"]\n    pkg_path.mkdir()\n    pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            f\"\"\"\n                from setuptools import setup\n                kwargs = {setup_kwargs!r}\n                setup(**kwargs)\n            \"\"\"\n        )\n    )\n    return pkg_path\n\n\ndef urlsafe_b64encode_nopad(data: bytes) -> str:\n    return urlsafe_b64encode(data).rstrip(b\"=\").decode(\"ascii\")\n\n\ndef create_really_basic_wheel(name: str, version: str) -> bytes:\n    def digest(contents: bytes) -> str:\n        return f\"sha256={urlsafe_b64encode_nopad(sha256(contents).digest())}\"\n\n    def add_file(path: str, text: str) -> None:\n        contents = text.encode(\"utf-8\")\n        z.writestr(path, contents)\n        records.append((path, digest(contents), str(len(contents))))\n\n    dist_info = f\"{name}-{version}.dist-info\"\n    record_path = f\"{dist_info}/RECORD\"\n    records = [(record_path, \"\", \"\")]\n    buf = BytesIO()\n    with ZipFile(buf, \"w\") as z:\n        add_file(\n            f\"{dist_info}/WHEEL\",\n            dedent(\n                \"\"\"\\\n                Wheel-Version: 1.0\n                Root-Is-Purelib: true\n                \"\"\"\n            ),\n        )\n        add_file(\n            f\"{dist_info}/METADATA\",\n            dedent(\n                f\"\"\"\\\n                Metadata-Version: 2.1\n                Name: {name}\n                Version: {version}\n                \"\"\"\n            ),\n        )\n        z.writestr(record_path, \"\\n\".join(\",\".join(r) for r in records))\n    buf.seek(0)\n    return buf.read()\n\n\ndef create_basic_wheel_for_package(\n    script: PipTestEnvironment,\n    name: str,\n    version: str,\n    depends: list[str] | None = None,\n    extras: dict[str, list[str]] | None = None,\n    requires_python: str | None = None,\n    extra_files: dict[str, bytes | str] | None = None,\n) -> pathlib.Path:\n    if depends is None:\n        depends = []\n    if extras is None:\n        extras = {}\n    if extra_files is None:\n        extra_files = {}\n\n    # Fix wheel distribution name by replacing runs of non-alphanumeric\n    # characters with an underscore _ as per PEP 491\n    name = re.sub(r\"[^\\w\\d.]+\", \"_\", name)\n    archive_name = f\"{name}-{version}-py2.py3-none-any.whl\"\n    archive_path = script.scratch_path / archive_name\n\n    package_init_py = f\"{name}/__init__.py\"\n    assert package_init_py not in extra_files\n    extra_files[package_init_py] = textwrap.dedent(\n        \"\"\"\n        __version__ = {version!r}\n        def hello():\n            return \"Hello From {name}\"\n        \"\"\",\n    ).format(version=version, name=name)\n\n    requires_dist = depends + [\n        f'{package}; extra == \"{extra}\"'\n        for extra, packages in extras.items()\n        for package in packages\n    ]\n\n    metadata_updates: dict[str, Any] = {\n        \"Provides-Extra\": list(extras),\n        \"Requires-Dist\": requires_dist,\n    }\n    if requires_python is not None:\n        metadata_updates[\"Requires-Python\"] = requires_python\n\n    wheel_builder = make_wheel(\n        name=name,\n        version=version,\n        wheel_metadata_updates={\"Tag\": [\"py2-none-any\", \"py3-none-any\"]},\n        metadata_updates=metadata_updates,\n        extra_metadata_files={\"top_level.txt\": name},\n        extra_files=extra_files,\n        # Have an empty RECORD because we don't want to be checking hashes.\n        record=\"\",\n    )\n    wheel_builder.save_to(archive_path)\n\n    return archive_path\n\n\ndef create_basic_sdist_for_package(\n    script: PipTestEnvironment,\n    name: str,\n    version: str,\n    extra_files: dict[str, str] | None = None,\n    *,\n    fails_build: bool = False,\n    depends: list[str] | None = None,\n    setup_py_prelude: str = \"\",\n) -> pathlib.Path:\n    files = {\n        \"setup.py\": textwrap.dedent(\n            \"\"\"\\\n            import sys\n            from setuptools import find_packages, setup\n\n            {setup_py_prelude}\n\n            fails_build = {fails_build!r}\n\n            if fails_build:\n                raise Exception(\"Simulated build failure.\")\n\n            setup(name={name!r}, version={version!r},\n                install_requires={depends!r})\n        \"\"\"\n        ).format(\n            name=name,\n            version=version,\n            depends=depends or [],\n            setup_py_prelude=setup_py_prelude,\n            fails_build=fails_build,\n        ),\n    }\n\n    # Some useful shorthands\n    archive_name = f\"{name}-{version}.tar.gz\"\n\n    # Add new files after formatting\n    if extra_files:\n        files.update(extra_files)\n\n    for fname in files:\n        path = script.temp_path / fname\n        path.parent.mkdir(exist_ok=True, parents=True)\n        path.write_bytes(files[fname].encode(\"utf-8\"))\n\n    retval = script.scratch_path / archive_name\n    generated = shutil.make_archive(\n        os.fspath(retval),\n        \"gztar\",\n        root_dir=script.temp_path,\n        base_dir=os.curdir,\n    )\n    shutil.move(generated, retval)\n\n    shutil.rmtree(script.temp_path)\n    script.temp_path.mkdir()\n\n    return retval\n\n\ndef need_executable(name: str, check_cmd: tuple[str, ...]) -> Callable[[_Test], _Test]:\n    def wrapper(fn: _Test) -> _Test:\n        try:\n            subprocess.check_output(check_cmd)\n        except (OSError, subprocess.CalledProcessError):\n            return pytest.mark.skip(reason=f\"{name} is not available\")(fn)\n        return fn\n\n    return wrapper\n\n\ndef is_bzr_installed() -> bool:\n    try:\n        subprocess.check_output((\"bzr\", \"version\", \"--short\"))\n    except OSError:\n        return False\n    return True\n\n\ndef is_svn_installed() -> bool:\n    try:\n        subprocess.check_output((\"svn\", \"--version\"))\n    except OSError:\n        return False\n    return True\n\n\ndef need_bzr(fn: _Test) -> _Test:\n    return pytest.mark.bzr(need_executable(\"Bazaar\", (\"bzr\", \"version\", \"--short\"))(fn))\n\n\ndef need_svn(fn: _Test) -> _Test:\n    return pytest.mark.svn(\n        need_executable(\"Subversion\", (\"svn\", \"--version\"))(\n            need_executable(\"Subversion Admin\", (\"svnadmin\", \"--version\"))(fn)\n        )\n    )\n\n\ndef need_mercurial(fn: _Test) -> _Test:\n    return pytest.mark.mercurial(need_executable(\"Mercurial\", (\"hg\", \"version\"))(fn))\n\n\nclass InMemoryPipResult:\n    def __init__(self, returncode: int, stdout: str) -> None:\n        self.returncode = returncode\n        self.stdout = stdout\n\n\nclass InMemoryPip:\n    def pip(self, *args: str | pathlib.Path) -> InMemoryPipResult:\n        orig_stdout = sys.stdout\n        stdout = StringIO()\n        sys.stdout = stdout\n        try:\n            returncode = pip_entry_point([os.fspath(a) for a in args])\n        except SystemExit as e:\n            if isinstance(e.code, int):\n                returncode = e.code\n            elif e.code:\n                returncode = 1\n            else:\n                returncode = 0\n        finally:\n            sys.stdout = orig_stdout\n        return InMemoryPipResult(returncode, stdout.getvalue())\n\n\nclass ScriptFactory(Protocol):\n    def __call__(\n        self,\n        tmpdir: pathlib.Path,\n        virtualenv: VirtualEnvironment | None = None,\n        environ: dict[AnyStr, AnyStr] | None = None,\n    ) -> PipTestEnvironment: ...\n\n\nCertFactory = Callable[[], str]\n\n# -------------------------------------------------------------------------\n# Accommodations for Windows path and URL changes in recent Python releases\n# -------------------------------------------------------------------------\n\n# Trailing slashes are now preserved on Windows, matching POSIX behaviour.\n# BPO: https://github.com/python/cpython/issues/126212\ndoes_pathname2url_preserve_trailing_slash = pathname2url(\"C:\\\\foo\\\\\").endswith(\"/\")\nskip_needs_new_pathname2url_trailing_slash_behavior_win = pytest.mark.skipif(\n    sys.platform != \"win32\" or not does_pathname2url_preserve_trailing_slash,\n    reason=\"testing windows (pathname2url) behavior for newer CPython\",\n)\nskip_needs_old_pathname2url_trailing_slash_behavior_win = pytest.mark.skipif(\n    sys.platform != \"win32\" or does_pathname2url_preserve_trailing_slash,\n    reason=\"testing windows (pathname2url) behavior for older CPython\",\n)\n"
  },
  {
    "path": "tests/lib/certs.py",
    "content": "from datetime import datetime, timedelta, timezone\n\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.x509.oid import ExtendedKeyUsageOID, NameOID\n\n\ndef make_tls_cert(hostname: str) -> tuple[x509.Certificate, rsa.RSAPrivateKey]:\n    key = rsa.generate_private_key(\n        public_exponent=65537, key_size=2048, backend=default_backend()\n    )\n    subject = issuer = x509.Name(\n        [\n            x509.NameAttribute(NameOID.COMMON_NAME, hostname),\n        ]\n    )\n    cert = (\n        x509.CertificateBuilder()\n        .subject_name(subject)\n        .issuer_name(issuer)\n        .public_key(key.public_key())\n        .serial_number(x509.random_serial_number())\n        .not_valid_before(datetime.now(timezone.utc))\n        .not_valid_after(datetime.now(timezone.utc) + timedelta(days=10))\n        .add_extension(\n            x509.BasicConstraints(ca=True, path_length=9),\n            critical=True,\n        )\n        .add_extension(\n            x509.SubjectAlternativeName([x509.DNSName(hostname)]),\n            critical=False,\n        )\n        .add_extension(\n            x509.ExtendedKeyUsage(\n                [\n                    ExtendedKeyUsageOID.CLIENT_AUTH,\n                    ExtendedKeyUsageOID.SERVER_AUTH,\n                ]\n            ),\n            critical=True,\n        )\n        .sign(key, hashes.SHA256(), default_backend())\n    )\n    return cert, key\n\n\ndef serialize_key(key: rsa.RSAPrivateKey) -> bytes:\n    return key.private_bytes(\n        encoding=serialization.Encoding.PEM,\n        format=serialization.PrivateFormat.TraditionalOpenSSL,\n        encryption_algorithm=serialization.NoEncryption(),\n    )\n\n\ndef serialize_cert(cert: x509.Certificate) -> bytes:\n    return cert.public_bytes(serialization.Encoding.PEM)\n"
  },
  {
    "path": "tests/lib/compat.py",
    "content": "# mypy: no-warn-unused-ignores\n\nimport contextlib\nimport signal\nfrom collections.abc import Iterator\nfrom contextlib import AbstractContextManager\nfrom typing import Callable\n\n# Applies on Windows.\nif not hasattr(signal, \"pthread_sigmask\"):\n    # We're not relying on this behavior anywhere currently, it's just best\n    # practice.\n    blocked_signals: Callable[[], AbstractContextManager[None]] = contextlib.nullcontext\nelse:\n\n    @contextlib.contextmanager\n    def blocked_signals() -> Iterator[None]:\n        \"\"\"Block all signals for e.g. starting a worker thread.\"\"\"\n        mask = signal.valid_signals()\n\n        old_mask = signal.pthread_sigmask(  # type: ignore[attr-defined]\n            signal.SIG_SETMASK,  # type: ignore[attr-defined]\n            mask,\n        )\n        try:\n            yield\n        finally:\n            signal.pthread_sigmask(  # type: ignore[attr-defined]\n                signal.SIG_SETMASK,  # type: ignore[attr-defined]\n                old_mask,\n            )\n"
  },
  {
    "path": "tests/lib/configuration_helpers.py",
    "content": "\"\"\"Helpers for tests that check configuration\"\"\"\n\nimport contextlib\nimport functools\nimport os\nimport tempfile\nimport textwrap\nfrom collections.abc import Iterator\nfrom typing import Any\n\nimport pip._internal.configuration\nfrom pip._internal.utils.misc import ensure_dir\n\n# This is so that tests don't need to import pip._internal.configuration.\nKind = pip._internal.configuration.Kind\nkinds = pip._internal.configuration.kinds\n\n\nclass ConfigurationMixin:\n    def setup_method(self) -> None:\n        self.configuration = pip._internal.configuration.Configuration(\n            isolated=False,\n        )\n\n    def patch_configuration(self, variant: Kind, di: dict[str, Any]) -> None:\n        old = self.configuration._load_config_files\n\n        @functools.wraps(old)\n        def overridden() -> None:\n            # Manual Overload\n            self.configuration._config[variant].setdefault(\"fakefile\", {})\n            self.configuration._config[variant][\"fakefile\"].update(di)\n            # Configuration._parsers has type:\n            # Dict[Kind, List[Tuple[str, RawConfigParser]]].\n            # As a testing convenience, pass a special value.\n            self.configuration._parsers[variant].append(\n                (None, None),  # type: ignore[arg-type]\n            )\n            old()\n\n        # https://github.com/python/mypy/issues/2427\n        self.configuration._load_config_files = overridden  # type: ignore[method-assign]\n\n    @contextlib.contextmanager\n    def tmpfile(self, contents: str) -> Iterator[str]:\n        # Create a temporary file\n        fd, path = tempfile.mkstemp(prefix=\"pip_\", suffix=\"_config.ini\", text=True)\n        os.close(fd)\n\n        contents = textwrap.dedent(contents).lstrip()\n        ensure_dir(os.path.dirname(path))\n        with open(path, \"w\") as f:\n            f.write(contents)\n\n        yield path\n\n        os.remove(path)\n"
  },
  {
    "path": "tests/lib/filesystem.py",
    "content": "\"\"\"Helpers for filesystem-dependent tests.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom itertools import chain\nfrom pathlib import Path\n\n\ndef get_filelist(base: str) -> set[str]:\n    def join(dirpath: str, dirnames: list[str], filenames: list[str]) -> Iterator[str]:\n        relative_dirpath = os.path.relpath(dirpath, base)\n        join_dirpath = partial(os.path.join, relative_dirpath)\n        return chain(\n            (join_dirpath(p) for p in dirnames),\n            (join_dirpath(p) for p in filenames),\n        )\n\n    return set(chain.from_iterable(join(*dirinfo) for dirinfo in os.walk(base)))\n\n\n@contextmanager\ndef chmod(path: str | Path, mode: int) -> Iterator[None]:\n    \"\"\"Contextmanager to temporarily update a path's mode.\"\"\"\n    old_mode = os.stat(path).st_mode\n    try:\n        os.chmod(path, mode)\n        yield\n    finally:\n        os.chmod(path, old_mode)\n\n\ndef create_file(path: str | Path, contents: str | None = None) -> None:\n    \"\"\"Create a file on the path, with the given contents\"\"\"\n    _path = Path(path)\n    _path.parent.mkdir(exist_ok=True, parents=True)\n    with _path.open(\"w\") as f:\n        if contents is not None:\n            f.write(contents)\n        else:\n            f.write(\"\\n\")\n"
  },
  {
    "path": "tests/lib/git_submodule_helpers.py",
    "content": "import os\nimport textwrap\nfrom pathlib import Path\n\nfrom tests.lib import PipTestEnvironment, _create_main_file, _git_commit\n\n\ndef _create_test_package_submodule(env: PipTestEnvironment) -> Path:\n    env.scratch_path.joinpath(\"version_pkg_submodule\").mkdir()\n    submodule_path = env.scratch_path / \"version_pkg_submodule\"\n    env.run(\"touch\", \"testfile\", cwd=submodule_path)\n    env.run(\"git\", \"init\", cwd=submodule_path)\n    env.run(\"git\", \"add\", \".\", cwd=submodule_path)\n    _git_commit(env, submodule_path, message=\"initial version / submodule\")\n\n    return submodule_path\n\n\ndef _change_test_package_submodule(\n    env: PipTestEnvironment, submodule_path: Path\n) -> None:\n    submodule_path.joinpath(\"testfile\").write_text(\"this is a changed file\")\n    submodule_path.joinpath(\"testfile2\").write_text(\"this is an added file\")\n    env.run(\"git\", \"add\", \".\", cwd=submodule_path)\n    _git_commit(env, submodule_path, message=\"submodule change\")\n\n\ndef _pull_in_submodule_changes_to_module(\n    env: PipTestEnvironment, module_path: Path, rel_path: str\n) -> None:\n    \"\"\"\n    Args:\n      rel_path: the location of the submodule relative to the superproject.\n    \"\"\"\n    submodule_path = module_path / rel_path\n    env.run(\"git\", \"pull\", \"-q\", \"origin\", \"master\", cwd=submodule_path)\n    # Pass -a to stage the submodule changes that were just pulled in.\n    _git_commit(env, module_path, message=\"submodule change\", stage_modified=True)\n\n\ndef _create_test_package_with_submodule(\n    env: PipTestEnvironment, rel_path: str\n) -> tuple[Path, Path]:\n    \"\"\"\n    Args:\n      rel_path: the location of the submodule relative to the superproject.\n    \"\"\"\n    env.scratch_path.joinpath(\"version_pkg\").mkdir()\n    version_pkg_path = env.scratch_path / \"version_pkg\"\n    version_pkg_path.joinpath(\"testpkg\").mkdir()\n    pkg_path = version_pkg_path / \"testpkg\"\n\n    pkg_path.joinpath(\"__init__.py\").write_text(\"# hello there\")\n    _create_main_file(pkg_path, name=\"version_pkg\", output=\"0.1\")\n    version_pkg_path.joinpath(\"setup.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n                        from setuptools import setup, find_packages\n                        setup(name='version_pkg',\n                              version='0.1',\n                              packages=find_packages(),\n                             )\n                        \"\"\"\n        )\n    )\n    env.run(\"git\", \"init\", cwd=version_pkg_path)\n    env.run(\"git\", \"add\", \".\", cwd=version_pkg_path)\n    _git_commit(env, version_pkg_path, message=\"initial version\")\n\n    submodule_path = _create_test_package_submodule(env)\n\n    env.run(\n        \"git\",\n        \"submodule\",\n        \"add\",\n        os.fspath(submodule_path),\n        rel_path,\n        cwd=version_pkg_path,\n    )\n    _git_commit(env, version_pkg_path, message=\"initial version w submodule\")\n\n    return version_pkg_path, submodule_path\n"
  },
  {
    "path": "tests/lib/index.py",
    "content": "from __future__ import annotations\n\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.link import Link\n\n\ndef make_mock_candidate(\n    version: str, yanked_reason: str | None = None, hex_digest: str | None = None\n) -> InstallationCandidate:\n    url = f\"https://example.com/pkg-{version}.tar.gz\"\n    if hex_digest is not None:\n        assert len(hex_digest) == 64\n        url += f\"#sha256={hex_digest}\"\n\n    link = Link(url, yanked_reason=yanked_reason)\n    candidate = InstallationCandidate(\"mypackage\", version, link)\n\n    return candidate\n"
  },
  {
    "path": "tests/lib/local_repos.py",
    "content": "import os\nimport subprocess\nimport urllib.request\nfrom pathlib import Path\n\nfrom pip._internal.utils.misc import hide_url\nfrom pip._internal.vcs import vcs\n\n\ndef _create_svn_initools_repo(initools_dir: str) -> None:\n    \"\"\"\n    Create the SVN INITools repo.\n    \"\"\"\n    directory = os.path.dirname(initools_dir)\n    subprocess.check_call(\"svnadmin create INITools\".split(), cwd=directory)\n\n    filename, _ = urllib.request.urlretrieve(\n        \"http://bitbucket.org/hltbra/pip-initools-dump/raw/8b55c908a320/\"\n        \"INITools_modified.dump\"\n    )\n    with open(filename, \"rb\") as dump:\n        subprocess.check_call(\n            [\"svnadmin\", \"load\", initools_dir],\n            stdin=dump,\n            stdout=subprocess.DEVNULL,\n        )\n    os.remove(filename)\n\n\ndef local_checkout(\n    remote_repo: str,\n    temp_path: Path,\n) -> str:\n    \"\"\"\n    :param temp_path: the return value of the tmpdir fixture, which is a\n        temp directory Path object unique to each test function invocation,\n        created as a sub directory of the base temp directory.\n    \"\"\"\n    assert \"+\" in remote_repo\n    vcs_name, vcs_url = remote_repo.split(\"+\", 1)\n    repository_name = os.path.basename(remote_repo)\n\n    directory = temp_path.joinpath(\"cache\")\n    repo_url_path = os.path.join(directory, repository_name)\n    assert not os.path.exists(repo_url_path)\n\n    if not os.path.exists(directory):\n        os.mkdir(directory)\n\n    if vcs_name == \"svn\":\n        assert repository_name == \"INITools\"\n        _create_svn_initools_repo(repo_url_path)\n        repo_url_path = os.path.join(repo_url_path, \"trunk\")\n    elif vcs_name == \"git\":\n        # Don't use vcs_backend.obtain() here because we don't want a partial clone:\n        # https://github.com/pypa/pip/issues/12719\n        subprocess.check_call(\n            [\"git\", \"clone\", vcs_url, repo_url_path],\n        )\n    else:\n        vcs_backend = vcs.get_backend(vcs_name)\n        assert vcs_backend is not None\n        vcs_backend.obtain(repo_url_path, url=hide_url(remote_repo), verbosity=0)\n\n    return f\"{vcs_name}+{Path(repo_url_path).as_uri()}\"\n\n\ndef local_repo(remote_repo: str, temp_path: Path) -> str:\n    return local_checkout(remote_repo, temp_path).split(\"+\", 1)[1]\n"
  },
  {
    "path": "tests/lib/options_helpers.py",
    "content": "\"\"\"Provides helper classes for testing option handling in pip\"\"\"\n\nfrom optparse import Values\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.commands import CommandInfo, commands_dict\n\n\nclass FakeCommand(Command):\n    def main(  # type: ignore[override]\n        self, args: list[str]\n    ) -> tuple[Values, list[str]]:\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n        self.parser.add_option_group(index_opts)\n        return self.parse_args(args)\n\n\nclass AddFakeCommandMixin:\n    def setup_method(self) -> None:\n        commands_dict[\"fake\"] = CommandInfo(\n            \"tests.lib.options_helpers\",\n            \"FakeCommand\",\n            \"fake summary\",\n        )\n\n    def teardown_method(self) -> None:\n        commands_dict.pop(\"fake\")\n"
  },
  {
    "path": "tests/lib/requests_mocks.py",
    "content": "\"\"\"Helper classes as mocks for requests objects.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom io import BytesIO\nfrom typing import Any, Callable\n\n_Hook = Callable[[\"MockResponse\"], None]\n\n\nclass FakeStream:\n    def __init__(self, contents: bytes) -> None:\n        self._io = BytesIO(contents)\n\n    def read(self, size: int, decode_content: bool | None = None) -> bytes:\n        return self._io.read(size)\n\n    def stream(self, size: int, decode_content: bool | None = None) -> Iterator[bytes]:\n        yield self._io.read(size)\n\n    def release_conn(self) -> None:\n        pass\n\n\nclass MockResponse:\n    request: MockRequest\n    connection: MockConnection\n    url: str\n\n    def __init__(self, contents: bytes) -> None:\n        self.raw = FakeStream(contents)\n        self.content = contents\n        self.reason = \"OK\"\n        self.status_code = 200\n        self.headers = {\"Content-Length\": str(len(contents))}\n        self.history: list[MockResponse] = []\n        self.from_cache = False\n\n\nclass MockConnection:\n    def _send(self, req: MockRequest, **kwargs: Any) -> MockResponse:\n        raise NotImplementedError(\"_send must be overridden for tests\")\n\n    def send(self, req: MockRequest, **kwargs: Any) -> MockResponse:\n        resp = self._send(req, **kwargs)\n        for cb in req.hooks.get(\"response\", []):\n            cb(resp)\n        return resp\n\n\nclass MockRequest:\n    def __init__(self, url: str) -> None:\n        self.url = url\n        self.headers: dict[str, str] = {}\n        self.hooks: dict[str, list[_Hook]] = {}\n\n    def register_hook(self, event_name: str, callback: _Hook) -> None:\n        self.hooks.setdefault(event_name, []).append(callback)\n"
  },
  {
    "path": "tests/lib/server.py",
    "content": "import pathlib\nimport ssl\nimport threading\nfrom base64 import b64encode\nfrom collections.abc import Iterable, Iterator\nfrom contextlib import ExitStack, contextmanager\nfrom textwrap import dedent\nfrom typing import TYPE_CHECKING, Any, Callable\nfrom unittest.mock import Mock, patch\n\nfrom werkzeug.serving import BaseWSGIServer, WSGIRequestHandler\nfrom werkzeug.serving import make_server as _make_server\n\nfrom .compat import blocked_signals\n\nif TYPE_CHECKING:\n    from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment\n\nBody = Iterable[bytes]\n\n\n@contextmanager\ndef patch_getfqdn() -> Iterator[None]:\n    # HTTPServer, which Werkzeug subclasses, will try to query the fully qualified\n    # domain name for the socket address during socket binding. This can be extremely\n    # slow (30s, even) due to DNS timeouts. It's only used for the SERVER_NAME CGI\n    # environment field which is not relevant for our tests, so patch it to\n    # immediately return a fake local FQDN.\n    #\n    # See also: https://apple.stackexchange.com/questions/175320/why-is-my-hostname-resolution-taking-so-long\n    with patch(\"socket.getfqdn\", lambda name: \"piptestserver.home.arpa\"):\n        yield\n\n\nclass _MockServer(BaseWSGIServer):\n    mock: Mock = Mock()\n\n\nclass _RequestHandler(WSGIRequestHandler):\n    def make_environ(self) -> dict[str, Any]:\n        environ = super().make_environ()\n\n        # From pallets/werkzeug#1469, will probably be in release after\n        # 0.16.0.\n        try:\n            # binary_form=False gives nicer information, but wouldn't be\n            # compatible with what Nginx or Apache could return.\n            peer_cert = self.connection.getpeercert(binary_form=True)\n            if peer_cert is not None:\n                # Nginx and Apache use PEM format.\n                environ[\"SSL_CLIENT_CERT\"] = ssl.DER_cert_to_PEM_cert(\n                    peer_cert,\n                )\n        except ValueError:\n            # SSL handshake hasn't finished.\n            self.server.log(\"error\", \"Cannot fetch SSL peer certificate info\")\n        except AttributeError:\n            # Not using TLS, the socket will not have getpeercert().\n            pass\n\n        return environ\n\n\ndef _mock_wsgi_adapter(\n    mock: Callable[[\"WSGIEnvironment\", \"StartResponse\"], \"WSGIApplication\"],\n) -> \"WSGIApplication\":\n    \"\"\"Uses a mock to record function arguments and provide\n    the actual function that should respond.\n    \"\"\"\n\n    def adapter(environ: \"WSGIEnvironment\", start_response: \"StartResponse\") -> Body:\n        try:\n            responder = mock(environ, start_response)\n        except StopIteration:\n            raise RuntimeError(\"Ran out of mocked responses.\")\n        return responder(environ, start_response)\n\n    return adapter\n\n\ndef make_mock_server(**kwargs: Any) -> _MockServer:\n    \"\"\"Creates a mock HTTP(S) server listening on a random port on localhost.\n\n    The `mock` property of the returned server provides and records all WSGI\n    interactions, so one approach to testing could be\n\n        server = make_mock_server()\n        server.mock.side_effects = [\n            page1,\n            page2,\n        ]\n\n        with server_running(server):\n            # ... use server...\n            ...\n\n        assert server.mock.call_count > 0\n        call_args_list = server.mock.call_args_list\n\n        # `environ` is a dictionary defined as per PEP 3333 with the associated\n        # contents. Additional properties may be added by werkzeug.\n        environ, _ = call_args_list[0].args\n        assert environ[\"PATH_INFO\"].startswith(\"/hello/simple\")\n\n    Note that the server interactions take place in a different thread, so you\n    do not want to touch the server.mock within the `server_running` block.\n\n    Note also for pip interactions that \"localhost\" is a \"secure origin\", so\n    be careful using this for failure tests of `--trusted-host`.\n    \"\"\"\n    kwargs.setdefault(\"request_handler\", _RequestHandler)\n\n    mock = Mock()\n    app = _mock_wsgi_adapter(mock)\n    with patch_getfqdn():\n        server = _make_server(\"localhost\", 0, app=app, **kwargs)\n    server.mock = mock\n    return server\n\n\n@contextmanager\ndef server_running(server: BaseWSGIServer) -> Iterator[None]:\n    \"\"\"Context manager for running the provided server in a separate thread.\"\"\"\n    thread = threading.Thread(target=server.serve_forever)\n    thread.daemon = True\n    with blocked_signals():\n        thread.start()\n    try:\n        yield\n    finally:\n        server.shutdown()\n        thread.join()\n\n\n# Helper functions for making responses in a declarative way.\n\n\ndef text_html_response(text: str) -> \"WSGIApplication\":\n    def responder(environ: \"WSGIEnvironment\", start_response: \"StartResponse\") -> Body:\n        start_response(\n            \"200 OK\",\n            [\n                (\"Content-Type\", \"text/html; charset=UTF-8\"),\n            ],\n        )\n        return [text.encode(\"utf-8\")]\n\n    return responder\n\n\ndef html5_page(text: str) -> str:\n    return (\n        dedent(\n            \"\"\"\n    <!DOCTYPE html>\n    <html>\n      <body>\n        {}\n      </body>\n    </html>\n    \"\"\"\n        )\n        .strip()\n        .format(text)\n    )\n\n\ndef package_page(spec: dict[str, str]) -> \"WSGIApplication\":\n    def link(name: str, value: str) -> str:\n        return f'<a href=\"{value}\">{name}</a>'\n\n    links = \"\".join(link(*kv) for kv in spec.items())\n    return text_html_response(html5_page(links))\n\n\ndef file_response(path: pathlib.Path) -> \"WSGIApplication\":\n    def responder(environ: \"WSGIEnvironment\", start_response: \"StartResponse\") -> Body:\n        start_response(\n            \"200 OK\",\n            [\n                (\"Content-Type\", \"application/octet-stream\"),\n                (\"Content-Length\", str(path.stat().st_size)),\n            ],\n        )\n        return [path.read_bytes()]\n\n    return responder\n\n\ndef authorization_response(path: pathlib.Path) -> \"WSGIApplication\":\n    correct_auth = \"Basic \" + b64encode(b\"USERNAME:PASSWORD\").decode(\"ascii\")\n\n    def responder(environ: \"WSGIEnvironment\", start_response: \"StartResponse\") -> Body:\n        if environ.get(\"HTTP_AUTHORIZATION\") != correct_auth:\n            start_response(\"401 Unauthorized\", [(\"WWW-Authenticate\", \"Basic\")])\n            return ()\n        start_response(\n            \"200 OK\",\n            [\n                (\"Content-Type\", \"application/octet-stream\"),\n                (\"Content-Length\", str(path.stat().st_size)),\n            ],\n        )\n        return [path.read_bytes()]\n\n    return responder\n\n\nclass MockServer:\n    def __init__(self, server: _MockServer) -> None:\n        self._server = server\n        self._running = False\n        self.context = ExitStack()\n\n    @property\n    def port(self) -> int:\n        return self._server.port\n\n    @property\n    def host(self) -> str:\n        return self._server.host\n\n    def set_responses(self, responses: Iterable[\"WSGIApplication\"]) -> None:\n        assert not self._running, \"responses cannot be set on running server\"\n        self._server.mock.side_effect = responses\n\n    def start(self) -> None:\n        assert not self._running, \"running server cannot be started\"\n        self.context.enter_context(server_running(self._server))\n        self.context.enter_context(self._set_running())\n\n    @contextmanager\n    def _set_running(self) -> Iterator[None]:\n        self._running = True\n        try:\n            yield\n        finally:\n            self._running = False\n\n    def stop(self) -> None:\n        assert self._running, \"idle server cannot be stopped\"\n        self.context.close()\n\n    def get_requests(self) -> list[dict[str, str]]:\n        \"\"\"Get environ for each received request.\"\"\"\n        assert not self._running, \"cannot get mock from running server\"\n        # Legacy: replace call[0][0] with call.args[0]\n        # when pip drops support for python3.7\n        return [call[0][0] for call in self._server.mock.call_args_list]\n"
  },
  {
    "path": "tests/lib/test_lib.py",
    "content": "\"\"\"Test the test support.\"\"\"\n\nimport filecmp\nimport pathlib\nimport re\nimport sys\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom os.path import isdir, join\nfrom typing import Any\n\nimport pytest\n\nfrom tests.lib import SRC_DIR, PipTestEnvironment\n\n\n@contextmanager\ndef assert_error_startswith(\n    exc_type: type[Exception], expected_start: str\n) -> Iterator[None]:\n    \"\"\"\n    Assert that an exception is raised starting with a certain message.\n    \"\"\"\n    with pytest.raises(exc_type) as err:\n        yield\n\n    assert str(err.value).startswith(expected_start), f\"full message: {err.value}\"\n\n\ndef test_tmp_dir_exists_in_env(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Test that $TMPDIR == env.temp_path and path exists and env.assert_no_temp()\n    passes (in fast env)\n    \"\"\"\n    # need these tests to ensure the assert_no_temp feature of scripttest is\n    # working\n    script.assert_no_temp()  # this fails if env.tmp_path doesn't exist\n    assert pathlib.Path(script.environ[\"TMPDIR\"]) == script.temp_path\n    assert isdir(script.temp_path)\n\n\ndef test_correct_pip_version(script: PipTestEnvironment) -> None:\n    \"\"\"\n    Check we are running proper version of pip in run_pip.\n    \"\"\"\n\n    if script.zipapp:\n        pytest.skip(\"Test relies on the pip under test being in the filesystem\")\n\n    # output is like:\n    # pip PIPVERSION from PIPDIRECTORY (python PYVERSION)\n    result = script.pip(\"--version\")\n\n    # compare the directory tree of the invoked pip with that of this source\n    # distribution\n    match = re.match(\n        r\"pip \\d+(\\.[\\d]+)+(\\.?(b|rc|dev|pre|post)\\d+)? from (.*) \"\n        r\"\\(python \\d+(\\.[\\d]+)+\\)$\",\n        result.stdout,\n    )\n    assert match is not None\n    pip_folder_outputted = match.group(4)\n    pip_folder = join(SRC_DIR, \"src\", \"pip\")\n\n    diffs = filecmp.dircmp(pip_folder, pip_folder_outputted)\n\n    # If any non-matching .py files exist, we have a problem: run_pip\n    # is picking up some other version!  N.B. if this project acquires\n    # primary resources other than .py files, this code will need\n    # maintenance\n    mismatch_py = [\n        x\n        for x in diffs.left_only + diffs.right_only + diffs.diff_files\n        if x.endswith(\".py\")\n    ]\n    assert not mismatch_py, (\n        f\"mismatched source files in {pip_folder!r} \"\n        f\"and {pip_folder_outputted!r}: {mismatch_py!r}\"\n    )\n\n\ndef test_as_import(script: PipTestEnvironment) -> None:\n    \"\"\"test that pip.__init__.py does not shadow\n    the command submodule with a dictionary\n    \"\"\"\n    import pip._internal.commands.install as inst\n\n    assert inst is not None\n\n\nclass TestPipTestEnvironment:\n    def run_stderr_with_prefix(\n        self, script: PipTestEnvironment, prefix: str, **kwargs: Any\n    ) -> None:\n        \"\"\"\n        Call run() that prints stderr with the given prefix.\n        \"\"\"\n        text = f\"{prefix}: hello, world\\\\n\"\n        command = f'import sys; sys.stderr.write(\"{text}\")'\n        args = [sys.executable, \"-c\", command]\n        script.run(*args, **kwargs)\n\n    def run_with_log_command(\n        self, script: PipTestEnvironment, sub_string: str, **kwargs: Any\n    ) -> None:\n        \"\"\"\n        Call run() on a command that logs a \"%\"-style format string using\n        the given substring as the string's replacement field.\n        \"\"\"\n        command = (\n            \"import logging; logging.basicConfig(level='INFO'); \"\n            f\"logging.getLogger().info('sub: {sub_string}', 'foo')\"\n        )\n        args = [sys.executable, \"-c\", command]\n        script.run(*args, **kwargs)\n\n    @pytest.mark.parametrize(\n        \"prefix\",\n        [\n            \"DEBUG\",\n            \"INFO\",\n            \"FOO\",\n        ],\n    )\n    def test_run__allowed_stderr(self, script: PipTestEnvironment, prefix: str) -> None:\n        \"\"\"\n        Test calling run() with allowed stderr.\n        \"\"\"\n        # Check that no error happens.\n        self.run_stderr_with_prefix(script, prefix)\n\n    def test_run__allow_stderr_warning(self, script: PipTestEnvironment) -> None:\n        \"\"\"\n        Test passing allow_stderr_warning=True.\n        \"\"\"\n        # Check that no error happens.\n        self.run_stderr_with_prefix(\n            script,\n            \"WARNING\",\n            allow_stderr_warning=True,\n        )\n\n        # Check that an error still happens with ERROR.\n        expected_start = \"stderr has an unexpected error\"\n        with assert_error_startswith(RuntimeError, expected_start):\n            self.run_stderr_with_prefix(\n                script,\n                \"ERROR\",\n                allow_stderr_warning=True,\n            )\n\n    @pytest.mark.parametrize(\n        \"prefix\",\n        [\n            \"WARNING\",\n            \"ERROR\",\n        ],\n    )\n    def test_run__allow_stderr_error(\n        self, script: PipTestEnvironment, prefix: str\n    ) -> None:\n        \"\"\"\n        Test passing allow_stderr_error=True.\n        \"\"\"\n        # Check that no error happens.\n        self.run_stderr_with_prefix(script, prefix, allow_stderr_error=True)\n\n    @pytest.mark.parametrize(\n        \"prefix, expected_start\",\n        [\n            (\"WARNING\", \"stderr has an unexpected warning\"),\n            (\"ERROR\", \"stderr has an unexpected error\"),\n        ],\n    )\n    def test_run__unexpected_stderr(\n        self, script: PipTestEnvironment, prefix: str, expected_start: str\n    ) -> None:\n        \"\"\"\n        Test calling run() with unexpected stderr output.\n        \"\"\"\n        with assert_error_startswith(RuntimeError, expected_start):\n            self.run_stderr_with_prefix(script, prefix)\n\n    def test_run__logging_error(self, script: PipTestEnvironment) -> None:\n        \"\"\"\n        Test calling run() with an unexpected logging error.\n        \"\"\"\n        # Pass a good substitution string.\n        self.run_with_log_command(script, sub_string=\"%r\")\n\n        expected_start = \"stderr has a logging error, which is never allowed\"\n        with assert_error_startswith(RuntimeError, expected_start):\n            # Pass a bad substitution string.  Also, pass\n            # allow_stderr_error=True to check that the RuntimeError occurs\n            # even under the stricter test condition of when we are allowing\n            # other types of errors.\n            self.run_with_log_command(\n                script,\n                sub_string=\"{!r}\",\n                allow_stderr_error=True,\n            )\n\n    def test_run__allow_stderr_error_false_error_with_expect_error(\n        self, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test passing allow_stderr_error=False with expect_error=True.\n        \"\"\"\n        expected_start = \"cannot pass allow_stderr_error=False with expect_error=True\"\n        with assert_error_startswith(RuntimeError, expected_start):\n            script.run(\"python\", allow_stderr_error=False, expect_error=True)\n\n    def test_run__allow_stderr_warning_false_error_with_expect_stderr(\n        self, script: PipTestEnvironment\n    ) -> None:\n        \"\"\"\n        Test passing allow_stderr_warning=False with expect_stderr=True.\n        \"\"\"\n        expected_start = (\n            \"cannot pass allow_stderr_warning=False with expect_stderr=True\"\n        )\n        with assert_error_startswith(RuntimeError, expected_start):\n            script.run(\n                \"python\",\n                allow_stderr_warning=False,\n                expect_stderr=True,\n            )\n\n    @pytest.mark.parametrize(\n        \"arg_name\",\n        [\n            \"expect_error\",\n            \"allow_stderr_error\",\n        ],\n    )\n    def test_run__allow_stderr_warning_false_error(\n        self, script: PipTestEnvironment, arg_name: str\n    ) -> None:\n        \"\"\"\n        Test passing allow_stderr_warning=False when it is not allowed.\n        \"\"\"\n        kwargs: dict[str, Any] = {\"allow_stderr_warning\": False, arg_name: True}\n        expected_start = (\n            \"cannot pass allow_stderr_warning=False with allow_stderr_error=True\"\n        )\n        with assert_error_startswith(RuntimeError, expected_start):\n            script.run(\"python\", **kwargs)\n\n    def test_run__expect_error_fails_when_zero_returncode(\n        self, script: PipTestEnvironment\n    ) -> None:\n        expected_start = \"Script passed unexpectedly\"\n        with assert_error_startswith(AssertionError, expected_start):\n            script.run(\"python\", expect_error=True)\n\n    def test_run__no_expect_error_fails_when_nonzero_returncode(\n        self, script: PipTestEnvironment\n    ) -> None:\n        expected_start = \"Script returned code: 1\"\n        with assert_error_startswith(AssertionError, expected_start):\n            script.run(\"python\", \"-c\", \"import sys; sys.exit(1)\")\n"
  },
  {
    "path": "tests/lib/test_wheel.py",
    "content": "\"\"\"Tests for wheel helper.\"\"\"\n\nimport csv\nfrom email import message_from_string\nfrom email.message import Message\nfrom functools import partial\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nfrom tests.lib.wheel import (\n    File,\n    _default,\n    make_metadata_file,\n    make_wheel,\n    make_wheel_metadata_file,\n    message_from_dict,\n)\n\n\ndef test_message_from_dict_one_value() -> None:\n    message = message_from_dict({\"a\": \"1\"})\n    assert set(message.get_all(\"a\")) == {\"1\"}  # type: ignore\n\n\ndef test_message_from_dict_multiple_values() -> None:\n    message = message_from_dict({\"a\": [\"1\", \"2\"]})\n    assert set(message.get_all(\"a\")) == {\"1\", \"2\"}  # type: ignore\n\n\ndef message_from_bytes(contents: bytes) -> Message:\n    return message_from_string(contents.decode(\"utf-8\"))\n\n\ndefault_make_metadata = partial(\n    make_metadata_file,\n    name=\"simple\",\n    value=_default,\n    version=\"0.1.0\",\n    updates=_default,\n    body=_default,\n)\n\n\ndef default_metadata_checks(f: File) -> Message:\n    assert f.name == \"simple-0.1.0.dist-info/METADATA\"\n    message = message_from_bytes(f.contents)\n    assert message.get_all(\"Metadata-Version\") == [\"2.1\"]\n    assert message.get_all(\"Name\") == [\"simple\"]\n    assert message.get_all(\"Version\") == [\"0.1.0\"]\n    return message\n\n\ndef test_make_metadata_file_defaults() -> None:\n    f = default_make_metadata()\n    assert f is not None\n    default_metadata_checks(f)\n\n\ndef test_make_metadata_file_custom_value() -> None:\n    f = default_make_metadata(updates={\"a\": \"1\"})\n    assert f is not None\n    message = default_metadata_checks(f)\n    assert message.get_all(\"a\") == [\"1\"]\n\n\ndef test_make_metadata_file_custom_value_list() -> None:\n    f = default_make_metadata(updates={\"a\": [\"1\", \"2\"]})\n    assert f is not None\n    message = default_metadata_checks(f)\n    assert set(message.get_all(\"a\")) == {\"1\", \"2\"}  # type: ignore\n\n\ndef test_make_metadata_file_custom_value_overrides() -> None:\n    f = default_make_metadata(updates={\"Metadata-Version\": \"2.2\"})\n    assert f is not None\n    message = message_from_bytes(f.contents)\n    assert message.get_all(\"Metadata-Version\") == [\"2.2\"]\n\n\ndef test_make_metadata_file_custom_contents() -> None:\n    value = b\"hello\"\n    f = default_make_metadata(value=value)  # type: ignore[arg-type]\n    assert f is not None\n    assert f.contents == value\n\n\ntags = [(\"py2\", \"none\", \"any\"), (\"py3\", \"none\", \"any\")]\ndefault_make_wheel_metadata = partial(\n    make_wheel_metadata_file,\n    name=\"simple\",\n    version=\"0.1.0\",\n    value=_default,\n    tags=tags,\n    updates=_default,\n)\n\n\ndef default_wheel_metadata_checks(f: File) -> Message:\n    assert f.name == \"simple-0.1.0.dist-info/WHEEL\"\n    message = message_from_bytes(f.contents)\n    assert message.get_all(\"Wheel-Version\") == [\"1.0\"]\n    assert message.get_all(\"Generator\") == [\"pip-test-suite\"]\n    assert message.get_all(\"Root-Is-Purelib\") == [\"true\"]\n    assert set(message.get_all(\"Tag\")) == {\"py2-none-any\", \"py3-none-any\"}  # type: ignore\n    return message\n\n\ndef test_make_wheel_metadata_file_defaults() -> None:\n    f = default_make_wheel_metadata()\n    assert f is not None\n    default_wheel_metadata_checks(f)\n\n\ndef test_make_wheel_metadata_file_custom_value() -> None:\n    f = default_make_wheel_metadata(updates={\"a\": \"1\"})\n    assert f is not None\n    message = default_wheel_metadata_checks(f)\n    assert message.get_all(\"a\") == [\"1\"]\n\n\ndef test_make_wheel_metadata_file_custom_value_list() -> None:\n    f = default_make_wheel_metadata(updates={\"a\": [\"1\", \"2\"]})\n    assert f is not None\n    message = default_wheel_metadata_checks(f)\n    assert set(message.get_all(\"a\")) == {\"1\", \"2\"}  # type: ignore\n\n\ndef test_make_wheel_metadata_file_custom_value_override() -> None:\n    f = default_make_wheel_metadata(updates={\"Wheel-Version\": \"1.1\"})\n    assert f is not None\n    message = message_from_bytes(f.contents)\n    assert message.get_all(\"Wheel-Version\") == [\"1.1\"]\n\n\ndef test_make_wheel_metadata_file_custom_contents() -> None:\n    value = b\"hello\"\n    f = default_make_wheel_metadata(value=value)\n    assert f is not None\n    assert f.name == \"simple-0.1.0.dist-info/WHEEL\"\n    assert f.contents == value\n\n\ndef test_make_wheel_metadata_file_no_contents() -> None:\n    f = default_make_wheel_metadata(value=None)\n    assert f is None\n\n\ndef test_make_wheel_basics(tmpdir: Path) -> None:\n    make_wheel(name=\"simple\", version=\"0.1.0\").save_to_dir(tmpdir)\n\n    expected_wheel_path = tmpdir / \"simple-0.1.0-py2.py3-none-any.whl\"\n    assert expected_wheel_path.exists()\n\n    with ZipFile(expected_wheel_path) as z:\n        names = z.namelist()\n        assert set(names) == {\n            \"simple-0.1.0.dist-info/METADATA\",\n            \"simple-0.1.0.dist-info/RECORD\",\n            \"simple-0.1.0.dist-info/WHEEL\",\n        }\n\n\ndef test_make_wheel_default_record() -> None:\n    with make_wheel(\n        name=\"simple\",\n        version=\"0.1.0\",\n        extra_files={\"simple/__init__.py\": \"a\"},\n        extra_metadata_files={\"LICENSE\": \"b\"},\n        extra_data_files={\"purelib/info.txt\": \"c\"},\n    ).as_zipfile() as z:\n        record_bytes = z.read(\"simple-0.1.0.dist-info/RECORD\")\n        record_text = record_bytes.decode()\n        record_rows = list(csv.reader(record_text.splitlines()))\n        records = {row[0]: row[1:] for row in record_rows}\n\n        expected = {\n            \"simple/__init__.py\": [\n                \"sha256=ypeBEsobvcr6wjGzmiPcTaeG7_gUfE5yuYB3ha_uSLs\",\n                \"1\",\n            ],\n            \"simple-0.1.0.data/purelib/info.txt\": [\n                \"sha256=Ln0sA6lQeuJl7PW1NWiFpTOTogKdJBOUmXJloaJa78Y\",\n                \"1\",\n            ],\n            \"simple-0.1.0.dist-info/LICENSE\": [\n                \"sha256=PiPoFgA5WUoziU9lZOGxNIu9egCI1CxKy3PurtWcAJ0\",\n                \"1\",\n            ],\n            \"simple-0.1.0.dist-info/RECORD\": [\"\", \"\"],\n        }\n        for name, values in expected.items():\n            assert records[name] == values, name\n\n        # WHEEL and METADATA aren't constructed in a stable way, so just spot\n        # check.\n        expected_variable = {\n            \"simple-0.1.0.dist-info/METADATA\": \"51\",\n            \"simple-0.1.0.dist-info/WHEEL\": \"104\",\n        }\n        for name, length in expected_variable.items():\n            assert records[name][0].startswith(\"sha256=\"), name\n            assert records[name][1] == length, name\n\n\ndef test_make_wheel_extra_files() -> None:\n    with make_wheel(\n        name=\"simple\",\n        version=\"0.1.0\",\n        extra_files={\"simple/__init__.py\": \"a\"},\n        extra_metadata_files={\"LICENSE\": \"b\"},\n        extra_data_files={\"info.txt\": \"c\"},\n    ).as_zipfile() as z:\n        names = z.namelist()\n        assert set(names) == {\n            \"simple/__init__.py\",\n            \"simple-0.1.0.data/info.txt\",\n            \"simple-0.1.0.dist-info/LICENSE\",\n            \"simple-0.1.0.dist-info/METADATA\",\n            \"simple-0.1.0.dist-info/RECORD\",\n            \"simple-0.1.0.dist-info/WHEEL\",\n        }\n\n        assert z.read(\"simple/__init__.py\") == b\"a\"\n        assert z.read(\"simple-0.1.0.dist-info/LICENSE\") == b\"b\"\n        assert z.read(\"simple-0.1.0.data/info.txt\") == b\"c\"\n\n\ndef test_make_wheel_no_files() -> None:\n    with make_wheel(\n        name=\"simple\",\n        version=\"0.1.0\",\n        wheel_metadata=None,\n        metadata=None,\n        record=None,\n    ).as_zipfile() as z:\n        assert not z.namelist()\n\n\ndef test_make_wheel_custom_files() -> None:\n    with make_wheel(\n        name=\"simple\",\n        version=\"0.1.0\",\n        wheel_metadata=b\"a\",\n        metadata=b\"b\",\n        record=b\"c\",\n    ).as_zipfile() as z:\n        assert z.read(\"simple-0.1.0.dist-info/WHEEL\") == b\"a\"\n        assert z.read(\"simple-0.1.0.dist-info/METADATA\") == b\"b\"\n        assert z.read(\"simple-0.1.0.dist-info/RECORD\") == b\"c\"\n"
  },
  {
    "path": "tests/lib/venv.py",
    "content": "from __future__ import annotations\n\nimport compileall\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport sysconfig\nimport textwrap\nimport venv as _venv\nfrom pathlib import Path\nfrom typing import Literal\n\nimport virtualenv as _virtualenv\n\nVirtualEnvironmentType = Literal[\"virtualenv\", \"venv\"]\n\n\nclass VirtualEnvironment:\n    \"\"\"\n    An abstraction around virtual environments, currently it only uses\n    virtualenv but in the future it could use pyvenv.\n    \"\"\"\n\n    def __init__(\n        self,\n        location: Path,\n        template: VirtualEnvironment | None = None,\n        venv_type: VirtualEnvironmentType | None = None,\n    ) -> None:\n        self.location = location\n        assert template is None or venv_type is None\n        self._venv_type: VirtualEnvironmentType\n        if template is not None:\n            self._venv_type = template._venv_type\n        elif venv_type is not None:\n            self._venv_type = venv_type\n        else:\n            self._venv_type = \"virtualenv\"\n        self._user_site_packages = False\n        self._template = template\n        self._sitecustomize: str | None = None\n        self._update_paths()\n        self._create()\n\n    @property\n    def _legacy_virtualenv(self) -> bool:\n        if self._venv_type != \"virtualenv\":\n            return False\n        return int(_virtualenv.__version__.split(\".\", 1)[0]) < 20\n\n    def __update_paths_legacy(self) -> None:\n        home, lib, inc, bin = _virtualenv.path_locations(self.location)  # type: ignore[attr-defined]\n        self.bin = Path(bin)\n        self.site = Path(lib) / \"site-packages\"\n        # Workaround for https://github.com/pypa/virtualenv/issues/306\n        if hasattr(sys, \"pypy_version_info\"):\n            version_dir = str(sys.version_info.major)\n            self.lib = Path(home, \"lib-python\", version_dir)\n        else:\n            self.lib = Path(lib)\n\n    def _update_paths(self) -> None:\n        if self._legacy_virtualenv:\n            self.__update_paths_legacy()\n            return\n        bases = {\n            \"installed_base\": self.location,\n            \"installed_platbase\": self.location,\n            \"base\": self.location,\n            \"platbase\": self.location,\n        }\n        paths = sysconfig.get_paths(vars=bases)\n        self.bin = Path(paths[\"scripts\"])\n        self.site = Path(paths[\"purelib\"])\n        self.lib = Path(paths[\"stdlib\"])\n\n    def __repr__(self) -> str:\n        return f\"<VirtualEnvironment {self.location}>\"\n\n    def _create(self, clear: bool = False) -> None:\n        if clear:\n            shutil.rmtree(self.location)\n        if self._template:\n            # On Windows, calling `_virtualenv.path_locations(target)`\n            # will have created the `target` directory...\n            if (\n                self._legacy_virtualenv\n                and sys.platform == \"win32\"\n                and self.location.exists()\n            ):\n                self.location.rmdir()\n            # Clone virtual environment from template.\n            shutil.copytree(self._template.location, self.location, symlinks=True)\n            self._sitecustomize = self._template.sitecustomize\n            self._user_site_packages = self._template.user_site_packages\n        else:\n            # Create a new virtual environment.\n            if self._legacy_virtualenv:\n                subprocess.check_call(\n                    [\n                        sys.executable,\n                        \"-m\",\n                        \"virtualenv\",\n                        \"--no-pip\",\n                        \"--no-wheel\",\n                        \"--no-setuptools\",\n                        os.fspath(self.location),\n                    ]\n                )\n                self._fix_legacy_virtualenv_site_module()\n            elif self._venv_type == \"virtualenv\":\n                _virtualenv.cli_run(\n                    [\n                        \"--no-pip\",\n                        \"--no-setuptools\",\n                        os.fspath(self.location),\n                    ],\n                )\n            elif self._venv_type == \"venv\":\n                builder = _venv.EnvBuilder()\n                context = builder.ensure_directories(os.fspath(self.location))\n                builder.create_configuration(context)\n                builder.setup_python(context)\n                self.site.mkdir(parents=True, exist_ok=True)\n            else:\n                raise RuntimeError(f\"Unsupported venv type {self._venv_type!r}\")\n            self.sitecustomize = self._sitecustomize\n            self.user_site_packages = self._user_site_packages\n\n    def _fix_legacy_virtualenv_site_module(self) -> None:\n        # Patch `site.py` so user site work as expected.\n        site_py = self.lib / \"site.py\"\n        with open(site_py) as fp:\n            site_contents = fp.read()\n        for pattern, replace in (\n            (\n                # Ensure enabling user site does not result in adding\n                # the real site-packages' directory to `sys.path`.\n                (\"\\ndef virtual_addsitepackages(known_paths):\\n\"),\n                (\n                    \"\\ndef virtual_addsitepackages(known_paths):\\n\"\n                    \"    return known_paths\\n\"\n                ),\n            ),\n            (\n                # Fix sites ordering: user site must be added before system.\n                (\n                    \"\\n    paths_in_sys = addsitepackages(paths_in_sys)\"\n                    \"\\n    paths_in_sys = addusersitepackages(paths_in_sys)\\n\"\n                ),\n                (\n                    \"\\n    paths_in_sys = addusersitepackages(paths_in_sys)\"\n                    \"\\n    paths_in_sys = addsitepackages(paths_in_sys)\\n\"\n                ),\n            ),\n        ):\n            assert pattern in site_contents\n            site_contents = site_contents.replace(pattern, replace)\n        with open(site_py, \"w\") as fp:\n            fp.write(site_contents)\n        # Make sure bytecode is up-to-date too.\n        assert compileall.compile_file(str(site_py), quiet=1, force=True)\n\n    def _customize_site(self) -> None:\n        if self._legacy_virtualenv:\n            contents = \"\"\n        else:\n            # Enable user site (before system).\n            contents = textwrap.dedent(\n                f\"\"\"\n                import os, site, sys\n                if not os.environ.get('PYTHONNOUSERSITE', False):\n                    site.ENABLE_USER_SITE = {self._user_site_packages}\n                    # First, drop system-sites related paths.\n                    original_sys_path = sys.path[:]\n                    known_paths = set()\n                    for path in site.getsitepackages():\n                        site.addsitedir(path, known_paths=known_paths)\n                    system_paths = sys.path[len(original_sys_path):]\n                    for path in system_paths:\n                        if path in original_sys_path:\n                            original_sys_path.remove(path)\n                    sys.path = original_sys_path\n                    # Second, add user-site.\n                    if {self._user_site_packages}:\n                        site.addsitedir(site.getusersitepackages())\n                    # Third, add back system-sites related paths.\n                    for path in site.getsitepackages():\n                        site.addsitedir(path)\n                \"\"\"\n            ).strip()\n        if self._sitecustomize is not None:\n            contents += \"\\n\" + self._sitecustomize\n        sitecustomize = self.site / \"sitecustomize.py\"\n        sitecustomize.write_text(contents)\n        # Make sure bytecode is up-to-date too.\n        assert compileall.compile_file(str(sitecustomize), quiet=1, force=True)\n\n    def _rewrite_pyvenv_cfg(self, replacements: dict[str, str]) -> None:\n        pyvenv_cfg = self.location.joinpath(\"pyvenv.cfg\")\n        lines = pyvenv_cfg.read_text(encoding=\"utf-8\").splitlines()\n\n        def maybe_replace_line(line: str) -> str:\n            key = line.split(\"=\", 1)[0].strip()\n            try:\n                value = replacements[key]\n            except KeyError:  # No need to replace.\n                return line\n            return f\"{key} = {value}\"\n\n        lines = [maybe_replace_line(line) for line in lines]\n        pyvenv_cfg.write_text(\"\\n\".join(lines), encoding=\"utf-8\")\n\n    def clear(self) -> None:\n        self._create(clear=True)\n\n    def move(self, location: Path | str) -> None:\n        shutil.move(os.fspath(self.location), location)\n        self.location = Path(location)\n        self._update_paths()\n\n    @property\n    def sitecustomize(self) -> str | None:\n        return self._sitecustomize\n\n    @sitecustomize.setter\n    def sitecustomize(self, value: str | None) -> None:\n        self._sitecustomize = value\n        self._customize_site()\n\n    @property\n    def user_site_packages(self) -> bool:\n        return self._user_site_packages\n\n    @user_site_packages.setter\n    def user_site_packages(self, value: bool) -> None:\n        self._user_site_packages = value\n        if self._legacy_virtualenv:\n            marker = self.lib / \"no-global-site-packages.txt\"\n            if self._user_site_packages:\n                marker.unlink()\n            else:\n                marker.touch()\n        else:\n            self._rewrite_pyvenv_cfg(\n                {\"include-system-site-packages\": str(bool(value)).lower()}\n            )\n            self._customize_site()\n"
  },
  {
    "path": "tests/lib/wheel.py",
    "content": "\"\"\"Helper for building wheels as would be in test cases.\"\"\"\n\nfrom __future__ import annotations\n\nimport csv\nimport itertools\nfrom base64 import urlsafe_b64encode\nfrom collections import namedtuple\nfrom collections.abc import Iterable, Sequence\nfrom copy import deepcopy\nfrom email.message import Message\nfrom enum import Enum\nfrom functools import partial\nfrom hashlib import sha256\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom typing import (\n    AnyStr,\n    TypeVar,\n    Union,\n)\nfrom zipfile import ZipFile\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\n\nfrom pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution\n\n# As would be used in metadata\nHeaderValue = Union[str, list[str]]\n\n\nFile = namedtuple(\"File\", [\"name\", \"contents\"])\nRecord = namedtuple(\"Record\", [\"path\", \"digest\", \"size\"])\n\n\nclass Default(Enum):\n    token = 0\n\n\n_default = Default.token\n\nT = TypeVar(\"T\")\n\n# A type which may be defaulted.\nDefaulted = Union[Default, T]\n\n\ndef ensure_binary(value: bytes | str) -> bytes:\n    if isinstance(value, bytes):\n        return value\n    return value.encode()\n\n\ndef message_from_dict(headers: dict[str, HeaderValue]) -> Message:\n    \"\"\"Plain key-value pairs are set in the returned message.\n\n    List values are converted into repeated headers in the result.\n    \"\"\"\n    message = Message()\n    for name, value in headers.items():\n        if isinstance(value, list):\n            for v in value:\n                message[name] = v\n        else:\n            message[name] = value\n    return message\n\n\ndef dist_info_path(name: str, version: str, path: str) -> str:\n    return f\"{name}-{version}.dist-info/{path}\"\n\n\ndef make_metadata_file(\n    name: str,\n    version: str,\n    value: Defaulted[AnyStr | None],\n    updates: Defaulted[dict[str, HeaderValue]],\n    body: Defaulted[AnyStr],\n) -> File | None:\n    if value is None:\n        return None\n\n    path = dist_info_path(name, version, \"METADATA\")\n\n    if value is not _default:\n        return File(path, ensure_binary(value))\n\n    metadata = CaseInsensitiveDict(\n        {\n            \"Metadata-Version\": \"2.1\",\n            \"Name\": name,\n            \"Version\": version,\n        }\n    )\n    if updates is not _default:\n        metadata.update(updates)\n\n    message = message_from_dict(metadata)\n    if body is not _default:\n        message.set_payload(body)\n\n    return File(path, message.as_bytes())\n\n\ndef make_wheel_metadata_file(\n    name: str,\n    version: str,\n    value: Defaulted[bytes | str | None],\n    tags: Sequence[tuple[str, str, str]],\n    updates: Defaulted[dict[str, HeaderValue]],\n) -> File | None:\n    if value is None:\n        return None\n\n    path = dist_info_path(name, version, \"WHEEL\")\n\n    if value is not _default:\n        return File(path, ensure_binary(value))\n\n    metadata = CaseInsensitiveDict(\n        {\n            \"Wheel-Version\": \"1.0\",\n            \"Generator\": \"pip-test-suite\",\n            \"Root-Is-Purelib\": \"true\",\n            \"Tag\": [\"-\".join(parts) for parts in tags],\n        }\n    )\n\n    if updates is not _default:\n        metadata.update(updates)\n\n    return File(path, message_from_dict(metadata).as_bytes())\n\n\ndef make_entry_points_file(\n    name: str,\n    version: str,\n    entry_points: Defaulted[dict[str, list[str]]],\n    console_scripts: Defaulted[list[str]],\n) -> File | None:\n    if entry_points is _default and console_scripts is _default:\n        return None\n\n    if entry_points is _default:\n        entry_points_data = {}\n    else:\n        entry_points_data = deepcopy(entry_points)\n\n    if console_scripts is not _default:\n        entry_points_data[\"console_scripts\"] = console_scripts\n\n    lines = []\n    for section, values in entry_points_data.items():\n        lines.append(f\"[{section}]\")\n        lines.extend(values)\n\n    return File(\n        dist_info_path(name, version, \"entry_points.txt\"),\n        \"\\n\".join(lines).encode(),\n    )\n\n\ndef make_files(files: dict[str, bytes | str]) -> list[File]:\n    return [File(name, ensure_binary(contents)) for name, contents in files.items()]\n\n\ndef make_metadata_files(\n    name: str, version: str, files: dict[str, AnyStr]\n) -> list[File]:\n    get_path = partial(dist_info_path, name, version)\n    return [\n        File(get_path(name), ensure_binary(contents))\n        for name, contents in files.items()\n    ]\n\n\ndef make_data_files(name: str, version: str, files: dict[str, AnyStr]) -> list[File]:\n    data_dir = f\"{name}-{version}.data\"\n    return [\n        File(f\"{data_dir}/{name}\", ensure_binary(contents))\n        for name, contents in files.items()\n    ]\n\n\ndef urlsafe_b64encode_nopad(data: bytes) -> str:\n    return urlsafe_b64encode(data).rstrip(b\"=\").decode(\"ascii\")\n\n\ndef digest(contents: bytes) -> str:\n    return f\"sha256={urlsafe_b64encode_nopad(sha256(contents).digest())}\"\n\n\ndef record_file_maker_wrapper(\n    name: str,\n    version: str,\n    files: Iterable[File],\n    record: Defaulted[AnyStr | None],\n) -> Iterable[File]:\n    records: list[Record] = []\n    for file in files:\n        records.append(\n            Record(file.name, digest(file.contents), str(len(file.contents)))\n        )\n        yield file\n\n    if record is None:\n        return\n\n    record_path = dist_info_path(name, version, \"RECORD\")\n\n    if record is not _default:\n        yield File(record_path, ensure_binary(record))\n        return\n\n    records.append(Record(record_path, \"\", \"\"))\n\n    with StringIO(newline=\"\") as buf:\n        writer = csv.writer(buf)\n        for r in records:\n            writer.writerow(r)\n        contents = buf.getvalue().encode(\"utf-8\")\n\n    yield File(record_path, contents)\n\n\ndef wheel_name(\n    name: str,\n    version: str,\n    pythons: Iterable[str],\n    abis: Iterable[str],\n    platforms: Iterable[str],\n) -> str:\n    stem = \"-\".join(\n        [\n            name,\n            version,\n            \".\".join(pythons),\n            \".\".join(abis),\n            \".\".join(platforms),\n        ]\n    )\n    return f\"{stem}.whl\"\n\n\nclass WheelBuilder:\n    \"\"\"A wheel that can be saved or converted to several formats.\"\"\"\n\n    def __init__(self, name: str, files: Iterable[File]) -> None:\n        self._name = name\n        self._files = files\n\n    def save_to_dir(self, path: Path | str) -> str:\n        \"\"\"Generate wheel file with correct name and save into the provided\n        directory.\n\n        :returns the wheel file path\n        \"\"\"\n        p = Path(path) / self._name\n        p.write_bytes(self.as_bytes())\n        return str(p)\n\n    def save_to(self, path: Path | str) -> str:\n        \"\"\"Generate wheel file, saving to the provided path. Any parent\n        directories must already exist.\n\n        :returns the wheel file path\n        \"\"\"\n        path = Path(path)\n        path.write_bytes(self.as_bytes())\n        return str(path)\n\n    def as_bytes(self) -> bytes:\n        with BytesIO() as buf:\n            with ZipFile(buf, \"w\") as z:\n                for file in self._files:\n                    z.writestr(file.name, file.contents)\n            return buf.getvalue()\n\n    def as_zipfile(self) -> ZipFile:\n        return ZipFile(BytesIO(self.as_bytes()))\n\n    def as_distribution(self, name: str) -> BaseDistribution:\n        stream = BytesIO(self.as_bytes())\n        return get_wheel_distribution(\n            MemoryWheel(self._name, stream), canonicalize_name(name)\n        )\n\n\ndef make_wheel(\n    name: str,\n    version: str,\n    wheel_metadata: Defaulted[AnyStr | None] = _default,\n    wheel_metadata_updates: Defaulted[dict[str, HeaderValue]] = _default,\n    metadata: Defaulted[AnyStr | None] = _default,\n    metadata_body: Defaulted[AnyStr] = _default,\n    metadata_updates: Defaulted[dict[str, HeaderValue]] = _default,\n    extra_files: Defaulted[dict[str, bytes | str]] = _default,\n    extra_metadata_files: Defaulted[dict[str, AnyStr]] = _default,\n    extra_data_files: Defaulted[dict[str, AnyStr]] = _default,\n    console_scripts: Defaulted[list[str]] = _default,\n    entry_points: Defaulted[dict[str, list[str]]] = _default,\n    record: Defaulted[AnyStr | None] = _default,\n) -> WheelBuilder:\n    \"\"\"\n    Helper function for generating test wheels which are compliant by default.\n\n    Examples:\n\n    ```\n    # Basic wheel, which will have valid metadata, RECORD, etc\n    make_wheel(name=\"foo\", version=\"0.1.0\")\n    # Wheel with custom metadata\n    make_wheel(\n        name=\"foo\",\n        version=\"0.1.0\",\n        metadata_updates={\n            # Overrides default\n            \"Name\": \"hello\",\n            # Expands into separate Requires-Dist entries\n            \"Requires-Dist\": [\"a == 1.0\", \"b == 2.0; sys_platform == 'win32'\"],\n        },\n    )\n    ```\n\n    After specifying the wheel, it can be consumed in several ways:\n\n    ```\n    # Normal case, valid wheel we want pip to pick up.\n    make_wheel(...).save_to_dir(tmpdir)\n    # For a test case, to check that pip validates contents against wheel name.\n    make_wheel(name=\"simple\", ...).save_to(tmpdir / \"notsimple-...\")\n    # In-memory, for unit tests.\n    z = make_wheel(...).as_zipfile()\n    ```\n\n    Below, any unicode value provided for AnyStr will be encoded as utf-8.\n\n    :param name: name of the distribution, propagated to the .dist-info\n        directory, METADATA, and wheel file name\n    :param version: version of the distribution, propagated to the .dist-info\n        directory, METADATA, and wheel file name\n    :param wheel_metadata: if provided and None, then no WHEEL metadata file\n        is generated; else if a string then sets the content of the WHEEL file\n    :param wheel_metadata_updates: override the default WHEEL metadata fields,\n        ignored if wheel_metadata is provided\n    :param metadata: if provided and None, then no METADATA file is generated;\n        else if a string then sets the content of the METADATA file\n    :param metadata_body: sets the value of the body text in METADATA, ignored\n        if metadata is provided\n    :param metadata_updates: override the default METADATA fields,\n        ignored if metadata is provided\n    :param extra_files: map from path to file contents for additional files to\n        be put in the wheel\n    :param extra_metadata_files: map from path (relative to .dist-info) to file\n        contents for additional files to be put in the wheel\n    :param extra_data_files: map from path (relative to .data) to file contents\n        for additional files to be put in the wheel\n    :param console_scripts: list of console scripts text to be put into\n        entry_points.txt - overrides any value set in entry_points\n    :param entry_points:\n    :param record: if provided and None, then no RECORD file is generated;\n        else if a string then sets the content of the RECORD file\n    \"\"\"\n    pythons = [\"py2\", \"py3\"]\n    abis = [\"none\"]\n    platforms = [\"any\"]\n    tags = list(itertools.product(pythons, abis, platforms))\n\n    possible_files = [\n        make_metadata_file(name, version, metadata, metadata_updates, metadata_body),\n        make_wheel_metadata_file(\n            name, version, wheel_metadata, tags, wheel_metadata_updates\n        ),\n        make_entry_points_file(name, version, entry_points, console_scripts),\n    ]\n\n    if extra_files is not _default:\n        possible_files.extend(make_files(extra_files))\n\n    if extra_metadata_files is not _default:\n        possible_files.extend(make_metadata_files(name, version, extra_metadata_files))\n\n    if extra_data_files is not _default:\n        possible_files.extend(make_data_files(name, version, extra_data_files))\n\n    actual_files = filter(None, possible_files)\n\n    files_and_record_file = record_file_maker_wrapper(\n        name, version, actual_files, record\n    )\n    wheel_file_name = wheel_name(name, version, pythons, abis, platforms)\n\n    return WheelBuilder(wheel_file_name, files_and_record_file)\n"
  },
  {
    "path": "tests/ruff.toml",
    "content": "# Extend the `pyproject.toml` file in the parent directory.\nextend = \"../pyproject.toml\"\n\n# And extend linting to include pytest specific rules and configuration\n[lint]\nextend-select = [\"PT\"]\nignore = [\"PT011\"]\n\n[lint.flake8-pytest-style]\nmark-parentheses = false\nfixture-parentheses = false\nparametrize-names-type = \"csv\"\nparametrize-values-type = \"list\"\nparametrize-values-row-type = \"tuple\"\n"
  },
  {
    "path": "tests/unit/__init__.py",
    "content": ""
  },
  {
    "path": "tests/unit/metadata/test_metadata.py",
    "content": "import logging\nimport os\nfrom pathlib import Path\nfrom typing import cast\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    get_directory_distribution,\n    get_environment,\n    get_wheel_distribution,\n)\nfrom pip._internal.metadata.base import FilesystemWheel\nfrom pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, ArchiveInfo\n\nfrom tests.lib.wheel import make_wheel\n\n\n@mock.patch.object(BaseDistribution, \"read_text\", side_effect=FileNotFoundError)\ndef test_dist_get_direct_url_no_metadata(mock_read_text: mock.Mock) -> None:\n    class FakeDistribution(BaseDistribution):\n        pass\n\n    dist = FakeDistribution()  # type: ignore\n    assert dist.direct_url is None\n    mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME)\n\n\n@mock.patch.object(BaseDistribution, \"read_text\", return_value=\"{}\")\ndef test_dist_get_direct_url_invalid_json(\n    mock_read_text: mock.Mock, caplog: pytest.LogCaptureFixture\n) -> None:\n    class FakeDistribution(BaseDistribution):\n        canonical_name = cast(NormalizedName, \"whatever\")  # Needed for error logging.\n\n    dist = FakeDistribution()  # type: ignore\n    with caplog.at_level(logging.WARNING):\n        assert dist.direct_url is None\n\n    mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME)\n    assert (\n        caplog.records[-1]\n        .getMessage()\n        .startswith(\n            \"Error parsing direct_url.json for whatever:\",\n        )\n    )\n\n\ndef test_metadata_reads_egg_info_requires_txt(tmp_path: Path) -> None:\n    \"\"\"Check Requires-Dist is obtained from requires.txt if absent in PKG-INFO.\"\"\"\n    egg_info_path = tmp_path / \"whatever.egg-info\"\n    egg_info_path.mkdir()\n    dist = get_directory_distribution(str(egg_info_path))\n    assert dist.installed_with_setuptools_egg_info\n    pkg_info_path = egg_info_path / \"PKG-INFO\"\n    pkg_info_path.write_text(\"Name: whatever\\n\")\n    egg_info_path.joinpath(\"requires.txt\").write_text(\"pkga\\npkgb\\n\")\n    assert dist.metadata.get_all(\"Requires-Dist\") == [\"pkga\", \"pkgb\"]\n\n\ndef test_metadata_pkg_info_requires_priority(tmp_path: Path) -> None:\n    \"\"\"Check Requires-Dist in PKG-INFO has priority over requires.txt.\"\"\"\n    egg_info_path = tmp_path / \"whatever.egg-info\"\n    egg_info_path.mkdir()\n    dist = get_directory_distribution(str(egg_info_path))\n    assert dist.installed_with_setuptools_egg_info\n    pkg_info_path = egg_info_path / \"PKG-INFO\"\n    pkg_info_path.write_text(\n        \"Name: whatever\\nRequires-Dist: pkgc\\nRequires-Dist: pkgd\\n\"\n    )\n    egg_info_path.joinpath(\"requires.txt\").write_text(\"pkga\\npkgb\\n\")\n    assert dist.metadata.get_all(\"Requires-Dist\") == [\"pkgc\", \"pkgd\"]\n\n\n@mock.patch.object(\n    BaseDistribution,\n    \"read_text\",\n    return_value='{\"url\": \"https://e.c/p.tgz\", \"archive_info\": {}}',\n)\ndef test_dist_get_direct_url_valid_metadata(mock_read_text: mock.Mock) -> None:\n    class FakeDistribution(BaseDistribution):\n        pass\n\n    dist = FakeDistribution()  # type: ignore\n    direct_url = dist.direct_url\n    assert direct_url is not None\n    mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME)\n    assert direct_url.url == \"https://e.c/p.tgz\"\n    assert isinstance(direct_url.info, ArchiveInfo)\n\n\ndef test_metadata_dict(tmp_path: Path) -> None:\n    \"\"\"Basic test of BaseDistribution metadata_dict.\n\n    More tests are available in the original pkg_metadata project where this\n    function comes from, and which we may vendor in the future.\n    \"\"\"\n    wheel_path = make_wheel(name=\"pkga\", version=\"1.0.1\").save_to_dir(tmp_path)\n    wheel = FilesystemWheel(wheel_path)\n    dist = get_wheel_distribution(wheel, canonicalize_name(\"pkga\"))\n    metadata_dict = dist.metadata_dict\n    assert metadata_dict[\"name\"] == \"pkga\"\n    assert metadata_dict[\"version\"] == \"1.0.1\"\n\n\ndef test_no_dist_found_in_wheel(tmp_path: Path) -> None:\n    location = os.fspath(tmp_path.joinpath(\"pkg-1-py3-none-any.whl\"))\n    make_wheel(name=\"pkg\", version=\"1\").save_to(location)\n    assert get_environment([location]).get_distribution(\"pkg\") is None\n\n\ndef test_dist_found_in_directory_named_whl(tmp_path: Path) -> None:\n    dir_path = tmp_path.joinpath(\"pkg-1-py3-none-any.whl\")\n    info_path = dir_path.joinpath(\"pkg-1.dist-info\")\n    info_path.mkdir(parents=True)\n    info_path.joinpath(\"METADATA\").write_text(\"Name: pkg\")\n    location = os.fspath(dir_path)\n    dist = get_environment([location]).get_distribution(\"pkg\")\n    assert dist is not None\n    assert dist.location is not None\n    assert Path(dist.location) == Path(location)\n\n\ndef test_dist_found_in_zip(tmp_path: Path) -> None:\n    location = os.fspath(tmp_path.joinpath(\"pkg.zip\"))\n    make_wheel(name=\"pkg\", version=\"1\").save_to(location)\n    dist = get_environment([location]).get_distribution(\"pkg\")\n    assert dist is not None\n    assert dist.location is not None\n    assert Path(dist.location) == Path(location)\n\n\n@pytest.mark.parametrize(\n    \"path\",\n    [\n        \"/path/to/foo.egg-info\".replace(\"/\", os.path.sep),\n        # Tests issue fixed by https://github.com/pypa/pip/pull/2530\n        \"/path/to/foo.egg-info/\".replace(\"/\", os.path.sep),\n    ],\n)\ndef test_trailing_slash_directory_metadata(path: str) -> None:\n    dist = get_directory_distribution(path)\n    assert dist.raw_name == dist.canonical_name == \"foo\"\n    assert dist.location == \"/path/to\".replace(\"/\", os.path.sep)\n"
  },
  {
    "path": "tests/unit/metadata/test_metadata_pkg_resources.py",
    "content": "import email.message\nimport itertools\nfrom typing import cast\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import UnsupportedWheel\nfrom pip._internal.metadata.pkg_resources import (\n    Distribution,\n    Environment,\n    InMemoryMetadata,\n)\n\npkg_resources = pytest.importorskip(\"pip._vendor.pkg_resources\")\n\n\ndef _dist_is_local(dist: mock.Mock) -> bool:\n    return dist.kind != \"global\" and dist.kind != \"user\"\n\n\ndef _dist_in_usersite(dist: mock.Mock) -> bool:\n    return dist.kind == \"user\"\n\n\n@pytest.fixture(autouse=True)\ndef patch_distribution_lookups(monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setattr(Distribution, \"local\", property(_dist_is_local))\n    monkeypatch.setattr(Distribution, \"in_usersite\", property(_dist_in_usersite))\n\n\nclass _MockWorkingSet(list[mock.Mock]):\n    def require(self, name: str) -> None:\n        pass\n\n\nworkingset = _MockWorkingSet(\n    (\n        mock.Mock(test_name=\"global\", project_name=\"global\"),\n        mock.Mock(test_name=\"editable\", project_name=\"editable\"),\n        mock.Mock(test_name=\"normal\", project_name=\"normal\"),\n        mock.Mock(test_name=\"user\", project_name=\"user\"),\n    )\n)\n\nworkingset_stdlib = _MockWorkingSet(\n    (\n        mock.Mock(test_name=\"normal\", project_name=\"argparse\"),\n        mock.Mock(test_name=\"normal\", project_name=\"wsgiref\"),\n    )\n)\n\n\n@pytest.mark.parametrize(\n    \"ws, req_name\",\n    itertools.chain(\n        itertools.product(\n            [workingset],\n            (d.project_name for d in workingset),\n        ),\n        itertools.product(\n            [workingset_stdlib],\n            (d.project_name for d in workingset_stdlib),\n        ),\n    ),\n)\ndef test_get_distribution(ws: _MockWorkingSet, req_name: str) -> None:\n    \"\"\"Ensure get_distribution() finds all kinds of distributions.\"\"\"\n    dist = Environment(ws).get_distribution(req_name)\n    assert dist is not None\n    assert cast(Distribution, dist)._dist.project_name == req_name\n\n\ndef test_get_distribution_nonexist() -> None:\n    dist = Environment(workingset).get_distribution(\"non-exist\")\n    assert dist is None\n\n\ndef test_wheel_metadata_works() -> None:\n    name = \"simple\"\n    version = \"0.1.0\"\n    require_a = \"a==1.0\"\n    require_b = 'b==1.1; extra == \"also_b\"'\n    requires = [require_a, require_b, 'c==1.2; extra == \"also_c\"']\n    extras = [\"also_b\", \"also_c\"]\n    requires_python = \">=3\"\n\n    metadata = email.message.Message()\n    metadata[\"Name\"] = name\n    metadata[\"Version\"] = version\n    for require in requires:\n        metadata[\"Requires-Dist\"] = require\n    for extra in extras:\n        metadata[\"Provides-Extra\"] = extra\n    metadata[\"Requires-Python\"] = requires_python\n\n    dist = Distribution(\n        pkg_resources.DistInfoDistribution(\n            location=\"<in-memory>\",\n            metadata=InMemoryMetadata({\"METADATA\": metadata.as_bytes()}, \"<in-memory>\"),\n            project_name=name,\n        ),\n    )\n\n    assert name == dist.canonical_name == dist.raw_name\n    assert parse_version(version) == dist.version\n    assert {canonicalize_name(e) for e in extras} == set(dist.iter_provided_extras())\n    assert [require_a] == [str(r) for r in dist.iter_dependencies()]\n    assert [Requirement(require_a), Requirement(require_b)] == [\n        Requirement(str(r)) for r in dist.iter_dependencies([\"also_b\"])\n    ]\n    assert metadata.as_string() == dist.metadata.as_string()\n    assert SpecifierSet(requires_python) == dist.requires_python\n\n\ndef test_wheel_metadata_throws_on_bad_unicode() -> None:\n    metadata = InMemoryMetadata({\"METADATA\": b\"\\xff\"}, \"<in-memory>\")\n\n    with pytest.raises(UnsupportedWheel) as e:\n        metadata.get_metadata(\"METADATA\")\n    assert \"METADATA\" in str(e.value)\n"
  },
  {
    "path": "tests/unit/resolution_resolvelib/__init__.py",
    "content": ""
  },
  {
    "path": "tests/unit/resolution_resolvelib/conftest.py",
    "content": "from collections.abc import Iterator\n\nimport pytest\n\nfrom pip._internal.cli.req_command import RequirementCommand\nfrom pip._internal.commands.install import InstallCommand\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\n\n# from pip._internal.models.index import PyPI\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import install_req_from_line\nfrom pip._internal.resolution.resolvelib.factory import Factory\nfrom pip._internal.resolution.resolvelib.provider import PipProvider\nfrom pip._internal.utils.temp_dir import TempDirectory, global_tempdir_manager\n\nfrom tests.lib import TestData\n\n\n@pytest.fixture\ndef finder(data: TestData) -> PackageFinder:\n    session = PipSession()\n    scope = SearchScope([str(data.packages)], [], False)\n    collector = LinkCollector(session, scope)\n    prefs = SelectionPreferences(allow_yanked=False)\n    finder = PackageFinder.create(collector, prefs)\n    return finder\n\n\n@pytest.fixture\ndef preparer(finder: PackageFinder) -> Iterator[RequirementPreparer]:\n    session = PipSession()\n    rc = InstallCommand(\"x\", \"y\")\n    o = rc.parse_args([\"--no-build-isolation\"])\n\n    with global_tempdir_manager():\n        with TempDirectory() as tmp:\n            with get_build_tracker() as tracker:\n                preparer = RequirementCommand.make_requirement_preparer(\n                    tmp,\n                    options=o[0],\n                    build_tracker=tracker,\n                    session=session,\n                    finder=finder,\n                    use_user_site=False,\n                    verbosity=0,\n                )\n\n                yield preparer\n\n\n@pytest.fixture\ndef factory(finder: PackageFinder, preparer: RequirementPreparer) -> Factory:\n    return Factory(\n        finder=finder,\n        preparer=preparer,\n        make_install_req=install_req_from_line,\n        wheel_cache=None,\n        use_user_site=False,\n        force_reinstall=False,\n        ignore_installed=False,\n        ignore_requires_python=False,\n        py_version_info=None,\n    )\n\n\n@pytest.fixture\ndef provider(factory: Factory) -> PipProvider:\n    return PipProvider(\n        factory=factory,\n        constraints={},\n        ignore_dependencies=False,\n        upgrade_strategy=\"to-satisfy-only\",\n        user_requested={},\n    )\n"
  },
  {
    "path": "tests/unit/resolution_resolvelib/test_provider.py",
    "content": "from __future__ import annotations\n\nimport math\nfrom collections.abc import Iterable, Sequence\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom pip._vendor.resolvelib.resolvers import RequirementInformation\n\nfrom pip._internal.req.constructors import install_req_from_req_string\nfrom pip._internal.resolution.resolvelib.base import Candidate\nfrom pip._internal.resolution.resolvelib.candidates import REQUIRES_PYTHON_IDENTIFIER\nfrom pip._internal.resolution.resolvelib.factory import Factory\nfrom pip._internal.resolution.resolvelib.provider import PipProvider\nfrom pip._internal.resolution.resolvelib.requirements import (\n    ExplicitRequirement,\n    SpecifierRequirement,\n)\n\nif TYPE_CHECKING:\n    from pip._vendor.resolvelib.providers import Preference\n\n    from pip._internal.resolution.resolvelib.base import Candidate, Requirement\n\n    PreferenceInformation = RequirementInformation[Requirement, Candidate]\n\n\nclass FakeCandidate(Candidate):\n    \"\"\"A minimal fake candidate for testing purposes.\"\"\"\n\n    def __init__(self, *args: object, **kwargs: object) -> None: ...\n\n\ndef build_req_info(name: str, parent: Candidate | None = None) -> PreferenceInformation:\n    install_requirement = install_req_from_req_string(name)\n\n    requirement_information: PreferenceInformation = RequirementInformation(\n        requirement=SpecifierRequirement(install_requirement),\n        parent=parent,\n    )\n\n    return requirement_information\n\n\ndef build_explicit_req_info(\n    url: str, parent: Candidate | None = None\n) -> PreferenceInformation:\n    \"\"\"Build a direct requirement using a minimal FakeCandidate.\"\"\"\n    direct_requirement = ExplicitRequirement(FakeCandidate(url))\n    return RequirementInformation(requirement=direct_requirement, parent=parent)\n\n\n@pytest.mark.parametrize(\n    \"identifier, information, backtrack_causes, user_requested, expected\",\n    [\n        # Pinned package with \"==\"\n        (\n            \"pinned-package\",\n            {\"pinned-package\": [build_req_info(\"pinned-package==1.0\")]},\n            [],\n            {},\n            (True, False, True, math.inf, False, \"pinned-package\"),\n        ),\n        # Star-specified package, i.e. with \"*\"\n        (\n            \"star-specified-package\",\n            {\"star-specified-package\": [build_req_info(\"star-specified-package==1.*\")]},\n            [],\n            {},\n            (True, True, False, math.inf, False, \"star-specified-package\"),\n        ),\n        # Package that caused backtracking\n        (\n            \"backtrack-package\",\n            {\"backtrack-package\": [build_req_info(\"backtrack-package\")]},\n            [build_req_info(\"backtrack-package\")],\n            {},\n            (True, True, True, math.inf, True, \"backtrack-package\"),\n        ),\n        # Root package requested by user\n        (\n            \"root-package\",\n            {\"root-package\": [build_req_info(\"root-package\")]},\n            [],\n            {\"root-package\": 1},\n            (True, True, True, 1, True, \"root-package\"),\n        ),\n        # Unfree package (with specifier operator)\n        (\n            \"unfree-package\",\n            {\"unfree-package\": [build_req_info(\"unfree-package!=1\")]},\n            [],\n            {},\n            (True, True, True, math.inf, False, \"unfree-package\"),\n        ),\n        # Free package (no operator)\n        (\n            \"free-package\",\n            {\"free-package\": [build_req_info(\"free-package\")]},\n            [],\n            {},\n            (True, True, True, math.inf, True, \"free-package\"),\n        ),\n        # Test case for \"direct\" preference (explicit URL)\n        (\n            \"direct-package\",\n            {\"direct-package\": [build_explicit_req_info(\"direct-package\")]},\n            [],\n            {},\n            (False, True, True, math.inf, True, \"direct-package\"),\n        ),\n        # Upper bounded with <= operator\n        (\n            \"upper-bound-lte-package\",\n            {\n                \"upper-bound-lte-package\": [\n                    build_req_info(\"upper-bound-lte-package<=2.0\")\n                ]\n            },\n            [],\n            {},\n            (True, True, False, math.inf, False, \"upper-bound-lte-package\"),\n        ),\n        # Upper bounded with < operator\n        (\n            \"upper-bound-lt-package\",\n            {\"upper-bound-lt-package\": [build_req_info(\"upper-bound-lt-package<2.0\")]},\n            [],\n            {},\n            (True, True, False, math.inf, False, \"upper-bound-lt-package\"),\n        ),\n        # Upper bounded with ~= operator\n        (\n            \"upper-bound-compatible-package\",\n            {\n                \"upper-bound-compatible-package\": [\n                    build_req_info(\"upper-bound-compatible-package~=1.0\")\n                ]\n            },\n            [],\n            {},\n            (True, True, False, math.inf, False, \"upper-bound-compatible-package\"),\n        ),\n        # Not upper bounded, using only >= operator\n        (\n            \"lower-bound-package\",\n            {\"lower-bound-package\": [build_req_info(\"lower-bound-package>=1.0\")]},\n            [],\n            {},\n            (True, True, True, math.inf, False, \"lower-bound-package\"),\n        ),\n    ],\n)\ndef test_get_preference(\n    identifier: str,\n    information: dict[str, Iterable[PreferenceInformation]],\n    backtrack_causes: Sequence[PreferenceInformation],\n    user_requested: dict[str, int],\n    expected: Preference,\n    factory: Factory,\n) -> None:\n    provider = PipProvider(\n        factory=factory,\n        constraints={},\n        ignore_dependencies=False,\n        upgrade_strategy=\"to-satisfy-only\",\n        user_requested=user_requested,\n    )\n\n    preference = provider.get_preference(\n        identifier, {}, {}, information, backtrack_causes\n    )\n\n    assert preference == expected, f\"Expected {expected}, got {preference}\"\n\n\n@pytest.mark.parametrize(\n    \"identifiers, backtrack_causes, expected\",\n    [\n        # REQUIRES_PYTHON_IDENTIFIER is present\n        (\n            [REQUIRES_PYTHON_IDENTIFIER, \"package1\", \"package2\", \"backtrack-package\"],\n            [build_req_info(\"backtrack-package\")],\n            [REQUIRES_PYTHON_IDENTIFIER],\n        ),\n        # REQUIRES_PYTHON_IDENTIFIER is present after backtrack causes\n        (\n            [\"package1\", \"package2\", \"backtrack-package\", REQUIRES_PYTHON_IDENTIFIER],\n            [build_req_info(\"backtrack-package\")],\n            [REQUIRES_PYTHON_IDENTIFIER],\n        ),\n        # Backtrack causes present (direct requirement)\n        (\n            [\"package1\", \"package2\", \"backtrack-package\"],\n            [build_req_info(\"backtrack-package\")],\n            [\"backtrack-package\"],\n        ),\n        # Multiple backtrack causes\n        (\n            [\"package1\", \"backtrack1\", \"backtrack2\", \"package2\"],\n            [build_req_info(\"backtrack1\"), build_req_info(\"backtrack2\")],\n            [\"backtrack1\", \"backtrack2\"],\n        ),\n        # No special identifiers - return all\n        (\n            [\"package1\", \"package2\"],\n            [],\n            [\"package1\", \"package2\"],\n        ),\n        # Empty list of identifiers\n        (\n            [],\n            [],\n            [],\n        ),\n    ],\n)\ndef test_narrow_requirement_selection(\n    identifiers: list[str],\n    backtrack_causes: Sequence[PreferenceInformation],\n    expected: list[str],\n    factory: Factory,\n) -> None:\n    \"\"\"Test that narrow_requirement_selection correctly prioritizes identifiers:\n    1. REQUIRES_PYTHON_IDENTIFIER (if present)\n    2. Backtrack causes (if present)\n    3. All other identifiers (as-is)\n    \"\"\"\n    provider = PipProvider(\n        factory=factory,\n        constraints={},\n        ignore_dependencies=False,\n        upgrade_strategy=\"to-satisfy-only\",\n        user_requested={},\n    )\n\n    result = provider.narrow_requirement_selection(\n        identifiers, {}, {}, {}, backtrack_causes\n    )\n\n    assert list(result) == expected, f\"Expected {expected}, got {list(result)}\"\n"
  },
  {
    "path": "tests/unit/resolution_resolvelib/test_requirement.py",
    "content": "import os\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._vendor.resolvelib import BaseReporter, Resolver\n\nfrom pip._internal.resolution.resolvelib.base import Candidate, Constraint, Requirement\nfrom pip._internal.resolution.resolvelib.factory import Factory\nfrom pip._internal.resolution.resolvelib.provider import PipProvider\n\nfrom tests.lib import TestData\n\n# NOTE: All tests are prefixed `test_rlr` (for \"test resolvelib resolver\").\n#       This helps select just these tests using pytest's `-k` option, and\n#       keeps test names shorter.\n\n# Basic tests:\n#   Create a requirement from a project name - \"pip\"\n#   Create a requirement from a name + version constraint - \"pip >= 20.0\"\n#   Create a requirement from a wheel filename\n#   Create a requirement from a sdist filename\n#   Create a requirement from a local directory (which has no obvious name!)\n#   Editables\n\n\ndef _is_satisfied_by(requirement: Requirement, candidate: Candidate) -> bool:\n    \"\"\"A helper function to check if a requirement is satisfied by a candidate.\n\n    Used for mocking PipProvider.is_satisfied_by.\n    \"\"\"\n    return requirement.is_satisfied_by(candidate)\n\n\n@pytest.fixture\ndef test_cases(data: TestData) -> list[tuple[str, str, int]]:\n    def _data_file(name: str) -> Path:\n        return data.packages.joinpath(name)\n\n    def data_file(name: str) -> str:\n        return os.fspath(_data_file(name))\n\n    def data_url(name: str) -> str:\n        return _data_file(name).as_uri()\n\n    test_cases = [\n        # requirement, name, matches\n        # Version specifiers\n        (\"simple\", \"simple\", 3),\n        (\"simple>1.0\", \"simple\", 2),\n        # (\"simple[extra]==1.0\", \"simple[extra]\", 1),\n        # Wheels\n        (data_file(\"simplewheel-1.0-py2.py3-none-any.whl\"), \"simplewheel\", 1),\n        (data_url(\"simplewheel-1.0-py2.py3-none-any.whl\"), \"simplewheel\", 1),\n        # Direct URLs\n        # TODO: The following test fails\n        # (\"foo @ \" + data_url(\"simple-1.0.tar.gz\"), \"foo\", 1),\n        # SDists\n        # TODO: sdists should have a name\n        (data_file(\"simple-1.0.tar.gz\"), \"simple\", 1),\n        (data_url(\"simple-1.0.tar.gz\"), \"simple\", 1),\n        # TODO: directory, editables\n    ]\n\n    return test_cases\n\n\ndef test_new_resolver_requirement_has_name(\n    test_cases: list[tuple[str, str, int]], factory: Factory\n) -> None:\n    \"\"\"All requirements should have a name\"\"\"\n    for spec, name, _ in test_cases:\n        reqs = list(factory.make_requirements_from_spec(spec, comes_from=None))\n        assert len(reqs) == 1\n        assert reqs[0].name == name\n\n\ndef test_new_resolver_correct_number_of_matches(\n    test_cases: list[tuple[str, str, int]], factory: Factory\n) -> None:\n    \"\"\"Requirements should return the correct number of candidates\"\"\"\n    for spec, _, match_count in test_cases:\n        reqs = list(factory.make_requirements_from_spec(spec, comes_from=None))\n        assert len(reqs) == 1\n        req = reqs[0]\n        matches = factory.find_candidates(\n            req.name,\n            {req.name: [req]},\n            {},\n            Constraint.empty(),\n            prefers_installed=False,\n            is_satisfied_by=_is_satisfied_by,\n        )\n        assert sum(1 for _ in matches) == match_count\n\n\ndef test_new_resolver_candidates_match_requirement(\n    test_cases: list[tuple[str, str, int]], factory: Factory\n) -> None:\n    \"\"\"Candidates returned from find_candidates should satisfy the requirement\"\"\"\n    for spec, _, _ in test_cases:\n        reqs = list(factory.make_requirements_from_spec(spec, comes_from=None))\n        assert len(reqs) == 1\n        req = reqs[0]\n        candidates = factory.find_candidates(\n            req.name,\n            {req.name: [req]},\n            {},\n            Constraint.empty(),\n            prefers_installed=False,\n            is_satisfied_by=_is_satisfied_by,\n        )\n        for c in candidates:\n            assert isinstance(c, Candidate)\n            assert req.is_satisfied_by(c)\n\n\ndef test_new_resolver_full_resolve(factory: Factory, provider: PipProvider) -> None:\n    \"\"\"A very basic full resolve\"\"\"\n    reqs = list(factory.make_requirements_from_spec(\"simplewheel\", comes_from=None))\n    assert len(reqs) == 1\n    r: Resolver[Requirement, Candidate, str] = Resolver(provider, BaseReporter())\n    result = r.resolve(reqs)\n    assert set(result.mapping.keys()) == {\"simplewheel\"}\n"
  },
  {
    "path": "tests/unit/resolution_resolvelib/test_resolver.py",
    "content": "from __future__ import annotations\n\nfrom typing import cast\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.resolvelib.resolvers import Result\nfrom pip._vendor.resolvelib.structs import DirectedGraph\n\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import install_req_from_line\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.resolvelib.resolver import (\n    Resolver,\n    get_topological_weights,\n)\n\n\n@pytest.fixture\ndef resolver(preparer: RequirementPreparer, finder: PackageFinder) -> Resolver:\n    resolver = Resolver(\n        preparer=preparer,\n        finder=finder,\n        wheel_cache=None,\n        make_install_req=mock.Mock(),\n        use_user_site=False,\n        ignore_dependencies=False,\n        ignore_installed=False,\n        ignore_requires_python=False,\n        force_reinstall=False,\n        upgrade_strategy=\"to-satisfy-only\",\n    )\n    return resolver\n\n\ndef _make_graph(\n    edges: list[tuple[str | None, str | None]],\n) -> DirectedGraph[str | None]:\n    \"\"\"Build graph from edge declarations.\"\"\"\n\n    graph: DirectedGraph[str | None] = DirectedGraph()\n    for parent, child in edges:\n        parent = cast(str, canonicalize_name(parent)) if parent else None\n        child = cast(str, canonicalize_name(child)) if child else None\n        for v in (parent, child):\n            if v not in graph:\n                graph.add(v)\n        graph.connect(parent, child)\n    return graph\n\n\n@pytest.mark.parametrize(\n    \"edges, ordered_reqs\",\n    [\n        (\n            [(None, \"require-simple\"), (\"require-simple\", \"simple\")],\n            [\"simple==3.0\", \"require-simple==1.0\"],\n        ),\n        (\n            [(None, \"meta\"), (\"meta\", \"simple\"), (\"meta\", \"simple2\")],\n            [\"simple2==3.0\", \"simple==3.0\", \"meta==1.0\"],\n        ),\n        (\n            [\n                (None, \"toporequires\"),\n                (None, \"toporequires2\"),\n                (None, \"toporequires3\"),\n                (None, \"toporequires4\"),\n                (\"toporequires2\", \"toporequires\"),\n                (\"toporequires3\", \"toporequires\"),\n                (\"toporequires4\", \"toporequires\"),\n                (\"toporequires4\", \"toporequires2\"),\n                (\"toporequires4\", \"toporequires3\"),\n            ],\n            [\n                \"toporequires==0.0.1\",\n                \"toporequires3==0.0.1\",\n                \"toporequires2==0.0.1\",\n                \"toporequires4==0.0.1\",\n            ],\n        ),\n    ],\n)\ndef test_new_resolver_get_installation_order(\n    resolver: Resolver,\n    edges: list[tuple[str | None, str | None]],\n    ordered_reqs: list[str],\n) -> None:\n    graph = _make_graph(edges)\n\n    # Mapping values and criteria are not used in test, so we stub them out.\n    mapping = {vertex: None for vertex in graph if vertex is not None}\n    resolver._result = Result(mapping, graph, criteria=None)  # type: ignore\n\n    reqset = RequirementSet()\n    for r in ordered_reqs:\n        reqset.add_named_requirement(install_req_from_line(r))\n\n    ireqs = resolver.get_installation_order(reqset)\n    req_strs = [str(r.req) for r in ireqs]\n    assert req_strs == ordered_reqs\n\n\n@pytest.mark.parametrize(\n    \"name, edges, requirement_keys, expected_weights\",\n    [\n        (\n            # From https://github.com/pypa/pip/pull/8127#discussion_r414564664\n            \"deep second edge\",\n            [\n                (None, \"one\"),\n                (None, \"two\"),\n                (\"one\", \"five\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"five\": 5, \"four\": 4, \"one\": 4, \"three\": 2, \"two\": 1},\n        ),\n        (\n            \"linear\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND restricted\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n            ],\n            {\"one\", \"three\", \"five\"},\n            {\"one\": 1, \"three\": 3, \"five\": 5},\n        ),\n        (\n            \"linear AND root -> two\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (None, \"two\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND root -> three\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (None, \"three\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND root -> four\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (None, \"four\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND root -> five\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (None, \"five\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND one -> four\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"one\", \"four\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND two -> four\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"two\", \"four\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND four -> one (cycle)\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"four\", \"one\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND four -> two (cycle)\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"four\", \"two\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND four -> three (cycle)\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"four\", \"three\"),\n            ],\n            {\"one\", \"two\", \"three\", \"four\", \"five\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5},\n        ),\n        (\n            \"linear AND four -> three (cycle) AND restricted 1-2-3\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"four\", \"three\"),\n            ],\n            {\"one\", \"two\", \"three\"},\n            {\"one\": 1, \"two\": 2, \"three\": 3},\n        ),\n        (\n            \"linear AND four -> three (cycle) AND restricted 4-5\",\n            [\n                (None, \"one\"),\n                (\"one\", \"two\"),\n                (\"two\", \"three\"),\n                (\"three\", \"four\"),\n                (\"four\", \"five\"),\n                (\"four\", \"three\"),\n            ],\n            {\"four\", \"five\"},\n            {\"four\": 4, \"five\": 5},\n        ),\n    ],\n)\ndef test_new_resolver_topological_weights(\n    name: str,\n    edges: list[tuple[str | None, str | None]],\n    requirement_keys: set[str],\n    expected_weights: dict[str | None, int],\n) -> None:\n    graph = _make_graph(edges)\n\n    weights = get_topological_weights(graph, requirement_keys)\n    assert weights == expected_weights\n"
  },
  {
    "path": "tests/unit/test_appdirs.py",
    "content": "# mypy: no-warn-unused-ignores\n\nimport os\nimport sys\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor import platformdirs\n\nfrom pip._internal.utils import appdirs\n\n\nclass TestUserCacheDir:\n    @pytest.mark.skipif(sys.platform != \"win32\", reason=\"Windows-only test\")\n    def test_user_cache_dir_win(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        _get_win_folder = mock.Mock(return_value=\"C:\\\\Users\\\\test\\\\AppData\\\\Local\")\n\n        monkeypatch.setattr(\n            platformdirs.windows,  # type: ignore\n            \"get_win_folder\",\n            _get_win_folder,\n            raising=False,\n        )\n\n        assert (\n            appdirs.user_cache_dir(\"pip\")\n            == \"C:\\\\Users\\\\test\\\\AppData\\\\Local\\\\pip\\\\Cache\"\n        )\n        assert _get_win_folder.call_args_list == [mock.call(\"CSIDL_LOCAL_APPDATA\")]\n\n    @pytest.mark.skipif(sys.platform != \"darwin\", reason=\"MacOS-only test\")\n    def test_user_cache_dir_osx(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.user_cache_dir(\"pip\") == \"/home/test/Library/Caches/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_cache_dir_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.delenv(\"XDG_CACHE_HOME\", raising=False)\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.user_cache_dir(\"pip\") == \"/home/test/.cache/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_cache_dir_linux_override(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"XDG_CACHE_HOME\", \"/home/test/.other-cache\")\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.user_cache_dir(\"pip\") == \"/home/test/.other-cache/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_cache_dir_linux_home_slash(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # Verify that we are not affected by https://bugs.python.org/issue14768\n        monkeypatch.delenv(\"XDG_CACHE_HOME\", raising=False)\n        monkeypatch.setenv(\"HOME\", \"/\")\n\n        assert appdirs.user_cache_dir(\"pip\") == \"/.cache/pip\"\n\n    def test_user_cache_dir_unicode(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        if sys.platform != \"win32\":\n            return\n\n        def my_get_win_folder(csidl_name: str) -> str:\n            return \"\\u00df\\u00e4\\u03b1\\u20ac\"\n\n        monkeypatch.setattr(\n            platformdirs.windows,  # type: ignore\n            \"get_win_folder\",\n            my_get_win_folder,\n        )\n\n        # Do not use the isinstance expression directly in the\n        # assert statement, as the Unicode characters in the result\n        # cause pytest to fail with an internal error on Python 2.7\n        result_is_str = isinstance(appdirs.user_cache_dir(\"test\"), str)\n        assert result_is_str, \"user_cache_dir did not return a str\"\n\n        # Test against regression #3463\n        from pip._internal.cli.main_parser import create_main_parser\n\n        create_main_parser().print_help()  # This should not crash\n\n\nclass TestSiteConfigDirs:\n    @pytest.mark.skipif(sys.platform != \"win32\", reason=\"Windows-only test\")\n    def test_site_config_dirs_win(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        _get_win_folder = mock.Mock(return_value=\"C:\\\\ProgramData\")\n\n        monkeypatch.setattr(\n            platformdirs.windows,  # type: ignore\n            \"get_win_folder\",\n            _get_win_folder,\n            raising=False,\n        )\n\n        assert appdirs.site_config_dirs(\"pip\") == [\"C:\\\\ProgramData\\\\pip\"]\n        assert _get_win_folder.call_args_list == [mock.call(\"CSIDL_COMMON_APPDATA\")]\n\n    @pytest.mark.skipif(sys.platform != \"darwin\", reason=\"MacOS-only test\")\n    def test_site_config_dirs_osx(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.site_config_dirs(\"pip\") == [\n            \"/Library/Application Support/pip\",\n        ]\n\n    @pytest.mark.skipif(sys.platform != \"darwin\", reason=\"MacOS-only test\")\n    def test_site_config_dirs_osx_homebrew(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        python_version = f\"{sys.version_info[0]}.{sys.version_info[1]}\"\n        monkeypatch.setattr(\n            sys,\n            \"prefix\",\n            f\"/opt/homebrew/opt/python@{python_version}/Frameworks/Python.framework/Versions/{python_version}\",\n        )\n\n        assert appdirs.site_config_dirs(\"pip\") == [\n            \"/opt/homebrew/share/pip\",\n            \"/Library/Application Support/pip\",\n        ]\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_site_config_dirs_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.delenv(\"XDG_CONFIG_DIRS\", raising=False)\n\n        assert appdirs.site_config_dirs(\"pip\") == [\n            \"/etc/xdg/pip\",\n            \"/etc\",\n        ]\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_site_config_dirs_linux_override(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(os, \"pathsep\", \":\")\n        monkeypatch.setenv(\"XDG_CONFIG_DIRS\", \"/spam:/etc:/etc/xdg\")\n\n        assert appdirs.site_config_dirs(\"pip\") == [\n            \"/spam/pip\",\n            \"/etc/pip\",\n            \"/etc/xdg/pip\",\n            \"/etc\",\n        ]\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_site_config_dirs_linux_empty(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(os, \"pathsep\", \":\")\n        monkeypatch.setenv(\"XDG_CONFIG_DIRS\", \"\")\n        assert appdirs.site_config_dirs(\"pip\") == [\n            \"/etc/xdg/pip\",\n            \"/etc\",\n        ]\n\n\nclass TestUserConfigDir:\n    @pytest.mark.skipif(sys.platform != \"win32\", reason=\"Windows-only test\")\n    def test_user_config_dir_win_no_roaming(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        _get_win_folder = mock.Mock(return_value=\"C:\\\\Users\\\\test\\\\AppData\\\\Local\")\n\n        monkeypatch.setattr(\n            platformdirs.windows,  # type: ignore\n            \"get_win_folder\",\n            _get_win_folder,\n            raising=False,\n        )\n\n        assert (\n            appdirs.user_config_dir(\"pip\", roaming=False)\n            == \"C:\\\\Users\\\\test\\\\AppData\\\\Local\\\\pip\"\n        )\n        assert _get_win_folder.call_args_list == [mock.call(\"CSIDL_LOCAL_APPDATA\")]\n\n    @pytest.mark.skipif(sys.platform != \"win32\", reason=\"Windows-only test\")\n    def test_user_config_dir_win_yes_roaming(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        _get_win_folder = mock.Mock(return_value=\"C:\\\\Users\\\\test\\\\AppData\\\\Roaming\")\n\n        monkeypatch.setattr(\n            platformdirs.windows,  # type: ignore\n            \"get_win_folder\",\n            _get_win_folder,\n            raising=False,\n        )\n\n        assert (\n            appdirs.user_config_dir(\"pip\") == \"C:\\\\Users\\\\test\\\\AppData\\\\Roaming\\\\pip\"\n        )\n        assert _get_win_folder.call_args_list == [mock.call(\"CSIDL_APPDATA\")]\n\n    @pytest.mark.skipif(sys.platform != \"darwin\", reason=\"MacOS-only test\")\n    def test_user_config_dir_osx(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        if os.path.isdir(\"/home/test/Library/Application Support/\"):\n            assert (\n                appdirs.user_config_dir(\"pip\")\n                == \"/home/test/Library/Application Support/pip\"\n            )\n        else:\n            assert appdirs.user_config_dir(\"pip\") == \"/home/test/.config/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_config_dir_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.delenv(\"XDG_CONFIG_HOME\", raising=False)\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.user_config_dir(\"pip\") == \"/home/test/.config/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_config_dir_linux_override(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"XDG_CONFIG_HOME\", \"/home/test/.other-config\")\n        monkeypatch.setenv(\"HOME\", \"/home/test\")\n\n        assert appdirs.user_config_dir(\"pip\") == \"/home/test/.other-config/pip\"\n\n    @pytest.mark.skipif(sys.platform != \"linux\", reason=\"Linux-only test\")\n    def test_user_config_dir_linux_home_slash(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # Verify that we are not affected by https://bugs.python.org/issue14768\n        monkeypatch.delenv(\"XDG_CONFIG_HOME\", raising=False)\n        monkeypatch.setenv(\"HOME\", \"/\")\n\n        assert appdirs.user_config_dir(\"pip\") == \"/.config/pip\"\n"
  },
  {
    "path": "tests/unit/test_base_command.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport time\nfrom collections.abc import Iterator\nfrom optparse import Values\nfrom pathlib import Path\nfrom typing import Callable, NoReturn\nfrom unittest.mock import Mock, patch\n\nimport pytest\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.utils import temp_dir\nfrom pip._internal.utils.logging import BrokenStdoutLoggingError\nfrom pip._internal.utils.temp_dir import TempDirectory\n\n\n@pytest.fixture\ndef fixed_time() -> Iterator[None]:\n    # Patch time so logs contain a constant timestamp. time.time_ns is used by\n    # logging starting with Python 3.13.\n    year2019 = 1547704837.040001 + time.timezone\n    with patch(\"time.time\", lambda: year2019):\n        with patch(\"time.time_ns\", lambda: int(year2019 * 1e9)):\n            yield\n\n\nclass FakeCommand(Command):\n    _name = \"fake\"\n\n    def __init__(\n        self, run_func: Callable[[], int] | None = None, error: bool = False\n    ) -> None:\n        if error:\n\n            def run_func() -> int:\n                raise SystemExit(1)\n\n        self.run_func = run_func\n        super().__init__(self._name, self._name)\n\n    def main(self, args: list[str]) -> int:\n        args.append(\"--disable-pip-version-check\")\n        return super().main(args)\n\n    def run(self, options: Values, args: list[str]) -> int:\n        logging.getLogger(\"pip.tests\").info(\"fake\")\n        # Return SUCCESS from run if run_func is not provided\n        if self.run_func:\n            return self.run_func()\n        else:\n            return SUCCESS\n\n\nclass FakeCommandWithUnicode(FakeCommand):\n    _name = \"fake_unicode\"\n\n    def run(self, options: Values, args: list[str]) -> int:\n        logging.getLogger(\"pip.tests\").info(b\"bytes here \\xe9\")\n        logging.getLogger(\"pip.tests\").info(b\"unicode here \\xc3\\xa9\".decode(\"utf-8\"))\n        return SUCCESS\n\n\nclass TestCommand:\n    def call_main(self, capsys: pytest.CaptureFixture[str], args: list[str]) -> str:\n        \"\"\"\n        Call command.main(), and return the command's stderr.\n        \"\"\"\n\n        def raise_broken_stdout() -> NoReturn:\n            raise BrokenStdoutLoggingError()\n\n        cmd = FakeCommand(run_func=raise_broken_stdout)\n        status = cmd.main(args)\n        assert status == 1\n        stderr = capsys.readouterr().err\n\n        return stderr\n\n    def test_raise_broken_stdout(self, capsys: pytest.CaptureFixture[str]) -> None:\n        \"\"\"\n        Test raising BrokenStdoutLoggingError.\n        \"\"\"\n        stderr = self.call_main(capsys, [])\n\n        assert stderr.rstrip() == \"ERROR: Pipe to stdout was broken\"\n\n    def test_raise_broken_stdout__debug_logging(\n        self, capsys: pytest.CaptureFixture[str]\n    ) -> None:\n        \"\"\"\n        Test raising BrokenStdoutLoggingError with debug logging enabled.\n        \"\"\"\n        stderr = self.call_main(capsys, [\"-vv\"])\n\n        assert \"ERROR: Pipe to stdout was broken\" in stderr\n        assert \"Traceback (most recent call last):\" in stderr\n\n\n@patch(\"pip._internal.cli.index_command.Command.handle_pip_version_check\")\ndef test_handle_pip_version_check_called(mock_handle_version_check: Mock) -> None:\n    \"\"\"\n    Check that Command.handle_pip_version_check() is called.\n    \"\"\"\n    cmd = FakeCommand()\n    cmd.main([])\n    mock_handle_version_check.assert_called_once()\n\n\ndef test_debug_enables_verbose_logs() -> None:\n    cmd = FakeCommand()\n    cmd.main([\"fake\", \"--debug\"])\n    assert cmd.verbosity >= 2\n\n\ndef test_log_command_success(fixed_time: None, tmpdir: Path) -> None:\n    \"\"\"Test the --log option logs when command succeeds.\"\"\"\n    cmd = FakeCommand()\n    log_path = os.path.join(tmpdir, \"log\")\n    cmd.main([\"fake\", \"--log\", log_path])\n    with open(log_path) as f:\n        assert f.read().rstrip() == \"2019-01-17T06:00:37,040 fake\"\n\n\ndef test_log_command_error(fixed_time: None, tmpdir: Path) -> None:\n    \"\"\"Test the --log option logs when command fails.\"\"\"\n    cmd = FakeCommand(error=True)\n    log_path = os.path.join(tmpdir, \"log\")\n    cmd.main([\"fake\", \"--log\", log_path])\n    with open(log_path) as f:\n        assert f.read().startswith(\"2019-01-17T06:00:37,040 fake\")\n\n\ndef test_log_file_command_error(fixed_time: None, tmpdir: Path) -> None:\n    \"\"\"Test the --log-file option logs (when there's an error).\"\"\"\n    cmd = FakeCommand(error=True)\n    log_file_path = os.path.join(tmpdir, \"log_file\")\n    cmd.main([\"fake\", \"--log-file\", log_file_path])\n    with open(log_file_path) as f:\n        assert f.read().startswith(\"2019-01-17T06:00:37,040 fake\")\n\n\ndef test_log_unicode_messages(fixed_time: None, tmpdir: Path) -> None:\n    \"\"\"Tests that logging bytestrings and unicode objects\n    don't break logging.\n    \"\"\"\n    cmd = FakeCommandWithUnicode()\n    log_path = os.path.join(tmpdir, \"log\")\n    cmd.main([\"fake_unicode\", \"--log\", log_path])\n\n\n@pytest.mark.no_auto_tempdir_manager\ndef test_base_command_provides_tempdir_helpers() -> None:\n    assert temp_dir._tempdir_manager is None\n    assert temp_dir._tempdir_registry is None\n\n    def assert_helpers_set(options: Values, args: list[str]) -> int:\n        assert temp_dir._tempdir_manager is not None\n        assert temp_dir._tempdir_registry is not None\n        return SUCCESS\n\n    c = Command(\"fake\", \"fake\")\n    # https://github.com/python/mypy/issues/2427\n    c.run = Mock(side_effect=assert_helpers_set)  # type: ignore[method-assign]\n    assert c.main([\"fake\"]) == SUCCESS\n    c.run.assert_called_once()\n\n\nnot_deleted = \"not_deleted\"\n\n\n@pytest.mark.parametrize(\"kind,exists\", [(not_deleted, True), (\"deleted\", False)])\n@pytest.mark.no_auto_tempdir_manager\ndef test_base_command_global_tempdir_cleanup(kind: str, exists: bool) -> None:\n    assert temp_dir._tempdir_manager is None\n    assert temp_dir._tempdir_registry is None\n\n    class Holder:\n        value: str\n\n    def create_temp_dirs(options: Values, args: list[str]) -> int:\n        assert c.tempdir_registry is not None\n        c.tempdir_registry.set_delete(not_deleted, False)\n        Holder.value = TempDirectory(kind=kind, globally_managed=True).path\n        return SUCCESS\n\n    c = Command(\"fake\", \"fake\")\n    # https://github.com/python/mypy/issues/2427\n    c.run = Mock(side_effect=create_temp_dirs)  # type: ignore[method-assign]\n    assert c.main([\"fake\"]) == SUCCESS\n    c.run.assert_called_once()\n    assert os.path.exists(Holder.value) == exists\n\n\n@pytest.mark.parametrize(\"kind,exists\", [(not_deleted, True), (\"deleted\", False)])\n@pytest.mark.no_auto_tempdir_manager\ndef test_base_command_local_tempdir_cleanup(kind: str, exists: bool) -> None:\n    assert temp_dir._tempdir_manager is None\n    assert temp_dir._tempdir_registry is None\n\n    def create_temp_dirs(options: Values, args: list[str]) -> int:\n        assert c.tempdir_registry is not None\n        c.tempdir_registry.set_delete(not_deleted, False)\n\n        with TempDirectory(kind=kind) as d:\n            path = d.path\n            assert os.path.exists(path)\n        assert os.path.exists(path) == exists\n        return SUCCESS\n\n    c = Command(\"fake\", \"fake\")\n    # https://github.com/python/mypy/issues/2427\n    c.run = Mock(side_effect=create_temp_dirs)  # type: ignore[method-assign]\n    assert c.main([\"fake\"]) == SUCCESS\n    c.run.assert_called_once()\n"
  },
  {
    "path": "tests/unit/test_build_constraints.py",
    "content": "\"\"\"Tests for build constraints functionality.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom pathlib import Path\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.build_env import SubprocessBuildEnvironmentInstaller, _Prefix\nfrom pip._internal.utils.deprecation import PipDeprecationWarning\n\nfrom tests.lib import make_test_finder\n\n\nclass TestSubprocessBuildEnvironmentInstaller:\n    \"\"\"Test SubprocessBuildEnvironmentInstaller build constraints functionality.\"\"\"\n\n    @mock.patch.dict(os.environ, {}, clear=True)\n    def test_deprecation_check_no_pip_constraint(self) -> None:\n        \"\"\"Test no deprecation warning when PIP_CONSTRAINT is not set.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=False,\n        )\n\n        # Should not raise any warning\n        installer._deprecation_constraint_check()\n\n    @mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": \"\"})\n    def test_deprecation_check_empty_pip_constraint(self) -> None:\n        \"\"\"Test no deprecation warning for empty PIP_CONSTRAINT.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=False,\n        )\n\n        # Should not raise any warning since PIP_CONSTRAINT is empty\n        installer._deprecation_constraint_check()\n\n    @mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": \"   \"})\n    def test_deprecation_check_whitespace_pip_constraint(self) -> None:\n        \"\"\"Test no deprecation warning for whitespace-only PIP_CONSTRAINT.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=False,\n        )\n\n        # Should not raise any warning since PIP_CONSTRAINT is only whitespace\n        installer._deprecation_constraint_check()\n\n    @mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": \"constraints.txt\"})\n    def test_deprecation_check_feature_enabled(self) -> None:\n        \"\"\"Test no deprecation warning when build-constraint feature is enabled.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=True,\n        )\n\n        # Should not raise any warning\n        installer._deprecation_constraint_check()\n\n    @mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": \"constraints.txt\"})\n    def test_deprecation_check_warning_shown(self) -> None:\n        \"\"\"Test deprecation warning emitted when PIP_CONSTRAINT is set\n        and build-constraint is not enabled.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=False,\n        )\n\n        with pytest.warns(PipDeprecationWarning) as warning_info:\n            installer._deprecation_constraint_check()\n\n        assert len(warning_info) == 1\n        message = str(warning_info[0].message)\n        assert (\n            \"Setting PIP_CONSTRAINT will not affect build constraints in the future\"\n            in message\n        )\n        assert (\n            \"to specify build constraints using \"\n            \"--build-constraint or PIP_BUILD_CONSTRAINT\" in message\n        )\n\n    @mock.patch(\"pip._internal.build_env.call_subprocess\")\n    @mock.patch.dict(os.environ, {\"PIP_CONSTRAINT\": \"constraints.txt\"})\n    def test_install_calls_deprecation_check(\n        self, mock_call_subprocess: mock.Mock, tmp_path: Path\n    ) -> None:\n        \"\"\"Test install method calls deprecation check and proceeds with warning.\"\"\"\n        finder = make_test_finder()\n        installer = SubprocessBuildEnvironmentInstaller(\n            finder,\n            build_constraint_feature_enabled=False,\n        )\n        prefix = _Prefix(str(tmp_path))\n\n        with pytest.warns(PipDeprecationWarning):\n            installer.install(\n                requirements=[\"setuptools\"],\n                prefix=prefix,\n                kind=\"build dependencies\",\n                for_req=None,\n            )\n\n        # Verify that call_subprocess was called (install proceeded after warning)\n        mock_call_subprocess.assert_called_once()\n"
  },
  {
    "path": "tests/unit/test_cache.py",
    "content": "import os\nfrom pathlib import Path\n\nfrom pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version\n\nfrom pip._internal.cache import WheelCache, _hash_dict\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.misc import ensure_dir\n\n\ndef test_falsey_path_none() -> None:\n    wc = WheelCache(\"\")\n    assert wc.cache_dir is None\n\n\ndef test_subdirectory_fragment(tmp_path: Path) -> None:\n    \"\"\"\n    Test the subdirectory URL fragment is part of the cache key.\n    \"\"\"\n    wc = WheelCache(os.fspath(tmp_path))\n    link1 = Link(\"git+https://g.c/o/r#subdirectory=d1\")\n    link2 = Link(\"git+https://g.c/o/r#subdirectory=d2\")\n    assert wc.get_path_for_link(link1) != wc.get_path_for_link(link2)\n\n\ndef test_wheel_name_filter(tmpdir: Path) -> None:\n    \"\"\"\n    Test the wheel cache filters on wheel name when several wheels\n    for different package are stored under the same cache directory.\n    \"\"\"\n    wc = WheelCache(os.fspath(tmpdir))\n    link = Link(\"https://g.c/package.tar.gz\")\n    cache_path = wc.get_path_for_link(link)\n    ensure_dir(cache_path)\n    with open(os.path.join(cache_path, \"package-1.0-py3-none-any.whl\"), \"w\"):\n        pass\n    # package matches wheel name\n    cached_link = wc.get(link, \"package\", [Tag(\"py3\", \"none\", \"any\")])\n    assert cached_link is not link\n    assert os.path.exists(cached_link.file_path)\n    # package2 does not match wheel name\n    assert wc.get(link, \"package2\", [Tag(\"py3\", \"none\", \"any\")]) is link\n\n\ndef test_cache_hash() -> None:\n    h = _hash_dict({\"url\": \"https://g.c/o/r\"})\n    assert h == \"72aa79d3315c181d2cc23239d7109a782de663b6f89982624d8c1e86\"\n    h = _hash_dict({\"url\": \"https://g.c/o/r\", \"subdirectory\": \"sd\"})\n    assert h == \"8b13391b6791bf7f3edeabb41ea4698d21bcbdbba7f9c7dc9339750d\"\n    h = _hash_dict({\"subdirectory\": \"/\\xe9e\"})\n    assert h == \"f83b32dfa27a426dec08c21bf006065dd003d0aac78e7fc493d9014d\"\n\n\ndef test_link_to_cache(tmpdir: Path) -> None:\n    \"\"\"\n    Test that Link.from_json() produces Links with consistent cache\n    locations\n    \"\"\"\n    wc = WheelCache(os.fspath(tmpdir))\n    # Define our expectations for stable cache path.\n    i_name = interpreter_name()\n    i_version = interpreter_version()\n    key_parts = {\n        \"url\": \"https://files.pythonhosted.org/packages/a6/91/\"\n        \"86a6eac449ddfae239e93ffc1918cf33fd9bab35c04d1e963b311e347a73/\"\n        \"netifaces-0.11.0.tar.gz\",\n        \"sha256\": \"043a79146eb2907edf439899f262b3dfe41717d34124298ed281139a8b93ca32\",\n        \"interpreter_name\": i_name,\n        \"interpreter_version\": i_version,\n    }\n    expected_hash = _hash_dict(key_parts)\n    parts = [\n        expected_hash[:2],\n        expected_hash[2:4],\n        expected_hash[4:6],\n        expected_hash[6:],\n    ]\n    pathed_hash = os.path.join(*parts)\n    # Check working from a Link produces the same result.\n    file_data = {\n        \"filename\": \"netifaces-0.11.0.tar.gz\",\n        \"hashes\": {\n            \"sha256\": key_parts[\"sha256\"],\n        },\n        \"requires-python\": \"\",\n        \"url\": key_parts[\"url\"],\n        \"yanked\": False,\n    }\n    page_url = \"https://pypi.org/simple/netifaces/\"\n    link = Link.from_json(file_data=file_data, page_url=page_url)\n    assert link\n    path = wc.get_path_for_link(link)\n    assert pathed_hash in path\n\n\ndef test_get_cache_entry(tmpdir: Path) -> None:\n    wc = WheelCache(os.fspath(tmpdir))\n    persi_link = Link(\"https://g.c/o/r/persi\")\n    persi_path = wc.get_path_for_link(persi_link)\n    ensure_dir(persi_path)\n    with open(os.path.join(persi_path, \"persi-1.0.0-py3-none-any.whl\"), \"w\"):\n        pass\n    ephem_link = Link(\"https://g.c/o/r/ephem\")\n    ephem_path = wc.get_ephem_path_for_link(ephem_link)\n    ensure_dir(ephem_path)\n    with open(os.path.join(ephem_path, \"ephem-1.0.0-py3-none-any.whl\"), \"w\"):\n        pass\n    other_link = Link(\"https://g.c/o/r/other\")\n    supported_tags = [Tag(\"py3\", \"none\", \"any\")]\n    entry = wc.get_cache_entry(persi_link, \"persi\", supported_tags)\n    assert entry is not None\n    assert entry.persistent\n\n    entry = wc.get_cache_entry(ephem_link, \"ephem\", supported_tags)\n    assert entry is not None\n    assert not entry.persistent\n\n    assert wc.get_cache_entry(other_link, \"other\", supported_tags) is None\n"
  },
  {
    "path": "tests/unit/test_cli_colors.py",
    "content": "import optparse\n\nimport pip._internal.cli.parser\n\n\ndef test_color_formatter_option_strings() -> None:\n    formatter = pip._internal.cli.parser.PrettyHelpFormatter()\n    strs = formatter.format_option_strings(\n        optparse.Option(\n            \"--test-option\",\n            \"-t\",\n            help=\"A test option for colors\",\n        )\n    )\n\n    assert (\n        \"[optparse.shortargs]-t[/], [optparse.longargs]--test-option[/]\"\n        \" [optparse.metavar]<test_option>[/]\" == strs\n    )\n"
  },
  {
    "path": "tests/unit/test_cli_spinners.py",
    "content": "from __future__ import annotations\n\nimport logging\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom io import StringIO\nfrom typing import Callable\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._vendor.rich.console import Console\n\nfrom pip._internal.cli import spinners\nfrom pip._internal.cli.spinners import open_rich_spinner\n\n\n@contextmanager\ndef patch_logger_level(level: int) -> Generator[None]:\n    \"\"\"Patch the spinner logger level temporarily.\"\"\"\n    original_level = spinners.logger.level\n    spinners.logger.setLevel(level)\n    try:\n        yield\n    finally:\n        spinners.logger.setLevel(original_level)\n\n\nclass TestRichSpinner:\n    @pytest.mark.parametrize(\n        \"status, func\",\n        [\n            (\"done\", lambda: None),\n            (\"error\", lambda: 1 / 0),\n            (\"canceled\", Mock(side_effect=KeyboardInterrupt)),\n        ],\n    )\n    def test_finish(self, status: str, func: Callable[[], None]) -> None:\n        \"\"\"\n        Check that the spinner finish message is set correctly depending\n        on how the spinner came to a stop.\n        \"\"\"\n        stream = StringIO()\n        try:\n            with patch_logger_level(logging.INFO):\n                with open_rich_spinner(\"working\", Console(file=stream)):\n                    func()\n        except BaseException:\n            pass\n\n        output = stream.getvalue()\n        assert output == f\"working ... {status}\"\n\n    @pytest.mark.parametrize(\n        \"level, visible\",\n        [(logging.ERROR, False), (logging.INFO, True), (logging.DEBUG, True)],\n    )\n    def test_verbosity(self, level: int, visible: bool) -> None:\n        \"\"\"Is the spinner hidden at the appropriate verbosity?\"\"\"\n        stream = StringIO()\n        with patch_logger_level(level):\n            with open_rich_spinner(\"working\", Console(file=stream)):\n                pass\n\n        assert bool(stream.getvalue()) == visible\n"
  },
  {
    "path": "tests/unit/test_cmdoptions.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport os\nfrom optparse import Option, OptionParser, Values\nfrom pathlib import Path\nfrom venv import EnvBuilder\n\nimport pytest\n\nfrom pip._internal.cli.cmdoptions import (\n    _convert_python_version,\n    _handle_uploaded_prior_to,\n)\nfrom pip._internal.cli.main_parser import identify_python_interpreter\n\n\n@pytest.mark.parametrize(\n    \"value, expected\",\n    [\n        (\"\", (None, None)),\n        (\"2\", ((2,), None)),\n        (\"3\", ((3,), None)),\n        (\"3.7\", ((3, 7), None)),\n        (\"3.7.3\", ((3, 7, 3), None)),\n        # Test strings without dots of length bigger than 1.\n        (\"34\", ((3, 4), None)),\n        # Test a 2-digit minor version.\n        (\"310\", ((3, 10), None)),\n        # Test some values that fail to parse.\n        (\"ab\", ((), \"each version part must be an integer\")),\n        (\"3a\", ((), \"each version part must be an integer\")),\n        (\"3.7.a\", ((), \"each version part must be an integer\")),\n        (\"3.7.3.1\", ((), \"at most three version parts are allowed\")),\n    ],\n)\ndef test_convert_python_version(\n    value: str, expected: tuple[tuple[int, ...] | None, str | None]\n) -> None:\n    actual = _convert_python_version(value)\n    assert actual == expected, f\"actual: {actual!r}\"\n\n\ndef test_identify_python_interpreter_venv(tmpdir: Path) -> None:\n    env_path = tmpdir / \"venv\"\n    env = EnvBuilder(with_pip=False)\n    env.create(env_path)\n\n    # Passing a virtual environment returns the Python executable\n    interp = identify_python_interpreter(os.fspath(env_path))\n    assert interp is not None\n    assert Path(interp).exists()\n\n    # Passing an executable returns it\n    assert identify_python_interpreter(interp) == interp\n\n    # Passing a non-existent file returns None\n    assert identify_python_interpreter(str(tmpdir / \"nonexistent\")) is None\n\n\n@pytest.mark.parametrize(\n    \"value, expected_datetime\",\n    [\n        (\n            \"2023-01-01T00:00:00+00:00\",\n            datetime.datetime(2023, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n        ),\n        (\n            \"2023-01-01T12:00:00-05:00\",\n            datetime.datetime(\n                *(2023, 1, 1, 12, 0, 0),\n                tzinfo=datetime.timezone(datetime.timedelta(hours=-5)),\n            ),\n        ),\n    ],\n)\ndef test_handle_uploaded_prior_to_with_timezone(\n    value: str, expected_datetime: datetime.datetime\n) -> None:\n    \"\"\"Test that timezone-aware ISO 8601 date strings are parsed correctly.\"\"\"\n    option = Option(\"--uploaded-prior-to\", dest=\"uploaded_prior_to\")\n    opt = \"--uploaded-prior-to\"\n    parser = OptionParser()\n    parser.values = Values()\n\n    _handle_uploaded_prior_to(option, opt, value, parser)\n\n    result = parser.values.uploaded_prior_to\n    assert isinstance(result, datetime.datetime)\n    assert result == expected_datetime\n\n\n@pytest.mark.parametrize(\n    \"value, expected_date_time\",\n    [\n        (\"2023-01-01T00:00:00\", (2023, 1, 1, 0, 0, 0)),\n        (\"2023-12-31T23:59:59\", (2023, 12, 31, 23, 59, 59)),\n        (\"2023-01-01\", (2023, 1, 1, 0, 0, 0)),  # Date-only extends to midnight\n        (\"2023-06-15T14:30:00\", (2023, 6, 15, 14, 30, 0)),\n    ],\n)\ndef test_handle_uploaded_prior_to_naive_gets_local_timezone(\n    value: str, expected_date_time: tuple[int, int, int, int, int, int]\n) -> None:\n    \"\"\"Test naive datetimes are treated as local time, not converted from UTC.\"\"\"\n    option = Option(\"--uploaded-prior-to\", dest=\"uploaded_prior_to\")\n    opt = \"--uploaded-prior-to\"\n    parser = OptionParser()\n    parser.values = Values()\n\n    _handle_uploaded_prior_to(option, opt, value, parser)\n\n    result = parser.values.uploaded_prior_to\n    assert isinstance(result, datetime.datetime)\n    assert result.timetuple()[:6] == expected_date_time\n    assert result.tzinfo is not None\n\n    # Verify the result matches naive datetime with local timezone applied\n    naive_dt = datetime.datetime(*expected_date_time)\n    assert result == naive_dt.astimezone()\n\n\n@pytest.mark.parametrize(\n    \"invalid_value\",\n    [\n        \"not-a-date\",\n        \"2023-13-01\",  # Invalid month\n        \"2023-01-32\",  # Invalid day\n        \"2023-01-01T25:00:00\",  # Invalid hour\n        \"\",  # Empty string\n    ],\n)\ndef test_handle_uploaded_prior_to_invalid_dates(invalid_value: str) -> None:\n    \"\"\"Test that invalid date strings raise SystemExit via raise_option_error.\"\"\"\n    option = Option(\"--uploaded-prior-to\", dest=\"uploaded_prior_to\")\n    opt = \"--uploaded-prior-to\"\n    parser = OptionParser()\n    parser.values = Values()\n\n    with pytest.raises(SystemExit):\n        _handle_uploaded_prior_to(option, opt, invalid_value, parser)\n"
  },
  {
    "path": "tests/unit/test_collector.py",
    "content": "from __future__ import annotations\n\nimport itertools\nimport json\nimport logging\nimport os\nimport re\nimport uuid\nfrom pathlib import Path\nfrom textwrap import dedent\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor import requests\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.index.collector import (\n    IndexContent,\n    LinkCollector,\n    _get_index_content,\n    _get_simple_response,\n    _make_index_content,\n    _NotAPIContent,\n    _NotHTTP,\n    parse_links,\n)\nfrom pip._internal.index.sources import _FlatDirectorySource, _IndexDirectorySource\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.models.link import (\n    Link,\n    LinkHash,\n    MetadataFile,\n    _clean_url_path,\n    _ensure_quoted_url,\n)\nfrom pip._internal.network.session import PipSession\n\nfrom tests.lib import (\n    TestData,\n    make_test_link_collector,\n    skip_needs_new_pathname2url_trailing_slash_behavior_win,\n    skip_needs_old_pathname2url_trailing_slash_behavior_win,\n)\n\nACCEPT = \", \".join(\n    [\n        \"application/vnd.pypi.simple.v1+json\",\n        \"application/vnd.pypi.simple.v1+html; q=0.1\",\n        \"text/html; q=0.01\",\n    ]\n)\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        \"ftp://python.org/python-3.7.1.zip\",\n        \"file:///opt/data/pip-18.0.tar.gz\",\n    ],\n)\ndef test_get_simple_response_archive_to_naive_scheme(url: str) -> None:\n    \"\"\"\n    `_get_simple_response()` should error on an archive-like URL if the scheme\n    does not allow \"poking\" without getting data.\n    \"\"\"\n    with pytest.raises(_NotHTTP):\n        _get_simple_response(url, session=mock.Mock(PipSession))\n\n\n@pytest.mark.parametrize(\n    \"url, content_type\",\n    [\n        (\"http://python.org/python-3.7.1.zip\", \"application/zip\"),\n        (\"https://pypi.org/pip-18.0.tar.gz\", \"application/gzip\"),\n    ],\n)\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_get_simple_response_archive_to_http_scheme(\n    mock_raise_for_status: mock.Mock, url: str, content_type: str\n) -> None:\n    \"\"\"\n    `_get_simple_response()` should send a HEAD request on an archive-like URL\n    if the scheme supports it, and raise `_NotAPIContent` if the response isn't HTML.\n    \"\"\"\n    session = mock.Mock(PipSession)\n    session.head.return_value = mock.Mock(\n        **{\n            \"request.method\": \"HEAD\",\n            \"headers\": {\"Content-Type\": content_type},\n        }\n    )\n\n    with pytest.raises(_NotAPIContent) as ctx:\n        _get_simple_response(url, session=session)\n\n    session.assert_has_calls(\n        [\n            mock.call.head(url, allow_redirects=True),\n        ]\n    )\n    mock_raise_for_status.assert_called_once_with(session.head.return_value)\n    assert ctx.value.args == (content_type, \"HEAD\")\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        (\"ftp://python.org/python-3.7.1.zip\"),\n        (\"file:///opt/data/pip-18.0.tar.gz\"),\n    ],\n)\ndef test_get_index_content_invalid_content_type_archive(\n    caplog: pytest.LogCaptureFixture, url: str\n) -> None:\n    \"\"\"`_get_index_content()` should warn if an archive URL is not HTML\n    and therefore cannot be used for a HEAD request.\n    \"\"\"\n    caplog.set_level(logging.WARNING)\n    link = Link(url)\n\n    session = mock.Mock(PipSession)\n\n    assert _get_index_content(link, session=session) is None\n    assert (\n        \"pip._internal.index.collector\",\n        logging.WARNING,\n        f\"Skipping page {url} because it looks like an archive, and cannot \"\n        \"be checked by a HTTP HEAD request.\",\n    ) in caplog.record_tuples\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        \"http://python.org/python-3.7.1.zip\",\n        \"https://pypi.org/pip-18.0.tar.gz\",\n    ],\n)\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_get_simple_response_archive_to_http_scheme_is_html(\n    mock_raise_for_status: mock.Mock, url: str\n) -> None:\n    \"\"\"\n    `_get_simple_response()` should work with archive-like URLs if the HEAD\n    request is responded with text/html.\n    \"\"\"\n    session = mock.Mock(PipSession)\n    session.head.return_value = mock.Mock(\n        **{\n            \"request.method\": \"HEAD\",\n            \"headers\": {\"Content-Type\": \"text/html\"},\n        }\n    )\n    session.get.return_value = mock.Mock(headers={\"Content-Type\": \"text/html\"})\n\n    resp = _get_simple_response(url, session=session)\n\n    assert resp is not None\n    assert session.mock_calls == [\n        mock.call.head(url, allow_redirects=True),\n        mock.call.get(\n            url,\n            headers={\n                \"Accept\": ACCEPT,\n                \"Cache-Control\": \"max-age=0\",\n            },\n        ),\n    ]\n    assert mock_raise_for_status.mock_calls == [\n        mock.call(session.head.return_value),\n        mock.call(resp),\n    ]\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        \"https://pypi.org/simple/pip\",\n        \"https://pypi.org/simple/pip/\",\n        \"https://python.org/sitemap.xml\",\n    ],\n)\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_get_simple_response_no_head(\n    mock_raise_for_status: mock.Mock, url: str\n) -> None:\n    \"\"\"\n    `_get_simple_response()` shouldn't send a HEAD request if the URL does not\n    look like an archive, only the GET request that retrieves data.\n    \"\"\"\n    session = mock.Mock(PipSession)\n\n    # Mock the headers dict to ensure it is accessed.\n    session.get.return_value = mock.Mock(\n        headers=mock.Mock(\n            **{\n                \"get.return_value\": \"text/html\",\n            }\n        )\n    )\n\n    resp = _get_simple_response(url, session=session)\n\n    assert resp is not None\n    assert session.head.call_count == 0\n    assert session.get.mock_calls == [\n        mock.call(\n            url,\n            headers={\n                \"Accept\": ACCEPT,\n                \"Cache-Control\": \"max-age=0\",\n            },\n        ),\n        mock.call().headers.get(\"Content-Type\", \"Unknown\"),\n        mock.call().headers.get(\"Content-Type\", \"Unknown\"),\n    ]\n    mock_raise_for_status.assert_called_once_with(resp)\n\n\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_get_simple_response_dont_log_clear_text_password(\n    mock_raise_for_status: mock.Mock, caplog: pytest.LogCaptureFixture\n) -> None:\n    \"\"\"\n    `_get_simple_response()` should redact the password from the index URL\n    in its DEBUG log message.\n    \"\"\"\n    session = mock.Mock(PipSession)\n\n    # Mock the headers dict to ensure it is accessed.\n    session.get.return_value = mock.Mock(\n        headers=mock.Mock(\n            **{\n                \"get.return_value\": \"text/html\",\n            }\n        )\n    )\n\n    caplog.set_level(logging.DEBUG)\n\n    resp = _get_simple_response(\n        \"https://user:my_password@example.com/simple/\", session=session\n    )\n\n    assert resp is not None\n    mock_raise_for_status.assert_called_once_with(resp)\n\n    assert len(caplog.records) == 2\n    record = caplog.records[0]\n    assert record.levelname == \"DEBUG\"\n    assert record.message.splitlines() == [\n        \"Getting page https://user:****@example.com/simple/\",\n    ]\n    record = caplog.records[1]\n    assert record.levelname == \"DEBUG\"\n    assert record.message.splitlines() == [\n        \"Fetched page https://user:****@example.com/simple/ as text/html\",\n    ]\n\n\n@pytest.mark.parametrize(\n    \"path, expected\",\n    [\n        # Test a character that needs quoting.\n        (\"a b\", \"a%20b\"),\n        # Test an unquoted \"@\".\n        (\"a @ b\", \"a%20@%20b\"),\n        # Test multiple unquoted \"@\".\n        (\"a @ @ b\", \"a%20@%20@%20b\"),\n        # Test a quoted \"@\".\n        (\"a %40 b\", \"a%20%40%20b\"),\n        # Test a quoted \"@\" before an unquoted \"@\".\n        (\"a %40b@ c\", \"a%20%40b@%20c\"),\n        # Test a quoted \"@\" after an unquoted \"@\".\n        (\"a @b%40 c\", \"a%20@b%40%20c\"),\n        # Test alternating quoted and unquoted \"@\".\n        (\"a %40@b %40@c %40\", \"a%20%40@b%20%40@c%20%40\"),\n        # Test an unquoted \"/\".\n        (\"a / b\", \"a%20/%20b\"),\n        # Test multiple unquoted \"/\".\n        (\"a / / b\", \"a%20/%20/%20b\"),\n        # Test a quoted \"/\".\n        (\"a %2F b\", \"a%20%2F%20b\"),\n        # Test a quoted \"/\" before an unquoted \"/\".\n        (\"a %2Fb/ c\", \"a%20%2Fb/%20c\"),\n        # Test a quoted \"/\" after an unquoted \"/\".\n        (\"a /b%2F c\", \"a%20/b%2F%20c\"),\n        # Test alternating quoted and unquoted \"/\".\n        (\"a %2F/b %2F/c %2F\", \"a%20%2F/b%20%2F/c%20%2F\"),\n        # Test normalizing non-reserved quoted characters \"[\" and \"]\"\n        (\"a %5b %5d b\", \"a%20%5B%20%5D%20b\"),\n        # Test normalizing a reserved quoted \"/\"\n        (\"a %2f b\", \"a%20%2F%20b\"),\n    ],\n)\n@pytest.mark.parametrize(\"is_local_path\", [True, False])\ndef test_clean_url_path(path: str, expected: str, is_local_path: bool) -> None:\n    assert _clean_url_path(path, is_local_path=is_local_path) == expected\n\n\n@pytest.mark.parametrize(\n    \"path, expected\",\n    [\n        # Test a VCS path with a Windows drive letter and revision.\n        pytest.param(\n            \"/T:/with space/repo.git@1.0\",\n            \"/T:/with%20space/repo.git@1.0\",\n            marks=pytest.mark.skipif(\"sys.platform != 'win32'\"),\n        ),\n        # Test a VCS path with a Windows drive letter and revision,\n        # running on non-windows platform.\n        pytest.param(\n            \"/T:/with space/repo.git@1.0\",\n            \"/T%3A/with%20space/repo.git@1.0\",\n            marks=pytest.mark.skipif(\"sys.platform == 'win32'\"),\n        ),\n    ],\n)\ndef test_clean_url_path_with_local_path(path: str, expected: str) -> None:\n    actual = _clean_url_path(path, is_local_path=True)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"url, clean_url\",\n    [\n        # URL with hostname and port. Port separator should not be quoted.\n        (\n            \"https://localhost.localdomain:8181/path/with space/\",\n            \"https://localhost.localdomain:8181/path/with%20space/\",\n        ),\n        # URL that is already properly quoted. The quoting `%`\n        # characters should not be quoted again.\n        (\n            \"https://localhost.localdomain:8181/path/with%20quoted%20space/\",\n            \"https://localhost.localdomain:8181/path/with%20quoted%20space/\",\n        ),\n        # URL with IPv4 address and port.\n        (\n            \"https://127.0.0.1:8181/path/with space/\",\n            \"https://127.0.0.1:8181/path/with%20space/\",\n        ),\n        # URL with IPv6 address and port. The `[]` brackets around the\n        # IPv6 address should not be quoted.\n        (\n            \"https://[fd00:0:0:236::100]:8181/path/with space/\",\n            \"https://[fd00:0:0:236::100]:8181/path/with%20space/\",\n        ),\n        # URL with query. The leading `?` should not be quoted.\n        (\n            \"https://localhost.localdomain:8181/path/with/query?request=test\",\n            \"https://localhost.localdomain:8181/path/with/query?request=test\",\n        ),\n        # URL with colon in the path portion.\n        (\n            \"https://localhost.localdomain:8181/path:/with:/colon\",\n            \"https://localhost.localdomain:8181/path%3A/with%3A/colon\",\n        ),\n        # URL with something that looks like a drive letter, but is\n        # not. The `:` should be quoted.\n        (\n            \"https://localhost.localdomain/T:/path/\",\n            \"https://localhost.localdomain/T%3A/path/\",\n        ),\n        # URL with a quoted \"/\" in the path portion.\n        (\n            \"https://example.com/access%2Ftoken/path/\",\n            \"https://example.com/access%2Ftoken/path/\",\n        ),\n        # VCS URL containing revision string.\n        (\n            \"git+ssh://example.com/path to/repo.git@1.0#egg=my-package-1.0\",\n            \"git+ssh://example.com/path%20to/repo.git@1.0#egg=my-package-1.0\",\n        ),\n        # VCS URL with a quoted \"#\" in the revision string.\n        (\n            \"git+https://example.com/repo.git@hash%23symbol#egg=my-package-1.0\",\n            \"git+https://example.com/repo.git@hash%23symbol#egg=my-package-1.0\",\n        ),\n        # VCS URL with a quoted \"@\" in the revision string.\n        (\n            \"git+https://example.com/repo.git@at%40 space#egg=my-package-1.0\",\n            \"git+https://example.com/repo.git@at%40%20space#egg=my-package-1.0\",\n        ),\n        # URL with Windows drive letter. The `:` after the drive\n        # letter should not be quoted. The trailing `/` should be\n        # removed.\n        pytest.param(\n            \"file:///T:/path/with spaces/\",\n            \"file:///T:/path/with%20spaces\",\n            marks=skip_needs_old_pathname2url_trailing_slash_behavior_win,\n        ),\n        pytest.param(\n            \"file:///T:/path/with spaces/\",\n            \"file:///T:/path/with%20spaces/\",\n            marks=skip_needs_new_pathname2url_trailing_slash_behavior_win,\n        ),\n        # URL with Windows drive letter, running on non-windows\n        # platform. The `:` after the drive should be quoted.\n        pytest.param(\n            \"file:///T:/path/with spaces/\",\n            \"file:///T%3A/path/with%20spaces/\",\n            marks=pytest.mark.skipif(\"sys.platform == 'win32'\"),\n        ),\n        # Test a VCS URL with a Windows drive letter and revision.\n        pytest.param(\n            \"git+file:///T:/with space/repo.git@1.0#egg=my-package-1.0\",\n            \"git+file:///T:/with%20space/repo.git@1.0#egg=my-package-1.0\",\n            marks=pytest.mark.skipif(\"sys.platform != 'win32'\"),\n        ),\n        # Test a VCS URL with a Windows drive letter and revision,\n        # running on non-windows platform.\n        pytest.param(\n            \"git+file:///T:/with space/repo.git@1.0#egg=my-package-1.0\",\n            \"git+file:///T%3A/with%20space/repo.git@1.0#egg=my-package-1.0\",\n            marks=pytest.mark.skipif(\"sys.platform == 'win32'\"),\n        ),\n    ],\n)\ndef test_ensure_quoted_url(url: str, clean_url: str) -> None:\n    assert _ensure_quoted_url(url) == clean_url\n\n\ndef _test_parse_links_data_attribute(\n    anchor_html: str, attr: str, expected: str | None\n) -> Link:\n    html = (\n        \"<!DOCTYPE html>\"\n        '<html><head><meta charset=\"utf-8\"><head>'\n        f\"<body>{anchor_html}</body></html>\"\n    )\n    html_bytes = html.encode(\"utf-8\")\n    page = IndexContent(\n        html_bytes,\n        \"text/html\",\n        encoding=None,\n        # parse_links() is cached by url, so we inject a random uuid to ensure\n        # the page content isn't cached.\n        url=f\"https://example.com/simple-{uuid.uuid4()}/\",\n    )\n    links = list(parse_links(page))\n    (link,) = links\n    actual = getattr(link, attr)\n    assert actual == expected\n    return link\n\n\n@pytest.mark.parametrize(\n    \"anchor_html, expected\",\n    [\n        # Test not present.\n        ('<a href=\"/pkg-1.0.tar.gz\"></a>', None),\n        # Test present with no value.\n        ('<a href=\"/pkg-1.0.tar.gz\" data-requires-python></a>', None),\n        # Test a value with an escaped character.\n        (\n            '<a href=\"/pkg-1.0.tar.gz\" data-requires-python=\"&gt;=3.6\"></a>',\n            \">=3.6\",\n        ),\n        # Test requires python is unescaped once.\n        (\n            '<a href=\"/pkg-1.0.tar.gz\" data-requires-python=\"&amp;gt;=3.6\"></a>',\n            \"&gt;=3.6\",\n        ),\n    ],\n)\ndef test_parse_links__requires_python(anchor_html: str, expected: str | None) -> None:\n    _test_parse_links_data_attribute(anchor_html, \"requires_python\", expected)\n\n\n# TODO: this test generates its own examples to validate the json client implementation\n# instead of sharing those examples with the html client testing. We expect this won't\n# hide any bugs because operations like resolving PEP 658 metadata should use the same\n# code for both types of indices, but it might be nice to explicitly have all our tests\n# in test_download.py execute over both html and json indices with\n# a pytest.mark.parameterize decorator to ensure nothing slips through the cracks.\ndef test_parse_links_json() -> None:\n    json_bytes = json.dumps(\n        {\n            \"meta\": {\"api-version\": \"1.0\"},\n            \"name\": \"holygrail\",\n            \"files\": [\n                {\n                    \"filename\": \"holygrail-1.0.tar.gz\",\n                    \"url\": \"https://example.com/files/holygrail-1.0.tar.gz\",\n                    \"hashes\": {\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n                    \"requires-python\": \">=3.7\",\n                    \"yanked\": \"Had a vulnerability\",\n                },\n                {\n                    \"filename\": \"holygrail-1.0-py3-none-any.whl\",\n                    \"url\": \"/files/holygrail-1.0-py3-none-any.whl\",\n                    \"hashes\": {\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n                    \"requires-python\": \">=3.7\",\n                    \"dist-info-metadata\": False,\n                },\n                # Same as above, but parsing core-metadata.\n                {\n                    \"filename\": \"holygrail-1.0-py3-none-any.whl\",\n                    \"url\": \"/files/holygrail-1.0-py3-none-any.whl\",\n                    \"hashes\": {\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n                    \"requires-python\": \">=3.7\",\n                    \"core-metadata\": {\"sha512\": \"aabdd41\"},\n                },\n                # Ensure fallback to dist-info-metadata works\n                {\n                    \"filename\": \"holygrail-1.0-py3-none-any.whl\",\n                    \"url\": \"/files/holygrail-1.0-py3-none-any.whl\",\n                    \"hashes\": {\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n                    \"requires-python\": \">=3.7\",\n                    \"dist-info-metadata\": {\"sha512\": \"aabdd41\"},\n                },\n                # Ensure that core-metadata gets priority.\n                {\n                    \"filename\": \"holygrail-1.0-py3-none-any.whl\",\n                    \"url\": \"/files/holygrail-1.0-py3-none-any.whl\",\n                    \"hashes\": {\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n                    \"requires-python\": \">=3.7\",\n                    \"core-metadata\": {\"sha512\": \"aabdd41\"},\n                    \"dist-info-metadata\": {\"sha512\": \"this_is_wrong\"},\n                },\n            ],\n        }\n    ).encode(\"utf8\")\n    page = IndexContent(\n        json_bytes,\n        \"application/vnd.pypi.simple.v1+json\",\n        encoding=None,\n        # parse_links() is cached by url, so we inject a random uuid to ensure\n        # the page content isn't cached.\n        url=f\"https://example.com/simple-{uuid.uuid4()}/\",\n    )\n    links = list(parse_links(page))\n\n    assert links == [\n        Link(\n            \"https://example.com/files/holygrail-1.0.tar.gz\",\n            comes_from=page.url,\n            requires_python=\">=3.7\",\n            yanked_reason=\"Had a vulnerability\",\n            hashes={\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n        ),\n        Link(\n            \"https://example.com/files/holygrail-1.0-py3-none-any.whl\",\n            comes_from=page.url,\n            requires_python=\">=3.7\",\n            yanked_reason=None,\n            hashes={\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n        ),\n        Link(\n            \"https://example.com/files/holygrail-1.0-py3-none-any.whl\",\n            comes_from=page.url,\n            requires_python=\">=3.7\",\n            yanked_reason=None,\n            hashes={\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n            metadata_file_data=MetadataFile({\"sha512\": \"aabdd41\"}),\n        ),\n        Link(\n            \"https://example.com/files/holygrail-1.0-py3-none-any.whl\",\n            comes_from=page.url,\n            requires_python=\">=3.7\",\n            yanked_reason=None,\n            hashes={\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n            metadata_file_data=MetadataFile({\"sha512\": \"aabdd41\"}),\n        ),\n        Link(\n            \"https://example.com/files/holygrail-1.0-py3-none-any.whl\",\n            comes_from=page.url,\n            requires_python=\">=3.7\",\n            yanked_reason=None,\n            hashes={\"sha256\": \"sha256 hash\", \"blake2b\": \"blake2b hash\"},\n            metadata_file_data=MetadataFile({\"sha512\": \"aabdd41\"}),\n        ),\n    ]\n\n    # Ensure the metadata info can be parsed into the correct link.\n    metadata_link = links[2].metadata_link()\n    assert metadata_link is not None\n    assert (\n        metadata_link.url\n        == \"https://example.com/files/holygrail-1.0-py3-none-any.whl.metadata\"\n    )\n    assert metadata_link._hashes == {\"sha512\": \"aabdd41\"}\n\n\n@pytest.mark.parametrize(\n    \"anchor_html, expected\",\n    [\n        # Test not present.\n        ('<a href=\"/pkg1-1.0.tar.gz\"></a>', None),\n        # Test present with no value.\n        ('<a href=\"/pkg2-1.0.tar.gz\" data-yanked></a>', None),\n        # Test the empty string.\n        ('<a href=\"/pkg3-1.0.tar.gz\" data-yanked=\"\"></a>', \"\"),\n        # Test a non-empty string.\n        ('<a href=\"/pkg4-1.0.tar.gz\" data-yanked=\"error\"></a>', \"error\"),\n        # Test a value with an escaped character.\n        ('<a href=\"/pkg4-1.0.tar.gz\" data-yanked=\"version &lt 1\"></a>', \"version < 1\"),\n        # Test a yanked reason with a non-ascii character.\n        (\n            '<a href=\"/pkg-1.0.tar.gz\" data-yanked=\"curlyquote \\u2018\"></a>',\n            \"curlyquote \\u2018\",\n        ),\n        # Test yanked reason is unescaped once.\n        (\n            '<a href=\"/pkg-1.0.tar.gz\" data-yanked=\"version &amp;lt; 1\"></a>',\n            \"version &lt; 1\",\n        ),\n    ],\n)\ndef test_parse_links__yanked_reason(anchor_html: str, expected: str | None) -> None:\n    _test_parse_links_data_attribute(anchor_html, \"yanked_reason\", expected)\n\n\n# Requirement objects do not == each other unless they point to the same instance!\n_pkg1_requirement = Requirement(\"pkg1==1.0\")\n\n\n@pytest.mark.parametrize(\n    \"anchor_html, expected, hashes\",\n    [\n        # Test not present.\n        (\n            '<a href=\"/pkg1-1.0.tar.gz\"></a>',\n            None,\n            {},\n        ),\n        # Test with value \"true\".\n        (\n            '<a href=\"/pkg1-1.0.tar.gz\" data-core-metadata=\"true\"></a>',\n            MetadataFile(None),\n            {},\n        ),\n        # Test with a provided hash value.\n        (\n            '<a href=\"/pkg1-1.0.tar.gz\" data-core-metadata=\"sha256=aa113592bbe\"></a>',\n            MetadataFile({\"sha256\": \"aa113592bbe\"}),\n            {},\n        ),\n        # Test with a provided hash value for both the requirement as well as metadata.\n        (\n            '<a href=\"/pkg1-1.0.tar.gz#sha512=abc132409cb\" data-core-metadata=\"sha256=aa113592bbe\"></a>',  # noqa: E501\n            MetadataFile({\"sha256\": \"aa113592bbe\"}),\n            {\"sha512\": \"abc132409cb\"},\n        ),\n        # Ensure the fallback to the old name works.\n        (\n            '<a href=\"/pkg1-1.0.tar.gz\" data-dist-info-metadata=\"sha256=aa113592bbe\"></a>',  # noqa: E501\n            MetadataFile({\"sha256\": \"aa113592bbe\"}),\n            {},\n        ),\n        # Ensure that the data-core-metadata name gets priority.\n        (\n            '<a href=\"/pkg1-1.0.tar.gz\" data-core-metadata=\"sha256=aa113592bbe\" data-dist-info-metadata=\"sha256=invalid_value\"></a>',  # noqa: E501\n            MetadataFile({\"sha256\": \"aa113592bbe\"}),\n            {},\n        ),\n    ],\n)\ndef test_parse_links__metadata_file_data(\n    anchor_html: str,\n    expected: str | None,\n    hashes: dict[str, str],\n) -> None:\n    link = _test_parse_links_data_attribute(anchor_html, \"metadata_file_data\", expected)\n    assert link._hashes == hashes\n\n\ndef test_parse_links_caches_same_page_by_url() -> None:\n    html = (\n        \"<!DOCTYPE html>\"\n        '<html><head><meta charset=\"utf-8\"><head>'\n        '<body><a href=\"/pkg1-1.0.tar.gz\"></a></body></html>'\n    )\n    html_bytes = html.encode(\"utf-8\")\n\n    url = \"https://example.com/simple/\"\n\n    page_1 = IndexContent(\n        html_bytes,\n        \"text/html\",\n        encoding=None,\n        url=url,\n    )\n    # Make a second page with zero content, to ensure that it's not accessed,\n    # because the page was cached by url.\n    page_2 = IndexContent(\n        b\"\",\n        \"text/html\",\n        encoding=None,\n        url=url,\n    )\n    # Make a third page which represents an index url, which should not be\n    # cached, even for the same url. We modify the page content slightly to\n    # verify that the result is not cached.\n    page_3 = IndexContent(\n        re.sub(b\"pkg1\", b\"pkg2\", html_bytes),\n        \"text/html\",\n        encoding=None,\n        url=url,\n        cache_link_parsing=False,\n    )\n\n    parsed_links_1 = list(parse_links(page_1))\n    assert len(parsed_links_1) == 1\n    assert \"pkg1\" in parsed_links_1[0].url\n\n    parsed_links_2 = list(parse_links(page_2))\n    assert parsed_links_2 == parsed_links_1\n\n    parsed_links_3 = list(parse_links(page_3))\n    assert len(parsed_links_3) == 1\n    assert parsed_links_3 != parsed_links_1\n    assert \"pkg2\" in parsed_links_3[0].url\n\n\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_request_http_error(\n    mock_raise_for_status: mock.Mock, caplog: pytest.LogCaptureFixture\n) -> None:\n    caplog.set_level(logging.DEBUG)\n    link = Link(\"http://localhost\")\n    session = mock.Mock(PipSession)\n    session.get.return_value = mock.Mock()\n    mock_raise_for_status.side_effect = NetworkConnectionError(\"Http error\")\n    assert _get_index_content(link, session=session) is None\n    assert \"Could not fetch URL http://localhost: Http error - skipping\" in caplog.text\n\n\ndef test_request_retries(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.DEBUG)\n    link = Link(\"http://localhost\")\n    session = mock.Mock(PipSession)\n    session.get.side_effect = requests.exceptions.RetryError(\"Retry error\")\n    assert _get_index_content(link, session=session) is None\n    assert \"Could not fetch URL http://localhost: Retry error - skipping\" in caplog.text\n\n\ndef test_make_index_content() -> None:\n    headers = {\"Content-Type\": \"text/html; charset=UTF-8\"}\n    response = mock.Mock(\n        content=b\"<content>\",\n        url=\"https://example.com/index.html\",\n        headers=headers,\n    )\n\n    actual = _make_index_content(response)\n    assert actual.content == b\"<content>\"\n    assert actual.encoding == \"UTF-8\"\n    assert actual.url == \"https://example.com/index.html\"\n\n\n@pytest.mark.parametrize(\n    \"url, vcs_scheme\",\n    [\n        (\"svn+http://pypi.org/something\", \"svn\"),\n        (\"git+https://github.com/pypa/pip.git\", \"git\"),\n    ],\n)\ndef test_get_index_content_invalid_scheme(\n    caplog: pytest.LogCaptureFixture, url: str, vcs_scheme: str\n) -> None:\n    \"\"\"`_get_index_content()` should error if an invalid scheme is given.\n\n    Only file:, http:, https:, and ftp: are allowed.\n    \"\"\"\n    with caplog.at_level(logging.WARNING):\n        page = _get_index_content(Link(url), session=mock.Mock(PipSession))\n\n    assert page is None\n    assert caplog.record_tuples == [\n        (\n            \"pip._internal.index.collector\",\n            logging.WARNING,\n            f\"Cannot look at {vcs_scheme} URL {url} because it does not support \"\n            \"lookup as web pages.\",\n        ),\n    ]\n\n\n@pytest.mark.parametrize(\n    \"content_type\",\n    [\n        \"application/xhtml+xml\",\n        \"application/json\",\n    ],\n)\n@mock.patch(\"pip._internal.index.collector.raise_for_status\")\ndef test_get_index_content_invalid_content_type(\n    mock_raise_for_status: mock.Mock,\n    caplog: pytest.LogCaptureFixture,\n    content_type: str,\n) -> None:\n    \"\"\"`_get_index_content()` should warn if an invalid content-type is given.\n    Only text/html is allowed.\n    \"\"\"\n    caplog.set_level(logging.DEBUG)\n    url = \"https://pypi.org/simple/pip\"\n    link = Link(url)\n\n    session = mock.Mock(PipSession)\n    session.get.return_value = mock.Mock(\n        **{\n            \"request.method\": \"GET\",\n            \"headers\": {\"Content-Type\": content_type},\n        }\n    )\n    assert _get_index_content(link, session=session) is None\n    mock_raise_for_status.assert_called_once_with(session.get.return_value)\n    assert (\n        \"pip._internal.index.collector\",\n        logging.WARNING,\n        f\"Skipping page {url} because the GET request got Content-Type: {content_type}.\"\n        \" The only supported Content-Types are application/vnd.pypi.simple.v1+json, \"\n        \"application/vnd.pypi.simple.v1+html, and text/html\",\n    ) in caplog.record_tuples\n\n\ndef make_fake_html_response(url: str) -> mock.Mock:\n    \"\"\"\n    Create a fake requests.Response object.\n    \"\"\"\n    html = dedent(\n        \"\"\"\\\n    <html><head><meta name=\"api-version\" value=\"2\" /></head>\n    <body>\n    <a href=\"/abc-1.0.tar.gz#md5=000000000\">abc-1.0.tar.gz</a>\n    </body></html>\n    \"\"\"\n    )\n    content = html.encode(\"utf-8\")\n    return mock.Mock(content=content, url=url, headers={\"Content-Type\": \"text/html\"})\n\n\ndef test_get_index_content_directory_append_index(tmpdir: Path) -> None:\n    \"\"\"`_get_index_content()` should append \"index.html\" to a directory URL.\"\"\"\n    dirpath = tmpdir / \"something\"\n    dirpath.mkdir()\n    dir_url = dirpath.as_uri()\n    expected_url = \"{}/index.html\".format(dir_url.rstrip(\"/\"))\n\n    session = mock.Mock(PipSession)\n    fake_response = make_fake_html_response(expected_url)\n    mock_func = mock.patch(\"pip._internal.index.collector._get_simple_response\")\n    with mock_func as mock_func:\n        mock_func.return_value = fake_response\n        actual = _get_index_content(Link(dir_url), session=session)\n        assert mock_func.mock_calls == [\n            mock.call(expected_url, session=session),\n        ], f\"actual calls: {mock_func.mock_calls}\"\n\n        assert actual is not None\n        assert actual.content == fake_response.content\n        assert actual.encoding is None\n        assert actual.url == expected_url\n\n\ndef test_collect_sources__file_expand_dir(data: TestData) -> None:\n    \"\"\"\n    Test that a file:// dir from --find-links becomes _FlatDirectorySource\n    \"\"\"\n    collector = LinkCollector.create(\n        session=mock.Mock(is_secure_origin=None),  # Shouldn't be used.\n        options=mock.Mock(\n            index_url=\"ignored-by-no-index\",\n            extra_index_urls=[],\n            no_index=True,\n            find_links=[data.find_links],\n        ),\n    )\n    sources = collector.collect_sources(\n        # Shouldn't be used.\n        project_name=\"\",\n        candidates_from_page=None,  # type: ignore[arg-type]\n    )\n    assert not sources.index_urls\n    assert len(sources.find_links) == 1\n    assert isinstance(sources.find_links[0], _FlatDirectorySource), (\n        \"Directory source should have been found \"\n        f\"at find-links url: {data.find_links}\"\n    )\n\n\ndef test_collect_sources__file_not_find_link(data: TestData) -> None:\n    \"\"\"\n    Test that a file:// dir from --index-url doesn't become _FlatDirectorySource\n    run\n    \"\"\"\n    collector = LinkCollector.create(\n        session=mock.Mock(is_secure_origin=None),  # Shouldn't be used.\n        options=mock.Mock(\n            index_url=data.index_url(\"empty_with_pkg\"),\n            extra_index_urls=[],\n            no_index=False,\n            find_links=[],\n        ),\n    )\n    sources = collector.collect_sources(\n        project_name=\"\",\n        # Shouldn't be used.\n        candidates_from_page=None,  # type: ignore[arg-type]\n    )\n    assert not sources.find_links\n    assert len(sources.index_urls) == 1\n    assert isinstance(\n        sources.index_urls[0], _IndexDirectorySource\n    ), \"Directory specified as index should be treated as a page\"\n\n\ndef test_collect_sources__non_existing_path() -> None:\n    \"\"\"\n    Test that a non-existing path is ignored.\n    \"\"\"\n    collector = LinkCollector.create(\n        session=mock.Mock(is_secure_origin=None),  # Shouldn't be used.\n        options=mock.Mock(\n            index_url=\"ignored-by-no-index\",\n            extra_index_urls=[],\n            no_index=True,\n            find_links=[os.path.join(\"this\", \"does\", \"not\", \"exist\")],\n        ),\n    )\n    sources = collector.collect_sources(\n        # Shouldn't be used.\n        project_name=None,  # type: ignore[arg-type]\n        candidates_from_page=None,  # type: ignore[arg-type]\n    )\n    assert not sources.index_urls\n    assert sources.find_links == [None], \"Nothing should have been found\"\n\n\ndef check_links_include(links: list[Link], names: list[str]) -> None:\n    \"\"\"\n    Assert that the given list of Link objects includes, for each of the\n    given names, a link whose URL has a base name matching that name.\n    \"\"\"\n    for name in names:\n        assert any(\n            link.url.endswith(name) for link in links\n        ), f\"name {name!r} not among links: {links}\"\n\n\nclass TestLinkCollector:\n    @mock.patch(\"pip._internal.index.collector._get_simple_response\")\n    def test_fetch_response(self, mock_get_simple_response: mock.Mock) -> None:\n        url = \"https://pypi.org/simple/twine/\"\n\n        fake_response = make_fake_html_response(url)\n        mock_get_simple_response.return_value = fake_response\n\n        location = Link(url, cache_link_parsing=False)\n        link_collector = make_test_link_collector()\n        actual = link_collector.fetch_response(location)\n\n        assert actual is not None\n        assert actual.content == fake_response.content\n        assert actual.encoding is None\n        assert actual.url == url\n        assert actual.cache_link_parsing == location.cache_link_parsing\n\n        # Also check that the right session object was passed to\n        # _get_simple_response().\n        mock_get_simple_response.assert_called_once_with(\n            url,\n            session=link_collector.session,\n        )\n\n    def test_collect_page_sources(\n        self, caplog: pytest.LogCaptureFixture, data: TestData\n    ) -> None:\n        caplog.set_level(logging.DEBUG)\n\n        link_collector = make_test_link_collector(\n            find_links=[data.find_links],\n            # Include two copies of the URL to check that the second one\n            # is skipped.\n            index_urls=[PyPI.simple_url, PyPI.simple_url],\n        )\n        collected_sources = link_collector.collect_sources(\n            \"twine\",\n            candidates_from_page=lambda link: [\n                InstallationCandidate(\"twine\", \"1.0\", link)\n            ],\n        )\n\n        files_it = itertools.chain.from_iterable(\n            source.file_links()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        pages_it = itertools.chain.from_iterable(\n            source.page_candidates()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        files = list(files_it)\n        pages = list(pages_it)\n\n        # Only \"twine\" should return from collecting sources\n        assert len(files) == 1\n\n        assert [page.link for page in pages] == [Link(\"https://pypi.org/simple/twine/\")]\n        # Check that index URLs are marked as *un*cacheable.\n        assert not pages[0].link.cache_link_parsing\n\n        expected_message = dedent(\n            \"\"\"\\\n        1 location(s) to search for versions of twine:\n        * https://pypi.org/simple/twine/\"\"\"\n        )\n        assert caplog.record_tuples == [\n            (\"pip._internal.index.collector\", logging.DEBUG, expected_message),\n        ]\n\n    def test_collect_file_sources(\n        self, caplog: pytest.LogCaptureFixture, data: TestData\n    ) -> None:\n        caplog.set_level(logging.DEBUG)\n\n        link_collector = make_test_link_collector(\n            find_links=[data.find_links],\n            # Include two copies of the URL to check that the second one\n            # is skipped.\n            index_urls=[PyPI.simple_url, PyPI.simple_url],\n        )\n        collected_sources = link_collector.collect_sources(\n            \"singlemodule\",\n            candidates_from_page=lambda link: [\n                InstallationCandidate(\"singlemodule\", \"0.0.1\", link)\n            ],\n        )\n\n        files_it = itertools.chain.from_iterable(\n            source.file_links()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        pages_it = itertools.chain.from_iterable(\n            source.page_candidates()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        files = list(files_it)\n        _ = list(pages_it)\n\n        # singlemodule should return files\n        assert len(files) > 0\n        check_links_include(files, names=[\"singlemodule-0.0.1.tar.gz\"])\n\n        expected_message = dedent(\n            \"\"\"\\\n        1 location(s) to search for versions of singlemodule:\n        * https://pypi.org/simple/singlemodule/\"\"\"\n        )\n        assert caplog.record_tuples == [\n            (\"pip._internal.index.collector\", logging.DEBUG, expected_message),\n        ]\n\n\n@pytest.mark.parametrize(\n    \"find_links, no_index, suppress_no_index, expected\",\n    [\n        ([\"link1\"], False, False, ([\"link1\"], [\"default_url\", \"url1\", \"url2\"])),\n        ([\"link1\"], False, True, ([\"link1\"], [\"default_url\", \"url1\", \"url2\"])),\n        ([\"link1\"], True, False, ([\"link1\"], [])),\n        # Passing suppress_no_index=True suppresses no_index=True.\n        ([\"link1\"], True, True, ([\"link1\"], [\"default_url\", \"url1\", \"url2\"])),\n        # Test options.find_links=False.\n        (False, False, False, ([], [\"default_url\", \"url1\", \"url2\"])),\n    ],\n)\ndef test_link_collector_create(\n    find_links: list[str],\n    no_index: bool,\n    suppress_no_index: bool,\n    expected: tuple[list[str], list[str]],\n) -> None:\n    \"\"\"\n    :param expected: the expected (find_links, index_urls) values.\n    \"\"\"\n    expected_find_links, expected_index_urls = expected\n    session = PipSession()\n    options = mock.Mock(\n        find_links=find_links,\n        index_url=\"default_url\",\n        extra_index_urls=[\"url1\", \"url2\"],\n        no_index=no_index,\n    )\n    link_collector = LinkCollector.create(\n        session,\n        options=options,\n        suppress_no_index=suppress_no_index,\n    )\n\n    assert link_collector.session is session\n\n    search_scope = link_collector.search_scope\n    assert search_scope.find_links == expected_find_links\n    assert search_scope.index_urls == expected_index_urls\n\n\n@mock.patch(\"os.path.expanduser\")\ndef test_link_collector_create_find_links_expansion(\n    mock_expanduser: mock.Mock, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test \"~\" expansion in --find-links paths.\n    \"\"\"\n\n    # This is a mock version of expanduser() that expands \"~\" to the tmpdir.\n    def expand_path(path: str) -> str:\n        if path.startswith(\"~/\"):\n            path = os.path.join(tmpdir, path[2:])\n        return path\n\n    mock_expanduser.side_effect = expand_path\n\n    session = PipSession()\n    options = mock.Mock(\n        find_links=[\"~/temp1\", \"~/temp2\"],\n        index_url=\"default_url\",\n        extra_index_urls=[],\n        no_index=False,\n    )\n    # Only create temp2 and not temp1 to test that \"~\" expansion only occurs\n    # when the directory exists.\n    temp2_dir = os.path.join(tmpdir, \"temp2\")\n    os.mkdir(temp2_dir)\n\n    link_collector = LinkCollector.create(session, options=options)\n\n    search_scope = link_collector.search_scope\n    # Only ~/temp2 gets expanded. Also, the path is normalized when expanded.\n    expected_temp2_dir = os.path.normcase(temp2_dir)\n    assert search_scope.find_links == [\"~/temp1\", expected_temp2_dir]\n    assert search_scope.index_urls == [\"default_url\"]\n\n\n@pytest.mark.parametrize(\n    \"url, result\",\n    [\n        (\n            \"https://pypi.org/pip-18.0.tar.gz#sha256=aa113592bbe\",\n            LinkHash(\"sha256\", \"aa113592bbe\"),\n        ),\n        (\n            \"https://pypi.org/pip-18.0.tar.gz#sha256=aa113592bbe&subdirectory=setup\",\n            LinkHash(\"sha256\", \"aa113592bbe\"),\n        ),\n        (\n            \"https://pypi.org/pip-18.0.tar.gz#subdirectory=setup&sha256=aa113592bbe\",\n            LinkHash(\"sha256\", \"aa113592bbe\"),\n        ),\n        # \"xsha256\" is not a valid algorithm, so we discard it.\n        (\"https://pypi.org/pip-18.0.tar.gz#xsha256=aa113592bbe\", None),\n        # Empty hash.\n        (\n            \"https://pypi.org/pip-18.0.tar.gz#sha256=\",\n            LinkHash(\"sha256\", \"\"),\n        ),\n        (\n            \"https://pypi.org/pip-18.0.tar.gz#md5=aa113592bbe\",\n            LinkHash(\"md5\", \"aa113592bbe\"),\n        ),\n        (\"https://pypi.org/pip-18.0.tar.gz\", None),\n        # We don't recognize the \"sha500\" algorithm, so we discard it.\n        (\"https://pypi.org/pip-18.0.tar.gz#sha500=aa113592bbe\", None),\n    ],\n)\ndef test_link_hash_parsing(url: str, result: LinkHash | None) -> None:\n    assert LinkHash.find_hash_url_fragment(url) == result\n\n\n@pytest.mark.parametrize(\n    \"metadata_attrib, expected\",\n    [\n        (\"sha256=aa113592bbe\", MetadataFile({\"sha256\": \"aa113592bbe\"})),\n        (\"sha256=\", MetadataFile({\"sha256\": \"\"})),\n        (\"sha500=aa113592bbe\", MetadataFile(None)),\n        (\"true\", MetadataFile(None)),\n        (None, None),\n        # Attribute is present but invalid\n        (\"\", MetadataFile(None)),\n        (\"aa113592bbe\", MetadataFile(None)),\n    ],\n)\ndef test_metadata_file_info_parsing_html(\n    metadata_attrib: str, expected: MetadataFile | None\n) -> None:\n    attribs: dict[str, str | None] = {\n        \"href\": \"something\",\n        \"data-dist-info-metadata\": metadata_attrib,\n    }\n    page_url = \"dummy_for_comes_from\"\n    base_url = \"https://index.url/simple\"\n    link = Link.from_element(attribs, page_url, base_url)\n    assert link is not None\n    assert link.metadata_file_data == expected\n"
  },
  {
    "path": "tests/unit/test_command_install.py",
    "content": "import errno\nimport sys\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.requests.exceptions import InvalidProxyURL\n\nfrom pip._internal.commands import install\nfrom pip._internal.commands.install import create_os_error_message, decide_user_install\n\n\nclass TestDecideUserInstall:\n    @mock.patch(\"site.ENABLE_USER_SITE\", True)\n    @mock.patch(\"pip._internal.commands.install.site_packages_writable\")\n    def test_prefix_and_target(self, sp_writable: mock.Mock) -> None:\n        sp_writable.return_value = False\n\n        assert decide_user_install(use_user_site=None, prefix_path=\"foo\") is False\n\n        assert decide_user_install(use_user_site=None, target_dir=\"bar\") is False\n\n    @pytest.mark.parametrize(\n        \"enable_user_site,site_packages_writable,result\",\n        [\n            (True, True, False),\n            (True, False, True),\n            (False, True, False),\n            (False, False, False),\n        ],\n    )\n    def test_most_cases(\n        self,\n        enable_user_site: bool,\n        site_packages_writable: bool,\n        result: bool,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        monkeypatch.setattr(\"site.ENABLE_USER_SITE\", enable_user_site)\n        monkeypatch.setattr(\n            \"pip._internal.commands.install.site_packages_writable\",\n            lambda **kw: site_packages_writable,\n        )\n        assert decide_user_install(use_user_site=None) is result\n\n\n@pytest.mark.parametrize(\n    \"error, show_traceback, using_user_site, expected\",\n    [\n        # show_traceback = True, using_user_site = True\n        (\n            OSError(\"Illegal byte sequence\"),\n            True,\n            True,\n            \"Could not install packages due to an OSError.\\n\",\n        ),\n        (\n            OSError(errno.EACCES, \"No file permission\"),\n            True,\n            True,\n            \"Could\"\n            \" not install packages due to an OSError.\\nCheck the\"\n            \" permissions.\\n\",\n        ),\n        # show_traceback = True, using_user_site = False\n        (\n            OSError(\"Illegal byte sequence\"),\n            True,\n            False,\n            \"Could not install packages due to an OSError.\\n\",\n        ),\n        (\n            OSError(errno.EACCES, \"No file permission\"),\n            True,\n            False,\n            \"Could\"\n            \" not install packages due to an OSError.\\nConsider using the\"\n            \" `--user` option or check the permissions.\\n\",\n        ),\n        # show_traceback = False, using_user_site = True\n        (\n            OSError(\"Illegal byte sequence\"),\n            False,\n            True,\n            \"Could not\"\n            \" install packages due to an OSError: Illegal byte\"\n            \" sequence\\n\",\n        ),\n        (\n            OSError(errno.EACCES, \"No file permission\"),\n            False,\n            True,\n            \"Could\"\n            \" not install packages due to an OSError: [Errno 13] No file\"\n            \" permission\\nCheck the permissions.\\n\",\n        ),\n        # show_traceback = False, using_user_site = False\n        (\n            OSError(\"Illegal byte sequence\"),\n            False,\n            False,\n            \"Could not\"\n            \" install packages due to an OSError: Illegal byte sequence\"\n            \"\\n\",\n        ),\n        (\n            OSError(errno.EACCES, \"No file permission\"),\n            False,\n            False,\n            \"Could not install packages due to an OSError: [Errno 13] No\"\n            \" file permission\\nConsider using the `--user` option or check the\"\n            \" permissions.\\n\",\n        ),\n        # Testing custom InvalidProxyURL with help message\n        #  show_traceback = True, using_user_site = True\n        (\n            InvalidProxyURL(),\n            True,\n            True,\n            \"Could not install packages due to an OSError.\\n\"\n            \"Consider checking your local proxy configuration\"\n            ' with \"pip config debug\".\\n',\n        ),\n        # Testing both long path error (ENOENT)\n        # and long file/folder name error (EINVAL) on Windows\n        pytest.param(\n            OSError(errno.ENOENT, \"No such file or directory\", f\"C:{'/a'*261}\"),\n            False,\n            False,\n            \"Could not install packages due to an OSError: \"\n            f\"[Errno 2] No such file or directory: 'C:{'/a'*261}'\\n\"\n            \"HINT: This error might have occurred since \"\n            \"this system does not have Windows Long Path \"\n            \"support enabled. You can find information on \"\n            \"how to enable this at \"\n            \"https://pip.pypa.io/warnings/enable-long-paths\\n\",\n            marks=pytest.mark.skipif(\n                sys.platform != \"win32\", reason=\"Windows-specific filename length test\"\n            ),\n        ),\n        pytest.param(\n            OSError(errno.EINVAL, \"No such file or directory\", f\"C:/{'a'*256}\"),\n            False,\n            False,\n            \"Could not install packages due to an OSError: \"\n            f\"[Errno 22] No such file or directory: 'C:/{'a'*256}'\\n\"\n            \"HINT: This error might be caused by a file or folder name exceeding \"\n            \"255 characters, which is a Windows limitation even if long paths \"\n            \"are enabled.\\n\",\n            marks=pytest.mark.skipif(\n                sys.platform != \"win32\", reason=\"Windows-specific filename length test\"\n            ),\n        ),\n        pytest.param(\n            OSError(\n                errno.EINVAL, \"No such file or directory\", f\"C:{'/a'*261}/{'b'*256}\"\n            ),\n            False,\n            False,\n            \"Could not install packages due to an OSError: \"\n            f\"[Errno 22] No such file or directory: 'C:{'/a' * 261}/{'b' * 256}'\\n\"\n            \"HINT: This error might be caused by a file or folder name exceeding \"\n            \"255 characters, which is a Windows limitation even if long paths \"\n            \"are enabled.\\n \"\n            \"HINT: This error might have occurred since \"\n            \"this system does not have Windows Long Path \"\n            \"support enabled. You can find information on \"\n            \"how to enable this at \"\n            \"https://pip.pypa.io/warnings/enable-long-paths\\n\",\n            marks=pytest.mark.skipif(\n                sys.platform != \"win32\", reason=\"Windows-specific filename length test\"\n            ),\n        ),\n    ],\n)\ndef test_create_os_error_message(\n    monkeypatch: pytest.MonkeyPatch,\n    error: OSError,\n    show_traceback: bool,\n    using_user_site: bool,\n    expected: str,\n) -> None:\n    monkeypatch.setattr(install, \"running_under_virtualenv\", lambda: False)\n    msg = create_os_error_message(error, show_traceback, using_user_site)\n    assert msg == expected\n"
  },
  {
    "path": "tests/unit/test_commands.py",
    "content": "import os\nfrom typing import Callable\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.req_command import (\n    IndexGroupCommand,\n    RequirementCommand,\n    SessionCommandMixin,\n)\nfrom pip._internal.commands import commands_dict, create_command\n\n# These are the expected names of the commands whose classes inherit from\n# IndexGroupCommand.\nEXPECTED_INDEX_GROUP_COMMANDS = [\n    \"download\",\n    \"index\",\n    \"install\",\n    \"list\",\n    \"lock\",\n    \"wheel\",\n]\n\n\ndef check_commands(pred: Callable[[Command], bool], expected: list[str]) -> None:\n    \"\"\"\n    Check the commands satisfying a predicate.\n    \"\"\"\n    commands = [create_command(name) for name in sorted(commands_dict)]\n    actual = [command.name for command in commands if pred(command)]\n    assert actual == expected, f\"actual: {actual}\"\n\n\ndef test_commands_dict__order() -> None:\n    \"\"\"\n    Check the ordering of commands_dict.\n    \"\"\"\n    names = list(commands_dict)\n    # A spot-check is sufficient to check that commands_dict encodes an\n    # ordering.\n    assert names[0] == \"install\"\n    assert names[-1] == \"help\"\n\n\n@pytest.mark.parametrize(\"name\", list(commands_dict))\ndef test_create_command(name: str) -> None:\n    \"\"\"Test creating an instance of each available command.\"\"\"\n    command = create_command(name)\n    assert command.name == name\n    assert command.summary == commands_dict[name].summary\n\n\ndef test_session_commands() -> None:\n    \"\"\"\n    Test which commands inherit from SessionCommandMixin.\n    \"\"\"\n\n    def is_session_command(command: Command) -> bool:\n        return isinstance(command, SessionCommandMixin)\n\n    expected = [\n        \"download\",\n        \"index\",\n        \"install\",\n        \"list\",\n        \"lock\",\n        \"search\",\n        \"uninstall\",\n        \"wheel\",\n    ]\n    check_commands(is_session_command, expected)\n\n\ndef test_index_group_commands() -> None:\n    \"\"\"\n    Test the commands inheriting from IndexGroupCommand.\n    \"\"\"\n\n    def is_index_group_command(command: Command) -> bool:\n        return isinstance(command, IndexGroupCommand)\n\n    check_commands(is_index_group_command, EXPECTED_INDEX_GROUP_COMMANDS)\n\n    # Also check that the commands inheriting from IndexGroupCommand are\n    # exactly the commands with the --no-index option.\n    def has_option_no_index(command: Command) -> bool:\n        return command.parser.has_option(\"--no-index\")\n\n    check_commands(has_option_no_index, EXPECTED_INDEX_GROUP_COMMANDS)\n\n\n@pytest.mark.parametrize(\"command_name\", EXPECTED_INDEX_GROUP_COMMANDS)\n@pytest.mark.parametrize(\n    \"disable_pip_version_check, no_index, expected_called\",\n    [\n        # pip_self_version_check() is only called when both\n        # disable_pip_version_check and no_index are False.\n        (False, False, True),\n        (False, True, False),\n        (True, False, False),\n        (True, True, False),\n    ],\n)\n@mock.patch(\"pip._internal.cli.index_command._pip_self_version_check\")\ndef test_index_group_handle_pip_version_check(\n    mock_version_check: mock.Mock,\n    command_name: str,\n    disable_pip_version_check: bool,\n    no_index: bool,\n    expected_called: bool,\n) -> None:\n    \"\"\"\n    Test whether pip_self_version_check() is called when\n    handle_pip_version_check() is called, for each of the\n    IndexGroupCommand classes.\n    \"\"\"\n    command = create_command(command_name)\n    options = command.parser.get_default_values()\n    options.disable_pip_version_check = disable_pip_version_check\n    options.no_index = no_index\n\n    # See test test_list_pip_version_check() below.\n    if command_name == \"list\":\n        expected_called = False\n\n    command.handle_pip_version_check(options)\n    if expected_called:\n        mock_version_check.assert_called_once()\n    else:\n        mock_version_check.assert_not_called()\n\n\ndef test_requirement_commands() -> None:\n    \"\"\"\n    Test which commands inherit from RequirementCommand.\n    \"\"\"\n\n    def is_requirement_command(command: Command) -> bool:\n        return isinstance(command, RequirementCommand)\n\n    check_commands(is_requirement_command, [\"download\", \"install\", \"lock\", \"wheel\"])\n\n\n@pytest.mark.parametrize(\"flag\", [\"\", \"--outdated\", \"--uptodate\"])\n@mock.patch(\"pip._internal.cli.index_command._pip_self_version_check\")\n@mock.patch.dict(os.environ, {\"PIP_DISABLE_PIP_VERSION_CHECK\": \"no\"})\ndef test_list_pip_version_check(version_check_mock: mock.Mock, flag: str) -> None:\n    \"\"\"\n    Ensure that pip list doesn't perform a version self-check unless given\n    --outdated or --uptodate (as they require hitting the network anyway).\n    \"\"\"\n    command = create_command(\"list\")\n    command.run = lambda *args, **kwargs: 0  # type: ignore[method-assign]\n    command.main([flag])\n    if flag != \"\":\n        version_check_mock.assert_called_once()\n    else:\n        version_check_mock.assert_not_called()\n"
  },
  {
    "path": "tests/unit/test_compat.py",
    "content": "import os\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.utils.compat import get_path_uid\n\n\ndef test_get_path_uid() -> None:\n    path = os.getcwd()\n    assert get_path_uid(path) == os.stat(path).st_uid\n\n\n@pytest.mark.skipif(\"not hasattr(os, 'O_NOFOLLOW')\")\ndef test_get_path_uid_without_NOFOLLOW(monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.delattr(\"os.O_NOFOLLOW\")\n    path = os.getcwd()\n    assert get_path_uid(path) == os.stat(path).st_uid\n\n\n# Skip unconditionally on Windows, as symlinks need admin privs there\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\n@pytest.mark.skipif(\"not hasattr(os, 'symlink')\")\ndef test_get_path_uid_symlink(tmpdir: Path) -> None:\n    f = tmpdir / \"symlink\" / \"somefile\"\n    f.parent.mkdir()\n    f.write_text(\"content\")\n    fs = f\"{f}_link\"\n    os.symlink(f, fs)\n    with pytest.raises(OSError):\n        get_path_uid(fs)\n\n\n@pytest.mark.skipif(\"not hasattr(os, 'O_NOFOLLOW')\")\n@pytest.mark.skipif(\"not hasattr(os, 'symlink')\")\ndef test_get_path_uid_symlink_without_NOFOLLOW(\n    tmpdir: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    monkeypatch.delattr(\"os.O_NOFOLLOW\")\n    f = tmpdir / \"symlink\" / \"somefile\"\n    f.parent.mkdir()\n    f.write_text(\"content\")\n    fs = f\"{f}_link\"\n    os.symlink(f, fs)\n    with pytest.raises(OSError):\n        get_path_uid(fs)\n"
  },
  {
    "path": "tests/unit/test_configuration.py",
    "content": "\"\"\"Tests for all things related to the configuration\"\"\"\n\nimport re\nfrom unittest.mock import MagicMock\n\nimport pytest\n\nfrom pip._internal.configuration import get_configuration_files, kinds\nfrom pip._internal.exceptions import ConfigurationError\n\nfrom tests.lib.configuration_helpers import ConfigurationMixin\n\n\nclass TestConfigurationLoading(ConfigurationMixin):\n    def test_global_loading(self) -> None:\n        self.patch_configuration(kinds.GLOBAL, {\"test.hello\": \"1\"})\n\n        self.configuration.load()\n        assert self.configuration.get_value(\"test.hello\") == \"1\"\n\n    def test_user_loading(self) -> None:\n        self.patch_configuration(kinds.USER, {\"test.hello\": \"2\"})\n\n        self.configuration.load()\n        assert self.configuration.get_value(\"test.hello\") == \"2\"\n\n    def test_site_loading(self) -> None:\n        self.patch_configuration(kinds.SITE, {\"test.hello\": \"3\"})\n\n        self.configuration.load()\n        assert self.configuration.get_value(\"test.hello\") == \"3\"\n\n    def test_environment_config_loading(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        contents = \"\"\"\n            [test]\n            hello = 4\n        \"\"\"\n\n        with self.tmpfile(contents) as config_file:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", config_file)\n\n            self.configuration.load()\n            assert (\n                self.configuration.get_value(\"test.hello\") == \"4\"\n            ), self.configuration._config\n\n    def test_environment_var_loading(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setenv(\"PIP_HELLO\", \"5\")\n\n        self.configuration.load()\n        assert self.configuration.get_value(\":env:.hello\") == \"5\"\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_environment_var_does_not_load_lowercase(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"pip_hello\", \"5\")\n\n        self.configuration.load()\n        with pytest.raises(ConfigurationError):\n            self.configuration.get_value(\":env:.hello\")\n\n    def test_environment_var_does_not_load_version(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PIP_VERSION\", \"True\")\n\n        self.configuration.load()\n\n        with pytest.raises(ConfigurationError):\n            self.configuration.get_value(\":env:.version\")\n\n    def test_environment_config_errors_if_malformed(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        contents = \"\"\"\n            test]\n            hello = 4\n        \"\"\"\n        with self.tmpfile(contents) as config_file:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", config_file)\n            with pytest.raises(ConfigurationError) as err:\n                self.configuration.load()\n\n        assert \"section header\" in str(err.value)  # error kind\n        assert \"1\" in str(err.value)  # line number\n        assert config_file in str(err.value) or repr(config_file) in str(  # file name\n            err.value\n        )\n\n    def test_no_such_key_error_message_no_command(self) -> None:\n        self.configuration.load_only = kinds.GLOBAL\n        self.configuration.load()\n        expected_msg = (\n            \"Key does not contain dot separated section and key. \"\n            \"Perhaps you wanted to use 'global.index-url' instead?\"\n        )\n        pat = f\"^{re.escape(expected_msg)}$\"\n        with pytest.raises(ConfigurationError, match=pat):\n            self.configuration.get_value(\"index-url\")\n\n    def test_no_such_key_error_message_missing_option(self) -> None:\n        self.configuration.load_only = kinds.GLOBAL\n        self.configuration.load()\n        expected_msg = \"No such key - global.index-url\"\n        pat = f\"^{re.escape(expected_msg)}$\"\n        with pytest.raises(ConfigurationError, match=pat):\n            self.configuration.get_value(\"global.index-url\")\n\n\nclass TestConfigurationPrecedence(ConfigurationMixin):\n    # Tests for methods to that determine the order of precedence of\n    # configuration options\n\n    def test_env_overrides_site(self) -> None:\n        self.patch_configuration(kinds.SITE, {\"test.hello\": \"1\"})\n        self.patch_configuration(kinds.ENV, {\"test.hello\": \"0\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"0\"\n\n    def test_env_overrides_user(self) -> None:\n        self.patch_configuration(kinds.USER, {\"test.hello\": \"2\"})\n        self.patch_configuration(kinds.ENV, {\"test.hello\": \"0\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"0\"\n\n    def test_env_overrides_global(self) -> None:\n        self.patch_configuration(kinds.GLOBAL, {\"test.hello\": \"3\"})\n        self.patch_configuration(kinds.ENV, {\"test.hello\": \"0\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"0\"\n\n    def test_site_overrides_user(self) -> None:\n        self.patch_configuration(kinds.USER, {\"test.hello\": \"2\"})\n        self.patch_configuration(kinds.SITE, {\"test.hello\": \"1\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"1\"\n\n    def test_site_overrides_global(self) -> None:\n        self.patch_configuration(kinds.GLOBAL, {\"test.hello\": \"3\"})\n        self.patch_configuration(kinds.SITE, {\"test.hello\": \"1\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"1\"\n\n    def test_user_overrides_global(self) -> None:\n        self.patch_configuration(kinds.GLOBAL, {\"test.hello\": \"3\"})\n        self.patch_configuration(kinds.USER, {\"test.hello\": \"2\"})\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"2\"\n\n    def test_env_not_overridden_by_environment_var(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        self.patch_configuration(kinds.ENV, {\"test.hello\": \"1\"})\n        monkeypatch.setenv(\"PIP_HELLO\", \"5\")\n\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"1\"\n        assert self.configuration.get_value(\":env:.hello\") == \"5\"\n\n    def test_site_not_overridden_by_environment_var(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        self.patch_configuration(kinds.SITE, {\"test.hello\": \"2\"})\n        monkeypatch.setenv(\"PIP_HELLO\", \"5\")\n\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"2\"\n        assert self.configuration.get_value(\":env:.hello\") == \"5\"\n\n    def test_user_not_overridden_by_environment_var(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        self.patch_configuration(kinds.USER, {\"test.hello\": \"3\"})\n        monkeypatch.setenv(\"PIP_HELLO\", \"5\")\n\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"3\"\n        assert self.configuration.get_value(\":env:.hello\") == \"5\"\n\n    def test_global_not_overridden_by_environment_var(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        self.patch_configuration(kinds.GLOBAL, {\"test.hello\": \"4\"})\n        monkeypatch.setenv(\"PIP_HELLO\", \"5\")\n\n        self.configuration.load()\n\n        assert self.configuration.get_value(\"test.hello\") == \"4\"\n        assert self.configuration.get_value(\":env:.hello\") == \"5\"\n\n\nclass TestConfigurationModification(ConfigurationMixin):\n    # Tests for methods to that modify the state of a Configuration\n\n    def test_no_specific_given_modification(self) -> None:\n        self.configuration.load()\n\n        with pytest.raises(ConfigurationError):\n            self.configuration.set_value(\"test.hello\", \"10\")\n\n    def test_site_modification(self) -> None:\n        self.configuration.load_only = kinds.SITE\n        self.configuration.load()\n\n        # Mock out the method\n        mymock = MagicMock(spec=self.configuration._mark_as_modified)\n        # https://github.com/python/mypy/issues/2427\n        self.configuration._mark_as_modified = mymock  # type: ignore[method-assign]\n\n        self.configuration.set_value(\"test.hello\", \"10\")\n\n        # get the path to site config file\n        assert mymock.call_count == 1\n        assert mymock.call_args[0][0] == (get_configuration_files()[kinds.SITE][0])\n\n    def test_user_modification(self) -> None:\n        # get the path to local config file\n        self.configuration.load_only = kinds.USER\n        self.configuration.load()\n\n        # Mock out the method\n        mymock = MagicMock(spec=self.configuration._mark_as_modified)\n        # https://github.com/python/mypy/issues/2427\n        self.configuration._mark_as_modified = mymock  # type: ignore[method-assign]\n\n        self.configuration.set_value(\"test.hello\", \"10\")\n\n        # get the path to user config file\n        assert mymock.call_count == 1\n        assert mymock.call_args[0][0] == (\n            # Use new config file\n            get_configuration_files()[kinds.USER][1]\n        )\n\n    def test_global_modification(self) -> None:\n        # get the path to local config file\n        self.configuration.load_only = kinds.GLOBAL\n        self.configuration.load()\n\n        # Mock out the method\n        mymock = MagicMock(spec=self.configuration._mark_as_modified)\n        # https://github.com/python/mypy/issues/2427\n        self.configuration._mark_as_modified = mymock  # type: ignore[method-assign]\n\n        self.configuration.set_value(\"test.hello\", \"10\")\n\n        # get the path to user config file\n        assert mymock.call_count == 1\n        assert mymock.call_args[0][0] == (get_configuration_files()[kinds.GLOBAL][-1])\n\n    def test_normalization(self) -> None:\n        # underscores and dashes can be used interchangeably.\n        # internally, underscores get converted into dashes before reading/writing file\n        self.configuration.load_only = kinds.GLOBAL\n        self.configuration.load()\n        self.configuration.set_value(\"global.index_url\", \"example.org\")\n        assert self.configuration.get_value(\"global.index_url\") == \"example.org\"\n        assert self.configuration.get_value(\"global.index-url\") == \"example.org\"\n        self.configuration.unset_value(\"global.index-url\")\n        pat = r\"^No such key - global\\.index-url$\"\n        with pytest.raises(ConfigurationError, match=pat):\n            self.configuration.get_value(\"global.index-url\")\n"
  },
  {
    "path": "tests/unit/test_direct_url.py",
    "content": "import pytest\n\nfrom pip._internal.models.direct_url import (\n    ArchiveInfo,\n    DirectUrl,\n    DirectUrlValidationError,\n    DirInfo,\n    VcsInfo,\n)\n\n\ndef test_from_json() -> None:\n    json = '{\"url\": \"file:///home/user/project\", \"dir_info\": {}}'\n    direct_url = DirectUrl.from_json(json)\n    assert direct_url.url == \"file:///home/user/project\"\n    assert isinstance(direct_url.info, DirInfo)\n    assert direct_url.info.editable is False\n\n\ndef test_to_json() -> None:\n    direct_url = DirectUrl(\n        url=\"file:///home/user/archive.tgz\",\n        info=ArchiveInfo(),\n    )\n    direct_url.validate()\n    assert direct_url.to_json() == (\n        '{\"archive_info\": {}, \"url\": \"file:///home/user/archive.tgz\"}'\n    )\n\n\ndef test_archive_info() -> None:\n    direct_url_dict = {\n        \"url\": \"file:///home/user/archive.tgz\",\n        \"archive_info\": {\"hash\": \"sha1=1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"},\n    }\n    direct_url = DirectUrl.from_dict(direct_url_dict)\n    assert isinstance(direct_url.info, ArchiveInfo)\n    assert direct_url.url == direct_url_dict[\"url\"]\n    assert (\n        direct_url.info.hash == direct_url_dict[\"archive_info\"][\"hash\"]  # type: ignore\n    )\n    # test we add the hashes key automatically\n    direct_url_dict[\"archive_info\"][\"hashes\"] = {  # type: ignore\n        \"sha1\": \"1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    }\n    assert direct_url.to_dict() == direct_url_dict\n\n\ndef test_dir_info() -> None:\n    direct_url_dict = {\n        \"url\": \"file:///home/user/project\",\n        \"dir_info\": {\"editable\": True},\n    }\n    direct_url = DirectUrl.from_dict(direct_url_dict)\n    assert isinstance(direct_url.info, DirInfo)\n    assert direct_url.url == direct_url_dict[\"url\"]\n    assert direct_url.info.editable is True\n    assert direct_url.to_dict() == direct_url_dict\n    # test editable default to False\n    direct_url_dict = {\"url\": \"file:///home/user/project\", \"dir_info\": {}}\n    direct_url = DirectUrl.from_dict(direct_url_dict)\n    assert isinstance(direct_url.info, DirInfo)\n    assert direct_url.info.editable is False\n\n\ndef test_vcs_info() -> None:\n    direct_url_dict = {\n        \"url\": \"https:///g.c/u/p.git\",\n        \"vcs_info\": {\n            \"vcs\": \"git\",\n            \"requested_revision\": \"master\",\n            \"commit_id\": \"1b8c5bc61a86f377fea47b4276c8c8a5842d2220\",\n        },\n    }\n    direct_url = DirectUrl.from_dict(direct_url_dict)\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.url == direct_url_dict[\"url\"]\n    assert direct_url.info.vcs == \"git\"\n    assert direct_url.info.requested_revision == \"master\"\n    assert direct_url.info.commit_id == \"1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    assert direct_url.to_dict() == direct_url_dict\n\n\ndef test_parsing_validation() -> None:\n    with pytest.raises(DirectUrlValidationError, match=\"url must have a value\"):\n        DirectUrl.from_dict({\"dir_info\": {}})\n    with pytest.raises(\n        DirectUrlValidationError,\n        match=\"missing one of archive_info, dir_info, vcs_info\",\n    ):\n        DirectUrl.from_dict({\"url\": \"http://...\"})\n    with pytest.raises(DirectUrlValidationError, match=\"unexpected type for editable\"):\n        DirectUrl.from_dict({\"url\": \"http://...\", \"dir_info\": {\"editable\": \"false\"}})\n    with pytest.raises(DirectUrlValidationError, match=\"unexpected type for hash\"):\n        DirectUrl.from_dict({\"url\": \"http://...\", \"archive_info\": {\"hash\": 1}})\n    with pytest.raises(DirectUrlValidationError, match=\"unexpected type for vcs\"):\n        DirectUrl.from_dict({\"url\": \"http://...\", \"vcs_info\": {\"vcs\": None}})\n    with pytest.raises(DirectUrlValidationError, match=\"commit_id must have a value\"):\n        DirectUrl.from_dict({\"url\": \"http://...\", \"vcs_info\": {\"vcs\": \"git\"}})\n    with pytest.raises(\n        DirectUrlValidationError,\n        match=\"more than one of archive_info, dir_info, vcs_info\",\n    ):\n        DirectUrl.from_dict({\"url\": \"http://...\", \"dir_info\": {}, \"archive_info\": {}})\n    with pytest.raises(\n        DirectUrlValidationError,\n        match=\"invalid archive_info.hash format\",\n    ):\n        DirectUrl.from_dict(\n            {\"url\": \"http://...\", \"archive_info\": {\"hash\": \"sha256:aaa\"}}\n        )\n\n\ndef test_redact_url() -> None:\n    def _redact_git(url: str) -> str:\n        direct_url = DirectUrl(\n            url=url,\n            info=VcsInfo(vcs=\"git\", commit_id=\"1\"),\n        )\n        return direct_url.redacted_url\n\n    def _redact_archive(url: str) -> str:\n        direct_url = DirectUrl(\n            url=url,\n            info=ArchiveInfo(),\n        )\n        return direct_url.redacted_url\n\n    assert (\n        _redact_git(\"https://user:password@g.c/u/p.git@branch#egg=pkg\")\n        == \"https://g.c/u/p.git@branch#egg=pkg\"\n    )\n    assert _redact_git(\"https://${USER}:password@g.c/u/p.git\") == \"https://g.c/u/p.git\"\n    assert (\n        _redact_archive(\"file://${U}:${PIP_PASSWORD}@g.c/u/p.tgz\")\n        == \"file://${U}:${PIP_PASSWORD}@g.c/u/p.tgz\"\n    )\n    assert (\n        _redact_git(\"https://${PIP_TOKEN}@g.c/u/p.git\")\n        == \"https://${PIP_TOKEN}@g.c/u/p.git\"\n    )\n    assert _redact_git(\"ssh://git@g.c/u/p.git\") == \"ssh://git@g.c/u/p.git\"\n\n\ndef test_hash_to_hashes() -> None:\n    direct_url = DirectUrl(url=\"https://e.c/archive.tar.gz\", info=ArchiveInfo())\n    assert isinstance(direct_url.info, ArchiveInfo)\n    direct_url.info.hash = \"sha256=abcdef\"\n    assert direct_url.info.hashes == {\"sha256\": \"abcdef\"}\n\n\ndef test_hash_to_hashes_constructor() -> None:\n    direct_url = DirectUrl(\n        url=\"https://e.c/archive.tar.gz\", info=ArchiveInfo(hash=\"sha256=abcdef\")\n    )\n    assert isinstance(direct_url.info, ArchiveInfo)\n    assert direct_url.info.hashes == {\"sha256\": \"abcdef\"}\n    direct_url = DirectUrl(\n        url=\"https://e.c/archive.tar.gz\",\n        info=ArchiveInfo(hash=\"sha256=abcdef\", hashes={\"sha512\": \"123456\"}),\n    )\n    assert isinstance(direct_url.info, ArchiveInfo)\n    assert direct_url.info.hashes == {\"sha256\": \"abcdef\", \"sha512\": \"123456\"}\n    # In case of conflict between hash and hashes, hashes wins.\n    direct_url = DirectUrl(\n        url=\"https://e.c/archive.tar.gz\",\n        info=ArchiveInfo(\n            hash=\"sha256=abcdef\", hashes={\"sha256\": \"012345\", \"sha512\": \"123456\"}\n        ),\n    )\n    assert isinstance(direct_url.info, ArchiveInfo)\n    assert direct_url.info.hashes == {\"sha256\": \"012345\", \"sha512\": \"123456\"}\n"
  },
  {
    "path": "tests/unit/test_direct_url_helpers.py",
    "content": "import os\nfrom functools import partial\nfrom pathlib import Path\nfrom unittest import mock\n\nfrom pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.direct_url_helpers import (\n    direct_url_as_pep440_direct_reference,\n    direct_url_from_link,\n)\nfrom pip._internal.vcs.git import Git\n\n\ndef test_as_pep440_requirement_archive() -> None:\n    direct_url = DirectUrl(\n        url=\"file:///home/user/archive.tgz\",\n        info=ArchiveInfo(),\n    )\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ file:///home/user/archive.tgz\"\n    )\n    direct_url.subdirectory = \"subdir\"\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ file:///home/user/archive.tgz#subdirectory=subdir\"\n    )\n    assert isinstance(direct_url.info, ArchiveInfo)\n    direct_url.info.hash = \"sha1=1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ file:///home/user/archive.tgz\"\n        \"#sha1=1b8c5bc61a86f377fea47b4276c8c8a5842d2220&subdirectory=subdir\"\n    )\n\n\ndef test_as_pep440_requirement_dir() -> None:\n    direct_url = DirectUrl(\n        url=\"file:///home/user/project\",\n        info=DirInfo(editable=False),\n    )\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ file:///home/user/project\"\n    )\n\n\ndef test_as_pep440_requirement_editable_dir() -> None:\n    # direct_url_as_pep440_direct_reference behaves the same\n    # irrespective of the editable flag. It's the responsibility of\n    # callers to render it as editable\n    direct_url = DirectUrl(\n        url=\"file:///home/user/project\",\n        info=DirInfo(editable=True),\n    )\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ file:///home/user/project\"\n    )\n\n\ndef test_as_pep440_requirement_vcs() -> None:\n    direct_url = DirectUrl(\n        url=\"https:///g.c/u/p.git\",\n        info=VcsInfo(vcs=\"git\", commit_id=\"1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"),\n    )\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ git+https:///g.c/u/p.git\"\n        \"@1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    )\n    direct_url.subdirectory = \"subdir\"\n    direct_url.validate()\n    assert (\n        direct_url_as_pep440_direct_reference(direct_url, \"pkg\")\n        == \"pkg @ git+https:///g.c/u/p.git\"\n        \"@1b8c5bc61a86f377fea47b4276c8c8a5842d2220#subdirectory=subdir\"\n    )\n\n\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision\")\ndef test_from_link_vcs(mock_get_backend_for_scheme: mock.Mock) -> None:\n    _direct_url_from_link = partial(direct_url_from_link, source_dir=\"...\")\n    direct_url = _direct_url_from_link(Link(\"git+https://g.c/u/p.git\"))\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.vcs == \"git\"\n    direct_url = _direct_url_from_link(Link(\"git+https://g.c/u/p.git#egg=pkg\"))\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    direct_url = _direct_url_from_link(\n        Link(\"git+https://g.c/u/p.git#egg=pkg&subdirectory=subdir\")\n    )\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert direct_url.subdirectory == \"subdir\"\n    direct_url = _direct_url_from_link(Link(\"git+https://g.c/u/p.git@branch\"))\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.requested_revision == \"branch\"\n    direct_url = _direct_url_from_link(Link(\"git+https://g.c/u/p.git@branch#egg=pkg\"))\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.requested_revision == \"branch\"\n    direct_url = _direct_url_from_link(Link(\"git+https://token@g.c/u/p.git\"))\n    assert direct_url.to_dict()[\"url\"] == \"https://g.c/u/p.git\"\n\n\ndef test_from_link_vcs_with_source_dir_obtains_commit_id(tmpdir: Path) -> None:\n    repo_path = tmpdir / \"test-repo\"\n    repo_path.mkdir()\n    repo_dir = os.fspath(repo_path)\n    Git.run_command([\"init\"], cwd=repo_dir)\n    (repo_path / \"somefile\").touch()\n    Git.run_command([\"add\", \".\"], cwd=repo_dir)\n    Git.run_command([\"commit\", \"-m\", \"commit msg\"], cwd=repo_dir)\n    commit_id = Git.get_revision(repo_dir)\n    direct_url = direct_url_from_link(\n        Link(\"git+https://g.c/u/p.git\"), source_dir=repo_dir\n    )\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.commit_id == commit_id\n\n\ndef test_from_link_vcs_without_source_dir() -> None:\n    direct_url = direct_url_from_link(\n        Link(\"git+https://g.c/u/p.git@1\"), link_is_in_wheel_cache=True\n    )\n    assert direct_url.url == \"https://g.c/u/p.git\"\n    assert isinstance(direct_url.info, VcsInfo)\n    assert direct_url.info.commit_id == \"1\"\n\n\ndef test_from_link_archive() -> None:\n    direct_url = direct_url_from_link(Link(\"https://g.c/archive.tgz\"))\n    assert direct_url.url == \"https://g.c/archive.tgz\"\n    assert isinstance(direct_url.info, ArchiveInfo)\n    direct_url = direct_url_from_link(\n        Link(\"https://g.c/archive.tgz#sha1=1b8c5bc61a86f377fea47b4276c8c8a5842d2220\")\n    )\n    assert isinstance(direct_url.info, ArchiveInfo)\n    assert direct_url.info.hash == \"sha1=1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    # Test the hashes key has been automatically populated.\n    assert direct_url.info.hashes == {\n        \"sha1\": \"1b8c5bc61a86f377fea47b4276c8c8a5842d2220\"\n    }\n\n\ndef test_from_link_dir(tmpdir: Path) -> None:\n    dir_url = tmpdir.as_uri()\n    direct_url = direct_url_from_link(Link(dir_url))\n    assert direct_url.url == dir_url\n    assert isinstance(direct_url.info, DirInfo)\n\n\ndef test_from_link_hide_user_password() -> None:\n    # Basic test only here, other variants are covered by\n    # direct_url.redact_url tests.\n    direct_url = direct_url_from_link(\n        Link(\"git+https://user:password@g.c/u/p.git@branch#egg=pkg\"),\n        link_is_in_wheel_cache=True,\n    )\n    assert direct_url.to_dict()[\"url\"] == \"https://g.c/u/p.git\"\n    direct_url = direct_url_from_link(\n        Link(\"git+ssh://git@g.c/u/p.git@branch#egg=pkg\"),\n        link_is_in_wheel_cache=True,\n    )\n    assert direct_url.to_dict()[\"url\"] == \"ssh://git@g.c/u/p.git\"\n"
  },
  {
    "path": "tests/unit/test_exceptions.py",
    "content": "\"\"\"Tests the presentation style of exceptions.\"\"\"\n\nfrom __future__ import annotations\n\nimport io\nimport locale\nimport logging\nimport pathlib\nimport sys\nimport textwrap\n\nimport pytest\n\nfrom pip._vendor import rich\n\nfrom pip._internal.exceptions import DiagnosticPipError, ExternallyManagedEnvironment\n\n\nclass TestDiagnosticPipErrorCreation:\n    def test_fails_without_reference(self) -> None:\n        class DerivedError(DiagnosticPipError):\n            pass\n\n        with pytest.raises(AssertionError) as exc_info:\n            DerivedError(message=\"\", context=None, hint_stmt=None)\n\n        assert str(exc_info.value) == \"error reference not provided!\"\n\n    def test_can_fetch_reference_from_subclass(self) -> None:\n        class DerivedError(DiagnosticPipError):\n            reference = \"subclass-reference\"\n\n        obj = DerivedError(message=\"\", context=None, hint_stmt=None)\n        assert obj.reference == \"subclass-reference\"\n\n    def test_can_fetch_reference_from_arguments(self) -> None:\n        class DerivedError(DiagnosticPipError):\n            pass\n\n        obj = DerivedError(\n            message=\"\", context=None, hint_stmt=None, reference=\"subclass-reference\"\n        )\n        assert obj.reference == \"subclass-reference\"\n\n    @pytest.mark.parametrize(\n        \"name\",\n        [\n            \"BADNAME\",\n            \"BadName\",\n            \"bad_name\",\n            \"BAD_NAME\",\n            \"_bad\",\n            \"bad-name-\",\n            \"bad--name\",\n            \"-bad-name\",\n            \"bad-name-due-to-1-number\",\n        ],\n    )\n    def test_rejects_non_kebab_case_names(self, name: str) -> None:\n        class DerivedError(DiagnosticPipError):\n            reference = name\n\n        with pytest.raises(AssertionError) as exc_info:\n            DerivedError(message=\"\", context=None, hint_stmt=None)\n\n        assert str(exc_info.value) == \"error reference must be kebab-case!\"\n\n\ndef rendered_in_ascii(error: DiagnosticPipError, *, color: bool = False) -> str:\n    with io.BytesIO() as stream:\n        console = rich.console.Console(\n            force_terminal=False,\n            file=io.TextIOWrapper(stream, encoding=\"ascii\", newline=\"\"),\n            color_system=\"truecolor\" if color else None,\n        )\n        console.print(error)\n        return stream.getvalue().decode(\"ascii\")\n\n\nclass TestDiagnosticPipErrorPresentation_ASCII:\n    def test_complete(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            Something went wrong\n            very wrong.\n\n            note: You did something wrong, which is what caused this error.\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_complete_color(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke.\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        def esc(code: str = \"0\") -> str:\n            return f\"\\x1b[{code}m\"\n\n        assert rendered_in_ascii(err, color=True) == textwrap.dedent(\n            f\"\"\"\\\n            {esc(\"1;31\")}error{esc(\"0\")}: {esc(\"1\")}test-diagnostic{esc(\"0\")}\n\n            Oh no!\n            It broke.\n\n            Something went wrong\n            very wrong.\n\n            {esc(\"1;35\")}note{esc(\"0\")}: You did something wrong.\n            {esc(\"1;36\")}hint{esc(\"0\")}: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_context(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            note: You did something wrong, which is what caused this error.\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=None,\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            Something went wrong\n            very wrong.\n\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_hint(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=None,\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            Something went wrong\n            very wrong.\n\n            note: You did something wrong, which is what caused this error.\n            \"\"\"\n        )\n\n    def test_no_context_no_hint(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=None,\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            note: You did something wrong, which is what caused this error.\n            \"\"\"\n        )\n\n    def test_no_context_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=None,\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_hint_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=None,\n            hint_stmt=None,\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n\n            Something went wrong\n            very wrong.\n            \"\"\"\n        )\n\n    def test_no_hint_no_note_no_context(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            hint_stmt=None,\n            note_stmt=None,\n        )\n\n        assert rendered_in_ascii(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            Oh no!\n            It broke. :(\n            \"\"\"\n        )\n\n\ndef rendered(error: DiagnosticPipError, *, color: bool = False) -> str:\n    with io.StringIO() as stream:\n        console = rich.console.Console(\n            force_terminal=False,\n            file=stream,\n            color_system=\"truecolor\" if color else None,\n        )\n        console.print(error)\n        return stream.getvalue()\n\n\nclass TestDiagnosticPipErrorPresentation_Unicode:\n    def test_complete(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n            │ It broke. :(\n            ╰─> Something went wrong\n                very wrong.\n\n            note: You did something wrong, which is what caused this error.\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_complete_color(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke.\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        def esc(code: str = \"0\") -> str:\n            return f\"\\x1b[{code}m\"\n\n        assert rendered(err, color=True) == textwrap.dedent(\n            f\"\"\"\\\n            {esc(\"1;31\")}error{esc(\"0\")}: {esc(\"1\")}test-diagnostic{esc(\"0\")}\n\n            {esc(\"31\")}×{esc(\"0\")} Oh no!\n            {esc(\"31\")}│{esc(\"0\")} It broke.\n            {esc(\"31\")}╰─>{esc(\"0\")} Something went wrong\n            {esc(\"31\")}   {esc(\"0\")} very wrong.\n\n            {esc(\"1;35\")}note{esc(\"0\")}: You did something wrong.\n            {esc(\"1;36\")}hint{esc(\"0\")}: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_context(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n              It broke. :(\n\n            note: You did something wrong, which is what caused this error.\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=None,\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n            │ It broke. :(\n            ╰─> Something went wrong\n                very wrong.\n\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_hint(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=None,\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n            │ It broke. :(\n            ╰─> Something went wrong\n                very wrong.\n\n            note: You did something wrong, which is what caused this error.\n            \"\"\"\n        )\n\n    def test_no_context_no_hint(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=\"You did something wrong, which is what caused this error.\",\n            hint_stmt=None,\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n              It broke. :(\n\n            note: You did something wrong, which is what caused this error.\n            \"\"\"\n        )\n\n    def test_no_context_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            note_stmt=None,\n            hint_stmt=\"Do it better next time, by trying harder.\",\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n              It broke. :(\n\n            hint: Do it better next time, by trying harder.\n            \"\"\"\n        )\n\n    def test_no_hint_no_note(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=\"Something went wrong\\nvery wrong.\",\n            note_stmt=None,\n            hint_stmt=None,\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n            │ It broke. :(\n            ╰─> Something went wrong\n                very wrong.\n            \"\"\"\n        )\n\n    def test_no_hint_no_note_no_context(self) -> None:\n        err = DiagnosticPipError(\n            reference=\"test-diagnostic\",\n            message=\"Oh no!\\nIt broke. :(\",\n            context=None,\n            hint_stmt=None,\n            note_stmt=None,\n        )\n\n        assert rendered(err) == textwrap.dedent(\n            \"\"\"\\\n            error: test-diagnostic\n\n            × Oh no!\n              It broke. :(\n            \"\"\"\n        )\n\n\nclass TestExternallyManagedEnvironment:\n    default_text = (\n        f\"The Python environment under {sys.prefix} is managed externally, \"\n        f\"and may not be\\nmanipulated by the user. Please use specific \"\n        f\"tooling from the distributor of\\nthe Python installation to \"\n        f\"interact with this environment instead.\\n\"\n    )\n\n    @pytest.fixture(autouse=True)\n    def patch_locale(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        orig_getlocal = locale.getlocale\n\n        def fake_getlocale(category: int) -> tuple[str | None, str | None]:\n            \"\"\"Fake getlocale() that always reports zh_Hant for LC_MESSAGES.\"\"\"\n            result = orig_getlocal(category)\n            if category == getattr(locale, \"LC_MESSAGES\", None):\n                return \"zh_Hant\", result[1]\n            return result\n\n        monkeypatch.setattr(locale, \"getlocale\", fake_getlocale)\n\n    @pytest.fixture\n    def marker(self, tmp_path: pathlib.Path) -> pathlib.Path:\n        marker = tmp_path.joinpath(\"EXTERNALLY-MANAGED\")\n        marker.touch()\n        return marker\n\n    def test_invalid_config_format(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        marker: pathlib.Path,\n    ) -> None:\n        marker.write_text(\"invalid\", encoding=\"utf8\")\n\n        with caplog.at_level(logging.WARNING, \"pip._internal.exceptions\"):\n            exc = ExternallyManagedEnvironment.from_config(marker)\n        assert len(caplog.records) == 1\n        assert caplog.records[-1].getMessage() == f\"Failed to read {marker}\"\n\n        assert str(exc.context) == self.default_text\n\n    @pytest.mark.parametrize(\n        \"config\",\n        [\n            pytest.param(\"\", id=\"empty\"),\n            pytest.param(\"[foo]\\nblah = blah\", id=\"no-section\"),\n            pytest.param(\"[externally-managed]\\nblah = blah\", id=\"no-key\"),\n        ],\n    )\n    def test_config_without_key(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        marker: pathlib.Path,\n        config: str,\n    ) -> None:\n        marker.write_text(config, encoding=\"utf8\")\n\n        with caplog.at_level(logging.WARNING, \"pip._internal.exceptions\"):\n            exc = ExternallyManagedEnvironment.from_config(marker)\n        assert not caplog.records\n        assert str(exc.context) == self.default_text\n\n    @pytest.mark.skipif(\n        sys.platform == \"win32\",\n        reason=\"Localization disabled on Windows\",\n    )\n    @pytest.mark.parametrize(\n        \"config, expected\",\n        [\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                Error-zh = 中文\n                Error-zh_Hant = 繁體\n                Error-zh_Hans = 简体\n                \"\"\",\n                \"繁體\",\n                id=\"full\",\n            ),\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                Error-zh = 中文\n                Error-zh_Hans = 简体\n                \"\"\",\n                \"中文\",\n                id=\"no-variant\",\n            ),\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                \"\"\",\n                \"最後\",\n                id=\"fallback\",\n            ),\n        ],\n    )\n    def test_config_canonical(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        marker: pathlib.Path,\n        config: str,\n        expected: str,\n    ) -> None:\n        marker.write_text(\n            textwrap.dedent(config),\n            encoding=\"utf8\",\n        )\n\n        with caplog.at_level(logging.WARNING, \"pip._internal.exceptions\"):\n            exc = ExternallyManagedEnvironment.from_config(marker)\n        assert not caplog.records\n        assert str(exc.context) == expected\n\n    @pytest.mark.skipif(\n        sys.platform != \"win32\",\n        reason=\"Non-Windows should implement localization\",\n    )\n    @pytest.mark.parametrize(\n        \"config\",\n        [\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                Error-zh = 中文\n                Error-zh_Hant = 繁體\n                Error-zh_Hans = 简体\n                \"\"\",\n                id=\"full\",\n            ),\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                Error-zh = 中文\n                Error-zh_Hans = 简体\n                \"\"\",\n                id=\"no-variant\",\n            ),\n            pytest.param(\n                \"\"\"\\\n                [externally-managed]\n                Error = 最後\n                Error-en = English\n                \"\"\",\n                id=\"fallback\",\n            ),\n        ],\n    )\n    def test_config_canonical_no_localization(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        marker: pathlib.Path,\n        config: str,\n    ) -> None:\n        marker.write_text(\n            textwrap.dedent(config),\n            encoding=\"utf8\",\n        )\n\n        with caplog.at_level(logging.WARNING, \"pip._internal.exceptions\"):\n            exc = ExternallyManagedEnvironment.from_config(marker)\n        assert not caplog.records\n        assert str(exc.context) == \"最後\"\n"
  },
  {
    "path": "tests/unit/test_finder.py",
    "content": "import datetime\nimport logging\nfrom collections.abc import Iterable\nfrom unittest.mock import Mock, patch\n\nimport pytest\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.tags import Tag\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import parse as parse_version\n\nimport pip._internal.utils.compatibility_tags\nfrom pip._internal.exceptions import BestVersionAlreadyInstalled, DistributionNotFound\nfrom pip._internal.index.package_finder import (\n    CandidateEvaluator,\n    InstallationCandidate,\n    Link,\n    LinkEvaluator,\n    LinkType,\n)\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.req.constructors import install_req_from_line\n\nfrom tests.lib import TestData, make_test_finder\n\n\ndef test_no_mpkg(data: TestData) -> None:\n    \"\"\"Finder skips zipfiles with \"macosx10\" in the name.\"\"\"\n    finder = make_test_finder(find_links=[data.find_links])\n    req = install_req_from_line(\"pkgwithmpkg\")\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"pkgwithmpkg-1.0.tar.gz\"), found\n\n\ndef test_no_partial_name_match(data: TestData) -> None:\n    \"\"\"Finder requires the full project name to match, not just beginning.\"\"\"\n    finder = make_test_finder(find_links=[data.find_links])\n    req = install_req_from_line(\"gmpy\")\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"gmpy-1.15.tar.gz\"), found\n\n\ndef test_tilde() -> None:\n    \"\"\"Finder can accept a path with ~ in it and will normalize it.\"\"\"\n    patched_exists = patch(\n        \"pip._internal.index.collector.os.path.exists\", return_value=True\n    )\n    with patched_exists:\n        finder = make_test_finder(find_links=[\"~/python-pkgs\"])\n    req = install_req_from_line(\"gmpy\")\n    with pytest.raises(DistributionNotFound):\n        finder.find_requirement(req, False)\n\n\ndef test_duplicates_sort_ok(data: TestData) -> None:\n    \"\"\"Finder successfully finds one of a set of duplicates in different\n    locations\"\"\"\n    finder = make_test_finder(find_links=[data.find_links, data.find_links2])\n    req = install_req_from_line(\"duplicate\")\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"duplicate-1.0.tar.gz\"), found\n\n\ndef test_finder_detects_latest_find_links(data: TestData) -> None:\n    \"\"\"Test PackageFinder detects latest using find-links\"\"\"\n    req = install_req_from_line(\"simple\")\n    finder = make_test_finder(find_links=[data.find_links])\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"simple-3.0.tar.gz\")\n\n\ndef test_incorrect_case_file_index(data: TestData) -> None:\n    \"\"\"Test PackageFinder detects latest using wrong case\"\"\"\n    req = install_req_from_line(\"dinner\")\n    finder = make_test_finder(index_urls=[data.find_links3])\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"Dinner-2.0.tar.gz\")\n\n\ndef test_finder_detects_latest_already_satisfied_find_links(data: TestData) -> None:\n    \"\"\"Test PackageFinder detects latest already satisfied using find-links\"\"\"\n    req = install_req_from_line(\"simple\")\n    # the latest simple in local pkgs is 3.0\n    latest_version = \"3.0\"\n    satisfied_by = Mock(\n        location=\"/path\",\n        version=parse_version(latest_version),\n    )\n    req.satisfied_by = satisfied_by\n    finder = make_test_finder(find_links=[data.find_links])\n\n    with pytest.raises(BestVersionAlreadyInstalled):\n        finder.find_requirement(req, True)\n\n\ndef test_finder_detects_latest_already_satisfied_pypi_links() -> None:\n    \"\"\"Test PackageFinder detects latest already satisfied using pypi links\"\"\"\n    req = install_req_from_line(\"initools\")\n    # the latest initools on PyPI is 0.3.1\n    latest_version = \"0.3.1\"\n    satisfied_by = Mock(\n        location=\"/path\",\n        version=parse_version(latest_version),\n    )\n    req.satisfied_by = satisfied_by\n    finder = make_test_finder(index_urls=[\"http://pypi.org/simple/\"])\n\n    with pytest.raises(BestVersionAlreadyInstalled):\n        finder.find_requirement(req, True)\n\n\nclass TestWheel:\n    def test_skip_invalid_wheel_link(\n        self, caplog: pytest.LogCaptureFixture, data: TestData\n    ) -> None:\n        \"\"\"\n        Test if PackageFinder skips invalid wheel filenames\n        \"\"\"\n        caplog.set_level(logging.DEBUG)\n\n        req = install_req_from_line(\"invalid\")\n        # data.find_links contains \"invalid.whl\", which is an invalid wheel\n        finder = make_test_finder(find_links=[data.find_links])\n        with pytest.raises(DistributionNotFound):\n            finder.find_requirement(req, True)\n\n        assert (\n            \"Could not find a version that satisfies the requirement invalid\"\n            \" (from versions:\" in caplog.text\n        )\n\n    def test_not_find_wheel_not_supported(self, data: TestData) -> None:\n        \"\"\"\n        Test not finding an unsupported wheel.\n        \"\"\"\n        req = install_req_from_line(\"simple.dist\")\n        target_python = TargetPython()\n        # Make sure no tags will match.\n        target_python._valid_tags = []\n        finder = make_test_finder(\n            find_links=[data.find_links],\n            target_python=target_python,\n        )\n\n        with pytest.raises(DistributionNotFound):\n            finder.find_requirement(req, True)\n\n    def test_find_wheel_supported(\n        self, data: TestData, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test finding supported wheel.\n        \"\"\"\n        monkeypatch.setattr(\n            pip._internal.utils.compatibility_tags,\n            \"get_supported\",\n            lambda **kw: [(\"py2\", \"none\", \"any\")],\n        )\n\n        req = install_req_from_line(\"simple.dist\")\n        finder = make_test_finder(find_links=[data.find_links])\n        found = finder.find_requirement(req, True)\n        assert found is not None\n        assert found.link.url.endswith(\"simple.dist-0.1-py2.py3-none-any.whl\"), found\n\n    def test_wheel_over_sdist_priority(self, data: TestData) -> None:\n        \"\"\"\n        Test wheels have priority over sdists.\n        `test_link_sorting` also covers this at lower level\n        \"\"\"\n        req = install_req_from_line(\"priority\")\n        finder = make_test_finder(find_links=[data.find_links])\n        found = finder.find_requirement(req, True)\n        assert found is not None\n        assert found.link.url.endswith(\"priority-1.0-py2.py3-none-any.whl\"), found\n\n    def test_existing_over_wheel_priority(self, data: TestData) -> None:\n        \"\"\"\n        Test existing install has priority over wheels.\n        `test_link_sorting` also covers this at a lower level\n        \"\"\"\n        req = install_req_from_line(\"priority\")\n        latest_version = \"1.0\"\n        satisfied_by = Mock(\n            location=\"/path\",\n            version=parse_version(latest_version),\n        )\n        req.satisfied_by = satisfied_by\n        finder = make_test_finder(find_links=[data.find_links])\n\n        with pytest.raises(BestVersionAlreadyInstalled):\n            finder.find_requirement(req, True)\n\n\nclass TestCandidateEvaluator:\n    def test_link_sorting(self) -> None:\n        \"\"\"\n        Test link sorting\n        \"\"\"\n        links = [\n            InstallationCandidate(\"simple\", \"2.0\", Link(\"simple-2.0.tar.gz\")),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-pyT-none-TEST.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-pyT-TEST-any.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-pyT-none-any.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0.tar.gz\"),\n            ),\n        ]\n        valid_tags = [\n            Tag(\"pyT\", \"none\", \"TEST\"),\n            Tag(\"pyT\", \"TEST\", \"any\"),\n            Tag(\"pyT\", \"none\", \"any\"),\n        ]\n        specifier = SpecifierSet()\n        evaluator = CandidateEvaluator(\n            \"my-project\",\n            supported_tags=valid_tags,\n            specifier=specifier,\n        )\n        sort_key = evaluator._sort_key\n        results = sorted(links, key=sort_key, reverse=True)\n        results2 = sorted(reversed(links), key=sort_key, reverse=True)\n\n        assert links == results, results\n        assert links == results2, results2\n\n    def test_link_sorting_wheels_with_build_tags(self) -> None:\n        \"\"\"Verify build tags affect sorting.\"\"\"\n        links = [\n            InstallationCandidate(\n                \"simplewheel\",\n                \"2.0\",\n                Link(\"simplewheel-2.0-1-py2.py3-none-any.whl\"),\n            ),\n            InstallationCandidate(\n                \"simplewheel\",\n                \"2.0\",\n                Link(\"simplewheel-2.0-py2.py3-none-any.whl\"),\n            ),\n            InstallationCandidate(\n                \"simplewheel\",\n                \"1.0\",\n                Link(\"simplewheel-1.0-py2.py3-none-any.whl\"),\n            ),\n        ]\n        candidate_evaluator = CandidateEvaluator.create(\"my-project\")\n        sort_key = candidate_evaluator._sort_key\n        results = sorted(links, key=sort_key, reverse=True)\n        results2 = sorted(reversed(links), key=sort_key, reverse=True)\n\n        assert links == results, results\n        assert links == results2, results2\n\n    def test_build_tag_is_less_important_than_other_tags(self) -> None:\n        links = [\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-1-py3-abi3-linux_x86_64.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-2-py3-abi3-linux_i386.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0-2-py3-any-none.whl\"),\n            ),\n            InstallationCandidate(\n                \"simple\",\n                \"1.0\",\n                Link(\"simple-1.0.tar.gz\"),\n            ),\n        ]\n        valid_tags = [\n            Tag(\"py3\", \"abi3\", \"linux_x86_64\"),\n            Tag(\"py3\", \"abi3\", \"linux_i386\"),\n            Tag(\"py3\", \"any\", \"none\"),\n        ]\n        evaluator = CandidateEvaluator(\n            \"my-project\",\n            supported_tags=valid_tags,\n            specifier=SpecifierSet(),\n        )\n        sort_key = evaluator._sort_key\n        results = sorted(links, key=sort_key, reverse=True)\n        results2 = sorted(reversed(links), key=sort_key, reverse=True)\n\n        assert links == results, results\n        assert links == results2, results2\n\n\ndef test_finder_priority_file_over_page(data: TestData) -> None:\n    \"\"\"Test PackageFinder prefers file links over equivalent page links\"\"\"\n    req = install_req_from_line(\"gmpy==1.15\")\n    finder = make_test_finder(\n        find_links=[data.find_links],\n        index_urls=[\"http://pypi.org/simple/\"],\n    )\n    name = req.name\n    assert name == \"gmpy\"\n\n    all_versions = finder.find_all_candidates(name)\n    # 1 file InstallationCandidate followed by all https ones\n    assert all_versions[0].link.scheme == \"file\"\n    assert all(\n        version.link.scheme == \"https\" for version in all_versions[1:]\n    ), all_versions\n\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.startswith(\"file://\")\n\n\ndef test_finder_priority_nonegg_over_eggfragments() -> None:\n    \"\"\"Test PackageFinder prefers non-egg links over \"#egg=\" links\"\"\"\n    req = install_req_from_line(\"bar==1.0\")\n    links = [\"http://foo/bar.py#egg=bar-1.0\", \"http://foo/bar-1.0.tar.gz\"]\n    name = req.name\n    assert name == \"bar\"\n\n    finder = make_test_finder(links)\n    all_versions = finder.find_all_candidates(name)\n    assert all_versions[0].link.url.endswith(\"tar.gz\")\n    assert all_versions[1].link.url.endswith(\"#egg=bar-1.0\")\n\n    found = finder.find_requirement(req, False)\n\n    assert found is not None\n    assert found.link.url.endswith(\"tar.gz\")\n\n    links.reverse()\n\n    finder = make_test_finder(links)\n    all_versions = finder.find_all_candidates(name)\n    assert all_versions[0].link.url.endswith(\"tar.gz\")\n    assert all_versions[1].link.url.endswith(\"#egg=bar-1.0\")\n    found = finder.find_requirement(req, False)\n\n    assert found is not None\n    assert found.link.url.endswith(\"tar.gz\")\n\n\ndef test_finder_only_installs_stable_releases(data: TestData) -> None:\n    \"\"\"\n    Test PackageFinder only accepts stable versioned releases by default.\n    \"\"\"\n\n    req = install_req_from_line(\"bar\")\n\n    # using a local index (that has pre & dev releases)\n    finder = make_test_finder(index_urls=[data.index_url(\"pre\")])\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"bar-1.0.tar.gz\"), found.link.url\n\n    # using find-links\n    links = [\"https://foo/bar-1.0.tar.gz\", \"https://foo/bar-2.0b1.tar.gz\"]\n\n    finder = make_test_finder(links)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-1.0.tar.gz\"\n\n    links.reverse()\n\n    finder = make_test_finder(links)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-1.0.tar.gz\"\n\n\ndef test_finder_only_installs_data_require(data: TestData) -> None:\n    \"\"\"\n    Test whether the PackageFinder understand data-python-requires\n\n    This can optionally be exposed by a simple-repository to tell which\n    distribution are compatible with which version of Python by adding a\n    data-python-require to the anchor links.\n\n    See pep 503 for more information.\n    \"\"\"\n\n    # using a local index (that has pre & dev releases)\n    finder = make_test_finder(index_urls=[data.index_url(\"datarequire\")])\n    links = finder.find_all_candidates(\"fakepackage\")\n    assert {str(v.version) for v in links} == {\"1.0.0\", \"3.3.0\", \"9.9.9\"}\n\n\ndef test_finder_installs_pre_releases(data: TestData) -> None:\n    \"\"\"\n    Test PackageFinder finds pre-releases if asked to.\n    \"\"\"\n\n    req = install_req_from_line(\"bar\")\n\n    # using a local index (that has pre & dev releases)\n    finder = make_test_finder(\n        index_urls=[data.index_url(\"pre\")],\n        allow_all_prereleases=True,\n    )\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"bar-2.0b1.tar.gz\"), found.link.url\n\n    # using find-links\n    links = [\"https://foo/bar-1.0.tar.gz\", \"https://foo/bar-2.0b1.tar.gz\"]\n\n    finder = make_test_finder(links, allow_all_prereleases=True)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-2.0b1.tar.gz\"\n\n    links.reverse()\n\n    finder = make_test_finder(links, allow_all_prereleases=True)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-2.0b1.tar.gz\"\n\n\ndef test_finder_installs_dev_releases(data: TestData) -> None:\n    \"\"\"\n    Test PackageFinder finds dev releases if asked to.\n    \"\"\"\n\n    req = install_req_from_line(\"bar\")\n\n    # using a local index (that has dev releases)\n    finder = make_test_finder(\n        index_urls=[data.index_url(\"dev\")],\n        allow_all_prereleases=True,\n    )\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url.endswith(\"bar-2.0.dev1.tar.gz\"), found.link.url\n\n\ndef test_finder_installs_pre_releases_with_version_spec() -> None:\n    \"\"\"\n    Test PackageFinder only accepts stable versioned releases by default.\n    \"\"\"\n    req = install_req_from_line(\"bar>=0.0.dev0\")\n    links = [\"https://foo/bar-1.0.tar.gz\", \"https://foo/bar-2.0b1.tar.gz\"]\n\n    finder = make_test_finder(links)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-2.0b1.tar.gz\"\n\n    links.reverse()\n\n    finder = make_test_finder(links)\n    found = finder.find_requirement(req, False)\n    assert found is not None\n    assert found.link.url == \"https://foo/bar-2.0b1.tar.gz\"\n\n\nclass TestLinkEvaluator:\n    def make_test_link_evaluator(self, formats: Iterable[str]) -> LinkEvaluator:\n        target_python = TargetPython()\n        return LinkEvaluator(\n            project_name=\"pytest\",\n            canonical_name=canonicalize_name(\"pytest\"),\n            formats=frozenset(formats),\n            target_python=target_python,\n            allow_yanked=True,\n        )\n\n    @pytest.mark.parametrize(\n        \"url, expected_version\",\n        [\n            (\"http:/yo/pytest-1.0.tar.gz\", \"1.0\"),\n            (\"http:/yo/pytest-1.0-py2.py3-none-any.whl\", \"1.0\"),\n        ],\n    )\n    def test_evaluate_link__match(self, url: str, expected_version: str) -> None:\n        \"\"\"Test that 'pytest' archives match for 'pytest'\"\"\"\n        link = Link(url)\n        evaluator = self.make_test_link_evaluator(formats=[\"source\", \"binary\"])\n        actual = evaluator.evaluate_link(link)\n        assert actual == (LinkType.candidate, expected_version)\n\n    @pytest.mark.parametrize(\n        \"url, link_type, fail_reason\",\n        [\n            # TODO: Uncomment this test case when #1217 is fixed.\n            # 'http:/yo/pytest-xdist-1.0.tar.gz',\n            (\n                \"http:/yo/pytest2-1.0.tar.gz\",\n                LinkType.format_invalid,\n                \"Missing project version for pytest\",\n            ),\n            (\n                \"http:/yo/pytest_xdist-1.0-py2.py3-none-any.whl\",\n                LinkType.different_project,\n                \"wrong project name (not pytest)\",\n            ),\n        ],\n    )\n    def test_evaluate_link__substring_fails(\n        self,\n        url: str,\n        link_type: LinkType,\n        fail_reason: str,\n    ) -> None:\n        \"\"\"Test that 'pytest<something> archives won't match for 'pytest'.\"\"\"\n        link = Link(url)\n        evaluator = self.make_test_link_evaluator(formats=[\"source\", \"binary\"])\n        actual = evaluator.evaluate_link(link)\n        assert actual == (link_type, fail_reason)\n\n\ndef test_process_project_url(data: TestData) -> None:\n    project_name = \"simple\"\n    index_url = data.index_url(\"simple\")\n    project_url = Link(f\"{index_url}/{project_name}\")\n    finder = make_test_finder(index_urls=[index_url])\n    link_evaluator = finder.make_link_evaluator(project_name)\n    actual = finder.process_project_url(\n        project_url,\n        link_evaluator=link_evaluator,\n    )\n\n    assert len(actual) == 1\n    package_link = actual[0]\n    assert package_link.name == \"simple\"\n    assert str(package_link.version) == \"1.0\"\n\n\ndef test_find_all_candidates_nothing() -> None:\n    \"\"\"Find nothing without anything\"\"\"\n    finder = make_test_finder()\n    assert not finder.find_all_candidates(\"pip\")\n\n\ndef test_find_all_candidates_find_links(data: TestData) -> None:\n    finder = make_test_finder(find_links=[data.find_links])\n    versions = finder.find_all_candidates(\"simple\")\n    assert [str(v.version) for v in versions] == [\"3.0\", \"2.0\", \"1.0\"]\n\n\ndef test_find_all_candidates_index(data: TestData) -> None:\n    finder = make_test_finder(index_urls=[data.index_url(\"simple\")])\n    versions = finder.find_all_candidates(\"simple\")\n    assert [str(v.version) for v in versions] == [\"1.0\"]\n\n\ndef test_find_all_candidates_find_links_and_index(data: TestData) -> None:\n    finder = make_test_finder(\n        find_links=[data.find_links],\n        index_urls=[data.index_url(\"simple\")],\n    )\n    versions = finder.find_all_candidates(\"simple\")\n    # first the find-links versions then the page versions\n    assert [str(v.version) for v in versions] == [\"3.0\", \"2.0\", \"1.0\", \"1.0\"]\n\n\nclass TestPackageFinderUploadedPriorTo:\n    \"\"\"Test PackageFinder integration with uploaded_prior_to functionality.\n\n    Only effective with indexes that provide upload-time metadata.\n    \"\"\"\n\n    def test_package_finder_create_with_uploaded_prior_to(self) -> None:\n        \"\"\"Test that PackageFinder.create() accepts uploaded_prior_to parameter.\"\"\"\n        uploaded_prior_to = datetime.datetime(\n            2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc\n        )\n\n        finder = make_test_finder(uploaded_prior_to=uploaded_prior_to)\n\n        assert finder._uploaded_prior_to == uploaded_prior_to\n\n    def test_package_finder_make_link_evaluator_with_uploaded_prior_to(self) -> None:\n        \"\"\"Test that PackageFinder creates LinkEvaluator with uploaded_prior_to.\"\"\"\n        uploaded_prior_to = datetime.datetime(\n            2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc\n        )\n\n        finder = make_test_finder(uploaded_prior_to=uploaded_prior_to)\n\n        link_evaluator = finder.make_link_evaluator(\"test-package\")\n        assert link_evaluator._uploaded_prior_to == uploaded_prior_to\n\n    def test_package_finder_uploaded_prior_to_none(self) -> None:\n        \"\"\"Test that PackageFinder works correctly when uploaded_prior_to is None.\"\"\"\n        finder = make_test_finder(uploaded_prior_to=None)\n\n        assert finder._uploaded_prior_to is None\n\n        link_evaluator = finder.make_link_evaluator(\"test-package\")\n        assert link_evaluator._uploaded_prior_to is None\n"
  },
  {
    "path": "tests/unit/test_format_control.py",
    "content": "from optparse import Values\n\nimport pytest\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.models.format_control import FormatControl\n\n\nclass SimpleCommand(Command):\n    def __init__(self) -> None:\n        super().__init__(\"fake\", \"fake summary\")\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.no_binary())\n        self.cmd_opts.add_option(cmdoptions.only_binary())\n\n    def run(self, options: Values, args: list[str]) -> int:\n        self.options = options\n        return SUCCESS\n\n\ndef test_no_binary_overrides() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--only-binary=:all:\", \"--no-binary=fred\"])\n    format_control = FormatControl({\"fred\"}, {\":all:\"})\n    assert cmd.options.format_control == format_control\n\n\ndef test_only_binary_overrides() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--no-binary=:all:\", \"--only-binary=fred\"])\n    format_control = FormatControl({\":all:\"}, {\"fred\"})\n    assert cmd.options.format_control == format_control\n\n\ndef test_none_resets() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--no-binary=:all:\", \"--no-binary=:none:\"])\n    format_control = FormatControl(set(), set())\n    assert cmd.options.format_control == format_control\n\n\ndef test_none_preserves_other_side() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--no-binary=:all:\", \"--only-binary=fred\", \"--no-binary=:none:\"])\n    format_control = FormatControl(set(), {\"fred\"})\n    assert cmd.options.format_control == format_control\n\n\ndef test_comma_separated_values() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--no-binary=1,2,3\"])\n    format_control = FormatControl({\"1\", \"2\", \"3\"}, set())\n    assert cmd.options.format_control == format_control\n\n\n@pytest.mark.parametrize(\n    \"no_binary,only_binary,argument,expected\",\n    [\n        ({\"fred\"}, set(), \"fred\", frozenset([\"source\"])),\n        ({\"fred\"}, {\":all:\"}, \"fred\", frozenset([\"source\"])),\n        (set(), {\"fred\"}, \"fred\", frozenset([\"binary\"])),\n        ({\":all:\"}, {\"fred\"}, \"fred\", frozenset([\"binary\"])),\n    ],\n)\ndef test_fmt_ctl_matches(\n    no_binary: set[str], only_binary: set[str], argument: str, expected: frozenset[str]\n) -> None:\n    fmt = FormatControl(no_binary, only_binary)\n    assert fmt.get_allowed_formats(argument) == expected\n"
  },
  {
    "path": "tests/unit/test_index.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport logging\n\nimport pytest\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.tags import Tag\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import (\n    CandidateEvaluator,\n    CandidatePreferences,\n    FormatControl,\n    LinkEvaluator,\n    LinkType,\n    PackageFinder,\n    _check_link_requires_python,\n    _extract_version_from_fragment,\n    _find_name_version_sep,\n    filter_unallowed_hashes,\n)\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.release_control import ReleaseControl\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.hashes import Hashes\n\nfrom tests.lib import CURRENT_PY_VERSION_INFO\nfrom tests.lib.index import make_mock_candidate\n\n\n@pytest.mark.parametrize(\n    \"requires_python, expected\",\n    [\n        (\"== 3.6.4\", False),\n        (\"== 3.6.5\", True),\n        # Test an invalid Requires-Python value.\n        (\"invalid\", True),\n    ],\n)\ndef test_check_link_requires_python(requires_python: str, expected: bool) -> None:\n    version_info = (3, 6, 5)\n    link = Link(\"https://example.com\", requires_python=requires_python)\n    actual = _check_link_requires_python(link, version_info)\n    assert actual == expected\n\n\ndef check_caplog(\n    caplog: pytest.LogCaptureFixture, expected_level: str, expected_message: str\n) -> None:\n    assert len(caplog.records) == 1\n    record = caplog.records[0]\n    assert record.levelname == expected_level\n    assert record.message == expected_message\n\n\n@pytest.mark.parametrize(\n    \"ignore_requires_python, expected\",\n    [\n        (\n            False,\n            (\n                False,\n                \"VERBOSE\",\n                \"Link requires a different Python (3.6.5 not in: '== 3.6.4'): \"\n                \"https://example.com\",\n            ),\n        ),\n        (\n            True,\n            (\n                True,\n                \"DEBUG\",\n                \"Ignoring failed Requires-Python check (3.6.5 not in: '== 3.6.4') \"\n                \"for link: https://example.com\",\n            ),\n        ),\n    ],\n)\ndef test_check_link_requires_python__incompatible_python(\n    caplog: pytest.LogCaptureFixture,\n    ignore_requires_python: bool,\n    expected: tuple[bool, str, str],\n) -> None:\n    \"\"\"\n    Test an incompatible Python.\n    \"\"\"\n    expected_return, expected_level, expected_message = expected\n    link = Link(\"https://example.com\", requires_python=\"== 3.6.4\")\n    caplog.set_level(logging.DEBUG)\n    actual = _check_link_requires_python(\n        link,\n        version_info=(3, 6, 5),\n        ignore_requires_python=ignore_requires_python,\n    )\n    assert actual == expected_return\n\n    check_caplog(caplog, expected_level, expected_message)\n\n\ndef test_check_link_requires_python__invalid_requires(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    \"\"\"\n    Test the log message for an invalid Requires-Python.\n    \"\"\"\n    link = Link(\"https://example.com\", requires_python=\"invalid\")\n    caplog.set_level(logging.DEBUG)\n    actual = _check_link_requires_python(link, version_info=(3, 6, 5))\n    assert actual\n\n    expected_message = (\n        \"Ignoring invalid Requires-Python ('invalid') for link: https://example.com\"\n    )\n    check_caplog(caplog, \"DEBUG\", expected_message)\n\n\nclass TestLinkEvaluator:\n    @pytest.mark.parametrize(\n        \"py_version_info, ignore_requires_python, expected\",\n        [\n            pytest.param(\n                (3, 6, 5),\n                False,\n                (LinkType.candidate, \"1.12\"),\n                id=\"compatible\",\n            ),\n            pytest.param(\n                (3, 6, 4),\n                False,\n                (\n                    LinkType.requires_python_mismatch,\n                    \"1.12 Requires-Python ==3.6.5,!=3.13.3\",\n                ),\n                id=\"requires-python-mismatch\",\n            ),\n            pytest.param(\n                (3, 6, 4),\n                True,\n                (LinkType.candidate, \"1.12\"),\n                id=\"requires-python-mismatch-ignored\",\n            ),\n        ],\n    )\n    def test_evaluate_link(\n        self,\n        py_version_info: tuple[int, int, int],\n        ignore_requires_python: bool,\n        expected: tuple[LinkType, str],\n    ) -> None:\n        target_python = TargetPython(py_version_info=py_version_info)\n        evaluator = LinkEvaluator(\n            project_name=\"twine\",\n            canonical_name=canonicalize_name(\"twine\"),\n            formats=frozenset([\"source\"]),\n            target_python=target_python,\n            allow_yanked=True,\n            ignore_requires_python=ignore_requires_python,\n        )\n        link = Link(\n            \"https://example.com/#egg=twine-1.12\",\n            requires_python=\"!= 3.13.3, == 3.6.5\",\n        )\n        actual = evaluator.evaluate_link(link)\n        assert actual == expected\n\n    @pytest.mark.parametrize(\n        \"yanked_reason, allow_yanked, expected\",\n        [\n            (None, True, (LinkType.candidate, \"1.12\")),\n            (None, False, (LinkType.candidate, \"1.12\")),\n            (\"\", True, (LinkType.candidate, \"1.12\")),\n            (\n                \"\",\n                False,\n                (LinkType.yanked, \"yanked for reason: <none given>\"),\n            ),\n            (\"bad metadata\", True, (LinkType.candidate, \"1.12\")),\n            (\n                \"bad metadata\",\n                False,\n                (LinkType.yanked, \"yanked for reason: bad metadata\"),\n            ),\n            # Test a unicode string with a non-ascii character.\n            (\"curly quote: \\u2018\", True, (LinkType.candidate, \"1.12\")),\n            (\n                \"curly quote: \\u2018\",\n                False,\n                (\n                    LinkType.yanked,\n                    \"yanked for reason: curly quote: \\u2018\",\n                ),\n            ),\n        ],\n    )\n    def test_evaluate_link__allow_yanked(\n        self,\n        yanked_reason: str,\n        allow_yanked: bool,\n        expected: tuple[LinkType, str],\n    ) -> None:\n        target_python = TargetPython(py_version_info=(3, 6, 4))\n        evaluator = LinkEvaluator(\n            project_name=\"twine\",\n            canonical_name=canonicalize_name(\"twine\"),\n            formats=frozenset([\"source\"]),\n            target_python=target_python,\n            allow_yanked=allow_yanked,\n        )\n        link = Link(\n            \"https://example.com/#egg=twine-1.12\",\n            yanked_reason=yanked_reason,\n        )\n        actual = evaluator.evaluate_link(link)\n        assert actual == expected\n\n    def test_evaluate_link__incompatible_wheel(self) -> None:\n        \"\"\"\n        Test an incompatible wheel.\n        \"\"\"\n        target_python = TargetPython(py_version_info=(3, 6, 4))\n        # Set the valid tags to an empty list to make sure nothing matches.\n        target_python._valid_tags = []\n        evaluator = LinkEvaluator(\n            project_name=\"sample\",\n            canonical_name=canonicalize_name(\"sample\"),\n            formats=frozenset([\"binary\"]),\n            target_python=target_python,\n            allow_yanked=True,\n        )\n        link = Link(\"https://example.com/sample-1.0-py2.py3-none-any.whl\")\n        actual = evaluator.evaluate_link(link)\n        expected = (\n            LinkType.platform_mismatch,\n            \"none of the wheel's tags (py2-none-any, py3-none-any) are compatible \"\n            \"(run pip debug --verbose to show compatible tags)\",\n        )\n        assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"hex_digest, expected_versions\",\n    [\n        (64 * \"a\", [\"1.0\", \"1.1\"]),\n        (64 * \"b\", [\"1.0\", \"1.2\"]),\n        (64 * \"c\", [\"1.0\", \"1.1\", \"1.2\"]),\n    ],\n)\ndef test_filter_unallowed_hashes(hex_digest: str, expected_versions: list[str]) -> None:\n    candidates = [\n        make_mock_candidate(\"1.0\"),\n        make_mock_candidate(\"1.1\", hex_digest=(64 * \"a\")),\n        make_mock_candidate(\"1.2\", hex_digest=(64 * \"b\")),\n    ]\n    hashes_data = {\n        \"sha256\": [hex_digest],\n    }\n    hashes = Hashes(hashes_data)\n    actual = filter_unallowed_hashes(\n        candidates,\n        hashes=hashes,\n        project_name=\"my-project\",\n    )\n\n    actual_versions = [str(candidate.version) for candidate in actual]\n    assert actual_versions == expected_versions\n    # Check that the return value is always different from the given value.\n    assert actual is not candidates\n\n\ndef test_filter_unallowed_hashes__no_hashes(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.DEBUG)\n\n    candidates = [\n        make_mock_candidate(\"1.0\"),\n        make_mock_candidate(\"1.1\"),\n    ]\n    actual = filter_unallowed_hashes(\n        candidates,\n        hashes=Hashes(),\n        project_name=\"my-project\",\n    )\n\n    # Check that the return value is a copy.\n    assert actual == candidates\n    assert actual is not candidates\n\n    expected_message = (\n        \"Given no hashes to check 2 links for project 'my-project': \"\n        \"discarding no candidates\"\n    )\n    check_caplog(caplog, \"DEBUG\", expected_message)\n\n\ndef test_filter_unallowed_hashes__log_message_with_match(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    caplog.set_level(logging.DEBUG)\n\n    # Test 1 match, 2 non-matches, 3 no hashes so all 3 values will be\n    # different.\n    candidates = [\n        make_mock_candidate(\"1.0\"),\n        make_mock_candidate(\n            \"1.1\",\n        ),\n        make_mock_candidate(\n            \"1.2\",\n        ),\n        make_mock_candidate(\"1.3\", hex_digest=(64 * \"a\")),\n        make_mock_candidate(\"1.4\", hex_digest=(64 * \"b\")),\n        make_mock_candidate(\"1.5\", hex_digest=(64 * \"c\")),\n    ]\n    hashes_data = {\n        \"sha256\": [64 * \"a\", 64 * \"d\"],\n    }\n    hashes = Hashes(hashes_data)\n    actual = filter_unallowed_hashes(\n        candidates,\n        hashes=hashes,\n        project_name=\"my-project\",\n    )\n    assert len(actual) == 4\n\n    expected_message = (\n        \"Checked 6 links for project 'my-project' against 2 hashes \"\n        \"(1 matches, 3 no digest): discarding 2 non-matches:\\n\"\n        \"  https://example.com/pkg-1.4.tar.gz#sha256=\"\n        \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\\n\"\n        \"  https://example.com/pkg-1.5.tar.gz#sha256=\"\n        \"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"\n    )\n    check_caplog(caplog, \"DEBUG\", expected_message)\n\n\ndef test_filter_unallowed_hashes__log_message_with_no_match(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    caplog.set_level(logging.DEBUG)\n\n    candidates = [\n        make_mock_candidate(\"1.0\"),\n        make_mock_candidate(\"1.1\", hex_digest=(64 * \"b\")),\n        make_mock_candidate(\"1.2\", hex_digest=(64 * \"c\")),\n    ]\n    hashes_data = {\n        \"sha256\": [64 * \"a\", 64 * \"d\"],\n    }\n    hashes = Hashes(hashes_data)\n    actual = filter_unallowed_hashes(\n        candidates,\n        hashes=hashes,\n        project_name=\"my-project\",\n    )\n    assert len(actual) == 3\n\n    expected_message = (\n        \"Checked 3 links for project 'my-project' against 2 hashes \"\n        \"(0 matches, 1 no digest): discarding no candidates\"\n    )\n    check_caplog(caplog, \"DEBUG\", expected_message)\n\n\nclass TestLinkEvaluatorUploadedPriorTo:\n    \"\"\"Test the uploaded_prior_to functionality in LinkEvaluator.\n\n    Only effective with indexes that provide upload-time metadata.\n    \"\"\"\n\n    def make_test_link_evaluator(\n        self, uploaded_prior_to: datetime.datetime | None = None\n    ) -> LinkEvaluator:\n        \"\"\"Create a LinkEvaluator for testing.\"\"\"\n        target_python = TargetPython()\n        return LinkEvaluator(\n            project_name=\"myproject\",\n            canonical_name=canonicalize_name(\"myproject\"),\n            formats=frozenset([\"source\", \"binary\"]),\n            target_python=target_python,\n            allow_yanked=True,\n            uploaded_prior_to=uploaded_prior_to,\n        )\n\n    @pytest.mark.parametrize(\n        \"upload_time, uploaded_prior_to, expected_result\",\n        [\n            # Test case: upload time is before the cutoff (should be accepted)\n            (\n                datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc),\n                datetime.datetime(2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n                (LinkType.candidate, \"1.0\"),\n            ),\n            # Test case: upload time is after the cutoff (should be rejected)\n            (\n                datetime.datetime(2023, 8, 1, 12, 0, 0, tzinfo=datetime.timezone.utc),\n                datetime.datetime(2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n                (\n                    LinkType.upload_too_late,\n                    \"Upload time 2023-08-01 12:00:00+00:00 not prior to \"\n                    \"2023-06-01 00:00:00+00:00\",\n                ),\n            ),\n            # Test case: upload time equals the cutoff (should be rejected)\n            (\n                datetime.datetime(2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n                datetime.datetime(2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n                (\n                    LinkType.upload_too_late,\n                    \"Upload time 2023-06-01 00:00:00+00:00 not prior to \"\n                    \"2023-06-01 00:00:00+00:00\",\n                ),\n            ),\n            # Test case: no uploaded_prior_to set (should be accepted)\n            (\n                datetime.datetime(2023, 8, 1, 12, 0, 0, tzinfo=datetime.timezone.utc),\n                None,\n                (LinkType.candidate, \"1.0\"),\n            ),\n            # Test case: no upload time with filter set (should be rejected)\n            (\n                None,\n                datetime.datetime(2023, 6, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n                (\n                    LinkType.upload_time_missing,\n                    \"does not provide upload-time metadata\",\n                ),\n            ),\n        ],\n    )\n    def test_evaluate_link_uploaded_prior_to(\n        self,\n        upload_time: datetime.datetime | None,\n        uploaded_prior_to: datetime.datetime | None,\n        expected_result: tuple[LinkType, str],\n    ) -> None:\n        \"\"\"Test that links are properly filtered by upload time.\"\"\"\n        evaluator = self.make_test_link_evaluator(uploaded_prior_to)\n        link = Link(\n            \"https://example.com/myproject-1.0.tar.gz\",\n            upload_time=upload_time,\n        )\n\n        actual = evaluator.evaluate_link(link)\n        if expected_result[0] == LinkType.upload_time_missing:\n            # For upload_time_missing, just check the type and\n            # that the message contains expected text\n            assert actual[0] == expected_result[0]\n            assert expected_result[1] in actual[1]\n        else:\n            assert actual == expected_result\n\n    def test_evaluate_link_no_upload_time_no_filter(self) -> None:\n        \"\"\"Test that links with no upload time are accepted when no filter is set.\"\"\"\n        # No uploaded_prior_to filter set\n        evaluator = self.make_test_link_evaluator(uploaded_prior_to=None)\n\n        # Link with no upload_time should be accepted when no filter is set\n        link = Link(\"https://example.com/myproject-1.0.tar.gz\")\n        actual = evaluator.evaluate_link(link)\n\n        # Should be accepted as candidate (assuming no other issues)\n        assert actual[0] == LinkType.candidate\n        assert actual[1] == \"1.0\"\n\n    def test_evaluate_link_timezone_handling(self) -> None:\n        \"\"\"Test that timezone-aware datetimes are handled correctly.\"\"\"\n        # Set cutoff time in UTC\n        uploaded_prior_to = datetime.datetime(\n            2023, 6, 1, 12, 0, 0, tzinfo=datetime.timezone.utc\n        )\n        evaluator = self.make_test_link_evaluator(uploaded_prior_to)\n\n        # Test upload time in different timezone (earlier in UTC)\n        upload_time_est = datetime.datetime(\n            *(2023, 6, 1, 10, 0, 0),\n            tzinfo=datetime.timezone(datetime.timedelta(hours=-5)),  # EST\n        )\n        link = Link(\n            \"https://example.com/myproject-1.0.tar.gz\",\n            upload_time=upload_time_est,\n        )\n\n        actual = evaluator.evaluate_link(link)\n        # 10:00 EST = 15:00 UTC, which is after 12:00 UTC cutoff\n        assert actual[0] == LinkType.upload_too_late\n\n    @pytest.mark.parametrize(\n        \"uploaded_prior_to\",\n        [\n            datetime.datetime(2023, 6, 1, 12, 0, 0, tzinfo=datetime.timezone.utc),\n            datetime.datetime(\n                *(2023, 6, 1, 12, 0, 0),\n                tzinfo=datetime.timezone(datetime.timedelta(hours=2)),\n            ),\n        ],\n    )\n    def test_uploaded_prior_to_different_timezone_formats(\n        self, uploaded_prior_to: datetime.datetime\n    ) -> None:\n        \"\"\"Test that different timezone formats for uploaded_prior_to work.\"\"\"\n        evaluator = self.make_test_link_evaluator(uploaded_prior_to)\n\n        # Create a link with upload time clearly after the cutoff\n        upload_time = datetime.datetime(\n            2023, 12, 31, 23, 59, 59, tzinfo=datetime.timezone.utc\n        )\n        link = Link(\n            \"https://example.com/myproject-1.0.tar.gz\",\n            upload_time=upload_time,\n        )\n\n        actual = evaluator.evaluate_link(link)\n        # Should be rejected regardless of timezone format\n        assert actual[0] == LinkType.upload_too_late\n\n\nclass TestCandidateEvaluator:\n    @pytest.mark.parametrize(\n        \"allow_all_prereleases, prefer_binary\",\n        [\n            (False, False),\n            (False, True),\n            (True, False),\n            (True, True),\n        ],\n    )\n    def test_create(self, allow_all_prereleases: bool, prefer_binary: bool) -> None:\n        target_python = TargetPython()\n        target_python._valid_tags = [Tag(\"py36\", \"none\", \"any\")]\n        specifier = SpecifierSet()\n\n        # Convert allow_all_prereleases to release_control\n        release_control = ReleaseControl()\n        if allow_all_prereleases:\n            release_control.all_releases.add(\":all:\")\n\n        evaluator = CandidateEvaluator.create(\n            project_name=\"my-project\",\n            target_python=target_python,\n            release_control=release_control,\n            prefer_binary=prefer_binary,\n            specifier=specifier,\n        )\n        assert evaluator._release_control == release_control\n        assert evaluator._prefer_binary == prefer_binary\n        assert evaluator._specifier is specifier\n        assert evaluator._supported_tags == [Tag(\"py36\", \"none\", \"any\")]\n\n    def test_create__target_python_none(self) -> None:\n        \"\"\"\n        Test passing target_python=None.\n        \"\"\"\n        evaluator = CandidateEvaluator.create(\"my-project\")\n        expected_tags = get_supported()\n        assert evaluator._supported_tags == expected_tags\n\n    def test_create__specifier_none(self) -> None:\n        \"\"\"\n        Test passing specifier=None.\n        \"\"\"\n        evaluator = CandidateEvaluator.create(\"my-project\")\n        expected_specifier = SpecifierSet()\n        assert evaluator._specifier == expected_specifier\n\n    def test_get_applicable_candidates(self) -> None:\n        specifier = SpecifierSet(\"<= 1.11\")\n        versions = [\"1.10\", \"1.11\", \"1.12\"]\n        candidates = [make_mock_candidate(version) for version in versions]\n        evaluator = CandidateEvaluator.create(\n            \"my-project\",\n            specifier=specifier,\n        )\n        actual = evaluator.get_applicable_candidates(candidates)\n        expected_applicable = candidates[:2]\n        assert [str(c.version) for c in expected_applicable] == [\n            \"1.10\",\n            \"1.11\",\n        ]\n        assert actual == expected_applicable\n\n    @pytest.mark.parametrize(\n        \"specifier, expected_versions\",\n        [\n            # Test no version constraint.\n            (SpecifierSet(), [\"1.0\", \"1.2\"]),\n            # Test a version constraint that excludes the candidate whose\n            # hash matches.  Then the non-allowed hash is a candidate.\n            (SpecifierSet(\"<= 1.1\"), [\"1.0\", \"1.1\"]),\n        ],\n    )\n    def test_get_applicable_candidates__hashes(\n        self,\n        specifier: SpecifierSet,\n        expected_versions: list[str],\n    ) -> None:\n        \"\"\"\n        Test a non-None hashes value.\n        \"\"\"\n        candidates = [\n            make_mock_candidate(\"1.0\"),\n            make_mock_candidate(\"1.1\", hex_digest=(64 * \"a\")),\n            make_mock_candidate(\"1.2\", hex_digest=(64 * \"b\")),\n        ]\n        hashes_data = {\n            \"sha256\": [64 * \"b\"],\n        }\n        hashes = Hashes(hashes_data)\n        evaluator = CandidateEvaluator.create(\n            \"my-project\",\n            specifier=specifier,\n            hashes=hashes,\n        )\n        actual = evaluator.get_applicable_candidates(candidates)\n        actual_versions = [str(c.version) for c in actual]\n        assert actual_versions == expected_versions\n\n    def test_compute_best_candidate(self) -> None:\n        specifier = SpecifierSet(\"<= 1.11\")\n        versions = [\"1.10\", \"1.11\", \"1.12\"]\n        candidates = [make_mock_candidate(version) for version in versions]\n        evaluator = CandidateEvaluator.create(\n            \"my-project\",\n            specifier=specifier,\n        )\n        result = evaluator.compute_best_candidate(candidates)\n\n        assert result.all_candidates == candidates\n        expected_applicable = candidates[:2]\n        assert [str(c.version) for c in expected_applicable] == [\n            \"1.10\",\n            \"1.11\",\n        ]\n        assert result.applicable_candidates == expected_applicable\n\n        assert result.best_candidate is expected_applicable[1]\n\n    def test_compute_best_candidate__none_best(self) -> None:\n        \"\"\"\n        Test returning a None best candidate.\n        \"\"\"\n        specifier = SpecifierSet(\"<= 1.10\")\n        versions = [\"1.11\", \"1.12\"]\n        candidates = [make_mock_candidate(version) for version in versions]\n        evaluator = CandidateEvaluator.create(\n            \"my-project\",\n            specifier=specifier,\n        )\n        result = evaluator.compute_best_candidate(candidates)\n\n        assert result.all_candidates == candidates\n        assert result.applicable_candidates == []\n        assert result.best_candidate is None\n\n    @pytest.mark.parametrize(\n        \"hex_digest, expected\",\n        [\n            # Test a link with no hash.\n            (None, 0),\n            # Test a link with an allowed hash.\n            (64 * \"a\", 1),\n            # Test a link with a hash that isn't allowed.\n            (64 * \"b\", 0),\n        ],\n    )\n    def test_sort_key__hash(self, hex_digest: str | None, expected: int) -> None:\n        \"\"\"\n        Test the effect of the link's hash on _sort_key()'s return value.\n        \"\"\"\n        candidate = make_mock_candidate(\"1.0\", hex_digest=hex_digest)\n        hashes_data = {\n            \"sha256\": [64 * \"a\"],\n        }\n        hashes = Hashes(hashes_data)\n        evaluator = CandidateEvaluator.create(\"my-project\", hashes=hashes)\n        sort_value = evaluator._sort_key(candidate)\n        # The hash is reflected in the first element of the tuple.\n        actual = sort_value[0]\n        assert actual == expected\n\n    @pytest.mark.parametrize(\n        \"yanked_reason, expected\",\n        [\n            # Test a non-yanked file.\n            (None, 0),\n            # Test a yanked file (has a lower value than non-yanked).\n            (\"bad metadata\", -1),\n        ],\n    )\n    def test_sort_key__is_yanked(\n        self, yanked_reason: str | None, expected: int\n    ) -> None:\n        \"\"\"\n        Test the effect of is_yanked on _sort_key()'s return value.\n        \"\"\"\n        candidate = make_mock_candidate(\"1.0\", yanked_reason=yanked_reason)\n        evaluator = CandidateEvaluator.create(\"my-project\")\n        sort_value = evaluator._sort_key(candidate)\n        # Yanked / non-yanked is reflected in the second element of the tuple.\n        actual = sort_value[1]\n        assert actual == expected\n\n    def test_sort_best_candidate__no_candidates(self) -> None:\n        \"\"\"\n        Test passing an empty list.\n        \"\"\"\n        evaluator = CandidateEvaluator.create(\"my-project\")\n        actual = evaluator.sort_best_candidate([])\n        assert actual is None\n\n    def test_sort_best_candidate__best_yanked_but_not_all(\n        self,\n        caplog: pytest.LogCaptureFixture,\n    ) -> None:\n        \"\"\"\n        Test the best candidates being yanked, but not all.\n        \"\"\"\n        caplog.set_level(logging.INFO)\n        candidates = [\n            make_mock_candidate(\"4.0\", yanked_reason=\"bad metadata #4\"),\n            # Put the best candidate in the middle, to test sorting.\n            make_mock_candidate(\"2.0\"),\n            make_mock_candidate(\"3.0\", yanked_reason=\"bad metadata #3\"),\n            make_mock_candidate(\"1.0\"),\n        ]\n        expected_best = candidates[1]\n        evaluator = CandidateEvaluator.create(\"my-project\")\n        actual = evaluator.sort_best_candidate(candidates)\n        assert actual is expected_best\n        assert str(actual.version) == \"2.0\"\n\n        # Check the log messages.\n        assert len(caplog.records) == 0\n\n\nclass TestPackageFinder:\n    @pytest.mark.parametrize(\n        \"allow_all_prereleases, prefer_binary\",\n        [\n            (False, False),\n            (False, True),\n            (True, False),\n            (True, True),\n        ],\n    )\n    def test_create__candidate_prefs(\n        self,\n        allow_all_prereleases: bool,\n        prefer_binary: bool,\n    ) -> None:\n        \"\"\"\n        Test that the _candidate_prefs attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n\n        # Convert allow_all_prereleases to release_control\n        release_control = ReleaseControl()\n        if allow_all_prereleases:\n            release_control.all_releases.add(\":all:\")\n\n        selection_prefs = SelectionPreferences(\n            allow_yanked=True,\n            release_control=release_control,\n            prefer_binary=prefer_binary,\n        )\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n        candidate_prefs = finder._candidate_prefs\n        assert candidate_prefs.release_control == release_control\n        assert candidate_prefs.prefer_binary == prefer_binary\n\n    def test_create__link_collector(self) -> None:\n        \"\"\"\n        Test that the _link_collector attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=SelectionPreferences(allow_yanked=True),\n        )\n\n        assert finder._link_collector is link_collector\n\n    def test_create__target_python(self) -> None:\n        \"\"\"\n        Test that the _target_python attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        target_python = TargetPython(py_version_info=(3, 7, 3))\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=SelectionPreferences(allow_yanked=True),\n            target_python=target_python,\n        )\n        actual_target_python = finder._target_python\n        # The target_python attribute should be set as is.\n        assert actual_target_python is target_python\n        # Check that the attributes weren't reset.\n        assert actual_target_python.py_version_info == (3, 7, 3)\n\n    def test_create__target_python_none(self) -> None:\n        \"\"\"\n        Test passing target_python=None.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=SelectionPreferences(allow_yanked=True),\n            target_python=None,\n        )\n        # Spot-check the default TargetPython object.\n        actual_target_python = finder._target_python\n        assert actual_target_python._given_py_version_info is None\n        assert actual_target_python.py_version_info == CURRENT_PY_VERSION_INFO\n\n    @pytest.mark.parametrize(\"allow_yanked\", [False, True])\n    def test_create__allow_yanked(self, allow_yanked: bool) -> None:\n        \"\"\"\n        Test that the _allow_yanked attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        selection_prefs = SelectionPreferences(allow_yanked=allow_yanked)\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n        assert finder._allow_yanked == allow_yanked\n\n    @pytest.mark.parametrize(\"ignore_requires_python\", [False, True])\n    def test_create__ignore_requires_python(self, ignore_requires_python: bool) -> None:\n        \"\"\"\n        Test that the _ignore_requires_python attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        selection_prefs = SelectionPreferences(\n            allow_yanked=True,\n            ignore_requires_python=ignore_requires_python,\n        )\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n        assert finder._ignore_requires_python == ignore_requires_python\n\n    def test_create__format_control(self) -> None:\n        \"\"\"\n        Test that the format_control attribute is set correctly.\n        \"\"\"\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        format_control = FormatControl(set(), {\":all:\"})\n        selection_prefs = SelectionPreferences(\n            allow_yanked=True,\n            format_control=format_control,\n        )\n        finder = PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n        actual_format_control = finder.format_control\n        assert actual_format_control is format_control\n        # Check that the attributes weren't reset.\n        assert actual_format_control.only_binary == {\":all:\"}\n\n    @pytest.mark.parametrize(\n        \"allow_yanked, ignore_requires_python, only_binary, expected_formats\",\n        [\n            (False, False, {}, frozenset({\"binary\", \"source\"})),\n            # Test allow_yanked=True.\n            (True, False, {}, frozenset({\"binary\", \"source\"})),\n            # Test ignore_requires_python=True.\n            (False, True, {}, frozenset({\"binary\", \"source\"})),\n            # Test a non-trivial only_binary.\n            (False, False, {\"twine\"}, frozenset({\"binary\"})),\n        ],\n    )\n    def test_make_link_evaluator(\n        self,\n        allow_yanked: bool,\n        ignore_requires_python: bool,\n        only_binary: set[str],\n        expected_formats: frozenset[str],\n    ) -> None:\n        # Create a test TargetPython that we can check for.\n        target_python = TargetPython(py_version_info=(3, 7))\n        format_control = FormatControl(set(), only_binary)\n\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n\n        finder = PackageFinder(\n            link_collector=link_collector,\n            target_python=target_python,\n            allow_yanked=allow_yanked,\n            format_control=format_control,\n            ignore_requires_python=ignore_requires_python,\n        )\n\n        # Pass a project_name that will be different from canonical_name.\n        link_evaluator = finder.make_link_evaluator(\"Twine\")\n\n        assert link_evaluator.project_name == \"Twine\"\n        assert link_evaluator._canonical_name == \"twine\"\n        assert link_evaluator._allow_yanked == allow_yanked\n        assert link_evaluator._ignore_requires_python == ignore_requires_python\n        assert link_evaluator._formats == expected_formats\n\n        # Test the _target_python attribute.\n        actual_target_python = link_evaluator._target_python\n        # The target_python attribute should be set as is.\n        assert actual_target_python is target_python\n        # For good measure, check that the attributes weren't reset.\n        assert actual_target_python._given_py_version_info == (3, 7)\n        assert actual_target_python.py_version_info == (3, 7, 0)\n\n    @pytest.mark.parametrize(\n        \"allow_all_prereleases, prefer_binary\",\n        [\n            (False, False),\n            (False, True),\n            (True, False),\n            (True, True),\n        ],\n    )\n    def test_make_candidate_evaluator(\n        self,\n        allow_all_prereleases: bool,\n        prefer_binary: bool,\n    ) -> None:\n        target_python = TargetPython()\n        target_python._valid_tags = [Tag(\"py36\", \"none\", \"any\")]\n\n        # Convert allow_all_prereleases to release_control\n        release_control = ReleaseControl()\n        if allow_all_prereleases:\n            release_control.all_releases.add(\":all:\")\n\n        candidate_prefs = CandidatePreferences(\n            prefer_binary=prefer_binary,\n            release_control=release_control,\n        )\n        link_collector = LinkCollector(\n            session=PipSession(),\n            search_scope=SearchScope([], [], False),\n        )\n        finder = PackageFinder(\n            link_collector=link_collector,\n            target_python=target_python,\n            allow_yanked=True,\n            candidate_prefs=candidate_prefs,\n        )\n\n        specifier = SpecifierSet()\n        # Pass hashes to check that _hashes is set.\n        hashes = Hashes({\"sha256\": [64 * \"a\"]})\n        evaluator = finder.make_candidate_evaluator(\n            \"my-project\",\n            specifier=specifier,\n            hashes=hashes,\n        )\n        assert evaluator._release_control == release_control\n        assert evaluator._hashes == hashes\n        assert evaluator._prefer_binary == prefer_binary\n        assert evaluator._project_name == \"my-project\"\n        assert evaluator._specifier is specifier\n        assert evaluator._supported_tags == [Tag(\"py36\", \"none\", \"any\")]\n\n\n@pytest.mark.parametrize(\n    \"fragment, canonical_name, expected\",\n    [\n        # Trivial.\n        (\"pip-18.0\", \"pip\", 3),\n        (\"zope-interface-4.5.0\", \"zope-interface\", 14),\n        # Canonicalized name match non-canonicalized egg info. (pypa/pip#5870)\n        (\"Jinja2-2.10\", \"jinja2\", 6),\n        (\"zope.interface-4.5.0\", \"zope-interface\", 14),\n        (\"zope_interface-4.5.0\", \"zope-interface\", 14),\n        # Should be smart enough to parse ambiguous names from the provided\n        # package name.\n        (\"foo-2-2\", \"foo\", 3),\n        (\"foo-2-2\", \"foo-2\", 5),\n        # Should be able to detect collapsed characters in the egg info.\n        (\"foo--bar-1.0\", \"foo-bar\", 8),\n        (\"foo-_bar-1.0\", \"foo-bar\", 8),\n        # The package name must not ends with a dash (PEP 508), so the first\n        # dash would be the separator, not the second.\n        (\"zope.interface--4.5.0\", \"zope-interface\", 14),\n        (\"zope.interface--\", \"zope-interface\", 14),\n        # The version part is missing, but the split function does not care.\n        (\"zope.interface-\", \"zope-interface\", 14),\n    ],\n)\ndef test_find_name_version_sep(\n    fragment: str, canonical_name: str, expected: int\n) -> None:\n    index = _find_name_version_sep(fragment, canonical_name)\n    assert index == expected\n\n\n@pytest.mark.parametrize(\n    \"fragment, canonical_name\",\n    [\n        # A dash must follow the package name.\n        (\"zope.interface4.5.0\", \"zope-interface\"),\n        (\"zope.interface.4.5.0\", \"zope-interface\"),\n        (\"zope.interface.-4.5.0\", \"zope-interface\"),\n        (\"zope.interface\", \"zope-interface\"),\n    ],\n)\ndef test_find_name_version_sep_failure(fragment: str, canonical_name: str) -> None:\n    with pytest.raises(ValueError) as ctx:\n        _find_name_version_sep(fragment, canonical_name)\n    message = f\"{fragment} does not match {canonical_name}\"\n    assert str(ctx.value) == message\n\n\n@pytest.mark.parametrize(\n    \"fragment, canonical_name, expected\",\n    [\n        # Trivial.\n        (\"pip-18.0\", \"pip\", \"18.0\"),\n        (\"zope-interface-4.5.0\", \"zope-interface\", \"4.5.0\"),\n        # Canonicalized name match non-canonicalized egg info. (pypa/pip#5870)\n        (\"Jinja2-2.10\", \"jinja2\", \"2.10\"),\n        (\"zope.interface-4.5.0\", \"zope-interface\", \"4.5.0\"),\n        (\"zope_interface-4.5.0\", \"zope-interface\", \"4.5.0\"),\n        # Should be smart enough to parse ambiguous names from the provided\n        # package name.\n        (\"foo-2-2\", \"foo\", \"2-2\"),\n        (\"foo-2-2\", \"foo-2\", \"2\"),\n        (\"zope.interface--4.5.0\", \"zope-interface\", \"-4.5.0\"),\n        (\"zope.interface--\", \"zope-interface\", \"-\"),\n        # Should be able to detect collapsed characters in the egg info.\n        (\"foo--bar-1.0\", \"foo-bar\", \"1.0\"),\n        (\"foo-_bar-1.0\", \"foo-bar\", \"1.0\"),\n        # Invalid.\n        (\"the-package-name-8.19\", \"does-not-match\", None),\n        (\"zope.interface.-4.5.0\", \"zope.interface\", None),\n        (\"zope.interface-\", \"zope-interface\", None),\n        (\"zope.interface4.5.0\", \"zope-interface\", None),\n        (\"zope.interface.4.5.0\", \"zope-interface\", None),\n        (\"zope.interface.-4.5.0\", \"zope-interface\", None),\n        (\"zope.interface\", \"zope-interface\", None),\n    ],\n)\ndef test_extract_version_from_fragment(\n    fragment: str, canonical_name: str, expected: str | None\n) -> None:\n    version = _extract_version_from_fragment(fragment, canonical_name)\n    assert version == expected\n"
  },
  {
    "path": "tests/unit/test_link.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pip._internal.exceptions import InvalidEggFragment, PipError\nfrom pip._internal.models.link import Link, links_equivalent\nfrom pip._internal.utils.hashes import Hashes\n\n\nclass TestLink:\n    @pytest.mark.parametrize(\n        \"url, expected\",\n        [\n            (\n                \"https://user:password@example.com/path/page.html\",\n                \"<Link https://user:****@example.com/path/page.html>\",\n            ),\n        ],\n    )\n    def test_repr(self, url: str, expected: str) -> None:\n        link = Link(url)\n        assert repr(link) == expected\n\n    @pytest.mark.parametrize(\n        \"url, expected\",\n        [\n            (\"http://yo/wheel.whl\", \"wheel.whl\"),\n            (\"http://yo/wheel\", \"wheel\"),\n            (\"https://example.com/path/page.html\", \"page.html\"),\n            # Test a quoted character.\n            (\"https://example.com/path/page%231.html\", \"page#1.html\"),\n            (\n                \"http://yo/myproject-1.0%2Bfoobar.0-py2.py3-none-any.whl\",\n                \"myproject-1.0+foobar.0-py2.py3-none-any.whl\",\n            ),\n            # Test a path that ends in a slash.\n            (\"https://example.com/path/\", \"path\"),\n            (\"https://example.com/path//\", \"path\"),\n            # Test a url with no filename.\n            (\"https://example.com/\", \"example.com\"),\n            # Test a url with no filename and with auth information.\n            (\n                \"https://user:password@example.com/\",\n                \"example.com\",\n            ),\n        ],\n    )\n    def test_filename(self, url: str, expected: str) -> None:\n        link = Link(url)\n        assert link.filename == expected\n\n    def test_splitext(self) -> None:\n        assert (\"wheel\", \".whl\") == Link(\"http://yo/wheel.whl\").splitext()\n\n    def test_no_ext(self) -> None:\n        assert \"\" == Link(\"http://yo/wheel\").ext\n\n    def test_ext(self) -> None:\n        assert \".whl\" == Link(\"http://yo/wheel.whl\").ext\n\n    def test_ext_fragment(self) -> None:\n        assert \".whl\" == Link(\"http://yo/wheel.whl#frag\").ext\n\n    def test_ext_query(self) -> None:\n        assert \".whl\" == Link(\"http://yo/wheel.whl?a=b\").ext\n\n    def test_is_wheel(self) -> None:\n        assert Link(\"http://yo/wheel.whl\").is_wheel\n\n    def test_is_wheel_false(self) -> None:\n        assert not Link(\"http://yo/not_a_wheel\").is_wheel\n\n    def test_fragments(self) -> None:\n        url = \"git+https://example.com/package#egg=eggname\"\n        assert \"eggname\" == Link(url).egg_fragment\n        assert None is Link(url).subdirectory_fragment\n        url = \"git+https://example.com/package#egg=eggname&subdirectory=subdir\"\n        assert \"eggname\" == Link(url).egg_fragment\n        assert \"subdir\" == Link(url).subdirectory_fragment\n        url = \"git+https://example.com/package#subdirectory=subdir&egg=eggname\"\n        assert \"eggname\" == Link(url).egg_fragment\n        assert \"subdir\" == Link(url).subdirectory_fragment\n\n    @pytest.mark.parametrize(\n        \"fragment\",\n        [\n            # Package names in egg fragments must be in PEP 508 form.\n            \"~invalid~package~name~\",\n            # Version specifiers are not valid in egg fragments.\n            \"eggname==1.2.3\",\n            \"eggname>=1.2.3\",\n            # Extras are also prohibited.\n            \"eggname[!]\",\n            \"eggname[extra]\",\n            \"eggname[extra1,extra2]\",\n            \"eggmame[]\",\n            \"eggname[extra]==1000\",\n        ],\n    )\n    def test_invalid_egg_fragments(self, fragment: str) -> None:\n        url = f\"git+https://example.com/package#egg={fragment}\"\n        with pytest.raises(PipError):\n            Link(url)\n\n    def test_invalid_egg_fragment_with_extras_and_version_hint(self) -> None:\n        \"\"\"Test that fragments with extras and version specifiers get proper hint.\"\"\"\n\n        url = \"git+https://example.com/package#egg=eggname[extra]==1.0\"\n        with pytest.raises(InvalidEggFragment) as exc_info:\n            Link(url)\n\n        # The hint should suggest Direct URL syntax, not just \"remove version\n        # specifiers\" because the extras require Direct URL syntax anyway.\n        hint = str(exc_info.value.hint_stmt)\n        assert r\"name\\[extra] @ URL\" in hint\n        assert \"Version specifiers are silently ignored\" in hint\n\n    @pytest.mark.parametrize(\n        \"yanked_reason, expected\",\n        [\n            (None, False),\n            (\"\", True),\n            (\"there was a mistake\", True),\n        ],\n    )\n    def test_is_yanked(self, yanked_reason: str | None, expected: bool) -> None:\n        link = Link(\n            \"https://example.com/wheel.whl\",\n            yanked_reason=yanked_reason,\n        )\n        assert link.is_yanked == expected\n\n    @pytest.mark.parametrize(\n        \"hash_name, hex_digest, expected\",\n        [\n            # Test a value that matches but with the wrong hash_name.\n            (\"sha384\", 128 * \"a\", False),\n            # Test matching values, including values other than the first.\n            (\"sha512\", 128 * \"a\", True),\n            (\"sha512\", 128 * \"b\", True),\n            # Test a matching hash_name with a value that doesn't match.\n            (\"sha512\", 128 * \"c\", False),\n            # Test a link without a hash value.\n            (\"sha512\", \"\", False),\n        ],\n    )\n    def test_is_hash_allowed(\n        self, hash_name: str, hex_digest: str, expected: bool\n    ) -> None:\n        url = f\"https://example.com/wheel.whl#{hash_name}={hex_digest}\"\n        link = Link(url)\n        hashes_data = {\n            \"sha512\": [128 * \"a\", 128 * \"b\"],\n        }\n        hashes = Hashes(hashes_data)\n        assert link.is_hash_allowed(hashes) == expected\n\n    def test_is_hash_allowed__no_hash(self) -> None:\n        link = Link(\"https://example.com/wheel.whl\")\n        hashes_data = {\n            \"sha512\": [128 * \"a\"],\n        }\n        hashes = Hashes(hashes_data)\n        assert not link.is_hash_allowed(hashes)\n\n    @pytest.mark.parametrize(\n        \"hashes, expected\",\n        [\n            (None, False),\n            # Also test a success case to show the test is correct.\n            (Hashes({\"sha512\": [128 * \"a\"]}), True),\n        ],\n    )\n    def test_is_hash_allowed__none_hashes(\n        self, hashes: Hashes | None, expected: bool\n    ) -> None:\n        url = \"https://example.com/wheel.whl#sha512={}\".format(128 * \"a\")\n        link = Link(url)\n        assert link.is_hash_allowed(hashes) == expected\n\n    @pytest.mark.parametrize(\n        \"url, expected\",\n        [\n            (\"git+https://github.com/org/repo\", True),\n            (\"bzr+http://bzr.myproject.org/MyProject/trunk/#egg=MyProject\", True),\n            (\"hg+file://hg.company.com/repo\", True),\n            (\"https://example.com/some.whl\", False),\n            (\"file://home/foo/some.whl\", False),\n        ],\n    )\n    def test_is_vcs(self, url: str, expected: bool) -> None:\n        link = Link(url)\n        assert link.is_vcs is expected\n\n\n@pytest.mark.parametrize(\n    \"url1, url2\",\n    [\n        pytest.param(\n            \"https://example.com/foo#egg=foo\",\n            \"https://example.com/foo\",\n            id=\"drop-egg\",\n        ),\n        pytest.param(\n            \"https://example.com/foo#subdirectory=bar&egg=foo\",\n            \"https://example.com/foo#subdirectory=bar&egg=bar\",\n            id=\"drop-egg-only\",\n        ),\n        pytest.param(\n            \"https://example.com/foo#subdirectory=bar&egg=foo\",\n            \"https://example.com/foo#egg=foo&subdirectory=bar\",\n            id=\"fragment-ordering\",\n        ),\n        pytest.param(\n            \"https://example.com/foo?a=1&b=2\",\n            \"https://example.com/foo?b=2&a=1\",\n            id=\"query-opordering\",\n        ),\n    ],\n)\ndef test_links_equivalent(url1: str, url2: str) -> None:\n    assert links_equivalent(Link(url1), Link(url2))\n\n\n@pytest.mark.parametrize(\n    \"url1, url2\",\n    [\n        pytest.param(\n            \"https://example.com/foo#sha512=1234567890abcdef\",\n            \"https://example.com/foo#sha512=abcdef1234567890\",\n            id=\"different-keys\",\n        ),\n        pytest.param(\n            \"https://example.com/foo#sha512=1234567890abcdef\",\n            \"https://example.com/foo#md5=1234567890abcdef\",\n            id=\"different-values\",\n        ),\n        pytest.param(\n            \"https://example.com/foo#subdirectory=bar&egg=foo\",\n            \"https://example.com/foo#subdirectory=rex\",\n            id=\"drop-egg-still-different\",\n        ),\n    ],\n)\ndef test_links_equivalent_false(url1: str, url2: str) -> None:\n    assert not links_equivalent(Link(url1), Link(url2))\n"
  },
  {
    "path": "tests/unit/test_locations.py",
    "content": "\"\"\"\nlocations.py tests\n\n\"\"\"\n\nimport getpass\nimport os\nimport shutil\nimport sys\nimport sysconfig\nimport tempfile\nfrom pathlib import Path\nfrom typing import Any\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._internal.locations import SCHEME_KEYS, _should_use_sysconfig, get_scheme\n\nif sys.platform == \"win32\":\n    pwd = Mock()\nelse:\n    import pwd\n\n\ndef _get_scheme_dict(*args: Any, **kwargs: Any) -> dict[str, str]:\n    scheme = get_scheme(*args, **kwargs)\n    return {k: getattr(scheme, k) for k in SCHEME_KEYS}\n\n\nclass TestLocations:\n    def setup_method(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n        self.st_uid = 9999\n        self.username = \"example\"\n        self.patch()\n\n    def teardown_method(self) -> None:\n        self.revert_patch()\n        shutil.rmtree(self.tempdir, ignore_errors=True)\n\n    def patch(self) -> None:\n        \"\"\"first store and then patch python methods pythons\"\"\"\n        self.tempfile_gettempdir = tempfile.gettempdir\n        self.old_os_fstat = os.fstat\n        if sys.platform != \"win32\":\n            # os.geteuid and pwd.getpwuid are not implemented on windows\n            self.old_os_geteuid = os.geteuid\n            self.old_pwd_getpwuid = pwd.getpwuid\n        self.old_getpass_getuser = getpass.getuser\n\n        # now patch\n        tempfile.gettempdir = lambda: self.tempdir\n        getpass.getuser = lambda: self.username\n        os.fstat = lambda fd: self.get_mock_fstat(fd)\n        if sys.platform != \"win32\":\n            os.geteuid = lambda: self.st_uid\n            pwd.getpwuid = self.get_mock_getpwuid\n\n    def revert_patch(self) -> None:\n        \"\"\"revert the patches to python methods\"\"\"\n        tempfile.gettempdir = self.tempfile_gettempdir\n        getpass.getuser = self.old_getpass_getuser\n        if sys.platform != \"win32\":\n            # os.geteuid and pwd.getpwuid are not implemented on windows\n            os.geteuid = self.old_os_geteuid\n            pwd.getpwuid = self.old_pwd_getpwuid\n        os.fstat = self.old_os_fstat\n\n    def get_mock_fstat(self, fd: int) -> os.stat_result:\n        \"\"\"returns a basic mock fstat call result.\n        Currently only the st_uid attribute has been set.\n        \"\"\"\n        result = Mock()\n        result.st_uid = self.st_uid\n        return result\n\n    def get_mock_getpwuid(self, uid: int) -> Any:\n        \"\"\"returns a basic mock pwd.getpwuid call result.\n        Currently only the pw_name attribute has been set.\n        \"\"\"\n        result = Mock()\n        result.pw_name = self.username\n        return result\n\n    def test_default_should_use_sysconfig(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.delattr(sysconfig, \"_PIP_USE_SYSCONFIG\", raising=False)\n        if sys.version_info[:2] >= (3, 10):\n            assert _should_use_sysconfig() is True\n        else:\n            assert _should_use_sysconfig() is False\n\n    @pytest.mark.parametrize(\"vendor_value\", [True, False, None, \"\", 0, 1])\n    def test_vendor_overridden_should_use_sysconfig(\n        self, monkeypatch: pytest.MonkeyPatch, vendor_value: Any\n    ) -> None:\n        monkeypatch.setattr(\n            sysconfig, \"_PIP_USE_SYSCONFIG\", vendor_value, raising=False\n        )\n        assert _should_use_sysconfig() is bool(vendor_value)\n\n\nclass TestDistutilsScheme:\n    def test_root_modifies_appropriately(self) -> None:\n        # This deals with nt/posix path differences\n        # root is c:\\somewhere\\else or /somewhere/else\n        root = os.path.normcase(\n            os.path.abspath(os.path.join(os.path.sep, \"somewhere\", \"else\"))\n        )\n        norm_scheme = _get_scheme_dict(\"example\")\n        root_scheme = _get_scheme_dict(\"example\", root=root)\n\n        for key, value in norm_scheme.items():\n            drive, path = os.path.splitdrive(os.path.abspath(value))\n            expected = os.path.join(root, path[1:])\n            assert os.path.abspath(root_scheme[key]) == expected\n\n    @pytest.mark.incompatible_with_sysconfig\n    @pytest.mark.incompatible_with_venv\n    def test_distutils_config_file_read(\n        self, tmpdir: Path, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # This deals with nt/posix path differences\n        install_scripts = os.path.normcase(\n            os.path.abspath(os.path.join(os.path.sep, \"somewhere\", \"else\"))\n        )\n        f = tmpdir / \"config\" / \"setup.cfg\"\n        f.parent.mkdir()\n        f.write_text(\"[install]\\ninstall-scripts=\" + install_scripts)\n        from distutils.dist import Distribution\n\n        # patch the function that returns what config files are present\n        monkeypatch.setattr(\n            Distribution,\n            \"find_config_files\",\n            lambda self: [f],\n        )\n        scheme = _get_scheme_dict(\"example\")\n        assert scheme[\"scripts\"] == install_scripts\n\n    @pytest.mark.incompatible_with_sysconfig\n    @pytest.mark.incompatible_with_venv\n    # when we request install-lib, we should install everything (.py &\n    # .so) into that path; i.e. ensure platlib & purelib are set to\n    # this path. sysconfig does not support this.\n    def test_install_lib_takes_precedence(\n        self, tmpdir: Path, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # This deals with nt/posix path differences\n        install_lib = os.path.normcase(\n            os.path.abspath(os.path.join(os.path.sep, \"somewhere\", \"else\"))\n        )\n        f = tmpdir / \"config\" / \"setup.cfg\"\n        f.parent.mkdir()\n        f.write_text(\"[install]\\ninstall-lib=\" + install_lib)\n        from distutils.dist import Distribution\n\n        # patch the function that returns what config files are present\n        monkeypatch.setattr(\n            Distribution,\n            \"find_config_files\",\n            lambda self: [f],\n        )\n        scheme = _get_scheme_dict(\"example\")\n        assert scheme[\"platlib\"] == install_lib + os.path.sep\n        assert scheme[\"purelib\"] == install_lib + os.path.sep\n\n    def test_prefix_modifies_appropriately(self) -> None:\n        prefix = os.path.abspath(os.path.join(\"somewhere\", \"else\"))\n\n        normal_scheme = _get_scheme_dict(\"example\")\n        prefix_scheme = _get_scheme_dict(\"example\", prefix=prefix)\n\n        def _calculate_expected(value: str) -> str:\n            path = os.path.join(prefix, os.path.relpath(value, sys.prefix))\n            return os.path.normpath(path)\n\n        expected = {k: _calculate_expected(v) for k, v in normal_scheme.items()}\n        assert prefix_scheme == expected\n"
  },
  {
    "path": "tests/unit/test_logging.py",
    "content": "import logging\nimport time\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom io import StringIO\nfrom threading import Thread\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom pip._internal.utils.logging import (\n    BrokenStdoutLoggingError,\n    IndentingFormatter,\n    PipConsole,\n    RichPipStreamHandler,\n    indent_log,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestIndentingFormatter:\n    \"\"\"Test ``pip._internal.utils.logging.IndentingFormatter``.\"\"\"\n\n    def make_record(self, msg: str, level_name: str) -> logging.LogRecord:\n        level_number = getattr(logging, level_name)\n        attrs = {\n            \"msg\": msg,\n            \"created\": 1547704837.040001 + time.timezone,\n            \"msecs\": 40,\n            \"levelname\": level_name,\n            \"levelno\": level_number,\n        }\n        record = logging.makeLogRecord(attrs)\n\n        return record\n\n    @pytest.mark.parametrize(\n        \"level_name, expected\",\n        [\n            (\"DEBUG\", \"hello\\nworld\"),\n            (\"INFO\", \"hello\\nworld\"),\n            (\"WARNING\", \"WARNING: hello\\nworld\"),\n            (\"ERROR\", \"ERROR: hello\\nworld\"),\n            (\"CRITICAL\", \"ERROR: hello\\nworld\"),\n        ],\n    )\n    def test_format(self, level_name: str, expected: str) -> None:\n        \"\"\"\n        Args:\n          level_name: a logging level name (e.g. \"WARNING\").\n        \"\"\"\n        record = self.make_record(\"hello\\nworld\", level_name=level_name)\n        f = IndentingFormatter(fmt=\"%(message)s\")\n        assert f.format(record) == expected\n\n    @pytest.mark.parametrize(\n        \"level_name, expected\",\n        [\n            (\"INFO\", \"2019-01-17T06:00:37,040 hello\\n2019-01-17T06:00:37,040 world\"),\n            (\n                \"WARNING\",\n                \"2019-01-17T06:00:37,040 WARNING: hello\\n\"\n                \"2019-01-17T06:00:37,040 world\",\n            ),\n        ],\n    )\n    def test_format_with_timestamp(self, level_name: str, expected: str) -> None:\n        record = self.make_record(\"hello\\nworld\", level_name=level_name)\n        f = IndentingFormatter(fmt=\"%(message)s\", add_timestamp=True)\n        assert f.format(record) == expected\n\n    @pytest.mark.parametrize(\n        \"level_name, expected\",\n        [\n            (\"WARNING\", \"DEPRECATION: hello\\nworld\"),\n            (\"ERROR\", \"DEPRECATION: hello\\nworld\"),\n            (\"CRITICAL\", \"DEPRECATION: hello\\nworld\"),\n        ],\n    )\n    def test_format_deprecated(self, level_name: str, expected: str) -> None:\n        \"\"\"\n        Test that logged deprecation warnings coming from deprecated()\n        don't get another prefix.\n        \"\"\"\n        record = self.make_record(\n            \"DEPRECATION: hello\\nworld\",\n            level_name=level_name,\n        )\n        f = IndentingFormatter(fmt=\"%(message)s\")\n        assert f.format(record) == expected\n\n    def test_thread_safety_base(self) -> None:\n        record = self.make_record(\n            \"DEPRECATION: hello\\nworld\",\n            level_name=\"WARNING\",\n        )\n        f = IndentingFormatter(fmt=\"%(message)s\")\n        results = []\n\n        def thread_function() -> None:\n            results.append(f.format(record))\n\n        thread_function()\n        thread = Thread(target=thread_function)\n        thread.start()\n        thread.join()\n        assert results[0] == results[1]\n\n    def test_thread_safety_indent_log(self) -> None:\n        record = self.make_record(\n            \"DEPRECATION: hello\\nworld\",\n            level_name=\"WARNING\",\n        )\n        f = IndentingFormatter(fmt=\"%(message)s\")\n        results = []\n\n        def thread_function() -> None:\n            with indent_log():\n                results.append(f.format(record))\n\n        thread_function()\n        thread = Thread(target=thread_function)\n        thread.start()\n        thread.join()\n        assert results[0] == results[1]\n\n\nclass TestColorizedStreamHandler:\n    def _make_log_record(self) -> logging.LogRecord:\n        attrs = {\n            \"msg\": \"my error\",\n        }\n        record = logging.makeLogRecord(attrs)\n\n        return record\n\n    def test_broken_pipe_in_stderr_flush(self) -> None:\n        \"\"\"\n        Test sys.stderr.flush() raising BrokenPipeError.\n\n        This error should _not_ trigger an error in the logging framework.\n        \"\"\"\n        record = self._make_log_record()\n\n        with redirect_stderr(StringIO()) as stderr:\n            console = PipConsole(file=stderr, no_color=True, soft_wrap=True)\n            handler = RichPipStreamHandler(console)\n            with patch(\"sys.stderr.flush\") as mock_flush:\n                mock_flush.side_effect = BrokenPipeError()\n                # The emit() call raises no exception.\n                handler.emit(record)\n\n            err_text = stderr.getvalue()\n\n        assert err_text.startswith(\"my error\")\n        # Check that the logging framework tried to log the exception.\n        assert \"Logging error\" in err_text\n        assert \"BrokenPipeError\" in err_text\n        assert \"Message: 'my error'\" in err_text\n\n    def test_broken_pipe_in_stdout_write(self) -> None:\n        \"\"\"\n        Test sys.stdout.write() raising BrokenPipeError.\n\n        This error _should_ trigger an error in the logging framework.\n        \"\"\"\n        record = self._make_log_record()\n\n        with redirect_stdout(StringIO()) as stdout:\n            console = PipConsole(file=stdout, no_color=True, soft_wrap=True)\n            handler = RichPipStreamHandler(console)\n            with patch(\"sys.stdout.write\") as mock_write:\n                mock_write.side_effect = BrokenPipeError()\n                with pytest.raises(BrokenStdoutLoggingError):\n                    handler.emit(record)\n\n    def test_broken_pipe_in_stdout_flush(self) -> None:\n        \"\"\"\n        Test sys.stdout.flush() raising BrokenPipeError.\n\n        This error _should_ trigger an error in the logging framework.\n        \"\"\"\n        record = self._make_log_record()\n\n        with redirect_stdout(StringIO()) as stdout:\n            console = PipConsole(file=stdout, no_color=True, soft_wrap=True)\n            handler = RichPipStreamHandler(console)\n            with patch(\"sys.stdout.flush\") as mock_flush:\n                mock_flush.side_effect = BrokenPipeError()\n                with pytest.raises(BrokenStdoutLoggingError):\n                    handler.emit(record)\n\n            output = stdout.getvalue()\n\n        # Sanity check that the log record was written, since flush() happens\n        # after write().\n        assert output.startswith(\"my error\")\n"
  },
  {
    "path": "tests/unit/test_models.py",
    "content": "\"\"\"Tests for various classes in pip._internal.models\"\"\"\n\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.models import candidate, index\nfrom pip._internal.models.link import Link\n\n\nclass TestPackageIndex:\n    \"\"\"Tests for pip._internal.models.index.PackageIndex\"\"\"\n\n    def test_gives_right_urls(self) -> None:\n        url = \"https://mypypi.internal/path/\"\n        file_storage_domain = \"files.mypypi.internal\"\n        pack_index = index.PackageIndex(url, file_storage_domain)\n\n        assert pack_index.url == url\n        assert pack_index.file_storage_domain == file_storage_domain\n\n        assert pack_index.netloc == \"mypypi.internal\"\n        assert pack_index.simple_url == url + \"simple\"\n        assert pack_index.pypi_url == url + \"pypi\"\n\n    def test_PyPI_urls_are_correct(self) -> None:\n        pack_index = index.PyPI\n\n        assert pack_index.netloc == \"pypi.org\"\n        assert pack_index.url == \"https://pypi.org/\"\n        assert pack_index.simple_url == \"https://pypi.org/simple\"\n        assert pack_index.pypi_url == \"https://pypi.org/pypi\"\n        assert pack_index.file_storage_domain == \"files.pythonhosted.org\"\n\n    def test_TestPyPI_urls_are_correct(self) -> None:\n        pack_index = index.TestPyPI\n\n        assert pack_index.netloc == \"test.pypi.org\"\n        assert pack_index.url == \"https://test.pypi.org/\"\n        assert pack_index.simple_url == \"https://test.pypi.org/simple\"\n        assert pack_index.pypi_url == \"https://test.pypi.org/pypi\"\n        assert pack_index.file_storage_domain == \"test-files.pythonhosted.org\"\n\n\nclass TestInstallationCandidate:\n    def test_sets_correct_variables(self) -> None:\n        obj = candidate.InstallationCandidate(\n            \"A\", \"1.0.0\", Link(\"https://somewhere.com/path/A-1.0.0.tar.gz\")\n        )\n        assert obj.name == \"A\"\n        assert obj.version == parse_version(\"1.0.0\")\n        assert obj.link.url == \"https://somewhere.com/path/A-1.0.0.tar.gz\"\n"
  },
  {
    "path": "tests/unit/test_models_wheel.py",
    "content": "import pytest\n\nfrom pip._vendor.packaging.tags import Tag\n\nfrom pip._internal.exceptions import InvalidWheelFilename\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.utils import compatibility_tags\n\n\nclass TestWheelFile:\n    def test_std_wheel_pattern(self) -> None:\n        w = Wheel(\"simple-1.1.1-py2-none-any.whl\")\n        assert w.name == \"simple\"\n        assert w.version == \"1.1.1\"\n        assert w.build_tag == ()\n        assert w.file_tags == frozenset(\n            [Tag(interpreter=\"py2\", abi=\"none\", platform=\"any\")]\n        )\n\n    def test_wheel_pattern_multi_values(self) -> None:\n        w = Wheel(\"simple-1.1-py2.py3-abi1.abi2-any.whl\")\n        assert w.name == \"simple\"\n        assert w.version == \"1.1\"\n        assert w.build_tag == ()\n        assert w.file_tags == frozenset(\n            [\n                Tag(interpreter=\"py2\", abi=\"abi1\", platform=\"any\"),\n                Tag(interpreter=\"py2\", abi=\"abi2\", platform=\"any\"),\n                Tag(interpreter=\"py3\", abi=\"abi1\", platform=\"any\"),\n                Tag(interpreter=\"py3\", abi=\"abi2\", platform=\"any\"),\n            ]\n        )\n\n    def test_wheel_with_build_tag(self) -> None:\n        # pip doesn't do anything with build tags, but theoretically, we might\n        # see one, in this case the build tag = '4'\n        w = Wheel(\"simple-1.1-4-py2-none-any.whl\")\n        assert w.name == \"simple\"\n        assert w.version == \"1.1\"\n        assert w.build_tag == (4, \"\")\n        assert w.file_tags == frozenset(\n            [Tag(interpreter=\"py2\", abi=\"none\", platform=\"any\")]\n        )\n\n    def test_single_digit_version(self) -> None:\n        w = Wheel(\"simple-1-py2-none-any.whl\")\n        assert w.version == \"1\"\n\n    def test_non_pep440_version(self) -> None:\n        with pytest.raises(InvalidWheelFilename):\n            Wheel(\"simple-_invalid_-py2-none-any.whl\")\n\n    def test_missing_version_raises(self) -> None:\n        with pytest.raises(InvalidWheelFilename):\n            Wheel(\"Cython-cp27-none-linux_x86_64.whl\")\n\n    def test_invalid_filename_raises(self) -> None:\n        with pytest.raises(InvalidWheelFilename):\n            Wheel(\"invalid.whl\")\n\n    def test_supported_single_version(self) -> None:\n        \"\"\"\n        Test single-version wheel is known to be supported\n        \"\"\"\n        w = Wheel(\"simple-0.1-py2-none-any.whl\")\n        assert w.supported(tags=[Tag(\"py2\", \"none\", \"any\")])\n\n    def test_supported_multi_version(self) -> None:\n        \"\"\"\n        Test multi-version wheel is known to be supported\n        \"\"\"\n        w = Wheel(\"simple-0.1-py2.py3-none-any.whl\")\n        assert w.supported(tags=[Tag(\"py3\", \"none\", \"any\")])\n\n    def test_not_supported_version(self) -> None:\n        \"\"\"\n        Test unsupported wheel is known to be unsupported\n        \"\"\"\n        w = Wheel(\"simple-0.1-py2-none-any.whl\")\n        assert not w.supported(tags=[Tag(\"py1\", \"none\", \"any\")])\n\n    def test_supported_osx_version(self) -> None:\n        \"\"\"\n        Wheels built for macOS 10.6 are supported on 10.9\n        \"\"\"\n        tags = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_9_intel\"], impl=\"cp\"\n        )\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_6_intel.whl\")\n        assert w.supported(tags=tags)\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_9_intel.whl\")\n        assert w.supported(tags=tags)\n\n    def test_not_supported_osx_version(self) -> None:\n        \"\"\"\n        Wheels built for macOS 10.9 are not supported on 10.6\n        \"\"\"\n        tags = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_6_intel\"], impl=\"cp\"\n        )\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_9_intel.whl\")\n        assert not w.supported(tags=tags)\n\n    def test_supported_multiarch_darwin(self) -> None:\n        \"\"\"\n        Multi-arch wheels (intel) are supported on components (i386, x86_64)\n        \"\"\"\n        universal = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_universal\"], impl=\"cp\"\n        )\n        intel = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_intel\"], impl=\"cp\"\n        )\n        x64 = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_x86_64\"], impl=\"cp\"\n        )\n        i386 = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_i386\"], impl=\"cp\"\n        )\n        ppc = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_ppc\"], impl=\"cp\"\n        )\n        ppc64 = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_ppc64\"], impl=\"cp\"\n        )\n\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_5_intel.whl\")\n        assert w.supported(tags=intel)\n        assert w.supported(tags=x64)\n        assert w.supported(tags=i386)\n        assert not w.supported(tags=universal)\n        assert not w.supported(tags=ppc)\n        assert not w.supported(tags=ppc64)\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_5_universal.whl\")\n        assert w.supported(tags=universal)\n        assert w.supported(tags=intel)\n        assert w.supported(tags=x64)\n        assert w.supported(tags=i386)\n        assert w.supported(tags=ppc)\n        assert w.supported(tags=ppc64)\n\n    def test_not_supported_multiarch_darwin(self) -> None:\n        \"\"\"\n        Single-arch wheels (x86_64) are not supported on multi-arch (intel)\n        \"\"\"\n        universal = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_universal\"], impl=\"cp\"\n        )\n        intel = compatibility_tags.get_supported(\n            \"27\", platforms=[\"macosx_10_5_intel\"], impl=\"cp\"\n        )\n\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_5_i386.whl\")\n        assert not w.supported(tags=intel)\n        assert not w.supported(tags=universal)\n        w = Wheel(\"simple-0.1-cp27-none-macosx_10_5_x86_64.whl\")\n        assert not w.supported(tags=intel)\n        assert not w.supported(tags=universal)\n\n    def test_supported_ios_version(self) -> None:\n        \"\"\"\n        Wheels build for iOS 12.3 are supported on iOS 15.1\n        \"\"\"\n        tags = compatibility_tags.get_supported(\n            \"313\", platforms=[\"ios_15_1_arm64_iphoneos\"], impl=\"cp\"\n        )\n        w = Wheel(\"simple-0.1-cp313-none-ios_12_3_arm64_iphoneos.whl\")\n        assert w.supported(tags=tags)\n        w = Wheel(\"simple-0.1-cp313-none-ios_15_1_arm64_iphoneos.whl\")\n        assert w.supported(tags=tags)\n\n    def test_not_supported_ios_version(self) -> None:\n        \"\"\"\n        Wheels built for macOS 15.1 are not supported on 12.3\n        \"\"\"\n        tags = compatibility_tags.get_supported(\n            \"313\", platforms=[\"ios_12_3_arm64_iphoneos\"], impl=\"cp\"\n        )\n        w = Wheel(\"simple-0.1-cp313-none-ios_15_1_arm64_iphoneos.whl\")\n        assert not w.supported(tags=tags)\n\n    def test_android(self) -> None:\n        arm_old = compatibility_tags.get_supported(\n            \"313\", platforms=[\"android_21_arm64_v8a\"], impl=\"cp\"\n        )\n        arm_new = compatibility_tags.get_supported(\n            \"313\", platforms=[\"android_30_arm64_v8a\"], impl=\"cp\"\n        )\n        x86_old = compatibility_tags.get_supported(\n            \"313\", platforms=[\"android_21_x86_64\"], impl=\"cp\"\n        )\n        x86_new = compatibility_tags.get_supported(\n            \"313\", platforms=[\"android_30_x86_64\"], impl=\"cp\"\n        )\n\n        w = Wheel(\"simple-0.1-cp313-none-android_21_arm64_v8a.whl\")\n        assert w.supported(arm_old)\n        assert w.supported(arm_new)\n        assert not w.supported(x86_old)\n        assert not w.supported(x86_new)\n\n        w = Wheel(\"simple-0.1-cp313-none-android_22_arm64_v8a.whl\")\n        assert not w.supported(arm_old)\n        assert w.supported(arm_new)\n        assert not w.supported(x86_old)\n        assert not w.supported(x86_new)\n\n        w = Wheel(\"simple-0.1-cp313-none-android_31_arm64_v8a.whl\")\n        assert not w.supported(arm_old)\n        assert not w.supported(arm_new)\n        assert not w.supported(x86_old)\n        assert not w.supported(x86_new)\n\n        w = Wheel(\"simple-0.1-cp313-none-android_20_x86_64.whl\")\n        assert not w.supported(arm_old)\n        assert not w.supported(arm_new)\n        assert w.supported(x86_old)\n        assert w.supported(x86_new)\n\n        w = Wheel(\"simple-0.1-cp313-none-android_30_x86_64.whl\")\n        assert not w.supported(arm_old)\n        assert not w.supported(arm_new)\n        assert not w.supported(x86_old)\n        assert w.supported(x86_new)\n\n        w = Wheel(\"simple-0.1-cp313-none-android_31_x86_64.whl\")\n        assert not w.supported(arm_old)\n        assert not w.supported(arm_new)\n        assert not w.supported(x86_old)\n        assert not w.supported(x86_new)\n\n    def test_support_index_min(self) -> None:\n        \"\"\"\n        Test results from `support_index_min`\n        \"\"\"\n        tags = [\n            Tag(\"py2\", \"none\", \"TEST\"),\n            Tag(\"py2\", \"TEST\", \"any\"),\n            Tag(\"py2\", \"none\", \"any\"),\n        ]\n        w = Wheel(\"simple-0.1-py2-none-any.whl\")\n        assert w.support_index_min(tags=tags) == 2\n        w = Wheel(\"simple-0.1-py2-none-TEST.whl\")\n        assert w.support_index_min(tags=tags) == 0\n\n    def test_support_index_min__none_supported(self) -> None:\n        \"\"\"\n        Test a wheel not supported by the given tags.\n        \"\"\"\n        w = Wheel(\"simple-0.1-py2-none-any.whl\")\n        with pytest.raises(ValueError):\n            w.support_index_min(tags=[])\n\n    def test_version_underscore_conversion(self) -> None:\n        \"\"\"\n        Test that underscore versions are now invalid (no longer converted)\n        \"\"\"\n        with pytest.raises(InvalidWheelFilename):\n            Wheel(\"simple-0.1_1-py2-none-any.whl\")\n\n    def test_invalid_wheel_raises(self) -> None:\n        \"\"\"\n        Test that wheel with invalid name now raises exception\n        \"\"\"\n        with pytest.raises(InvalidWheelFilename):\n            Wheel(\"six-1.16.0_build1-py3-none-any.whl\")\n"
  },
  {
    "path": "tests/unit/test_network_auth.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport os\nimport subprocess\nimport sys\nfrom collections.abc import Iterable\nfrom typing import Any\n\nimport pytest\n\nimport pip._internal.network.auth\nfrom pip._internal.network.auth import MultiDomainBasicAuth\n\nfrom tests.lib.requests_mocks import MockConnection, MockRequest, MockResponse\n\n\n@pytest.fixture(autouse=True)\ndef reset_keyring() -> Iterable[None]:\n    yield None\n    # Reset the state of the module between tests\n    pip._internal.network.auth.KEYRING_DISABLED = False\n    pip._internal.network.auth.get_keyring_provider.cache_clear()\n\n\n@pytest.mark.parametrize(\n    \"input_url, url, username, password\",\n    [\n        (\n            \"http://user%40email.com:password@example.com/path\",\n            \"http://example.com/path\",\n            \"user@email.com\",\n            \"password\",\n        ),\n        (\n            \"http://username:password@example.com/path\",\n            \"http://example.com/path\",\n            \"username\",\n            \"password\",\n        ),\n        (\n            \"http://token@example.com/path\",\n            \"http://example.com/path\",\n            \"token\",\n            \"\",\n        ),\n        (\n            \"http://example.com/path\",\n            \"http://example.com/path\",\n            None,\n            None,\n        ),\n    ],\n)\ndef test_get_credentials_parses_correctly(\n    input_url: str, url: str, username: str | None, password: str | None\n) -> None:\n    auth = MultiDomainBasicAuth()\n    get = auth._get_url_and_credentials\n\n    # Check URL parsing\n    assert get(input_url) == (url, username, password)\n    assert (\n        # There are no credentials in the URL\n        (username is None and password is None)\n        or\n        # Credentials were found and \"cached\" appropriately\n        auth.passwords[\"example.com\"] == (username, password)\n    )\n\n\ndef test_get_credentials_not_to_uses_cached_credentials() -> None:\n    auth = MultiDomainBasicAuth()\n    auth.passwords[\"example.com\"] = (\"user\", \"pass\")\n\n    got = auth._get_url_and_credentials(\"http://foo:bar@example.com/path\")\n    expected = (\"http://example.com/path\", \"foo\", \"bar\")\n    assert got == expected\n\n\ndef test_get_credentials_not_to_uses_cached_credentials_only_username() -> None:\n    auth = MultiDomainBasicAuth()\n    auth.passwords[\"example.com\"] = (\"user\", \"pass\")\n\n    got = auth._get_url_and_credentials(\"http://foo@example.com/path\")\n    expected = (\"http://example.com/path\", \"foo\", \"\")\n    assert got == expected\n\n\ndef test_get_credentials_uses_cached_credentials() -> None:\n    auth = MultiDomainBasicAuth()\n    auth.passwords[\"example.com\"] = (\"user\", \"pass\")\n\n    got = auth._get_url_and_credentials(\"http://example.com/path\")\n    expected = (\"http://example.com/path\", \"user\", \"pass\")\n    assert got == expected\n\n\ndef test_get_credentials_uses_cached_credentials_only_username() -> None:\n    auth = MultiDomainBasicAuth()\n    auth.passwords[\"example.com\"] = (\"user\", \"pass\")\n\n    got = auth._get_url_and_credentials(\"http://user@example.com/path\")\n    expected = (\"http://example.com/path\", \"user\", \"pass\")\n    assert got == expected\n\n\ndef test_get_index_url_credentials() -> None:\n    auth = MultiDomainBasicAuth(\n        index_urls=[\n            \"http://example.com/\",\n            \"http://foo:bar@example.com/path\",\n        ]\n    )\n    get = functools.partial(\n        auth._get_new_credentials, allow_netrc=False, allow_keyring=False\n    )\n\n    # Check resolution of indexes\n    assert get(\"http://example.com/path/path2\") == (\"foo\", \"bar\")\n    assert get(\"http://example.com/path3/path2\") == (None, None)\n\n\ndef test_prioritize_longest_path_prefix_match_organization() -> None:\n    auth = MultiDomainBasicAuth(\n        index_urls=[\n            \"http://foo:bar@example.com/org-name-alpha/repo-alias/simple\",\n            \"http://bar:foo@example.com/org-name-beta/repo-alias/simple\",\n        ]\n    )\n    get = functools.partial(\n        auth._get_new_credentials, allow_netrc=False, allow_keyring=False\n    )\n\n    # Inspired by Azure DevOps URL structure, GitLab should look similar\n    assert get(\"http://example.com/org-name-alpha/repo-guid/dowbload/\") == (\n        \"foo\",\n        \"bar\",\n    )\n    assert get(\"http://example.com/org-name-beta/repo-guid/dowbload/\") == (\"bar\", \"foo\")\n\n\ndef test_prioritize_longest_path_prefix_match_project() -> None:\n    auth = MultiDomainBasicAuth(\n        index_urls=[\n            \"http://foo:bar@example.com/org-alpha/project-name-alpha/repo-alias/simple\",\n            \"http://bar:foo@example.com/org-alpha/project-name-beta/repo-alias/simple\",\n        ]\n    )\n    get = functools.partial(\n        auth._get_new_credentials, allow_netrc=False, allow_keyring=False\n    )\n\n    # Inspired by Azure DevOps URL structure, GitLab should look similar\n    assert get(\n        \"http://example.com/org-alpha/project-name-alpha/repo-guid/dowbload/\"\n    ) == (\"foo\", \"bar\")\n    assert get(\n        \"http://example.com/org-alpha/project-name-beta/repo-guid/dowbload/\"\n    ) == (\"bar\", \"foo\")\n\n\nclass KeyringModuleV1:\n    \"\"\"Represents the supported API of keyring before get_credential\n    was added.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.saved_passwords: list[tuple[str, str, str]] = []\n\n    def get_password(self, system: str, username: str) -> str | None:\n        if system == \"example.com\" and username:\n            return username + \"!netloc\"\n        if system == \"http://example.com/path2/\" and username:\n            return username + \"!url\"\n        return None\n\n    def set_password(self, system: str, username: str, password: str) -> None:\n        self.saved_passwords.append((system, username, password))\n\n\n@pytest.mark.parametrize(\n    \"url, expect\",\n    [\n        (\"http://example.com/path1\", (None, None)),\n        # path1 URLs will be resolved by netloc\n        (\"http://user@example.com/path3\", (\"user\", \"user!netloc\")),\n        (\"http://user2@example.com/path3\", (\"user2\", \"user2!netloc\")),\n        # path2 URLs will be resolved by index URL\n        (\"http://example.com/path2/path3\", (None, None)),\n        (\"http://foo@example.com/path2/path3\", (\"foo\", \"foo!url\")),\n    ],\n)\ndef test_keyring_get_password(\n    monkeypatch: pytest.MonkeyPatch,\n    url: str,\n    expect: tuple[str | None, str | None],\n) -> None:\n    keyring = KeyringModuleV1()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring)\n    auth = MultiDomainBasicAuth(\n        index_urls=[\"http://example.com/path2\", \"http://example.com/path3\"],\n        keyring_provider=\"import\",\n    )\n\n    actual = auth._get_new_credentials(url, allow_netrc=False, allow_keyring=True)\n    assert actual == expect\n\n\ndef test_keyring_get_password_after_prompt(monkeypatch: pytest.MonkeyPatch) -> None:\n    keyring = KeyringModuleV1()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring)\n    auth = MultiDomainBasicAuth(keyring_provider=\"import\")\n\n    def ask_input(prompt: str) -> str:\n        assert prompt == \"User for example.com: \"\n        return \"user\"\n\n    monkeypatch.setattr(\"pip._internal.network.auth.ask_input\", ask_input)\n    actual = auth._prompt_for_password(\"example.com\")\n    assert actual == (\"user\", \"user!netloc\", False)\n\n\ndef test_keyring_get_password_after_prompt_when_none(\n    monkeypatch: pytest.MonkeyPatch,\n) -> None:\n    keyring = KeyringModuleV1()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring)\n    auth = MultiDomainBasicAuth(keyring_provider=\"import\")\n\n    def ask_input(prompt: str) -> str:\n        assert prompt == \"User for unknown.com: \"\n        return \"user\"\n\n    def ask_password(prompt: str) -> str:\n        assert prompt == \"Password: \"\n        return \"fake_password\"\n\n    monkeypatch.setattr(\"pip._internal.network.auth.ask_input\", ask_input)\n    monkeypatch.setattr(\"pip._internal.network.auth.ask_password\", ask_password)\n    actual = auth._prompt_for_password(\"unknown.com\")\n    assert actual == (\"user\", \"fake_password\", True)\n\n\ndef test_keyring_get_password_username_in_index(\n    monkeypatch: pytest.MonkeyPatch,\n) -> None:\n    keyring = KeyringModuleV1()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring)\n    auth = MultiDomainBasicAuth(\n        index_urls=[\"http://user@example.com/path2\", \"http://example.com/path4\"],\n        keyring_provider=\"import\",\n    )\n    get = functools.partial(\n        auth._get_new_credentials, allow_netrc=False, allow_keyring=True\n    )\n\n    assert get(\"http://example.com/path2/path3\") == (\"user\", \"user!url\")\n    assert get(\"http://example.com/path4/path1\") == (None, None)\n\n\n@pytest.mark.parametrize(\n    \"response_status, creds, expect_save\",\n    [\n        (403, (\"user\", \"pass\", True), False),\n        (\n            200,\n            (\"user\", \"pass\", True),\n            True,\n        ),\n        (\n            200,\n            (\"user\", \"pass\", False),\n            False,\n        ),\n    ],\n)\ndef test_keyring_set_password(\n    monkeypatch: pytest.MonkeyPatch,\n    response_status: int,\n    creds: tuple[str, str, bool],\n    expect_save: bool,\n) -> None:\n    keyring = KeyringModuleV1()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring)\n    auth = MultiDomainBasicAuth(prompting=True, keyring_provider=\"import\")\n    monkeypatch.setattr(auth, \"_get_url_and_credentials\", lambda u: (u, None, None))\n    monkeypatch.setattr(auth, \"_prompt_for_password\", lambda *a: creds)\n    if creds[2]:\n        # when _prompt_for_password indicates to save, we should save\n        def should_save_password_to_keyring(*a: Any) -> bool:\n            return True\n\n    else:\n        # when _prompt_for_password indicates not to save, we should\n        # never call this function\n        def should_save_password_to_keyring(*a: Any) -> bool:\n            pytest.fail(\"_should_save_password_to_keyring should not be called\")\n\n    monkeypatch.setattr(\n        auth, \"_should_save_password_to_keyring\", should_save_password_to_keyring\n    )\n\n    req = MockRequest(\"https://example.com\")\n    resp = MockResponse(b\"\")\n    resp.url = req.url\n    connection = MockConnection()\n\n    def _send(sent_req: MockRequest, **kwargs: Any) -> MockResponse:\n        assert sent_req is req\n        assert \"Authorization\" in sent_req.headers\n        r = MockResponse(b\"\")\n        r.status_code = response_status\n        return r\n\n    # https://github.com/python/mypy/issues/2427\n    connection._send = _send  # type: ignore[assignment]\n\n    resp.request = req\n    resp.status_code = 401\n    resp.connection = connection\n\n    auth.handle_401(resp)\n\n    if expect_save:\n        assert keyring.saved_passwords == [(\"example.com\", creds[0], creds[1])]\n    else:\n        assert keyring.saved_passwords == []\n\n\nclass KeyringModuleV2:\n    \"\"\"Represents the current supported API of keyring\"\"\"\n\n    class Credential:\n        def __init__(self, username: str, password: str) -> None:\n            self.username = username\n            self.password = password\n\n    def get_password(self, system: str, username: str) -> None:\n        pytest.fail(\"get_password should not ever be called\")\n\n    def get_credential(self, system: str, username: str) -> Credential | None:\n        if system == \"http://example.com/path2/\":\n            return self.Credential(\"username\", \"url\")\n        if system == \"example.com\":\n            return self.Credential(\"username\", \"netloc\")\n        return None\n\n\n@pytest.mark.parametrize(\n    \"url, expect\",\n    [\n        (\"http://example.com/path1\", (\"username\", \"netloc\")),\n        (\"http://example.com/path2/path3\", (\"username\", \"url\")),\n        (\"http://user2@example.com/path2/path3\", (\"username\", \"url\")),\n    ],\n)\ndef test_keyring_get_credential(\n    monkeypatch: pytest.MonkeyPatch, url: str, expect: tuple[str, str]\n) -> None:\n    monkeypatch.setitem(sys.modules, \"keyring\", KeyringModuleV2())\n    auth = MultiDomainBasicAuth(\n        index_urls=[\"http://example.com/path1\", \"http://example.com/path2\"],\n        keyring_provider=\"import\",\n    )\n\n    assert (\n        auth._get_new_credentials(url, allow_netrc=False, allow_keyring=True) == expect\n    )\n\n\nclass KeyringModuleBroken:\n    \"\"\"Represents the current supported API of keyring, but broken\"\"\"\n\n    def __init__(self) -> None:\n        self._call_count = 0\n\n    def get_credential(self, system: str, username: str) -> None:\n        self._call_count += 1\n        raise Exception(\"This keyring is broken!\")\n\n\ndef test_broken_keyring_disables_keyring(monkeypatch: pytest.MonkeyPatch) -> None:\n    keyring_broken = KeyringModuleBroken()\n    monkeypatch.setitem(sys.modules, \"keyring\", keyring_broken)\n\n    auth = MultiDomainBasicAuth(\n        index_urls=[\"http://example.com/\"], keyring_provider=\"import\"\n    )\n\n    assert keyring_broken._call_count == 0\n    for i in range(5):\n        url = \"http://example.com/path\" + str(i)\n        assert auth._get_new_credentials(\n            url, allow_netrc=False, allow_keyring=True\n        ) == (None, None)\n        assert keyring_broken._call_count == 1\n\n\nclass KeyringSubprocessResult(KeyringModuleV1):\n    \"\"\"Represents the subprocess call to keyring\"\"\"\n\n    returncode = 0  # Default to zero retcode\n\n    def __call__(\n        self,\n        cmd: list[str],\n        *,\n        env: dict[str, str],\n        stdin: Any | None = None,\n        stdout: Any | None = None,\n        input: bytes | None = None,\n        check: bool | None = None,\n    ) -> Any:\n        if cmd[1] == \"get\":\n            assert stdin == -3  # subprocess.DEVNULL\n            assert stdout == subprocess.PIPE\n            assert env[\"PYTHONIOENCODING\"] == \"utf-8\"\n            assert check is None\n\n            password = self.get_password(*cmd[2:])\n            if password is None:\n                # Expect non-zero returncode if no password present\n                self.returncode = 1\n            else:\n                # Passwords are returned encoded with a newline appended\n                self.returncode = 0\n                self.stdout = (password + os.linesep).encode(\"utf-8\")\n\n        if cmd[1] == \"set\":\n            assert stdin is None\n            assert stdout is None\n            assert env[\"PYTHONIOENCODING\"] == \"utf-8\"\n            assert input is not None\n            assert check\n\n            # Input from stdin is encoded\n            self.set_password(cmd[2], cmd[3], input.decode(\"utf-8\").strip(os.linesep))\n\n        return self\n\n    def check_returncode(self) -> None:\n        if self.returncode:\n            raise Exception()\n\n\n@pytest.mark.parametrize(\n    \"url, expect\",\n    [\n        (\"http://example.com/path1\", (None, None)),\n        # path1 URLs will be resolved by netloc\n        (\"http://user@example.com/path3\", (\"user\", \"user!netloc\")),\n        (\"http://user2@example.com/path3\", (\"user2\", \"user2!netloc\")),\n        # path2 URLs will be resolved by index URL\n        (\"http://example.com/path2/path3\", (None, None)),\n        (\"http://foo@example.com/path2/path3\", (\"foo\", \"foo!url\")),\n    ],\n)\ndef test_keyring_cli_get_password(\n    monkeypatch: pytest.MonkeyPatch,\n    url: str,\n    expect: tuple[str | None, str | None],\n) -> None:\n    monkeypatch.setattr(pip._internal.network.auth.shutil, \"which\", lambda x: \"keyring\")\n    monkeypatch.setattr(\n        pip._internal.network.auth.subprocess, \"run\", KeyringSubprocessResult()\n    )\n    auth = MultiDomainBasicAuth(\n        index_urls=[\"http://example.com/path2\", \"http://example.com/path3\"],\n        keyring_provider=\"subprocess\",\n    )\n\n    actual = auth._get_new_credentials(url, allow_netrc=False, allow_keyring=True)\n    assert actual == expect\n\n\n@pytest.mark.parametrize(\n    \"response_status, creds, expect_save\",\n    [\n        (403, (\"user\", \"pass\", True), False),\n        (\n            200,\n            (\"user\", \"pass\", True),\n            True,\n        ),\n        (\n            200,\n            (\"user\", \"pass\", False),\n            False,\n        ),\n    ],\n)\ndef test_keyring_cli_set_password(\n    monkeypatch: pytest.MonkeyPatch,\n    response_status: int,\n    creds: tuple[str, str, bool],\n    expect_save: bool,\n) -> None:\n    monkeypatch.setattr(pip._internal.network.auth.shutil, \"which\", lambda x: \"keyring\")\n    keyring = KeyringSubprocessResult()\n    monkeypatch.setattr(pip._internal.network.auth.subprocess, \"run\", keyring)\n    auth = MultiDomainBasicAuth(prompting=True, keyring_provider=\"subprocess\")\n    monkeypatch.setattr(auth, \"_get_url_and_credentials\", lambda u: (u, None, None))\n    monkeypatch.setattr(auth, \"_prompt_for_password\", lambda *a: creds)\n    if creds[2]:\n        # when _prompt_for_password indicates to save, we should save\n        def should_save_password_to_keyring(*a: Any) -> bool:\n            return True\n\n    else:\n        # when _prompt_for_password indicates not to save, we should\n        # never call this function\n        def should_save_password_to_keyring(*a: Any) -> bool:\n            pytest.fail(\"_should_save_password_to_keyring should not be called\")\n\n    monkeypatch.setattr(\n        auth, \"_should_save_password_to_keyring\", should_save_password_to_keyring\n    )\n\n    req = MockRequest(\"https://example.com\")\n    resp = MockResponse(b\"\")\n    resp.url = req.url\n    connection = MockConnection()\n\n    def _send(sent_req: MockRequest, **kwargs: Any) -> MockResponse:\n        assert sent_req is req\n        assert \"Authorization\" in sent_req.headers\n        r = MockResponse(b\"\")\n        r.status_code = response_status\n        return r\n\n    # https://github.com/python/mypy/issues/2427\n    connection._send = _send  # type: ignore[assignment]\n\n    resp.request = req\n    resp.status_code = 401\n    resp.connection = connection\n\n    auth.handle_401(resp)\n\n    if expect_save:\n        assert keyring.saved_passwords == [(\"example.com\", creds[0], creds[1])]\n    else:\n        assert keyring.saved_passwords == []\n"
  },
  {
    "path": "tests/unit/test_network_cache.py",
    "content": "import os\nfrom pathlib import Path\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._vendor.cachecontrol.caches import FileCache\n\nfrom pip._internal.network.cache import SafeFileCache\n\nfrom tests.lib.filesystem import chmod\n\n\n@pytest.fixture\ndef cache_tmpdir(tmpdir: Path) -> Path:\n    cache_dir = tmpdir.joinpath(\"cache\")\n    cache_dir.mkdir(parents=True)\n    return cache_dir\n\n\nclass TestSafeFileCache:\n    \"\"\"\n    The no_perms test are useless on Windows since SafeFileCache uses\n    pip._internal.utils.filesystem.check_path_owner which is based on\n    os.geteuid which is absent on Windows.\n    \"\"\"\n\n    def test_cache_roundtrip(self, cache_tmpdir: Path) -> None:\n        cache = SafeFileCache(os.fspath(cache_tmpdir))\n        assert cache.get(\"test key\") is None\n        cache.set(\"test key\", b\"a test string\")\n        # Body hasn't been stored yet, so the entry isn't valid yet\n        assert cache.get(\"test key\") is None\n\n        # With a body, the cache entry is valid:\n        cache.set_body(\"test key\", b\"body\")\n        assert cache.get(\"test key\") == b\"a test string\"\n        cache.delete(\"test key\")\n        assert cache.get(\"test key\") is None\n\n    def test_cache_roundtrip_body(self, cache_tmpdir: Path) -> None:\n        cache = SafeFileCache(os.fspath(cache_tmpdir))\n        assert cache.get_body(\"test key\") is None\n        cache.set_body(\"test key\", b\"a test string\")\n        # Metadata isn't available, so the entry isn't valid yet (this\n        # shouldn't happen, but just in case)\n        assert cache.get_body(\"test key\") is None\n\n        # With metadata, the cache entry is valid:\n        cache.set(\"test key\", b\"metadata\")\n        body = cache.get_body(\"test key\")\n        assert body is not None\n        with body:\n            assert body.read() == b\"a test string\"\n        cache.delete(\"test key\")\n        assert cache.get_body(\"test key\") is None\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_safe_get_no_perms(\n        self, cache_tmpdir: Path, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(os.path, \"exists\", lambda x: True)\n\n        with chmod(cache_tmpdir, 000):\n            cache = SafeFileCache(os.fspath(cache_tmpdir))\n            cache.get(\"foo\")\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_safe_set_no_perms(self, cache_tmpdir: Path) -> None:\n        with chmod(cache_tmpdir, 000):\n            cache = SafeFileCache(os.fspath(cache_tmpdir))\n            cache.set(\"foo\", b\"bar\")\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_safe_delete_no_perms(self, cache_tmpdir: Path) -> None:\n        with chmod(cache_tmpdir, 000):\n            cache = SafeFileCache(os.fspath(cache_tmpdir))\n            cache.delete(\"foo\")\n\n    def test_cache_hashes_are_same(self, cache_tmpdir: Path) -> None:\n        cache = SafeFileCache(os.fspath(cache_tmpdir))\n        key = \"test key\"\n        fake_cache = Mock(FileCache, directory=cache.directory, encode=FileCache.encode)\n        assert cache._get_cache_path(key) == FileCache._fn(fake_cache, key)\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    @pytest.mark.skipif(\n        os.chmod not in os.supports_fd and os.chmod not in os.supports_follow_symlinks,\n        reason=\"requires os.chmod to support file descriptors or not follow symlinks\",\n    )\n    @pytest.mark.parametrize(\n        \"perms, expected_perms\", [(0o300, 0o600), (0o700, 0o600), (0o777, 0o666)]\n    )\n    def test_cache_inherit_perms(\n        self, cache_tmpdir: Path, perms: int, expected_perms: int\n    ) -> None:\n        key = \"foo\"\n        with chmod(cache_tmpdir, perms):\n            cache = SafeFileCache(os.fspath(cache_tmpdir))\n            cache.set(key, b\"bar\")\n        assert (os.stat(cache._get_cache_path(key)).st_mode & 0o777) == expected_perms\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_cache_not_inherit_perms(\n        self, cache_tmpdir: Path, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(os, \"supports_fd\", os.supports_fd - {os.chmod})\n        monkeypatch.setattr(\n            os, \"supports_follow_symlinks\", os.supports_follow_symlinks - {os.chmod}\n        )\n        key = \"foo\"\n        with chmod(cache_tmpdir, 0o777):\n            cache = SafeFileCache(os.fspath(cache_tmpdir))\n            cache.set(key, b\"bar\")\n        assert (os.stat(cache._get_cache_path(key)).st_mode & 0o777) == 0o600\n"
  },
  {
    "path": "tests/unit/test_network_download.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import MagicMock, call, patch\n\nimport pytest\n\nfrom pip._internal.exceptions import IncompleteDownloadError\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.download import (\n    Downloader,\n    _get_http_response_size,\n    _log_download,\n    parse_content_disposition,\n    sanitize_content_filename,\n)\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import HEADERS\n\nfrom tests.lib.requests_mocks import MockResponse\n\n\n@pytest.mark.parametrize(\n    \"url, headers, from_cache, range_start, expected\",\n    [\n        (\n            \"http://example.com/foo.tgz\",\n            {},\n            False,\n            None,\n            \"Downloading http://example.com/foo.tgz\",\n        ),\n        (\n            \"http://example.com/foo.tgz\",\n            {\"content-length\": \"2\"},\n            False,\n            None,\n            \"Downloading http://example.com/foo.tgz (2 bytes)\",\n        ),\n        (\n            \"http://example.com/foo.tgz\",\n            {\"content-length\": \"2\"},\n            True,\n            None,\n            \"Using cached http://example.com/foo.tgz (2 bytes)\",\n        ),\n        (\n            \"https://files.pythonhosted.org/foo.tgz\",\n            {},\n            False,\n            None,\n            \"Downloading foo.tgz\",\n        ),\n        (\n            \"https://files.pythonhosted.org/foo.tgz\",\n            {\"content-length\": \"2\"},\n            False,\n            None,\n            \"Downloading foo.tgz (2 bytes)\",\n        ),\n        (\n            \"https://files.pythonhosted.org/foo.tgz\",\n            {\"content-length\": \"2\"},\n            True,\n            None,\n            \"Using cached foo.tgz\",\n        ),\n        (\n            \"http://example.com/foo.tgz\",\n            {\"content-length\": \"200\"},\n            False,\n            100,\n            \"Resuming download http://example.com/foo.tgz (100 bytes/200 bytes)\",\n        ),\n    ],\n)\ndef test_log_download(\n    caplog: pytest.LogCaptureFixture,\n    url: str,\n    headers: dict[str, str],\n    from_cache: bool,\n    range_start: int | None,\n    expected: str,\n) -> None:\n    caplog.set_level(logging.INFO)\n    resp = MockResponse(b\"\")\n    resp.url = url\n    resp.headers = headers\n    if from_cache:\n        resp.from_cache = from_cache\n    link = Link(url)\n    total_length = _get_http_response_size(resp)\n    _log_download(\n        resp,\n        link,\n        progress_bar=\"on\",\n        total_length=total_length,\n        range_start=range_start,\n    )\n\n    assert len(caplog.records) == 1\n    record = caplog.records[0]\n    assert record.levelname == \"INFO\"\n    assert expected in record.message\n\n\n@pytest.mark.parametrize(\n    \"filename, expected\",\n    [\n        (\"dir/file\", \"file\"),\n        (\"../file\", \"file\"),\n        (\"../../file\", \"file\"),\n        (\"../\", \"\"),\n        (\"../..\", \"..\"),\n        (\"/\", \"\"),\n    ],\n)\ndef test_sanitize_content_filename(filename: str, expected: str) -> None:\n    \"\"\"\n    Test inputs where the result is the same for Windows and non-Windows.\n    \"\"\"\n    assert sanitize_content_filename(filename) == expected\n\n\n@pytest.mark.parametrize(\n    \"filename, win_expected, non_win_expected\",\n    [\n        (\"dir\\\\file\", \"file\", \"dir\\\\file\"),\n        (\"..\\\\file\", \"file\", \"..\\\\file\"),\n        (\"..\\\\..\\\\file\", \"file\", \"..\\\\..\\\\file\"),\n        (\"..\\\\\", \"\", \"..\\\\\"),\n        (\"..\\\\..\", \"..\", \"..\\\\..\"),\n        (\"\\\\\", \"\", \"\\\\\"),\n    ],\n)\ndef test_sanitize_content_filename__platform_dependent(\n    filename: str, win_expected: str, non_win_expected: str\n) -> None:\n    \"\"\"\n    Test inputs where the result is different for Windows and non-Windows.\n    \"\"\"\n    if sys.platform == \"win32\":\n        expected = win_expected\n    else:\n        expected = non_win_expected\n    assert sanitize_content_filename(filename) == expected\n\n\n@pytest.mark.parametrize(\n    \"content_disposition, default_filename, expected\",\n    [\n        ('attachment;filename=\"../file\"', \"df\", \"file\"),\n    ],\n)\ndef test_parse_content_disposition(\n    content_disposition: str, default_filename: str, expected: str\n) -> None:\n    actual = parse_content_disposition(content_disposition, default_filename)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"resume_retries,mock_responses,expected_resume_args,expected_bytes\",\n    [\n        # If content-length is not provided, the download will\n        # always \"succeed\" since we don't have a way to check if\n        # the download is complete.\n        (\n            0,\n            [({}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\")],\n            [],\n            b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n        ),\n        # Complete download (content-length matches body)\n        (\n            0,\n            [({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\")],\n            [],\n            b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n        ),\n        # Incomplete download without resume retries\n        (\n            0,\n            [({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-\")],\n            [],\n            None,\n        ),\n        # Incomplete download with resume retries\n        (\n            5,\n            [\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-\"),\n                ({\"content-length\": \"12\"}, 206, b\"f2561d5dfd89\"),\n            ],\n            [(24, None)],\n            b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n        ),\n        # If the server responds with 200 (e.g. no range header support or the file\n        # has changed between the requests) the downloader should restart instead of\n        # attempting to resume. The downloaded file should not be affected.\n        (\n            5,\n            [\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-\"),\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-\"),\n                (\n                    {\"content-length\": \"36\"},\n                    200,\n                    b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n                ),\n            ],\n            [(24, None), (14, None)],\n            b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n        ),\n        # File size could change between requests. Make sure this is handled correctly.\n        (\n            5,\n            [\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-\"),\n                (\n                    {\"content-length\": \"40\"},\n                    200,\n                    b\"new-0cfa7e9d-1868-4dd7-9fb3-f2561d5d\",\n                ),\n                ({\"content-length\": \"4\"}, 206, b\"fd89\"),\n            ],\n            [(24, None), (36, None)],\n            b\"new-0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n        ),\n        # The downloader should fail after N resume_retries attempts.\n        # This prevents the downloader from getting stuck if the connection\n        # is unstable and the server does NOT support range requests.\n        (\n            1,\n            [\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-4dd7-9fb3-\"),\n                ({\"content-length\": \"36\"}, 200, b\"0cfa7e9d-1868-\"),\n            ],\n            [(24, None)],\n            None,\n        ),\n        # The downloader should use the If-Range header to make the range\n        # request conditional if it is possible to check for modifications\n        # (e.g. if we know the creation time of the initial response).\n        (\n            5,\n            [\n                (\n                    {\n                        \"content-length\": \"36\",\n                        \"last-modified\": \"Wed, 21 Oct 2015 07:28:00 GMT\",\n                    },\n                    200,\n                    b\"0cfa7e9d-1868-4dd7-9fb3-\",\n                ),\n                (\n                    {\n                        \"content-length\": \"42\",\n                        \"last-modified\": \"Wed, 21 Oct 2015 07:30:00 GMT\",\n                    },\n                    200,\n                    b\"new-0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\",\n                ),\n                (\n                    {\n                        \"content-length\": \"12\",\n                        \"last-modified\": \"Wed, 21 Oct 2015 07:54:00 GMT\",\n                    },\n                    200,\n                    b\"f2561d5dfd89\",\n                ),\n            ],\n            [\n                (24, \"Wed, 21 Oct 2015 07:28:00 GMT\"),\n                (40, \"Wed, 21 Oct 2015 07:30:00 GMT\"),\n            ],\n            b\"f2561d5dfd89\",\n        ),\n        # ETag is preferred over Last-Modified for the If-Range condition.\n        (\n            5,\n            [\n                (\n                    {\n                        \"content-length\": \"36\",\n                        \"last-modified\": \"Wed, 21 Oct 2015 07:28:00 GMT\",\n                        \"etag\": '\"33a64df551425fcc55e4d42a148795d9f25f89d4\"',\n                    },\n                    200,\n                    b\"0cfa7e9d-1868-4dd7-9fb3-\",\n                ),\n                (\n                    {\n                        \"content-length\": \"12\",\n                        \"last-modified\": \"Wed, 21 Oct 2015 07:54:00 GMT\",\n                        \"etag\": '\"33a64df551425fcc55e4d42a148795d9f25f89d4\"',\n                    },\n                    200,\n                    b\"f2561d5dfd89\",\n                ),\n            ],\n            [(24, '\"33a64df551425fcc55e4d42a148795d9f25f89d4\"')],\n            b\"f2561d5dfd89\",\n        ),\n    ],\n)\ndef test_downloader(\n    resume_retries: int,\n    mock_responses: list[tuple[dict[str, str], int, bytes]],\n    # list of (range_start, if_range)\n    expected_resume_args: list[tuple[int | None, str | None]],\n    # expected_bytes is None means the download should fail\n    expected_bytes: bytes | None,\n    tmpdir: Path,\n) -> None:\n    session = PipSession(resume_retries=resume_retries)\n    link = Link(\"http://example.com/foo.tgz\")\n    downloader = Downloader(session, \"on\")\n\n    responses = []\n    for headers, status_code, body in mock_responses:\n        resp = MockResponse(body)\n        resp.headers = headers\n        resp.status_code = status_code\n        responses.append(resp)\n    _http_get_mock = MagicMock(side_effect=responses)\n\n    with patch.object(Downloader, \"_http_get\", _http_get_mock):\n        if expected_bytes is None:\n            remove = MagicMock(return_value=None)\n            with patch(\"os.remove\", remove):\n                with pytest.raises(IncompleteDownloadError):\n                    downloader(link, str(tmpdir))\n            # Make sure the incomplete file is removed\n            remove.assert_called_once()\n        else:\n            filepath, _ = downloader(link, str(tmpdir))\n            with open(filepath, \"rb\") as downloaded_file:\n                downloaded_bytes = downloaded_file.read()\n                assert downloaded_bytes == expected_bytes\n\n    calls = [call(link)]  # the initial GET request\n    for range_start, if_range in expected_resume_args:\n        headers = {**HEADERS, \"Range\": f\"bytes={range_start}-\"}\n        if if_range:\n            headers[\"If-Range\"] = if_range\n        calls.append(call(link, headers))\n\n    # Make sure that the downloader makes additional requests for resumption\n    _http_get_mock.assert_has_calls(calls)\n\n\ndef test_resumed_download_caching(tmpdir: Path) -> None:\n    \"\"\"Test that resumed downloads are cached properly for future use.\"\"\"\n    cache_dir = tmpdir / \"cache\"\n    session = PipSession(cache=str(cache_dir), resume_retries=5)\n    link = Link(\"https://example.com/foo.tgz\")\n    downloader = Downloader(session, \"on\")\n\n    # Mock an incomplete download followed by a successful resume\n    incomplete_resp = MockResponse(b\"0cfa7e9d-1868-4dd7-9fb3-\")\n    incomplete_resp.headers = {\"content-length\": \"36\"}\n    incomplete_resp.status_code = 200\n\n    resume_resp = MockResponse(b\"f2561d5dfd89\")\n    resume_resp.headers = {\"content-length\": \"12\"}\n    resume_resp.status_code = 206\n\n    responses = [incomplete_resp, resume_resp]\n    _http_get_mock = MagicMock(side_effect=responses)\n\n    with patch.object(Downloader, \"_http_get\", _http_get_mock):\n        # Perform the download (incomplete then resumed)\n        filepath, _ = downloader(link, str(tmpdir))\n\n        # Verify the file was downloaded correctly\n        with open(filepath, \"rb\") as downloaded_file:\n            downloaded_bytes = downloaded_file.read()\n            expected_bytes = b\"0cfa7e9d-1868-4dd7-9fb3-f2561d5dfd89\"\n            assert downloaded_bytes == expected_bytes\n\n        # Verify that the cache directory was created and contains cache files\n        # The resumed download should have been cached for future use\n        assert cache_dir.exists()\n        cache_files = list(cache_dir.rglob(\"*\"))\n        # Should have cache files (both metadata and body files)\n        assert len([f for f in cache_files if f.is_file()]) == 2\n"
  },
  {
    "path": "tests/unit/test_network_lazy_wheel.py",
    "content": "from collections.abc import Iterator\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.exceptions import InvalidWheel\nfrom pip._internal.network.lazy_wheel import (\n    HTTPRangeRequestUnsupported,\n    dist_from_wheel_url,\n)\nfrom pip._internal.network.session import PipSession\n\nfrom tests.lib import TestData\nfrom tests.lib.server import MockServer, file_response\n\nMYPY_0_782_WHL = (\n    \"https://files.pythonhosted.org/packages/9d/65/\"\n    \"b96e844150ce18b9892b155b780248955ded13a2581d31872e7daa90a503/\"\n    \"mypy-0.782-py3-none-any.whl\"\n)\nMYPY_0_782_REQS = {\n    \"typed-ast<1.5.0,>=1.4.0\",\n    \"typing-extensions>=3.7.4\",\n    \"mypy-extensions<0.5.0,>=0.4.3\",\n    'psutil>=4.0; extra == \"dmypy\"',\n}\n\n\n@pytest.fixture\ndef session() -> PipSession:\n    return PipSession()\n\n\n@pytest.fixture\ndef mypy_whl_no_range(mock_server: MockServer, shared_data: TestData) -> Iterator[str]:\n    mypy_whl = shared_data.packages / \"mypy-0.782-py3-none-any.whl\"\n    mock_server.set_responses([file_response(mypy_whl)])\n    mock_server.start()\n    base_address = f\"http://{mock_server.host}:{mock_server.port}\"\n    yield \"{}/{}\".format(base_address, \"mypy-0.782-py3-none-any.whl\")\n    mock_server.stop()\n\n\n@pytest.mark.network\ndef test_dist_from_wheel_url(session: PipSession) -> None:\n    \"\"\"Test if the acquired distribution contain correct information.\"\"\"\n    dist = dist_from_wheel_url(canonicalize_name(\"mypy\"), MYPY_0_782_WHL, session)\n    assert dist.canonical_name == \"mypy\"\n    assert dist.version == Version(\"0.782\")\n    extras = list(dist.iter_provided_extras())\n    assert extras == [\"dmypy\"]\n    assert {str(d) for d in dist.iter_dependencies(extras)} == MYPY_0_782_REQS\n\n\ndef test_dist_from_wheel_url_no_range(\n    session: PipSession, mypy_whl_no_range: str\n) -> None:\n    \"\"\"Test handling when HTTP range requests are not supported.\"\"\"\n    with pytest.raises(HTTPRangeRequestUnsupported):\n        dist_from_wheel_url(canonicalize_name(\"mypy\"), mypy_whl_no_range, session)\n\n\n@pytest.mark.network\ndef test_dist_from_wheel_url_not_zip(session: PipSession) -> None:\n    \"\"\"Test handling with the given URL does not point to a ZIP.\"\"\"\n    with pytest.raises(InvalidWheel):\n        dist_from_wheel_url(\n            canonicalize_name(\"python\"), \"https://www.python.org/\", session\n        )\n"
  },
  {
    "path": "tests/unit/test_network_session.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Any\nfrom urllib.parse import urlparse\nfrom urllib.request import getproxies\n\nimport pytest\n\nfrom pip._vendor import requests\n\nfrom pip import __version__\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.session import (\n    CI_ENVIRONMENT_VARIABLES,\n    PipSession,\n    user_agent,\n)\n\n\ndef get_user_agent() -> str:\n    # These tests are testing the computation of the user agent, so we want to\n    # avoid reusing cached values.\n    user_agent.cache_clear()\n    return PipSession().headers[\"User-Agent\"]\n\n\ndef test_user_agent() -> None:\n    user_agent = get_user_agent()\n\n    assert user_agent.startswith(f\"pip/{__version__}\")\n\n\n@pytest.mark.parametrize(\n    \"name, expected_like_ci\",\n    [\n        (\"BUILD_BUILDID\", True),\n        (\"BUILD_ID\", True),\n        (\"CI\", True),\n        (\"PIP_IS_CI\", True),\n        # Test a prefix substring of one of the variable names we use.\n        (\"BUILD\", False),\n    ],\n)\ndef test_user_agent__ci(\n    monkeypatch: pytest.MonkeyPatch, name: str, expected_like_ci: bool\n) -> None:\n    # Delete the variable names we use to check for CI to prevent the\n    # detection from always returning True in case the tests are being run\n    # under actual CI.  It is okay to depend on CI_ENVIRONMENT_VARIABLES\n    # here (part of the code under test) because this setup step can only\n    # prevent false test failures.  It can't cause a false test passage.\n    for ci_name in CI_ENVIRONMENT_VARIABLES:\n        monkeypatch.delenv(ci_name, raising=False)\n\n    # Confirm the baseline before setting the environment variable.\n    user_agent = get_user_agent()\n    assert '\"ci\":null' in user_agent\n    assert '\"ci\":true' not in user_agent\n\n    monkeypatch.setenv(name, \"true\")\n    user_agent = get_user_agent()\n    assert ('\"ci\":true' in user_agent) == expected_like_ci\n    assert ('\"ci\":null' in user_agent) == (not expected_like_ci)\n\n\ndef test_user_agent_user_data(monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setenv(\"PIP_USER_AGENT_USER_DATA\", \"some_string\")\n    assert \"some_string\" in get_user_agent()\n\n\nclass TestPipSession:\n    def test_cache_defaults_off(self) -> None:\n        session = PipSession()\n\n        assert not hasattr(session.adapters[\"http://\"], \"cache\")\n        assert not hasattr(session.adapters[\"https://\"], \"cache\")\n\n    def test_cache_is_enabled(self, tmpdir: Path) -> None:\n        cache_directory = os.fspath(tmpdir.joinpath(\"test-cache\"))\n        session = PipSession(cache=cache_directory)\n\n        assert hasattr(session.adapters[\"https://\"], \"cache\")\n\n        assert session.adapters[\"https://\"].cache.directory == cache_directory\n\n    def test_http_cache_is_not_enabled(self, tmpdir: Path) -> None:\n        session = PipSession(cache=os.fspath(tmpdir.joinpath(\"test-cache\")))\n\n        assert not hasattr(session.adapters[\"http://\"], \"cache\")\n\n    def test_trusted_hosts_adapter(self, tmpdir: Path) -> None:\n        session = PipSession(\n            cache=os.fspath(tmpdir.joinpath(\"test-cache\")),\n            trusted_hosts=[\"example.com\"],\n        )\n\n        assert \"https://example.com/\" in session.adapters\n        # Check that the \"port wildcard\" is present.\n        assert \"https://example.com:\" in session.adapters\n        # Check that the cache is enabled.\n        assert hasattr(session.adapters[\"http://example.com/\"], \"cache\")\n        assert hasattr(session.adapters[\"https://example.com/\"], \"cache\")\n\n    def test_add_trusted_host(self) -> None:\n        # Leave a gap to test how the ordering is affected.\n        trusted_hosts = [\"host1\", \"host3\"]\n        session = PipSession(trusted_hosts=trusted_hosts)\n        trusted_host_adapter = session._trusted_host_adapter\n        prefix2 = \"https://host2/\"\n        prefix3 = \"https://host3/\"\n        prefix3_wildcard = \"https://host3:\"\n\n        prefix2_http = \"http://host2/\"\n        prefix3_http = \"http://host3/\"\n        prefix3_wildcard_http = \"http://host3:\"\n\n        # Confirm some initial conditions as a baseline.\n        assert session.pip_trusted_origins == [(\"host1\", None), (\"host3\", None)]\n        assert session.adapters[prefix3] is trusted_host_adapter\n        assert session.adapters[prefix3_wildcard] is trusted_host_adapter\n\n        assert session.adapters[prefix3_http] is trusted_host_adapter\n        assert session.adapters[prefix3_wildcard_http] is trusted_host_adapter\n\n        assert prefix2 not in session.adapters\n        assert prefix2_http not in session.adapters\n\n        # Test adding a new host.\n        session.add_trusted_host(\"host2\")\n        assert session.pip_trusted_origins == [\n            (\"host1\", None),\n            (\"host3\", None),\n            (\"host2\", None),\n        ]\n        # Check that prefix3 is still present.\n        assert session.adapters[prefix3] is trusted_host_adapter\n        assert session.adapters[prefix2] is trusted_host_adapter\n        assert session.adapters[prefix2_http] is trusted_host_adapter\n\n        # Test that adding the same host doesn't create a duplicate.\n        session.add_trusted_host(\"host3\")\n        assert session.pip_trusted_origins == [\n            (\"host1\", None),\n            (\"host3\", None),\n            (\"host2\", None),\n        ], f\"actual: {session.pip_trusted_origins}\"\n\n        session.add_trusted_host(\"host4:8080\")\n        prefix4 = \"https://host4:8080/\"\n        prefix4_http = \"http://host4:8080/\"\n        assert session.pip_trusted_origins == [\n            (\"host1\", None),\n            (\"host3\", None),\n            (\"host2\", None),\n            (\"host4\", 8080),\n        ]\n        assert session.adapters[prefix4] is trusted_host_adapter\n        assert session.adapters[prefix4_http] is trusted_host_adapter\n\n    def test_add_trusted_host__logging(self, caplog: pytest.LogCaptureFixture) -> None:\n        \"\"\"\n        Test logging when add_trusted_host() is called.\n        \"\"\"\n        trusted_hosts = [\"host0\", \"host1\"]\n        session = PipSession(trusted_hosts=trusted_hosts)\n        with caplog.at_level(logging.INFO):\n            # Test adding an existing host.\n            session.add_trusted_host(\"host1\", source=\"somewhere\")\n            session.add_trusted_host(\"host2\")\n            # Test calling add_trusted_host() on the same host twice.\n            session.add_trusted_host(\"host2\")\n\n        actual = [(r.levelname, r.message) for r in caplog.records]\n        # Observe that \"host0\" isn't included in the logs.\n        expected = [\n            (\"INFO\", \"adding trusted host: 'host1' (from somewhere)\"),\n            (\"INFO\", \"adding trusted host: 'host2'\"),\n            (\"INFO\", \"adding trusted host: 'host2'\"),\n        ]\n        assert actual == expected\n\n    def test_iter_secure_origins(self) -> None:\n        trusted_hosts = [\"host1\", \"host2\", \"host3:8080\"]\n        session = PipSession(trusted_hosts=trusted_hosts)\n\n        actual = list(session.iter_secure_origins())\n        assert len(actual) == 9\n        # Spot-check that SECURE_ORIGINS is included.\n        assert actual[0] == (\"https\", \"*\", \"*\")\n        assert actual[-3:] == [\n            (\"*\", \"host1\", \"*\"),\n            (\"*\", \"host2\", \"*\"),\n            (\"*\", \"host3\", 8080),\n        ]\n\n    def test_iter_secure_origins__trusted_hosts_empty(self) -> None:\n        \"\"\"\n        Test iter_secure_origins() after passing trusted_hosts=[].\n        \"\"\"\n        session = PipSession(trusted_hosts=[])\n\n        actual = list(session.iter_secure_origins())\n        assert len(actual) == 6\n        # Spot-check that SECURE_ORIGINS is included.\n        assert actual[0] == (\"https\", \"*\", \"*\")\n\n    @pytest.mark.parametrize(\n        \"location, trusted, expected\",\n        [\n            (\"http://pypi.org/something\", [], False),\n            (\"https://pypi.org/something\", [], True),\n            (\"git+http://pypi.org/something\", [], False),\n            (\"git+https://pypi.org/something\", [], True),\n            (\"git+ssh://git@pypi.org/something\", [], True),\n            (\"http://localhost\", [], True),\n            (\"http://127.0.0.1\", [], True),\n            (\"http://example.com/something/\", [], False),\n            (\"http://example.com/something/\", [\"example.com\"], True),\n            # Try changing the case.\n            (\"http://eXample.com/something/\", [\"example.cOm\"], True),\n            # Test hosts with port.\n            (\"http://example.com:8080/something/\", [\"example.com\"], True),\n            # Test a trusted_host with a port.\n            (\"http://example.com:8080/something/\", [\"example.com:8080\"], True),\n            (\"http://example.com/something/\", [\"example.com:8080\"], False),\n            (\"http://example.com:8888/something/\", [\"example.com:8080\"], False),\n        ],\n    )\n    def test_is_secure_origin(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        location: str,\n        trusted: list[str],\n        expected: bool,\n    ) -> None:\n        class MockLogger:\n            def __init__(self) -> None:\n                self.called = False\n\n            def warning(self, *args: Any, **kwargs: Any) -> None:\n                self.called = True\n\n        session = PipSession(trusted_hosts=trusted)\n        actual = session.is_secure_origin(Link(location))\n        assert actual == expected\n\n        log_records = [(r.levelname, r.message) for r in caplog.records]\n        if expected:\n            assert not log_records\n            return\n\n        assert len(log_records) == 1\n        actual_level, actual_message = log_records[0]\n        assert actual_level == \"WARNING\"\n        assert \"is not a trusted or secure host\" in actual_message\n\n    @pytest.mark.network\n    def test_proxy(self, proxy: str | None) -> None:\n        session = PipSession(trusted_hosts=[])\n\n        if not proxy:\n            # if user didn't pass --proxy then try to get it from the system.\n            env_proxy = getproxies().get(\"http\", None)\n            proxy = urlparse(env_proxy).netloc if env_proxy else None\n\n        if proxy:\n            # set proxy scheme to session.proxies\n            session.proxies = {\n                \"http\": f\"{proxy}\",\n                \"https\": f\"{proxy}\",\n                \"ftp\": f\"{proxy}\",\n            }\n\n        connection_error = None\n        try:\n            session.request(\"GET\", \"https://pypi.org\", timeout=1)\n        except requests.exceptions.ConnectionError as e:\n            connection_error = e\n\n        assert connection_error is None, (\n            f\"Invalid proxy {proxy} or session.proxies: \"\n            f\"{session.proxies} is not correctly passed to session.request.\"\n        )\n"
  },
  {
    "path": "tests/unit/test_network_utils.py",
    "content": "import pytest\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.network.utils import raise_for_status\n\nfrom tests.lib.requests_mocks import MockResponse\n\n\n@pytest.mark.parametrize(\n    \"status_code, error_type\",\n    [\n        (401, \"Client Error\"),\n        (501, \"Server Error\"),\n    ],\n)\ndef test_raise_for_status_raises_exception(status_code: int, error_type: str) -> None:\n    contents = b\"downloaded\"\n    resp = MockResponse(contents)\n    resp.status_code = status_code\n    resp.url = \"http://www.example.com/whatever.tgz\"\n    resp.reason = \"Network Error\"\n    with pytest.raises(NetworkConnectionError) as excinfo:\n        raise_for_status(resp)\n    assert str(excinfo.value) == (\n        f\"{status_code} {error_type}: Network Error for url:\"\n        \" http://www.example.com/whatever.tgz\"\n    )\n\n\ndef test_raise_for_status_does_not_raises_exception() -> None:\n    contents = b\"downloaded\"\n    resp = MockResponse(contents)\n    resp.status_code = 201\n    resp.url = \"http://www.example.com/whatever.tgz\"\n    resp.reason = \"No error\"\n    raise_for_status(resp)\n"
  },
  {
    "path": "tests/unit/test_operations_prepare.py",
    "content": "import os\nimport shutil\nfrom pathlib import Path\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\nfrom typing import Any\nfrom unittest.mock import Mock, patch\n\nimport pytest\n\nfrom pip._internal.exceptions import HashMismatch\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.download import Downloader\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.prepare import unpack_url\nfrom pip._internal.utils.hashes import Hashes\n\nfrom tests.lib import TestData\nfrom tests.lib.requests_mocks import MockResponse\n\n\ndef test_unpack_url_with_urllib_response_without_content_type(data: TestData) -> None:\n    \"\"\"\n    It should download and unpack files even if no Content-Type header exists\n    \"\"\"\n    _real_session = PipSession()\n\n    def _fake_session_get(*args: Any, **kwargs: Any) -> dict[str, str]:\n        resp = _real_session.get(*args, **kwargs)\n        del resp.headers[\"Content-Type\"]\n        return resp\n\n    session = Mock()\n    session.resume_retries = 0\n    session.get = _fake_session_get\n    download = Downloader(session, progress_bar=\"on\")\n\n    uri = data.packages.joinpath(\"simple-1.0.tar.gz\").as_uri()\n    link = Link(uri)\n    temp_dir = mkdtemp()\n    try:\n        unpack_url(\n            link,\n            temp_dir,\n            download=download,\n            download_dir=None,\n            verbosity=0,\n        )\n        assert set(os.listdir(temp_dir)) == {\n            \"PKG-INFO\",\n            \"setup.cfg\",\n            \"setup.py\",\n            \"simple\",\n            \"simple.egg-info\",\n        }\n    finally:\n        rmtree(temp_dir)\n\n\n@patch(\"pip._internal.network.download.raise_for_status\")\ndef test_download_http_url__no_directory_traversal(\n    mock_raise_for_status: Mock, tmpdir: Path\n) -> None:\n    \"\"\"\n    Test that directory traversal doesn't happen on download when the\n    Content-Disposition header contains a filename with a \"..\" path part.\n    \"\"\"\n    mock_url = \"http://www.example.com/whatever.tgz\"\n    contents = b\"downloaded\"\n    link = Link(mock_url)\n\n    session = Mock()\n    session.resume_retries = 0\n    resp = MockResponse(contents)\n    resp.url = mock_url\n    resp.headers = {\n        # Set the content-type to a random value to prevent\n        # mimetypes.guess_extension from guessing the extension.\n        \"content-type\": \"random\",\n        \"content-disposition\": 'attachment;filename=\"../out_dir_file\"',\n    }\n    session.get.return_value = resp\n    download = Downloader(session, progress_bar=\"on\")\n\n    download_dir = os.fspath(tmpdir.joinpath(\"download\"))\n    os.mkdir(download_dir)\n    file_path, content_type = download(link, download_dir)\n    # The file should be downloaded to download_dir.\n    actual = os.listdir(download_dir)\n    assert actual == [\"out_dir_file\"]\n    mock_raise_for_status.assert_called_once_with(resp)\n\n\n@pytest.fixture\ndef clean_project(tmpdir_factory: pytest.TempPathFactory, data: TestData) -> Path:\n    tmpdir = tmpdir_factory.mktemp(\"clean_project\")\n    new_project_dir = tmpdir.joinpath(\"FSPkg\")\n    path = data.packages.joinpath(\"FSPkg\")\n    shutil.copytree(path, new_project_dir)\n    return new_project_dir\n\n\nclass Test_unpack_url:\n    def prep(self, tmpdir: Path, data: TestData) -> None:\n        self.build_dir = os.fspath(tmpdir.joinpath(\"build\"))\n        self.download_dir = tmpdir.joinpath(\"download\")\n        os.mkdir(self.build_dir)\n        os.mkdir(self.download_dir)\n        self.dist_file = \"simple-1.0.tar.gz\"\n        self.dist_file2 = \"simple-2.0.tar.gz\"\n        self.dist_path = data.packages.joinpath(self.dist_file)\n        self.dist_path2 = data.packages.joinpath(self.dist_file2)\n        self.dist_url = Link(self.dist_path.as_uri())\n        self.dist_url2 = Link(self.dist_path2.as_uri())\n        self.no_download = Mock(side_effect=AssertionError)\n\n    def test_unpack_url_no_download(self, tmpdir: Path, data: TestData) -> None:\n        self.prep(tmpdir, data)\n        unpack_url(self.dist_url, self.build_dir, self.no_download, verbosity=0)\n        assert os.path.isdir(os.path.join(self.build_dir, \"simple\"))\n        assert not os.path.isfile(os.path.join(self.download_dir, self.dist_file))\n\n    def test_unpack_url_bad_hash(self, tmpdir: Path, data: TestData) -> None:\n        \"\"\"\n        Test when the file url hash fragment is wrong\n        \"\"\"\n        self.prep(tmpdir, data)\n        url = f\"{self.dist_url.url}#md5=bogus\"\n        dist_url = Link(url)\n        with pytest.raises(HashMismatch):\n            unpack_url(\n                dist_url,\n                self.build_dir,\n                download=self.no_download,\n                hashes=Hashes({\"md5\": [\"bogus\"]}),\n                verbosity=0,\n            )\n"
  },
  {
    "path": "tests/unit/test_options.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom optparse import Values\nfrom tempfile import NamedTemporaryFile\nfrom typing import Any, cast\n\nimport pytest\n\nimport pip._internal.configuration\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.main import main\nfrom pip._internal.commands import create_command\nfrom pip._internal.commands.configuration import ConfigurationCommand\nfrom pip._internal.exceptions import CommandError, PipError\n\nfrom tests.lib.options_helpers import AddFakeCommandMixin\n\n\n@contextmanager\ndef assert_option_error(\n    capsys: pytest.CaptureFixture[str], expected: str\n) -> Iterator[None]:\n    \"\"\"\n    Assert that a SystemExit occurred because of a parsing error.\n\n    Args:\n      expected: an expected substring of stderr.\n    \"\"\"\n    with pytest.raises(SystemExit) as excinfo:\n        yield\n\n    assert excinfo.value.code == 2\n    stderr = capsys.readouterr().err\n    assert expected in stderr\n\n\ndef assert_is_default_cache_dir(value: str) -> None:\n    # This path looks different on different platforms, but the path always\n    # has the substring \"pip\".\n    assert \"pip\" in value\n\n\nclass TestOptionPrecedence(AddFakeCommandMixin):\n    \"\"\"\n    Tests for confirming our option precedence:\n        cli -> environment -> subcommand config -> global config -> option\n        defaults\n    \"\"\"\n\n    def get_config_section(self, section: str) -> list[tuple[str, str]]:\n        config = {\n            \"global\": [(\"timeout\", \"-3\")],\n            \"fake\": [(\"timeout\", \"-2\")],\n        }\n        return config[section]\n\n    def get_config_section_global(self, section: str) -> list[tuple[str, str]]:\n        config: dict[str, list[tuple[str, str]]] = {\n            \"global\": [(\"timeout\", \"-3\")],\n            \"fake\": [],\n        }\n        return config[section]\n\n    def test_env_override_default_int(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        \"\"\"\n        Test that environment variable overrides an int option default.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_TIMEOUT\", \"-1\")\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert options.timeout == -1\n\n    @pytest.mark.parametrize(\"values\", [[\"F1\"], [\"F1\", \"F2\"]])\n    def test_env_override_default_append(\n        self, values: list[str], monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test that environment variable overrides an append option default.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_FIND_LINKS\", \" \".join(values))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert options.find_links == values\n\n    @pytest.mark.parametrize(\"choices\", [[\"w\"], [\"s\", \"w\"]])\n    def test_env_override_default_choice(\n        self, choices: list[str], monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test that environment variable overrides a choice option default.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_EXISTS_ACTION\", \" \".join(choices))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert options.exists_action == choices\n\n    @pytest.mark.parametrize(\"name\", [\"PIP_LOG_FILE\", \"PIP_LOCAL_LOG\"])\n    def test_env_alias_override_default(\n        self, name: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        When an option has multiple long forms, test that the technique of\n        using the env variable, \"PIP_<long form>\" works for all cases.\n        (e.g. PIP_LOG_FILE and PIP_LOCAL_LOG should all work)\n        \"\"\"\n        monkeypatch.setenv(name, \"override.log\")\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert options.log == \"override.log\"\n\n    def test_cli_override_environment(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        \"\"\"\n        Test the cli overrides and environment variable\n        \"\"\"\n        monkeypatch.setenv(\"PIP_TIMEOUT\", \"-1\")\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--timeout\", \"-2\"])\n        )\n        assert options.timeout == -2\n\n    @pytest.mark.parametrize(\n        \"pip_no_cache_dir\",\n        [\n            # Enabling --no-cache-dir means no cache directory.\n            \"1\",\n            \"true\",\n            \"on\",\n            \"yes\",\n            # For historical / backwards compatibility reasons, we also disable\n            # the cache directory if provided a value that translates to 0.\n            \"0\",\n            \"false\",\n            \"off\",\n            \"no\",\n        ],\n    )\n    def test_cache_dir__PIP_NO_CACHE_DIR(\n        self, pip_no_cache_dir: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test setting the PIP_NO_CACHE_DIR environment variable without\n        passing any command-line flags.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_NO_CACHE_DIR\", pip_no_cache_dir)\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert options.cache_dir is False\n\n    @pytest.mark.parametrize(\"pip_no_cache_dir\", [\"yes\", \"no\"])\n    def test_cache_dir__PIP_NO_CACHE_DIR__with_cache_dir(\n        self,\n        pip_no_cache_dir: str,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        \"\"\"\n        Test setting PIP_NO_CACHE_DIR while also passing an explicit\n        --cache-dir value.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_NO_CACHE_DIR\", pip_no_cache_dir)\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--cache-dir\", \"/cache/dir\", \"fake\"])\n        )\n        # The command-line flag takes precedence.\n        assert options.cache_dir == \"/cache/dir\"\n\n    @pytest.mark.parametrize(\"pip_no_cache_dir\", [\"yes\", \"no\"])\n    def test_cache_dir__PIP_NO_CACHE_DIR__with_no_cache_dir(\n        self,\n        pip_no_cache_dir: str,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        \"\"\"\n        Test setting PIP_NO_CACHE_DIR while also passing --no-cache-dir.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_NO_CACHE_DIR\", pip_no_cache_dir)\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"--no-cache-dir\", \"fake\"]))\n        # The command-line flag should take precedence (which has the same\n        # value in this case).\n        assert options.cache_dir is False\n\n    def test_cache_dir__PIP_NO_CACHE_DIR_invalid__with_no_cache_dir(\n        self,\n        monkeypatch: pytest.MonkeyPatch,\n        capsys: pytest.CaptureFixture[str],\n    ) -> None:\n        \"\"\"\n        Test setting PIP_NO_CACHE_DIR to an invalid value while also passing\n        --no-cache-dir.\n        \"\"\"\n        monkeypatch.setenv(\"PIP_NO_CACHE_DIR\", \"maybe\")\n        expected_err = \"--no-cache-dir error: invalid truth value 'maybe'\"\n        with assert_option_error(capsys, expected=expected_err):\n            main([\"--no-cache-dir\", \"fake\"])\n\n\nclass TestOptionsInterspersed(AddFakeCommandMixin):\n    def test_general_option_after_subcommand(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--timeout\", \"-1\"])\n        )\n        assert options.timeout == -1\n\n    def test_option_after_subcommand_arg(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"fake\", \"arg\", \"--timeout\", \"-1\"])\n        )\n        assert options.timeout == -1\n\n    def test_additive_before_after_subcommand(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"-v\", \"fake\", \"-v\"]))\n        assert options.verbose == 2\n\n    def test_subcommand_option_before_subcommand_fails(self) -> None:\n        with pytest.raises(SystemExit):\n            main([\"--find-links\", \"F1\", \"fake\"])\n\n\n@contextmanager\ndef tmpconfig(option: str, value: Any, section: str = \"global\") -> Iterator[str]:\n    with NamedTemporaryFile(mode=\"w\", delete=False) as f:\n        f.write(f\"[{section}]\\n{option}={value}\\n\")\n        name = f.name\n    try:\n        yield name\n    finally:\n        os.unlink(name)\n\n\nclass TestCountOptions(AddFakeCommandMixin):\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(4))\n    def test_cli_long(self, option: str, value: int) -> None:\n        flags = [f\"--{option}\"] * value\n        # FakeCommand intentionally returns the wrong type.\n        opt1, args1 = cast(tuple[Values, list[str]], main(flags + [\"fake\"]))\n        opt2, args2 = cast(tuple[Values, list[str]], main([\"fake\"] + flags))\n        assert getattr(opt1, option) == getattr(opt2, option) == value\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(1, 4))\n    def test_cli_short(self, option: str, value: int) -> None:\n        flag = \"-\" + option[0] * value\n        # FakeCommand intentionally returns the wrong type.\n        opt1, args1 = cast(tuple[Values, list[str]], main([flag, \"fake\"]))\n        opt2, args2 = cast(tuple[Values, list[str]], main([\"fake\", flag]))\n        assert getattr(opt1, option) == getattr(opt2, option) == value\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(4))\n    def test_env_var(\n        self, option: str, value: int, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PIP_\" + option.upper(), str(value))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert getattr(options, option) == value\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(3))\n    def test_env_var_integrate_cli(\n        self, option: str, value: int, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PIP_\" + option.upper(), str(value))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\", \"--\" + option]))\n        assert getattr(options, option) == value + 1\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [-1, \"foobar\"])\n    def test_env_var_invalid(\n        self,\n        option: str,\n        value: Any,\n        monkeypatch: pytest.MonkeyPatch,\n        capsys: pytest.CaptureFixture[str],\n    ) -> None:\n        monkeypatch.setenv(\"PIP_\" + option.upper(), str(value))\n        with assert_option_error(capsys, expected=\"a non-negative integer\"):\n            main([\"fake\"])\n\n    # Undocumented, support for backward compatibility\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [\"no\", \"false\"])\n    def test_env_var_false(\n        self, option: str, value: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PIP_\" + option.upper(), str(value))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert getattr(options, option) == 0\n\n    # Undocumented, support for backward compatibility\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [\"yes\", \"true\"])\n    def test_env_var_true(\n        self, option: str, value: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PIP_\" + option.upper(), str(value))\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        assert getattr(options, option) == 1\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(4))\n    def test_config_file(\n        self, option: str, value: int, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        with tmpconfig(option, value) as name:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", name)\n            # FakeCommand intentionally returns the wrong type.\n            options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n            assert getattr(options, option) == value\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", range(3))\n    def test_config_file_integrate_cli(\n        self, option: str, value: int, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        with tmpconfig(option, value) as name:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", name)\n            # FakeCommand intentionally returns the wrong type.\n            options, args = cast(\n                tuple[Values, list[str]], main([\"fake\", \"--\" + option])\n            )\n            assert getattr(options, option) == value + 1\n\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [-1, \"foobar\"])\n    def test_config_file_invalid(\n        self,\n        option: str,\n        value: Any,\n        monkeypatch: pytest.MonkeyPatch,\n        capsys: pytest.CaptureFixture[str],\n    ) -> None:\n        with tmpconfig(option, value) as name:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", name)\n            with assert_option_error(capsys, expected=\"non-negative integer\"):\n                main([\"fake\"])\n\n    # Undocumented, support for backward compatibility\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [\"no\", \"false\"])\n    def test_config_file_false(\n        self, option: str, value: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        with tmpconfig(option, value) as name:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", name)\n            # FakeCommand intentionally returns the wrong type.\n            options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n            assert getattr(options, option) == 0\n\n    # Undocumented, support for backward compatibility\n    @pytest.mark.parametrize(\"option\", [\"verbose\", \"quiet\"])\n    @pytest.mark.parametrize(\"value\", [\"yes\", \"true\"])\n    def test_config_file_true(\n        self, option: str, value: str, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        with tmpconfig(option, value) as name:\n            monkeypatch.setenv(\"PIP_CONFIG_FILE\", name)\n            # FakeCommand intentionally returns the wrong type.\n            options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n            assert getattr(options, option) == 1\n\n\nclass TestGeneralOptions(AddFakeCommandMixin):\n    # the reason to specifically test general options is due to the\n    # extra processing they receive, and the number of bugs we've had\n\n    def test_cache_dir__default(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"fake\"]))\n        # With no options the default cache dir should be used.\n        assert_is_default_cache_dir(options.cache_dir)\n\n    def test_cache_dir__provided(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--cache-dir\", \"/cache/dir\", \"fake\"])\n        )\n        assert options.cache_dir == \"/cache/dir\"\n\n    def test_no_cache_dir__provided(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(tuple[Values, list[str]], main([\"--no-cache-dir\", \"fake\"]))\n        assert options.cache_dir is False\n\n    def test_require_virtualenv(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--require-virtualenv\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--require-virtualenv\"])\n        )\n        assert options1.require_venv\n        assert options2.require_venv\n\n    def test_log(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--log\", \"path\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--log\", \"path\"])\n        )\n        assert options1.log == options2.log == \"path\"\n\n    def test_local_log(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--local-log\", \"path\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--local-log\", \"path\"])\n        )\n        assert options1.log == options2.log == \"path\"\n\n    def test_no_input(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(tuple[Values, list[str]], main([\"--no-input\", \"fake\"]))\n        options2, args2 = cast(tuple[Values, list[str]], main([\"fake\", \"--no-input\"]))\n        assert options1.no_input\n        assert options2.no_input\n\n    def test_proxy(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--proxy\", \"path\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--proxy\", \"path\"])\n        )\n        assert options1.proxy == options2.proxy == \"path\"\n\n    def test_retries(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--retries\", \"-1\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--retries\", \"-1\"])\n        )\n        assert options1.retries == options2.retries == -1\n\n    def test_timeout(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--timeout\", \"-1\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--timeout\", \"-1\"])\n        )\n        assert options1.timeout == options2.timeout == -1\n\n    def test_exists_action(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--exists-action\", \"w\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--exists-action\", \"w\"])\n        )\n        assert options1.exists_action == options2.exists_action == [\"w\"]\n\n    def test_cert(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--cert\", \"path\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--cert\", \"path\"])\n        )\n        assert options1.cert == options2.cert == \"path\"\n\n    def test_client_cert(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options1, args1 = cast(\n            tuple[Values, list[str]], main([\"--client-cert\", \"path\", \"fake\"])\n        )\n        options2, args2 = cast(\n            tuple[Values, list[str]], main([\"fake\", \"--client-cert\", \"path\"])\n        )\n        assert options1.client_cert == options2.client_cert == \"path\"\n\n\nclass TestOptionsConfigFiles:\n    def test_venv_config_file_found(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        # strict limit on the global config files list\n        monkeypatch.setattr(\n            pip._internal.utils.appdirs, \"site_config_dirs\", lambda _: [\"/a/place\"]\n        )\n\n        cp = pip._internal.configuration.Configuration(isolated=False)\n\n        files = []\n        for _, val in cp.iter_config_files():\n            files.extend(val)\n\n        assert len(files) == 4\n\n    @pytest.mark.parametrize(\n        \"args, expect\",\n        [\n            ([], None),\n            ([\"--global\"], \"global\"),\n            ([\"--site\"], \"site\"),\n            ([\"--user\"], \"user\"),\n            ([\"--global\", \"--user\"], PipError),\n            ([\"--global\", \"--site\"], PipError),\n            ([\"--global\", \"--site\", \"--user\"], PipError),\n        ],\n    )\n    def test_config_file_options(\n        self,\n        monkeypatch: pytest.MonkeyPatch,\n        args: list[str],\n        expect: None | str | type[PipError],\n    ) -> None:\n        cmd = cast(ConfigurationCommand, create_command(\"config\"))\n        # Replace a handler with a no-op to avoid side effects\n        monkeypatch.setattr(cmd, \"get_name\", lambda *a: None)\n\n        options, args = cmd.parser.parse_args(args + [\"get\", \"name\"])\n        if expect is PipError:\n            with pytest.raises(PipError):\n                cmd._determine_file(options, need_value=False)\n        else:\n            assert expect == cmd._determine_file(options, need_value=False)\n\n\nclass TestOptionsExpandUser(AddFakeCommandMixin):\n    def test_cache_dir(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--cache-dir\", \"~/cache/dir\", \"fake\"])\n        )\n        assert options.cache_dir == os.path.expanduser(\"~/cache/dir\")\n\n    def test_log(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--log\", \"~/path\", \"fake\"])\n        )\n        assert options.log == os.path.expanduser(\"~/path\")\n\n    def test_local_log(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--local-log\", \"~/path\", \"fake\"])\n        )\n        assert options.log == os.path.expanduser(\"~/path\")\n\n    def test_cert(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--cert\", \"~/path\", \"fake\"])\n        )\n        assert options.cert == os.path.expanduser(\"~/path\")\n\n    def test_client_cert(self) -> None:\n        # FakeCommand intentionally returns the wrong type.\n        options, args = cast(\n            tuple[Values, list[str]], main([\"--client-cert\", \"~/path\", \"fake\"])\n        )\n        assert options.client_cert == os.path.expanduser(\"~/path\")\n\n\nclass TestReleaseControlOptions:\n    \"\"\"Tests for --all-releases and --only-final options.\"\"\"\n\n    def test_all_releases_and_only_final_together(self) -> None:\n        \"\"\"Test --all-releases and --only-final together (last wins).\"\"\"\n        # This should not fail - the mutual exclusion is only with --pre\n        # The behavior follows --no-binary and --only-binary pattern\n        cmd = create_command(\"install\")\n        options, args = cmd.parser.parse_args(\n            [\"--all-releases=pkg1\", \"--only-final=pkg2\", \"dummy-package\"]\n        )\n        # Both should be present in their respective sets\n        assert \"pkg1\" in options.release_control.all_releases\n        assert \"pkg2\" in options.release_control.only_final\n\n    def test_pre_transforms_to_all_releases(self) -> None:\n        \"\"\"Test that --pre is transformed into --all-releases :all:.\"\"\"\n        cmd = create_command(\"install\")\n        options, args = cmd.parser.parse_args([\"--pre\", \"dummy-package\"])\n\n        # Before transformation\n        assert options.pre is True\n        assert \":all:\" not in options.release_control.all_releases\n\n        # Apply transformation\n        cmdoptions.check_release_control_exclusive(options)\n\n        # After transformation\n        assert \":all:\" in options.release_control.all_releases\n\n    def test_check_release_control_exclusive_with_pre_and_all_releases(self) -> None:\n        \"\"\"Test that check raises CommandError when --pre used with --all-releases.\"\"\"\n        cmd = create_command(\"install\")\n        options, args = cmd.parser.parse_args(\n            [\"--pre\", \"--all-releases=pkg1\", \"dummy-package\"]\n        )\n\n        with pytest.raises(CommandError, match=\"--pre cannot be used with\"):\n            cmdoptions.check_release_control_exclusive(options)\n\n    def test_check_release_control_exclusive_with_pre_and_only_final(self) -> None:\n        \"\"\"Test that check raises CommandError when --pre used with --only-final.\"\"\"\n        cmd = create_command(\"install\")\n        options, args = cmd.parser.parse_args(\n            [\"--pre\", \"--only-final=pkg1\", \"dummy-package\"]\n        )\n\n        with pytest.raises(CommandError, match=\"--pre cannot be used with\"):\n            cmdoptions.check_release_control_exclusive(options)\n\n    def test_check_release_control_exclusive_without_pre(self) -> None:\n        \"\"\"Test that check passes when --pre is not used.\"\"\"\n        cmd = create_command(\"install\")\n        options, args = cmd.parser.parse_args(\n            [\"--all-releases=pkg1\", \"--only-final=pkg2\", \"dummy-package\"]\n        )\n\n        # Should not raise\n        cmdoptions.check_release_control_exclusive(options)\n"
  },
  {
    "path": "tests/unit/test_packaging.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pip._vendor.packaging import specifiers\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.utils.packaging import check_requires_python, get_requirement\n\n\n@pytest.mark.parametrize(\n    \"version_info, requires_python, expected\",\n    [\n        ((3, 6, 5), \"== 3.6.4\", False),\n        ((3, 6, 5), \"== 3.6.5\", True),\n        ((3, 6, 5), None, True),\n    ],\n)\ndef test_check_requires_python(\n    version_info: tuple[int, int, int], requires_python: str | None, expected: bool\n) -> None:\n    actual = check_requires_python(requires_python, version_info)\n    assert actual == expected\n\n\ndef test_check_requires_python__invalid() -> None:\n    \"\"\"\n    Test an invalid Requires-Python value.\n    \"\"\"\n    with pytest.raises(specifiers.InvalidSpecifier):\n        check_requires_python(\"invalid\", (3, 6, 5))\n\n\ndef test_get_or_create_caching() -> None:\n    \"\"\"test caching of get_or_create requirement\"\"\"\n    teststr = \"affinegap==1.10\"\n    from_helper = get_requirement(teststr)\n    freshly_made = Requirement(teststr)\n\n    # Requirement doesn't have an equality operator (yet) so test\n    # equality of attribute for list of attributes\n    for iattr in [\"name\", \"url\", \"extras\", \"specifier\", \"marker\"]:\n        assert getattr(from_helper, iattr) == getattr(freshly_made, iattr)\n    assert get_requirement(teststr) is not Requirement(teststr)\n    assert get_requirement(teststr) is get_requirement(teststr)\n"
  },
  {
    "path": "tests/unit/test_pep517.py",
    "content": "import os\nfrom pathlib import Path\nfrom textwrap import dedent\n\nimport pytest\n\nfrom pip._internal.exceptions import InvalidPyProjectBuildRequires\nfrom pip._internal.req import InstallRequirement\n\n\n@pytest.mark.parametrize(\n    \"spec\", [(\"./foo\",), (\"git+https://example.com/pkg@dev#egg=myproj\",)]\n)\ndef test_pep517_parsing_checks_requirements(tmpdir: Path, spec: tuple[str]) -> None:\n    tmpdir.joinpath(\"pyproject.toml\").write_text(\n        dedent(\n            f\"\"\"\n            [build-system]\n            requires = [{spec[0]!r}]\n            build-backend = \"foo\"\n            \"\"\"\n        )\n    )\n    req = InstallRequirement(None, None)\n    req.source_dir = os.fspath(tmpdir)  # make req believe it has been unpacked\n\n    with pytest.raises(InvalidPyProjectBuildRequires) as e:\n        req.load_pyproject_toml()\n\n    error = e.value\n\n    assert str(req) in error.message\n    assert error.context\n    assert \"build-system.requires\" in error.context\n    assert \"contains an invalid requirement\" in error.context\n    assert error.hint_stmt\n    assert \"PEP 518\" in error.hint_stmt\n"
  },
  {
    "path": "tests/unit/test_pyproject_config.py",
    "content": "import pytest\n\nfrom pip._internal.commands import create_command\n\n\n@pytest.mark.parametrize(\n    \"command, expected\",\n    [\n        (\"install\", True),\n        (\"wheel\", True),\n        (\"freeze\", False),\n    ],\n)\ndef test_supports_config(command: str, expected: bool) -> None:\n    c = create_command(command)\n    options, _ = c.parse_args([])\n    assert hasattr(options, \"config_settings\") == expected\n\n\ndef test_set_config_value_true() -> None:\n    i = create_command(\"install\")\n    # Invalid argument exits with an error\n    with pytest.raises(SystemExit):\n        options, _ = i.parse_args([\"xxx\", \"--config-settings\", \"x\"])\n\n\ndef test_set_config_value() -> None:\n    i = create_command(\"install\")\n    options, _ = i.parse_args([\"xxx\", \"--config-settings\", \"x=hello\"])\n    assert options.config_settings == {\"x\": \"hello\"}\n\n\ndef test_set_config_empty_value() -> None:\n    i = create_command(\"install\")\n    options, _ = i.parse_args([\"xxx\", \"--config-settings\", \"x=\"])\n    assert options.config_settings == {\"x\": \"\"}\n\n\n@pytest.mark.parametrize(\n    \"passed, expected\",\n    [\n        ([\"x=hello\", \"x=world\"], {\"x\": [\"hello\", \"world\"]}),\n        ([\"x=hello\", \"x=world\", \"x=other\"], {\"x\": [\"hello\", \"world\", \"other\"]}),\n    ],\n)\ndef test_multiple_config_values(passed: list[str], expected: dict[str, str]) -> None:\n    i = create_command(\"install\")\n    options, _ = i.parse_args(\n        [\"xxx\", *(f\"--config-settings={option}\" for option in passed)]\n    )\n    assert options.config_settings == expected\n"
  },
  {
    "path": "tests/unit/test_release_control.py",
    "content": "from __future__ import annotations\n\nfrom optparse import Values\n\nimport pytest\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.models.release_control import ReleaseControl\n\n\nclass SimpleCommand(Command):\n    def __init__(self) -> None:\n        super().__init__(\"fake\", \"fake summary\")\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.all_releases())\n        self.cmd_opts.add_option(cmdoptions.only_final())\n\n    def run(self, options: Values, args: list[str]) -> int:\n        self.options = options\n        return SUCCESS\n\n\ndef test_all_releases_overrides() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--only-final=:all:\", \"--all-releases=fred\"])\n    release_control = ReleaseControl({\"fred\"}, {\":all:\"})\n    assert cmd.options.release_control == release_control\n\n\ndef test_only_final_overrides() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=:all:\", \"--only-final=fred\"])\n    release_control = ReleaseControl({\":all:\"}, {\"fred\"})\n    assert cmd.options.release_control == release_control\n\n\ndef test_none_resets() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=:all:\", \"--all-releases=:none:\"])\n    release_control = ReleaseControl(set(), set())\n    assert cmd.options.release_control == release_control\n\n\ndef test_none_preserves_other_side() -> None:\n    cmd = SimpleCommand()\n    cmd.main(\n        [\"fake\", \"--all-releases=:all:\", \"--only-final=fred\", \"--all-releases=:none:\"]\n    )\n    release_control = ReleaseControl(set(), {\"fred\"})\n    assert cmd.options.release_control == release_control\n\n\ndef test_comma_separated_values() -> None:\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=pkg1,pkg2,pkg3\"])\n    release_control = ReleaseControl({\"pkg1\", \"pkg2\", \"pkg3\"}, set())\n    assert cmd.options.release_control == release_control\n\n\n@pytest.mark.parametrize(\n    \"all_releases,only_final,package,expected\",\n    [\n        # Package specifically in all_releases\n        ({\"fred\"}, set(), \"fred\", True),\n        # Package specifically in all_releases, even with :all: in only_final\n        ({\"fred\"}, {\":all:\"}, \"fred\", True),\n        # Package specifically in only_final\n        (set(), {\"fred\"}, \"fred\", False),\n        # Package specifically in only_final, even with :all: in all_releases\n        ({\":all:\"}, {\"fred\"}, \"fred\", False),\n        # No specific setting, :all: in all_releases\n        ({\":all:\"}, set(), \"fred\", True),\n        # No specific setting, :all: in only_final\n        (set(), {\":all:\"}, \"fred\", False),\n        # No specific setting at all\n        (set(), set(), \"fred\", None),\n    ],\n)\ndef test_allows_prereleases(\n    all_releases: set[str], only_final: set[str], package: str, expected: bool | None\n) -> None:\n    rc = ReleaseControl(all_releases, only_final)\n    assert rc.allows_prereleases(canonicalize_name(package)) == expected\n\n\ndef test_order_tracking_all_releases() -> None:\n    \"\"\"Test that order is tracked for --all-releases.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=pkg1\", \"--all-releases=pkg2\"])\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"all_releases\", \"pkg1\"),\n        (\"all_releases\", \"pkg2\"),\n    ]\n\n\ndef test_order_tracking_only_final() -> None:\n    \"\"\"Test that order is tracked for --only-final.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--only-final=pkg1\", \"--only-final=pkg2\"])\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"only_final\", \"pkg1\"),\n        (\"only_final\", \"pkg2\"),\n    ]\n\n\ndef test_order_tracking_mixed() -> None:\n    \"\"\"Test that order is tracked when mixing --all-releases and --only-final.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main(\n        [\n            \"fake\",\n            \"--all-releases=pkg1\",\n            \"--only-final=pkg2\",\n            \"--all-releases=pkg3\",\n        ]\n    )\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"all_releases\", \"pkg1\"),\n        (\"only_final\", \"pkg2\"),\n        (\"all_releases\", \"pkg3\"),\n    ]\n\n\ndef test_order_tracking_all_special() -> None:\n    \"\"\"Test that order is tracked for :all: special value.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=:all:\", \"--only-final=pkg1\"])\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"all_releases\", \":all:\"),\n        (\"only_final\", \"pkg1\"),\n    ]\n\n\ndef test_order_tracking_critical_case() -> None:\n    \"\"\"Test the critical case: --only-final=:all: --all-releases=pkg.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--only-final=:all:\", \"--all-releases=pkg1\"])\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    # The order should be preserved: only_final first, then all_releases\n    assert ordered_args == [\n        (\"only_final\", \":all:\"),\n        (\"all_releases\", \"pkg1\"),\n    ]\n\n\ndef test_order_tracking_none_reset() -> None:\n    \"\"\"Test that :none: is tracked in order.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main(\n        [\n            \"fake\",\n            \"--all-releases=:all:\",\n            \"--all-releases=:none:\",\n            \"--all-releases=pkg1\",\n        ]\n    )\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"all_releases\", \":all:\"),\n        (\"all_releases\", \":none:\"),\n        (\"all_releases\", \"pkg1\"),\n    ]\n\n\ndef test_order_tracking_comma_separated() -> None:\n    \"\"\"Test that comma-separated values are tracked individually.\"\"\"\n    cmd = SimpleCommand()\n    cmd.main([\"fake\", \"--all-releases=pkg1,pkg2,pkg3\"])\n\n    ordered_args = cmd.options.release_control.get_ordered_args()\n    assert ordered_args == [\n        (\"all_releases\", \"pkg1\"),\n        (\"all_releases\", \"pkg2\"),\n        (\"all_releases\", \"pkg3\"),\n    ]\n"
  },
  {
    "path": "tests/unit/test_req.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport email.message\nimport os\nimport shutil\nimport sys\nimport tempfile\nfrom collections.abc import Iterator\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import cast\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.markers import Marker\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.build_env import SubprocessBuildEnvironmentInstaller\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.commands import create_command\nfrom pip._internal.commands.install import InstallCommand\nfrom pip._internal.exceptions import (\n    HashErrors,\n    InstallationError,\n    InvalidWheelFilename,\n    PreviousBuildDirError,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req import InstallRequirement, RequirementSet\nfrom pip._internal.req.constructors import (\n    _get_url_from_path,\n    _looks_like_path,\n    install_req_drop_extras,\n    install_req_extend_extras,\n    install_req_from_editable,\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n    install_req_from_req_string,\n    parse_editable,\n)\nfrom pip._internal.req.req_file import (\n    ParsedLine,\n    get_line_parser,\n    handle_requirement_line,\n)\nfrom pip._internal.resolution.legacy.resolver import Resolver\nfrom pip._internal.utils.urls import path_to_url\n\nfrom tests.lib import TestData, make_test_finder, requirements_file, wheel\n\n\ndef get_processed_req_from_line(\n    line: str, fname: str = \"file\", lineno: int = 1\n) -> InstallRequirement:\n    line_parser = get_line_parser(None)\n    args_str, opts = line_parser(line)\n    parsed_line = ParsedLine(\n        fname,\n        lineno,\n        args_str,\n        opts,\n        False,\n    )\n    parsed_req = handle_requirement_line(parsed_line)\n    assert parsed_req is not None\n    req = install_req_from_parsed_requirement(parsed_req)\n    req.user_supplied = True\n    return req\n\n\nclass TestRequirementSet:\n    \"\"\"RequirementSet tests\"\"\"\n\n    def setup_method(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n\n    def teardown_method(self) -> None:\n        shutil.rmtree(self.tempdir, ignore_errors=True)\n\n    @contextlib.contextmanager\n    def _basic_resolver(\n        self,\n        finder: PackageFinder,\n        require_hashes: bool = False,\n        wheel_cache: WheelCache | None = None,\n        build_isolation: bool = True,\n    ) -> Iterator[Resolver]:\n        make_install_req = partial(\n            install_req_from_req_string,\n            isolated=False,\n        )\n        session = PipSession()\n\n        with get_build_tracker() as tracker:\n            installer = SubprocessBuildEnvironmentInstaller(finder)\n            preparer = RequirementPreparer(\n                build_dir=os.path.join(self.tempdir, \"build\"),\n                src_dir=os.path.join(self.tempdir, \"src\"),\n                download_dir=None,\n                build_isolation=build_isolation,\n                build_isolation_installer=installer,\n                check_build_deps=False,\n                build_tracker=tracker,\n                session=session,\n                progress_bar=\"on\",\n                finder=finder,\n                require_hashes=require_hashes,\n                use_user_site=False,\n                lazy_wheel=False,\n                verbosity=0,\n                legacy_resolver=True,\n            )\n            yield Resolver(\n                preparer=preparer,\n                make_install_req=make_install_req,\n                finder=finder,\n                wheel_cache=wheel_cache,\n                use_user_site=False,\n                upgrade_strategy=\"to-satisfy-only\",\n                ignore_dependencies=False,\n                ignore_installed=False,\n                ignore_requires_python=False,\n                force_reinstall=False,\n            )\n\n    def test_no_reuse_existing_build_dir(self, data: TestData) -> None:\n        \"\"\"Test prepare_files raise exception with previous build dir\"\"\"\n\n        build_dir = os.path.join(self.tempdir, \"build\", \"simple\")\n        os.makedirs(build_dir)\n        with open(os.path.join(build_dir, \"setup.py\"), \"w\"):\n            pass\n        reqset = RequirementSet()\n        req = install_req_from_line(\"simple\")\n        req.user_supplied = True\n        reqset.add_named_requirement(req)\n        finder = make_test_finder(find_links=[data.find_links])\n        with self._basic_resolver(finder) as resolver:\n            with pytest.raises(\n                PreviousBuildDirError,\n                match=(\n                    r\"pip can't proceed with [\\s\\S]*{req}[\\s\\S]*{build_dir_esc}\".format(\n                        build_dir_esc=build_dir.replace(\"\\\\\", \"\\\\\\\\\"), req=req\n                    )\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_environment_marker_extras(self, data: TestData) -> None:\n        \"\"\"\n        Test that the environment marker extras are used with\n        non-wheel installs.\n        \"\"\"\n        reqset = RequirementSet()\n        req = install_req_from_editable(\n            os.fspath(data.packages.joinpath(\"LocalEnvironMarker\")),\n        )\n        req.user_supplied = True\n        reqset.add_unnamed_requirement(req)\n        finder = make_test_finder(find_links=[data.find_links])\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            reqset = resolver.resolve(reqset.all_requirements, True)\n        assert not reqset.has_requirement(\"simple\")\n\n    def test_missing_hash_with_require_hashes(self, data: TestData) -> None:\n        \"\"\"Setting --require-hashes explicitly should raise errors if hashes\n        are missing.\n        \"\"\"\n        reqset = RequirementSet()\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\"simple==1.0\", lineno=1)\n        )\n\n        finder = make_test_finder(find_links=[data.find_links])\n\n        with self._basic_resolver(finder, require_hashes=True) as resolver:\n            with pytest.raises(\n                HashErrors,\n                match=(\n                    r\"Hashes are required in --require-hashes mode, but they are \"\n                    r\"missing .*\\n\"\n                    r\"    simple==1.0 --hash=sha256:393043e672415891885c9a2a0929b1\"\n                    r\"af95fb866d6ca016b42d2e6ce53619b653$\"\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_missing_hash_with_require_hashes_in_reqs_file(\n        self, data: TestData, tmpdir: Path\n    ) -> None:\n        \"\"\"--require-hashes in a requirements file should make its way to the\n        RequirementSet.\n        \"\"\"\n        finder = make_test_finder(find_links=[data.find_links])\n        session = finder._link_collector.session\n        command = cast(InstallCommand, create_command(\"install\"))\n        with requirements_file(\"--require-hashes\", tmpdir) as reqs_file:\n            options, args = command.parse_args([\"-r\", os.fspath(reqs_file)])\n            command.get_requirements(args, options, finder, session)\n        assert options.require_hashes\n\n    def test_unsupported_hashes(self, data: TestData) -> None:\n        \"\"\"VCS and dir links should raise errors when --require-hashes is\n        on.\n\n        In addition, complaints about the type of requirement (VCS or dir)\n        should trump the presence or absence of a hash.\n\n        \"\"\"\n        reqset = RequirementSet()\n        reqset.add_unnamed_requirement(\n            get_processed_req_from_line(\n                \"git+git://github.com/pypa/pip-test-package --hash=sha256:123\",\n                lineno=1,\n            )\n        )\n        dir_path = data.packages.joinpath(\"FSPkg\")\n        reqset.add_unnamed_requirement(\n            get_processed_req_from_line(\n                path_to_url(str(dir_path)),\n                lineno=2,\n            )\n        )\n        finder = make_test_finder(find_links=[data.find_links])\n\n        with self._basic_resolver(finder, require_hashes=True) as resolver:\n            with pytest.raises(\n                HashErrors,\n                match=(\n                    r\"Can't verify hashes for these requirements because we don't \"\n                    r\"have a way to hash version control repositories:\\n\"\n                    r\"    git\\+git://github\\.com/pypa/pip-test-package \\(from -r \"\n                    r\"file \\(line 1\\)\\)\\n\"\n                    r\"Can't verify hashes for these file:// requirements because \"\n                    r\"they point to directories:\\n\"\n                    r\"    file://.*/data/packages/FSPkg \"\n                    r\"\\(from -r file \\(line 2\\)\\)\"\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_unpinned_hash_checking(self, data: TestData) -> None:\n        \"\"\"Make sure prepare_files() raises an error when a requirement is not\n        version-pinned in hash-checking mode.\n        \"\"\"\n        reqset = RequirementSet()\n        # Test that there must be exactly 1 specifier:\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\n                \"simple --hash=sha256:a90427ae31f5d1d0d7ec06ee97d9fcf2d0fc9a786985\"\n                \"250c1c83fd68df5911dd\",\n                lineno=1,\n            )\n        )\n        # Test that the operator must be ==:\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\n                \"simple2>1.0 --hash=sha256:3ad45e1e9aa48b4462af0\"\n                \"123f6a7e44a9115db1ef945d4d92c123dfe21815a06\",\n                lineno=2,\n            )\n        )\n        finder = make_test_finder(find_links=[data.find_links])\n        with self._basic_resolver(finder, require_hashes=True) as resolver:\n            with pytest.raises(\n                HashErrors,\n                # Make sure all failing requirements are listed:\n                match=(\n                    r\"versions pinned with ==. These do not:\\n\"\n                    r\"    simple .* \\(from -r file \\(line 1\\)\\)\\n\"\n                    r\"    simple2>1.0 .* \\(from -r file \\(line 2\\)\\)\"\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_hash_mismatch(self, data: TestData) -> None:\n        \"\"\"A hash mismatch should raise an error.\"\"\"\n        file_url = data.packages.joinpath(\"simple-1.0.tar.gz\").resolve().as_uri()\n        reqset = RequirementSet()\n        reqset.add_unnamed_requirement(\n            get_processed_req_from_line(\n                f\"{file_url} --hash=sha256:badbad\",\n                lineno=1,\n            )\n        )\n        finder = make_test_finder(find_links=[data.find_links])\n        with self._basic_resolver(finder, require_hashes=True) as resolver:\n            with pytest.raises(\n                HashErrors,\n                match=(\n                    r\"THESE PACKAGES DO NOT MATCH THE HASHES.*\\n\"\n                    r\"    file:///.*/data/packages/simple-1\\.0\\.tar\\.gz .*:\\n\"\n                    r\"        Expected sha256 badbad\\n\"\n                    r\"             Got        393043e672415891885c9a2a0929b1af95fb\"\n                    r\"866d6ca016b42d2e6ce53619b653$\"\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_unhashed_deps_on_require_hashes(self, data: TestData) -> None:\n        \"\"\"Make sure unhashed, unpinned, or otherwise unrepeatable\n        dependencies get complained about when --require-hashes is on.\"\"\"\n        reqset = RequirementSet()\n        finder = make_test_finder(find_links=[data.find_links])\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\n                \"TopoRequires2==0.0.1 \"  # requires TopoRequires\n                \"--hash=sha256:eaf9a01242c9f2f42cf2bd82a6a848cd\"\n                \"e3591d14f7896bdbefcf48543720c970\",\n                lineno=1,\n            )\n        )\n\n        with self._basic_resolver(\n            finder, require_hashes=True, build_isolation=False\n        ) as resolver:\n            with pytest.raises(\n                HashErrors,\n                match=(\n                    r\"In --require-hashes mode, all requirements must have their \"\n                    r\"versions pinned.*\\n\"\n                    r\"    TopoRequires from .*$\"\n                ),\n            ):\n                resolver.resolve(reqset.all_requirements, True)\n\n    def test_hashed_deps_on_require_hashes(self) -> None:\n        \"\"\"Make sure hashed dependencies get installed when --require-hashes\n        is on.\n\n        (We actually just check that no \"not all dependencies are hashed!\"\n        error gets raised while preparing; there is no reason to expect\n        installation to then fail, as the code paths are the same as ever.)\n\n        \"\"\"\n        reqset = RequirementSet()\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\n                \"TopoRequires2==0.0.1 \"  # requires TopoRequires\n                \"--hash=sha256:eaf9a01242c9f2f42cf2bd82a6a848cd\"\n                \"e3591d14f7896bdbefcf48543720c970\",\n                lineno=1,\n            )\n        )\n        reqset.add_named_requirement(\n            get_processed_req_from_line(\n                \"TopoRequires==0.0.1 \"\n                \"--hash=sha256:d6dd1e22e60df512fdcf3640ced3039b3b02a56ab2cee81ebcb\"\n                \"3d0a6d4e8bfa6\",\n                lineno=2,\n            )\n        )\n\n    def test_download_info_find_links(self, data: TestData) -> None:\n        \"\"\"Test that download_info is set for requirements via find_links.\"\"\"\n        finder = make_test_finder(find_links=[data.find_links])\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            ireq = get_processed_req_from_line(\"simple\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert isinstance(req.download_info.info, ArchiveInfo)\n            assert req.download_info.info.hash\n\n    @pytest.mark.network\n    def test_download_info_index_url(self) -> None:\n        \"\"\"Test that download_info is set for requirements via index.\"\"\"\n        finder = make_test_finder(index_urls=[\"https://pypi.org/simple\"])\n        with self._basic_resolver(finder) as resolver:\n            ireq = get_processed_req_from_line(\"initools\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert isinstance(req.download_info.info, ArchiveInfo)\n\n    @pytest.mark.network\n    def test_download_info_web_archive(self) -> None:\n        \"\"\"Test that download_info is set for requirements from a web archive.\"\"\"\n        finder = make_test_finder()\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            ireq = get_processed_req_from_line(\n                \"pip-test-package @ \"\n                \"https://github.com/pypa/pip-test-package/tarball/0.1.1\"\n            )\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert (\n                req.download_info.url\n                == \"https://github.com/pypa/pip-test-package/tarball/0.1.1\"\n            )\n            assert isinstance(req.download_info.info, ArchiveInfo)\n            assert (\n                req.download_info.info.hash == \"sha256=\"\n                \"ad977496000576e1b6c41f6449a9897087ce9da6db4f15b603fe8372af4bf3c6\"\n            )\n\n    def test_download_info_archive_legacy_cache(\n        self, tmp_path: Path, shared_data: TestData\n    ) -> None:\n        \"\"\"Test download_info hash is not set for an archive with legacy cache entry.\"\"\"\n        url = shared_data.packages.joinpath(\"simple-1.0.tar.gz\").as_uri()\n        finder = make_test_finder()\n        wheel_cache = WheelCache(str(tmp_path / \"cache\"))\n        cache_entry_dir = wheel_cache.get_path_for_link(Link(url))\n        Path(cache_entry_dir).mkdir(parents=True)\n        wheel.make_wheel(name=\"simple\", version=\"1.0\").save_to_dir(cache_entry_dir)\n        with self._basic_resolver(finder, wheel_cache=wheel_cache) as resolver:\n            ireq = get_processed_req_from_line(f\"simple @ {url}\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.is_wheel_from_cache\n            assert req.cached_wheel_source_link\n            assert req.download_info\n            assert req.download_info.url == url\n            assert isinstance(req.download_info.info, ArchiveInfo)\n            assert not req.download_info.info.hash\n\n    def test_download_info_archive_cache_with_origin(\n        self, tmp_path: Path, shared_data: TestData\n    ) -> None:\n        \"\"\"Test download_info hash is set for a web archive with cache entry\n        that has origin.json.\"\"\"\n        url = shared_data.packages.joinpath(\"simple-1.0.tar.gz\").as_uri()\n        hash = \"sha256=ad977496000576e1b6c41f6449a9897087ce9da6db4f15b603fe8372af4bf3c6\"\n        finder = make_test_finder()\n        wheel_cache = WheelCache(str(tmp_path / \"cache\"))\n        cache_entry_dir = wheel_cache.get_path_for_link(Link(url))\n        Path(cache_entry_dir).mkdir(parents=True)\n        Path(cache_entry_dir).joinpath(\"origin.json\").write_text(\n            DirectUrl(url, ArchiveInfo(hash=hash)).to_json()\n        )\n        wheel.make_wheel(name=\"simple\", version=\"1.0\").save_to_dir(cache_entry_dir)\n        with self._basic_resolver(finder, wheel_cache=wheel_cache) as resolver:\n            ireq = get_processed_req_from_line(f\"simple @ {url}\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.is_wheel_from_cache\n            assert req.cached_wheel_source_link\n            assert req.download_info\n            assert req.download_info.url == url\n            assert isinstance(req.download_info.info, ArchiveInfo)\n            assert req.download_info.info.hash == hash\n\n    def test_download_info_archive_cache_with_invalid_origin(\n        self, tmp_path: Path, shared_data: TestData, caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"Test an invalid origin.json is ignored.\"\"\"\n        url = shared_data.packages.joinpath(\"simple-1.0.tar.gz\").as_uri()\n        finder = make_test_finder()\n        wheel_cache = WheelCache(str(tmp_path / \"cache\"))\n        cache_entry_dir = wheel_cache.get_path_for_link(Link(url))\n        Path(cache_entry_dir).mkdir(parents=True)\n        Path(cache_entry_dir).joinpath(\"origin.json\").write_text(\"{\")  # invalid json\n        wheel.make_wheel(name=\"simple\", version=\"1.0\").save_to_dir(cache_entry_dir)\n        with self._basic_resolver(finder, wheel_cache=wheel_cache) as resolver:\n            ireq = get_processed_req_from_line(f\"simple @ {url}\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.is_wheel_from_cache\n            assert any(\n                \"Ignoring invalid cache entry origin file\" in x for x in caplog.messages\n            )\n\n    def test_download_info_local_wheel(self, data: TestData) -> None:\n        \"\"\"Test that download_info is set for requirements from a local wheel.\"\"\"\n        finder = make_test_finder()\n        with self._basic_resolver(finder) as resolver:\n            ireq = get_processed_req_from_line(\n                f\"{data.packages}/simplewheel-1.0-py2.py3-none-any.whl\"\n            )\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert req.download_info.url.startswith(\"file://\")\n            assert isinstance(req.download_info.info, ArchiveInfo)\n            assert (\n                req.download_info.info.hash == \"sha256=\"\n                \"e63aa139caee941ec7f33f057a5b987708c2128238357cf905429846a2008718\"\n            )\n\n    def test_download_info_local_dir(self, data: TestData) -> None:\n        \"\"\"Test that download_info is set for requirements from a local dir.\"\"\"\n        finder = make_test_finder()\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            ireq_url = data.packages.joinpath(\"FSPkg\").as_uri()\n            ireq = get_processed_req_from_line(f\"FSPkg @ {ireq_url}\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert req.download_info.url.startswith(\"file://\")\n            assert isinstance(req.download_info.info, DirInfo)\n\n    def test_download_info_local_editable_dir(self, data: TestData) -> None:\n        \"\"\"Test that download_info is set for requirements from a local editable dir.\"\"\"\n        finder = make_test_finder()\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            ireq_url = data.packages.joinpath(\"FSPkg\").as_uri()\n            ireq = get_processed_req_from_line(f\"-e {ireq_url}#egg=FSPkg\")\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert req.download_info.url.startswith(\"file://\")\n            assert isinstance(req.download_info.info, DirInfo)\n            assert req.download_info.info.editable\n\n    @pytest.mark.network\n    def test_download_info_vcs(self) -> None:\n        \"\"\"Test that download_info is set for requirements from git.\"\"\"\n        finder = make_test_finder()\n        with self._basic_resolver(finder, build_isolation=False) as resolver:\n            ireq = get_processed_req_from_line(\n                \"pip-test-package @ git+https://github.com/pypa/pip-test-package\"\n            )\n            reqset = resolver.resolve([ireq], True)\n            assert len(reqset.all_requirements) == 1\n            req = reqset.all_requirements[0]\n            assert req.download_info\n            assert isinstance(req.download_info.info, VcsInfo)\n            assert req.download_info.url == \"https://github.com/pypa/pip-test-package\"\n            assert req.download_info.info.vcs == \"git\"\n\n\nclass TestInstallRequirement:\n    def setup_method(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n\n    def teardown_method(self) -> None:\n        shutil.rmtree(self.tempdir, ignore_errors=True)\n\n    def test_url_with_query(self) -> None:\n        \"\"\"InstallRequirement should strip the fragment, but not the query.\"\"\"\n        url = \"http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz\"\n        fragment = \"#egg=bar\"\n        req = install_req_from_line(url + fragment)\n        assert req.link is not None\n        assert req.link.url == url + fragment, req.link\n\n    def test_pep440_wheel_link_requirement(self) -> None:\n        url = \"https://whatever.com/test-0.4-py2.py3-bogus-any.whl\"\n        line = \"test @ https://whatever.com/test-0.4-py2.py3-bogus-any.whl\"\n        req = install_req_from_line(line)\n        parts = str(req.req).split(\"@\", 1)\n        assert len(parts) == 2\n        assert parts[0].strip() == \"test\"\n        assert parts[1].strip() == url\n\n    def test_pep440_url_link_requirement(self) -> None:\n        url = \"git+http://foo.com@ref#egg=foo\"\n        line = \"foo @ git+http://foo.com@ref#egg=foo\"\n        req = install_req_from_line(line)\n        parts = str(req.req).split(\"@\", 1)\n        assert len(parts) == 2\n        assert parts[0].strip() == \"foo\"\n        assert parts[1].strip() == url\n\n    def test_url_with_authentication_link_requirement(self) -> None:\n        url = \"https://what@whatever.com/test-0.4-py2.py3-bogus-any.whl\"\n        line = \"https://what@whatever.com/test-0.4-py2.py3-bogus-any.whl\"\n        req = install_req_from_line(line)\n        assert req.link is not None\n        assert req.link.is_wheel\n        assert req.link.scheme == \"https\"\n        assert req.link.url == url\n\n    def test_str(self) -> None:\n        req = install_req_from_line(\"simple==0.1\")\n        assert str(req) == \"simple==0.1\"\n\n    def test_repr(self) -> None:\n        req = install_req_from_line(\"simple==0.1\")\n        assert repr(req) == (\"<InstallRequirement object: simple==0.1 editable=False>\")\n\n    def test_invalid_wheel_requirement_raises(self) -> None:\n        with pytest.raises(InvalidWheelFilename):\n            install_req_from_line(\"invalid.whl\")\n\n    def test_wheel_requirement_sets_req_attribute(self) -> None:\n        req = install_req_from_line(\"simple-0.1-py2.py3-none-any.whl\")\n        assert isinstance(req.req, Requirement)\n        assert str(req.req) == \"simple==0.1\"\n\n    def test_url_preserved_line_req(self) -> None:\n        \"\"\"Confirm the url is preserved in a non-editable requirement\"\"\"\n        url = \"git+http://foo.com@ref#egg=foo\"\n        req = install_req_from_line(url)\n        assert req.link is not None\n        assert req.link.url == url\n\n    def test_url_preserved_editable_req(self) -> None:\n        \"\"\"Confirm the url is preserved in a editable requirement\"\"\"\n        url = \"git+http://foo.com@ref#egg=foo\"\n        req = install_req_from_editable(url)\n        assert req.link is not None\n        assert req.link.url == url\n\n    def test_markers(self) -> None:\n        for line in (\n            # recommended syntax\n            'mock3; python_version >= \"3\"',\n            # with more spaces\n            'mock3 ; python_version >= \"3\" ',\n            # without spaces\n            'mock3;python_version >= \"3\"',\n        ):\n            req = install_req_from_line(line)\n            assert req.req is not None\n            assert req.req.name == \"mock3\"\n            assert str(req.req.specifier) == \"\"\n            assert str(req.markers) == 'python_version >= \"3\"'\n\n    def test_markers_semicolon(self) -> None:\n        # check that the markers can contain a semicolon\n        req = install_req_from_line('semicolon; os_name == \"a; b\"')\n        assert req.req is not None\n        assert req.req.name == \"semicolon\"\n        assert str(req.req.specifier) == \"\"\n        assert str(req.markers) == 'os_name == \"a; b\"'\n\n    def test_markers_url(self) -> None:\n        # test \"URL; markers\" syntax\n        url = \"http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz\"\n        line = f'{url}; python_version >= \"3\"'\n        req = install_req_from_line(line)\n        assert req.link is not None\n        assert req.link.url == url, req.link.url\n        assert str(req.markers) == 'python_version >= \"3\"'\n\n        # without space, markers are part of the URL\n        url = \"http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz\"\n        line = f'{url};python_version >= \"3\"'\n        req = install_req_from_line(line)\n        assert req.link is not None\n        assert req.link.url == line, req.link.url\n        assert req.markers is None\n\n    def test_markers_match_from_line(self) -> None:\n        # match\n        for markers in (\n            'python_version >= \"1.0\"',\n            f\"sys_platform == {sys.platform!r}\",\n        ):\n            line = \"name; \" + markers\n            req = install_req_from_line(line)\n            assert str(req.markers) == str(Marker(markers))\n            assert req.match_markers()\n\n        # don't match\n        for markers in (\n            'python_version >= \"5.0\"',\n            f\"sys_platform != {sys.platform!r}\",\n        ):\n            line = \"name; \" + markers\n            req = install_req_from_line(line)\n            assert str(req.markers) == str(Marker(markers))\n            assert not req.match_markers()\n\n    def test_markers_match(self) -> None:\n        # match\n        for markers in (\n            'python_version >= \"1.0\"',\n            f\"sys_platform == {sys.platform!r}\",\n        ):\n            line = \"name; \" + markers\n            req = install_req_from_line(line, comes_from=\"\")\n            assert str(req.markers) == str(Marker(markers))\n            assert req.match_markers()\n\n        # don't match\n        for markers in (\n            'python_version >= \"5.0\"',\n            f\"sys_platform != {sys.platform!r}\",\n        ):\n            line = \"name; \" + markers\n            req = install_req_from_line(line, comes_from=\"\")\n            assert str(req.markers) == str(Marker(markers))\n            assert not req.match_markers()\n\n    def test_extras_for_line_path_requirement(self) -> None:\n        line = \"SomeProject[ex1,ex2]\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_line(line, comes_from=comes_from)\n        assert len(req.extras) == 2\n        assert req.extras == {\"ex1\", \"ex2\"}\n\n    def test_extras_for_line_url_requirement(self) -> None:\n        line = \"SomeProject[ex1,ex2] @ git+https://url\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_line(line, comes_from=comes_from)\n        assert len(req.extras) == 2\n        assert req.extras == {\"ex1\", \"ex2\"}\n\n    def test_extras_for_editable_path_requirement(self) -> None:\n        url = \".[ex1,ex2]\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_editable(url, comes_from=comes_from)\n        assert len(req.extras) == 2\n        assert req.extras == {\"ex1\", \"ex2\"}\n\n    def test_extras_for_editable_url_requirement(self) -> None:\n        url = \"SomeProject[ex1,ex2] @ git+https://url\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_editable(url, comes_from=comes_from)\n        assert len(req.extras) == 2\n        assert req.extras == {\"ex1\", \"ex2\"}\n\n    def test_unexisting_path(self) -> None:\n        with pytest.raises(InstallationError) as e:\n            install_req_from_line(os.path.join(\"this\", \"path\", \"does\", \"not\", \"exist\"))\n        err_msg = e.value.args[0]\n        assert \"Invalid requirement\" in err_msg\n        assert \"It looks like a path.\" in err_msg\n\n    def test_single_equal_sign(self) -> None:\n        with pytest.raises(InstallationError) as e:\n            install_req_from_line(\"toto=42\")\n        err_msg = e.value.args[0]\n        assert \"Invalid requirement\" in err_msg\n        assert \"= is not a valid operator. Did you mean == ?\" in err_msg\n\n    def test_unidentifiable_name(self) -> None:\n        test_name = \"-\"\n        with pytest.raises(InstallationError) as e:\n            install_req_from_line(test_name)\n        err_msg = e.value.args[0]\n        assert err_msg.startswith(f\"Invalid requirement: '{test_name}'\")\n\n    def test_requirement_file(self) -> None:\n        req_file_path = os.path.join(self.tempdir, \"test.txt\")\n        with open(req_file_path, \"w\") as req_file:\n            req_file.write(\"pip\\nsetuptools\")\n        with pytest.raises(InstallationError) as e:\n            install_req_from_line(req_file_path)\n        err_msg = e.value.args[0]\n        assert \"Invalid requirement\" in err_msg\n        assert \"It looks like a path. The path does exist.\" in err_msg\n        assert \"appears to be a requirements file.\" in err_msg\n        assert \"If that is the case, use the '-r' flag to install\" in err_msg\n\n    @pytest.mark.parametrize(\n        \"inp, out\",\n        [\n            (\"pkg\", \"pkg\"),\n            (\"pkg==1.0\", \"pkg==1.0\"),\n            (\"pkg ; python_version<='3.6'\", \"pkg\"),\n            (\"pkg[ext]\", \"pkg\"),\n            (\"pkg [ ext1, ext2 ]\", \"pkg\"),\n            (\"pkg [ ext1, ext2 ] @ https://example.com/\", \"pkg @ https://example.com/\"),\n            (\"pkg [ext] == 1.0; python_version<='3.6'\", \"pkg==1.0\"),\n            (\"pkg-all.allowed_chars0 ~= 2.0\", \"pkg-all.allowed_chars0~=2.0\"),\n            (\"pkg-all.allowed_chars0 [ext] ~= 2.0\", \"pkg-all.allowed_chars0~=2.0\"),\n            (\"simple-0.1-py2.py3-none-any.whl [ext]\", \"simple==0.1\"),\n        ],\n    )\n    def test_install_req_drop_extras(self, inp: str, out: str) -> None:\n        \"\"\"\n        Test behavior of install_req_drop_extras\n        \"\"\"\n        req = install_req_from_line(inp)\n        without_extras = install_req_drop_extras(req)\n        assert not without_extras.extras\n        assert str(without_extras.req) == out\n\n        # if there are no extras they should be the same object,\n        # otherwise they may be a copy due to cache\n        if req.extras:\n            assert req is not without_extras\n            assert req.req is not without_extras.req\n\n        # comes_from should point to original\n        assert without_extras.comes_from is req\n\n        # all else should be the same\n        assert without_extras.link == req.link\n        assert without_extras.markers == req.markers\n        assert without_extras.isolated == req.isolated\n        assert without_extras.hash_options == req.hash_options\n        assert without_extras.constraint == req.constraint\n        assert without_extras.config_settings == req.config_settings\n        assert without_extras.user_supplied == req.user_supplied\n        assert without_extras.permit_editable_wheels == req.permit_editable_wheels\n\n    @pytest.mark.parametrize(\n        \"inp, extras, out\",\n        [\n            (\"pkg\", set(), \"pkg\"),\n            (\"pkg==1.0\", set(), \"pkg==1.0\"),\n            (\"pkg[ext]\", set(), \"pkg[ext]\"),\n            (\"pkg\", {\"ext\"}, \"pkg[ext]\"),\n            (\"pkg==1.0\", {\"ext\"}, \"pkg[ext]==1.0\"),\n            (\"pkg==1.0\", {\"ext1\", \"ext2\"}, \"pkg[ext1,ext2]==1.0\"),\n            (\"pkg; python_version<='3.6'\", {\"ext\"}, \"pkg[ext]\"),\n            (\"pkg[ext1,ext2]==1.0\", {\"ext2\", \"ext3\"}, \"pkg[ext1,ext2,ext3]==1.0\"),\n            (\n                \"pkg-all.allowed_chars0 [ ext1 ] @ https://example.com/\",\n                {\"ext2\"},\n                \"pkg-all.allowed_chars0[ext1,ext2] @ https://example.com/\",\n            ),\n        ],\n    )\n    def test_install_req_extend_extras(\n        self, inp: str, extras: set[str], out: str\n    ) -> None:\n        \"\"\"\n        Test behavior of install_req_extend_extras\n        \"\"\"\n        req = install_req_from_line(inp)\n        extended = install_req_extend_extras(req, extras)\n        assert str(extended.req) == out\n        assert extended.req is not None\n        assert set(extended.extras) == set(extended.req.extras)\n\n        # if extras is not a subset of req.extras then the extended\n        # requirement object should not be the same, otherwise they\n        # might be a copy due to cache\n        if not extras.issubset(req.extras):\n            assert req is not extended\n            assert req.req is not extended.req\n\n        # all else should be the same\n        assert extended.link == req.link\n        assert extended.markers == req.markers\n        assert extended.isolated == req.isolated\n        assert extended.hash_options == req.hash_options\n        assert extended.constraint == req.constraint\n        assert extended.config_settings == req.config_settings\n        assert extended.user_supplied == req.user_supplied\n        assert extended.permit_editable_wheels == req.permit_editable_wheels\n\n\n@pytest.mark.parametrize(\n    \"req_str, expected\",\n    [\n        (\n            'foo[extra] @ svn+http://foo ; os_name == \"nt\"',\n            ('foo ; os_name == \"nt\"', \"svn+http://foo\", {\"extra\"}),\n        ),\n        (\n            \"foo @ svn+http://foo\",\n            (\"foo\", \"svn+http://foo\", set()),\n        ),\n    ],\n)\ndef test_parse_editable_pep508(\n    req_str: str, expected: tuple[str, str, set[str]]\n) -> None:\n    assert parse_editable(req_str) == expected\n\n\n@mock.patch(\"pip._internal.req.req_install.os.path.abspath\")\n@mock.patch(\"pip._internal.req.req_install.os.path.exists\")\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\ndef test_parse_editable_local(\n    isdir_mock: mock.Mock, exists_mock: mock.Mock, abspath_mock: mock.Mock\n) -> None:\n    exists_mock.return_value = isdir_mock.return_value = True\n    # mocks needed to support path operations on windows tests\n    abspath_mock.return_value = \"/some/path\"\n    assert parse_editable(\".\") == (None, \"file:///some/path\", set())\n    abspath_mock.return_value = \"/some/path/foo\"\n    assert parse_editable(\"foo\") == (\n        None,\n        \"file:///some/path/foo\",\n        set(),\n    )\n\n\ndef test_parse_editable_explicit_vcs() -> None:\n    assert parse_editable(\"svn+https://foo#egg=foo\") == (\n        \"foo\",\n        \"svn+https://foo#egg=foo\",\n        set(),\n    )\n\n\ndef test_parse_editable_vcs_extras() -> None:\n    assert parse_editable(\"foo[extras] @ svn+https://foo\") == (\n        \"foo\",\n        \"svn+https://foo\",\n        {\"extras\"},\n    )\n\n\n@mock.patch(\"pip._internal.req.req_install.os.path.abspath\")\n@mock.patch(\"pip._internal.req.req_install.os.path.exists\")\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\ndef test_parse_editable_local_extras(\n    isdir_mock: mock.Mock, exists_mock: mock.Mock, abspath_mock: mock.Mock\n) -> None:\n    exists_mock.return_value = isdir_mock.return_value = True\n    abspath_mock.return_value = \"/some/path\"\n    assert parse_editable(\".[extras]\") == (\n        None,\n        \"file:///some/path\",\n        {\"extras\"},\n    )\n    abspath_mock.return_value = \"/some/path/foo\"\n    assert parse_editable(\"foo[bar,baz]\") == (\n        None,\n        \"file:///some/path/foo\",\n        {\"bar\", \"baz\"},\n    )\n\n\ndef test_mismatched_versions(caplog: pytest.LogCaptureFixture) -> None:\n    req = InstallRequirement(\n        req=Requirement(\"simplewheel==2.0\"),\n        comes_from=None,\n    )\n    req.source_dir = \"/tmp/somewhere\"  # make req believe it has been unpacked\n    # Monkeypatch!\n    metadata = email.message.Message()\n    metadata[\"name\"] = \"simplewheel\"\n    metadata[\"version\"] = \"1.0\"\n    req._metadata = metadata\n\n    req.assert_source_matches_version()\n    assert caplog.records[-1].message == (\n        \"Requested simplewheel==2.0, but installing version 1.0\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test UNIX-like paths\n        ((\"/path/to/installable\"), True),\n        # Test relative paths\n        ((\"./path/to/installable\"), True),\n        # Test current path\n        ((\".\"), True),\n        # Test url paths\n        ((\"https://whatever.com/test-0.4-py2.py3-bogus-any.whl\"), True),\n        # Test pep440 paths\n        ((\"test @ https://whatever.com/test-0.4-py2.py3-bogus-any.whl\"), True),\n        # Test wheel\n        ((\"simple-0.1-py2.py3-none-any.whl\"), False),\n    ],\n)\ndef test_looks_like_path(args: str, expected: bool) -> None:\n    assert _looks_like_path(args) == expected\n\n\n@pytest.mark.skipif(\n    not sys.platform.startswith(\"win\"), reason=\"Test only available on Windows\"\n)\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test relative paths\n        ((\".\\\\path\\\\to\\\\installable\"), True),\n        ((\"relative\\\\path\"), True),\n        # Test absolute paths\n        ((\"C:\\\\absolute\\\\path\"), True),\n    ],\n)\ndef test_looks_like_path_win(args: str, expected: bool) -> None:\n    assert _looks_like_path(args) == expected\n\n\n@pytest.mark.parametrize(\n    \"args, mock_returns, expected\",\n    [\n        # Test pep440 urls\n        (\n            (\n                \"/path/to/foo @ git+http://foo.com@ref#egg=foo\",\n                \"foo @ git+http://foo.com@ref#egg=foo\",\n            ),\n            (False, False),\n            None,\n        ),\n        # Test pep440 urls without spaces\n        (\n            (\n                \"/path/to/foo@git+http://foo.com@ref#egg=foo\",\n                \"foo @ git+http://foo.com@ref#egg=foo\",\n            ),\n            (False, False),\n            None,\n        ),\n        # Test pep440 wheel\n        (\n            (\n                \"/path/to/test @ https://whatever.com/test-0.4-py2.py3-bogus-any.whl\",\n                \"test @ https://whatever.com/test-0.4-py2.py3-bogus-any.whl\",\n            ),\n            (False, False),\n            None,\n        ),\n        # Test name is not a file\n        ((\"/path/to/simple==0.1\", \"simple==0.1\"), (False, False), None),\n    ],\n)\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\n@mock.patch(\"pip._internal.req.req_install.os.path.isfile\")\ndef test_get_url_from_path(\n    isdir_mock: mock.Mock,\n    isfile_mock: mock.Mock,\n    args: tuple[str, str],\n    mock_returns: tuple[bool, bool],\n    expected: None,\n) -> None:\n    isdir_mock.return_value = mock_returns[0]\n    isfile_mock.return_value = mock_returns[1]\n    assert _get_url_from_path(*args) is expected\n\n\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\n@mock.patch(\"pip._internal.req.req_install.os.path.isfile\")\ndef test_get_url_from_path__archive_file(\n    isdir_mock: mock.Mock, isfile_mock: mock.Mock\n) -> None:\n    isdir_mock.return_value = False\n    isfile_mock.return_value = True\n    name = \"simple-0.1-py2.py3-none-any.whl\"\n    url = Path(f\"/path/to/{name}\").resolve(strict=False).as_uri()\n    assert _get_url_from_path(f\"/path/to/{name}\", name) == url\n\n\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\n@mock.patch(\"pip._internal.req.req_install.os.path.isfile\")\ndef test_get_url_from_path__installable_dir(\n    isdir_mock: mock.Mock, isfile_mock: mock.Mock\n) -> None:\n    isdir_mock.return_value = True\n    isfile_mock.return_value = True\n    name = \"some/setuptools/project\"\n    url = Path(f\"/path/to/{name}\").resolve(strict=False).as_uri()\n    assert _get_url_from_path(f\"/path/to/{name}\", name) == url\n\n\n@mock.patch(\"pip._internal.req.req_install.os.path.isdir\")\ndef test_get_url_from_path__installable_error(isdir_mock: mock.Mock) -> None:\n    isdir_mock.return_value = True\n    name = \"some/setuptools/project\"\n    path = os.path.join(\"/path/to/\" + name)\n    with pytest.raises(InstallationError) as e:\n        _get_url_from_path(path, name)\n    err_msg = e.value.args[0]\n    assert \"Neither 'setup.py' nor 'pyproject.toml' found\" in err_msg\n"
  },
  {
    "path": "tests/unit/test_req_dependency_group.py",
    "content": "import errno\nimport textwrap\nfrom pathlib import Path\nfrom typing import Any\n\nimport pytest\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.req.req_dependency_group import parse_dependency_groups\n\n\ndef test_parse_simple_dependency_groups(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    pyproject = tmp_path.joinpath(\"pyproject.toml\")\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups]\n            foo = [\"bar\"]\n            \"\"\"\n        )\n    )\n    monkeypatch.chdir(tmp_path)\n\n    result = list(parse_dependency_groups([(\"pyproject.toml\", \"foo\")]))\n\n    assert len(result) == 1, result\n    assert result[0] == \"bar\"\n\n\ndef test_parse_cyclic_dependency_groups(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    pyproject = tmp_path.joinpath(\"pyproject.toml\")\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups]\n            foo = [{include-group=\"bar\"}]\n            bar = [{include-group=\"foo\"}]\n            \"\"\"\n        )\n    )\n    monkeypatch.chdir(tmp_path)\n\n    with pytest.raises(\n        InstallationError,\n        match=(\n            r\"\\[dependency-groups\\] resolution failed for \"\n            r\"'foo' from 'pyproject\\.toml':\"\n        ),\n    ) as excinfo:\n        parse_dependency_groups([(\"pyproject.toml\", \"foo\")])\n\n    exception = excinfo.value\n    assert (\n        \"Cyclic dependency group include while resolving foo: foo -> bar, bar -> foo\"\n    ) in str(exception)\n\n\ndef test_parse_with_no_dependency_groups_defined(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    pyproject = tmp_path.joinpath(\"pyproject.toml\")\n    pyproject.write_text(\"\")\n    monkeypatch.chdir(tmp_path)\n\n    with pytest.raises(\n        InstallationError,\n        match=(r\"\\[dependency-groups\\] table was missing from 'pyproject\\.toml'\\.\"),\n    ):\n        parse_dependency_groups([(\"pyproject.toml\", \"foo\")])\n\n\ndef test_parse_with_no_pyproject_file(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    monkeypatch.chdir(tmp_path)\n\n    with pytest.raises(InstallationError, match=r\"pyproject\\.toml not found\\.\"):\n        parse_dependency_groups([(\"pyproject.toml\", \"foo\")])\n\n\ndef test_parse_with_malformed_pyproject_file(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    pyproject = tmp_path.joinpath(\"pyproject.toml\")\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups  # no closing bracket\n            foo = [\"bar\"]\n            \"\"\"\n        )\n    )\n    monkeypatch.chdir(tmp_path)\n\n    with pytest.raises(InstallationError, match=r\"Error parsing pyproject\\.toml\"):\n        parse_dependency_groups([(\"pyproject.toml\", \"foo\")])\n\n\ndef test_parse_gets_unexpected_oserror(\n    tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    pyproject = tmp_path.joinpath(\"pyproject.toml\")\n    pyproject.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            [dependency-groups]\n            foo = [\"bar\"]\n            \"\"\"\n        )\n    )\n    monkeypatch.chdir(tmp_path)\n\n    # inject an implementation of `tomli.load()` which emits an 'OSError(EPIPE, ...)'\n    # as though we were loading from a fifo or other unusual filetype\n    def epipe_toml_load(*args: Any, **kwargs: Any) -> None:\n        raise OSError(errno.EPIPE, \"Broken pipe\")\n\n    monkeypatch.setattr(\n        \"pip._internal.req.req_dependency_group.tomllib.load\", epipe_toml_load\n    )\n\n    with pytest.raises(InstallationError, match=r\"Error reading pyproject\\.toml\"):\n        parse_dependency_groups([(\"pyproject.toml\", \"foo\")])\n"
  },
  {
    "path": "tests/unit/test_req_file.py",
    "content": "from __future__ import annotations\n\nimport codecs\nimport collections\nimport logging\nimport os\nimport re\nimport textwrap\nfrom collections.abc import Iterator\nfrom optparse import Values\nfrom pathlib import Path\nfrom typing import Any, Protocol\nfrom unittest import mock\n\nimport pytest\n\nimport pip._internal.req.req_file  # this will be monkeypatched\nfrom pip._internal.exceptions import InstallationError, RequirementsFileParseError\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n)\nfrom pip._internal.req.req_file import (\n    break_args_options,\n    ignore_comments,\n    join_lines,\n    parse_requirements,\n    preprocess,\n)\nfrom pip._internal.req.req_install import InstallRequirement\n\nfrom tests.lib import TestData, make_test_finder\n\n\n@pytest.fixture\ndef session() -> PipSession:\n    return PipSession()\n\n\n@pytest.fixture\ndef finder(session: PipSession) -> PackageFinder:\n    return make_test_finder(session=session)\n\n\n@pytest.fixture\ndef options(session: PipSession) -> mock.Mock:\n    return mock.Mock(\n        isolated_mode=False,\n        index_url=\"default_url\",\n        format_control=FormatControl(set(), set()),\n        features_enabled=[],\n    )\n\n\ndef parse_reqfile(\n    filename: Path | str,\n    session: PipSession,\n    finder: PackageFinder | None = None,\n    options: Values | None = None,\n    constraint: bool = False,\n    isolated: bool = False,\n) -> Iterator[InstallRequirement]:\n    # Wrap parse_requirements/install_req_from_parsed_requirement to\n    # avoid having to write the same chunk of code in lots of tests.\n    for parsed_req in parse_requirements(\n        os.fspath(filename),\n        session,\n        finder=finder,\n        options=options,\n        constraint=constraint,\n    ):\n        yield install_req_from_parsed_requirement(\n            parsed_req,\n            isolated=isolated,\n            config_settings=(\n                parsed_req.options.get(\"config_settings\")\n                if parsed_req.options\n                else None\n            ),\n        )\n\n\ndef test_missing_constraint_file_message_mentions_constraints(\n    tmp_path: Path, session: PipSession\n) -> None:\n    missing = tmp_path / \"does-not-exist.txt\"\n\n    with pytest.raises(InstallationError) as exc:\n        list(parse_reqfile(missing, session=session, constraint=True))\n\n    assert \"Could not open constraint file:\" in str(exc.value)\n\n\ndef test_read_file_url(tmp_path: Path, session: PipSession) -> None:\n    reqs = tmp_path.joinpath(\"requirements.txt\")\n    reqs.write_text(\"foo\")\n    result = list(parse_requirements(reqs.as_posix(), session))\n\n    assert len(result) == 1, result\n    assert result[0].requirement == \"foo\"\n\n    # The comes_from value has three parts: -r or -c flag, path, and line.\n    # The path value in the middle needs some special logic due to our path\n    # normalization logic.\n    assert result[0].comes_from[:3] == \"-r \"\n    assert result[0].comes_from[-9:] == \" (line 1)\"\n    assert os.path.samefile(result[0].comes_from[3:-9], str(reqs))\n\n\nclass TestPreprocess:\n    \"\"\"tests for `preprocess`\"\"\"\n\n    def test_comments_and_joins_case1(self) -> None:\n        content = textwrap.dedent(\n            \"\"\"\\\n          req1 \\\\\n          # comment \\\\\n          req2\n        \"\"\"\n        )\n        result = preprocess(content)\n        assert list(result) == [(1, \"req1\"), (3, \"req2\")]\n\n    def test_comments_and_joins_case2(self) -> None:\n        content = textwrap.dedent(\n            \"\"\"\\\n          req1\\\\\n          # comment\n        \"\"\"\n        )\n        result = preprocess(content)\n        assert list(result) == [(1, \"req1\")]\n\n    def test_comments_and_joins_case3(self) -> None:\n        content = textwrap.dedent(\n            \"\"\"\\\n          req1 \\\\\n          # comment\n          req2\n        \"\"\"\n        )\n        result = preprocess(content)\n        assert list(result) == [(1, \"req1\"), (3, \"req2\")]\n\n\nclass TestIgnoreComments:\n    \"\"\"tests for `ignore_comment`\"\"\"\n\n    def test_ignore_line(self) -> None:\n        lines = [(1, \"\"), (2, \"req1\"), (3, \"req2\")]\n        result = ignore_comments(lines)\n        assert list(result) == [(2, \"req1\"), (3, \"req2\")]\n\n    def test_ignore_comment(self) -> None:\n        lines = [(1, \"req1\"), (2, \"# comment\"), (3, \"req2\")]\n        result = ignore_comments(lines)\n        assert list(result) == [(1, \"req1\"), (3, \"req2\")]\n\n    def test_strip_comment(self) -> None:\n        lines = [(1, \"req1\"), (2, \"req # comment\"), (3, \"req2\")]\n        result = ignore_comments(lines)\n        assert list(result) == [(1, \"req1\"), (2, \"req\"), (3, \"req2\")]\n\n\nclass TestJoinLines:\n    \"\"\"tests for `join_lines`\"\"\"\n\n    def test_join_lines(self) -> None:\n        lines = enumerate(\n            [\n                \"line 1\",\n                \"line 2:1 \\\\\",\n                \"line 2:2\",\n                \"line 3:1 \\\\\",\n                \"line 3:2 \\\\\",\n                \"line 3:3\",\n                \"line 4\",\n            ],\n            start=1,\n        )\n        expect = [\n            (1, \"line 1\"),\n            (2, \"line 2:1 line 2:2\"),\n            (4, \"line 3:1 line 3:2 line 3:3\"),\n            (7, \"line 4\"),\n        ]\n        assert expect == list(join_lines(lines))\n\n    def test_last_line_with_escape(self) -> None:\n        lines = enumerate(\n            [\n                \"line 1\",\n                \"line 2 \\\\\",\n            ],\n            start=1,\n        )\n        expect = [\n            (1, \"line 1\"),\n            (2, \"line 2 \"),\n        ]\n        assert expect == list(join_lines(lines))\n\n\nclass LineProcessor(Protocol):\n    def __call__(\n        self,\n        line: str,\n        filename: str,\n        line_number: int,\n        finder: PackageFinder | None = None,\n        options: Values | None = None,\n        session: PipSession | None = None,\n        constraint: bool = False,\n    ) -> list[InstallRequirement]: ...\n\n\n@pytest.fixture\ndef line_processor(monkeypatch: pytest.MonkeyPatch, tmpdir: Path) -> LineProcessor:\n    def process_line(\n        line: str,\n        filename: str,\n        line_number: int,\n        finder: PackageFinder | None = None,\n        options: Values | None = None,\n        session: PipSession | None = None,\n        constraint: bool = False,\n    ) -> list[InstallRequirement]:\n        if session is None:\n            session = PipSession()\n\n        prefix = \"\\n\" * (line_number - 1)\n        path = tmpdir.joinpath(filename)\n        path.parent.mkdir(exist_ok=True)\n        path.write_text(prefix + line)\n        monkeypatch.chdir(str(tmpdir))\n        return list(\n            parse_reqfile(\n                filename,\n                finder=finder,\n                options=options,\n                session=session,\n                constraint=constraint,\n                isolated=options.isolated_mode if options else False,\n            )\n        )\n\n    return process_line\n\n\nclass TestProcessLine:\n    \"\"\"tests for `process_line`\"\"\"\n\n    def test_parser_error(self, line_processor: LineProcessor) -> None:\n        with pytest.raises(RequirementsFileParseError):\n            line_processor(\"--bogus\", \"file\", 1)\n\n    def test_parser_offending_line(self, line_processor: LineProcessor) -> None:\n        line = \"pkg==1.0.0 --hash=somehash\"\n        with pytest.raises(RequirementsFileParseError) as err:\n            line_processor(line, \"file\", 1)\n        assert line in str(err.value)\n\n    def test_parser_non_offending_line(self, line_processor: LineProcessor) -> None:\n        try:\n            line_processor(\"pkg==1.0.0 --hash=sha256:somehash\", \"file\", 1)\n        except RequirementsFileParseError:\n            pytest.fail(\"Reported offending line where it should not.\")\n\n    def test_only_one_req_per_line(self, line_processor: LineProcessor) -> None:\n        # pkg_resources raises the ValueError\n        with pytest.raises(InstallationError):\n            line_processor(\"req1 req2\", \"file\", 1)\n\n    def test_error_message(self, line_processor: LineProcessor) -> None:\n        \"\"\"\n        Test the error message if a parsing error occurs (all of path,\n        line number, and hint).\n        \"\"\"\n        with pytest.raises(InstallationError) as exc:\n            line_processor(\n                \"my-package=1.0\", filename=\"path/requirements.txt\", line_number=3\n            )\n\n        expected = (\n            \"Invalid requirement: 'my-package=1.0': \"\n            \"Expected semicolon (after name with no version specifier) or end\\n\"\n            \"    my-package=1.0\\n\"\n            \"              ^ (from line 3 of path/requirements.txt)\\n\"\n            \"Hint: = is not a valid operator. Did you mean == ?\"\n        )\n        assert str(exc.value) == expected\n\n    def test_yield_line_requirement(self, line_processor: LineProcessor) -> None:\n        line = \"SomeProject\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_line(line, comes_from=comes_from)\n        assert repr(line_processor(line, filename, 1)[0]) == repr(req)\n\n    def test_yield_pep440_line_requirement(self, line_processor: LineProcessor) -> None:\n        line = \"SomeProject @ https://url/SomeProject-py2-py3-none-any.whl\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_line(line, comes_from=comes_from)\n        assert repr(line_processor(line, filename, 1)[0]) == repr(req)\n\n    def test_yield_line_constraint(self, line_processor: LineProcessor) -> None:\n        line = \"SomeProject\"\n        filename = \"filename\"\n        comes_from = f\"-c {filename} (line {1})\"\n        req = install_req_from_line(line, comes_from=comes_from, constraint=True)\n        found_req = line_processor(line, filename, 1, constraint=True)[0]\n        assert repr(found_req) == repr(req)\n        assert found_req.constraint is True\n\n    def test_yield_line_requirement_with_spaces_in_specifier(\n        self, line_processor: LineProcessor\n    ) -> None:\n        line = \"SomeProject >= 2\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_line(line, comes_from=comes_from)\n        assert repr(line_processor(line, filename, 1)[0]) == repr(req)\n        assert req.req is not None\n        assert str(req.req.specifier) == \">=2\"\n\n    def test_yield_editable_requirement(self, line_processor: LineProcessor) -> None:\n        url = \"git+https://url#egg=SomeProject\"\n        line = f\"-e {url}\"\n        filename = \"filename\"\n        comes_from = f\"-r {filename} (line 1)\"\n        req = install_req_from_editable(url, comes_from=comes_from)\n        assert repr(line_processor(line, filename, 1)[0]) == repr(req)\n\n    def test_nested_constraints_file(\n        self, monkeypatch: pytest.MonkeyPatch, tmpdir: Path, session: PipSession\n    ) -> None:\n        req_name = \"hello\"\n        req_file = tmpdir / \"parent\" / \"req_file.txt\"\n        req_file.parent.mkdir()\n        req_file.write_text(\"-c reqs.txt\")\n        req_file.parent.joinpath(\"reqs.txt\").write_text(req_name)\n\n        monkeypatch.chdir(str(tmpdir))\n\n        reqs = list(parse_reqfile(\"./parent/req_file.txt\", session=session))\n        assert len(reqs) == 1\n        assert reqs[0].name == req_name\n        assert reqs[0].constraint\n\n    def test_repeated_requirement_files(\n        self, tmp_path: Path, session: PipSession\n    ) -> None:\n        # Test that the same requirements file can be included multiple times\n        # as long as there is no recursion. https://github.com/pypa/pip/issues/13046\n        tmp_path.joinpath(\"a.txt\").write_text(\"requests\")\n        tmp_path.joinpath(\"b.txt\").write_text(\"-r a.txt\")\n        tmp_path.joinpath(\"c.txt\").write_text(\"-r a.txt\\n-r b.txt\")\n        parsed = parse_requirements(\n            filename=os.fspath(tmp_path.joinpath(\"c.txt\")), session=session\n        )\n        assert [r.requirement for r in parsed] == [\"requests\", \"requests\"]\n\n    def test_recursive_requirements_file(\n        self, tmpdir: Path, session: PipSession\n    ) -> None:\n        req_files: list[Path] = []\n        req_file_count = 4\n        for i in range(req_file_count):\n            req_file = tmpdir / f\"{i}.txt\"\n            req_file.write_text(f\"-r {(i+1) % req_file_count}.txt\")\n            req_files.append(req_file)\n\n        # When the passed requirements file recursively references itself\n        with pytest.raises(\n            RequirementsFileParseError,\n            match=(\n                f\"{re.escape(str(req_files[0]))} recursively references itself\"\n                f\" in {re.escape(str(req_files[req_file_count - 1]))}\"\n            ),\n        ):\n            list(parse_requirements(filename=str(req_files[0]), session=session))\n\n        # When one of other the requirements file recursively references itself\n        req_files[req_file_count - 1].write_text(\n            # Just name since they are in the same folder\n            f\"-r {req_files[req_file_count - 2].name}\"\n        )\n        with pytest.raises(\n            RequirementsFileParseError,\n            match=(\n                f\"{re.escape(str(req_files[req_file_count - 2]))} recursively\"\n                \" references itself in\"\n                f\" {re.escape(str(req_files[req_file_count - 1]))} and again in\"\n                f\" {re.escape(str(req_files[req_file_count - 3]))}\"\n            ),\n        ):\n            list(parse_requirements(filename=str(req_files[0]), session=session))\n\n    def test_recursive_relative_requirements_file(\n        self, tmpdir: Path, session: PipSession\n    ) -> None:\n        root_req_file = tmpdir / \"root.txt\"\n        (tmpdir / \"nest\" / \"nest\").mkdir(parents=True)\n        level_1_req_file = tmpdir / \"nest\" / \"level_1.txt\"\n        level_2_req_file = tmpdir / \"nest\" / \"nest\" / \"level_2.txt\"\n\n        root_req_file.write_text(\"-r nest/level_1.txt\")\n        level_1_req_file.write_text(\"-r nest/level_2.txt\")\n        level_2_req_file.write_text(\"-r ../../root.txt\")\n\n        with pytest.raises(\n            RequirementsFileParseError,\n            match=(\n                f\"{re.escape(str(root_req_file))} recursively references itself in\"\n                f\" {re.escape(str(level_2_req_file))}\"\n            ),\n        ):\n            list(parse_requirements(filename=str(root_req_file), session=session))\n\n    def test_options_on_a_requirement_line(self, line_processor: LineProcessor) -> None:\n        line = 'SomeProject --config-settings=\"yo3=yo4\" --config-settings \"yo1=yo2\"'\n        filename = \"filename\"\n        req = line_processor(line, filename, 1)[0]\n        assert req.config_settings == {\"yo3\": \"yo4\", \"yo1\": \"yo2\"}\n\n    def test_hash_options(self, line_processor: LineProcessor) -> None:\n        \"\"\"Test the --hash option: mostly its value storage.\n\n        Make sure it reads and preserve multiple hashes.\n\n        \"\"\"\n        line = (\n            \"SomeProject --hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b1\"\n            \"61e5c1fa7425e73043362938b9824 \"\n            \"--hash=sha384:59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c\"\n            \"3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f \"\n            \"--hash=sha256:486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8\"\n            \"e5a6c65260e9cb8a7\"\n        )\n        filename = \"filename\"\n        req = line_processor(line, filename, 1)[0]\n        assert req.hash_options == {\n            \"sha256\": [\n                \"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\n                \"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\",\n            ],\n            \"sha384\": [\n                \"59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcd\"\n                \"b9c666fa90125a3c79f90397bdf5f6a13de828684f\"\n            ],\n        }\n\n    def test_set_isolated(\n        self, line_processor: LineProcessor, options: mock.Mock\n    ) -> None:\n        line = \"SomeProject\"\n        filename = \"filename\"\n        options.isolated_mode = True\n        result = line_processor(line, filename, 1, options=options)\n        assert result[0].isolated\n\n    def test_set_finder_no_index(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--no-index\", \"file\", 1, finder=finder)\n        assert finder.index_urls == []\n\n    def test_set_finder_no_index_is_remembered_for_later_invocations(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--no-index\", \"file\", 1, finder=finder)\n        line_processor(\"--index-url=url\", \"file\", 1, finder=finder)\n        assert finder.index_urls == []\n\n    def test_set_finder_index_url(\n        self, line_processor: LineProcessor, finder: PackageFinder, session: PipSession\n    ) -> None:\n        line_processor(\"--index-url=url\", \"file\", 1, finder=finder, session=session)\n        assert finder.index_urls == [\"url\"]\n        assert session.auth.index_urls == [\"url\"]\n\n    def test_set_finder_find_links(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--find-links=url\", \"file\", 1, finder=finder)\n        assert finder.find_links == [\"url\"]\n\n    def test_set_finder_extra_index_urls(\n        self, line_processor: LineProcessor, finder: PackageFinder, session: PipSession\n    ) -> None:\n        line_processor(\n            \"--extra-index-url=url\", \"file\", 1, finder=finder, session=session\n        )\n        assert finder.index_urls == [\"url\"]\n        assert session.auth.index_urls == [\"url\"]\n\n    def test_set_finder_trusted_host(\n        self,\n        line_processor: LineProcessor,\n        caplog: pytest.LogCaptureFixture,\n        session: PipSession,\n        finder: PackageFinder,\n    ) -> None:\n        with caplog.at_level(logging.INFO):\n            line_processor(\n                \"--trusted-host=host1 --trusted-host=host2:8080\",\n                \"file.txt\",\n                1,\n                finder=finder,\n                session=session,\n            )\n        assert list(finder.trusted_hosts) == [\"host1\", \"host2:8080\"]\n        session = finder._link_collector.session\n        assert session.adapters[\"https://host1/\"] is session._trusted_host_adapter\n        assert session.adapters[\"https://host2:8080/\"] is session._trusted_host_adapter\n\n        # Test the log message.\n        actual = [(r.levelname, r.message) for r in caplog.records]\n        expected = (\"INFO\", \"adding trusted host: 'host1' (from line 1 of file.txt)\")\n        assert expected in actual\n\n    def test_set_finder_allow_all_prereleases(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--pre\", \"file\", 1, finder=finder)\n        # --pre should add :all: to release_control.all_releases\n        assert finder._candidate_prefs.release_control is not None\n        assert \":all:\" in finder._candidate_prefs.release_control.all_releases\n\n    def test_set_finder_all_releases(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--all-releases :all:\", \"file\", 1, finder=finder)\n        assert finder._candidate_prefs.release_control is not None\n        assert \":all:\" in finder._candidate_prefs.release_control.all_releases\n\n    def test_set_finder_all_releases_specific_package(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--all-releases pkg1,pkg2\", \"file\", 1, finder=finder)\n        assert finder._candidate_prefs.release_control is not None\n        assert \"pkg1\" in finder._candidate_prefs.release_control.all_releases\n        assert \"pkg2\" in finder._candidate_prefs.release_control.all_releases\n\n    def test_set_finder_only_final(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--only-final :all:\", \"file\", 1, finder=finder)\n        assert finder._candidate_prefs.release_control is not None\n        assert \":all:\" in finder._candidate_prefs.release_control.only_final\n\n    def test_set_finder_only_final_specific_package(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--only-final pkg1,pkg2\", \"file\", 1, finder=finder)\n        assert finder._candidate_prefs.release_control is not None\n        assert \"pkg1\" in finder._candidate_prefs.release_control.only_final\n        assert \"pkg2\" in finder._candidate_prefs.release_control.only_final\n\n    def test_use_feature(\n        self, line_processor: LineProcessor, options: mock.Mock\n    ) -> None:\n        \"\"\"--use-feature can be set in requirements files.\"\"\"\n        line_processor(\"--use-feature=fast-deps\", \"filename\", 1, options=options)\n\n    def test_use_feature_with_error(\n        self, line_processor: LineProcessor, options: mock.Mock\n    ) -> None:\n        \"\"\"--use-feature triggers error when parsing requirements files.\"\"\"\n        with pytest.raises(RequirementsFileParseError):\n            line_processor(\"--use-feature=resolvelib\", \"filename\", 1, options=options)\n\n    def test_relative_local_find_links(\n        self,\n        line_processor: LineProcessor,\n        finder: PackageFinder,\n        monkeypatch: pytest.MonkeyPatch,\n        tmpdir: Path,\n    ) -> None:\n        \"\"\"\n        Test a relative find_links path is joined with the req file directory\n        \"\"\"\n        base_path = tmpdir / \"path\"\n\n        def normalize(path: Path) -> str:\n            return os.path.normcase(os.path.abspath(os.path.normpath(str(path))))\n\n        # Make sure the test also passes on windows\n        req_file = normalize(base_path / \"req_file.txt\")\n        nested_link = normalize(base_path / \"rel_path\")\n        exists_ = os.path.exists\n\n        def exists(path: str) -> bool:\n            if path == nested_link:\n                return True\n            else:\n                return exists_(path)\n\n        monkeypatch.setattr(os.path, \"exists\", exists)\n        line_processor(\"--find-links=rel_path\", req_file, 1, finder=finder)\n        assert finder.find_links == [nested_link]\n\n    def test_relative_http_nested_req_files(\n        self,\n        finder: PackageFinder,\n        session: PipSession,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        \"\"\"\n        Test a relative nested req file path is joined with the req file url\n        \"\"\"\n        req_name = \"hello\"\n        req_file = \"http://me.com/me/req_file.txt\"\n\n        def get_file_content(\n            filename: str, *args: Any, **kwargs: Any\n        ) -> tuple[None, str]:\n            if filename == req_file:\n                return None, \"-r reqs.txt\"\n            elif filename == \"http://me.com/me/reqs.txt\":\n                return None, req_name\n            pytest.fail(f\"Unexpected file requested {filename}\")\n\n        monkeypatch.setattr(\n            pip._internal.req.req_file, \"get_file_content\", get_file_content\n        )\n\n        result = list(parse_reqfile(req_file, session=session))\n        assert len(result) == 1\n        assert result[0].name == req_name\n        assert not result[0].constraint\n\n    def test_relative_local_nested_req_files(\n        self, session: PipSession, monkeypatch: pytest.MonkeyPatch, tmpdir: Path\n    ) -> None:\n        \"\"\"\n        Test a relative nested req file path is joined with the req file dir\n        \"\"\"\n        req_name = \"hello\"\n        req_file = tmpdir / \"parent\" / \"req_file.txt\"\n        req_file.parent.mkdir()\n        req_file.write_text(\"-r reqs.txt\")\n        req_file.parent.joinpath(\"reqs.txt\").write_text(req_name)\n\n        monkeypatch.chdir(str(tmpdir))\n\n        reqs = list(parse_reqfile(\"./parent/req_file.txt\", session=session))\n        assert len(reqs) == 1\n        assert reqs[0].name == req_name\n        assert not reqs[0].constraint\n\n    def test_absolute_local_nested_req_files(\n        self, session: PipSession, tmpdir: Path\n    ) -> None:\n        \"\"\"\n        Test an absolute nested req file path\n        \"\"\"\n        req_name = \"hello\"\n        req_file = tmpdir / \"parent\" / \"req_file.txt\"\n        req_file.parent.mkdir()\n        other_req_file = tmpdir / \"other\" / \"reqs.txt\"\n        other_req_file.parent.mkdir()\n        # POSIX-ify the path, since Windows backslashes aren't supported.\n        other_req_file_str = str(other_req_file).replace(\"\\\\\", \"/\")\n\n        req_file.write_text(f\"-r {other_req_file_str}\")\n        other_req_file.write_text(req_name)\n\n        reqs = list(parse_reqfile(str(req_file), session=session))\n        assert len(reqs) == 1\n        assert reqs[0].name == req_name\n        assert not reqs[0].constraint\n\n    def test_absolute_http_nested_req_file_in_local(\n        self, session: PipSession, monkeypatch: pytest.MonkeyPatch, tmpdir: Path\n    ) -> None:\n        \"\"\"\n        Test a nested req file url in a local req file\n        \"\"\"\n        req_name = \"hello\"\n        req_file = tmpdir / \"req_file.txt\"\n        nested_req_file = \"http://me.com/me/req_file.txt\"\n\n        def get_file_content(\n            filename: str, *args: Any, **kwargs: Any\n        ) -> tuple[None, str]:\n            if filename == str(req_file):\n                return None, f\"-r {nested_req_file}\"\n            elif filename == nested_req_file:\n                return None, req_name\n            pytest.fail(f\"Unexpected file requested {filename}\")\n\n        monkeypatch.setattr(\n            pip._internal.req.req_file, \"get_file_content\", get_file_content\n        )\n\n        result = list(parse_reqfile(req_file, session=session))\n        assert len(result) == 1\n        assert result[0].name == req_name\n        assert not result[0].constraint\n\n\nclass TestBreakOptionsArgs:\n    def test_no_args(self) -> None:\n        assert (\"\", \"--option\") == break_args_options(\"--option\")\n\n    def test_no_options(self) -> None:\n        assert (\"arg arg\", \"\") == break_args_options(\"arg arg\")\n\n    def test_args_short_options(self) -> None:\n        result = break_args_options(\"arg arg -s\")\n        assert (\"arg arg\", \"-s\") == result\n\n    def test_args_long_options(self) -> None:\n        result = break_args_options(\"arg arg --long\")\n        assert (\"arg arg\", \"--long\") == result\n\n\nclass TestOptionVariants:\n    # this suite is really just testing optparse, but added it anyway\n\n    def test_variant1(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"-i url\", \"file\", 1, finder=finder)\n        assert finder.index_urls == [\"url\"]\n\n    def test_variant2(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"-i 'url'\", \"file\", 1, finder=finder)\n        assert finder.index_urls == [\"url\"]\n\n    def test_variant3(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--index-url=url\", \"file\", 1, finder=finder)\n        assert finder.index_urls == [\"url\"]\n\n    def test_variant4(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--index-url url\", \"file\", 1, finder=finder)\n        assert finder.index_urls == [\"url\"]\n\n    def test_variant5(\n        self, line_processor: LineProcessor, finder: PackageFinder\n    ) -> None:\n        line_processor(\"--index-url='url'\", \"file\", 1, finder=finder)\n        assert finder.index_urls == [\"url\"]\n\n\nclass TestParseRequirements:\n    \"\"\"tests for `parse_reqfile`\"\"\"\n\n    @pytest.mark.network\n    def test_remote_reqs_parse(self) -> None:\n        \"\"\"\n        Test parsing a simple remote requirements file\n        \"\"\"\n        # this requirements file just contains a comment previously this has\n        # failed in py3: https://github.com/pypa/pip/issues/760\n        for _ in parse_reqfile(\n            \"https://raw.githubusercontent.com/pypa/\"\n            \"pip-test-package/master/\"\n            \"tests/req_just_comment.txt\",\n            session=PipSession(),\n        ):\n            pass\n\n    def test_multiple_appending_options(\n        self, tmpdir: Path, finder: PackageFinder, options: mock.Mock\n    ) -> None:\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"--extra-index-url url1 \\n\")\n            fp.write(\"--extra-index-url url2 \")\n\n        list(\n            parse_reqfile(\n                tmpdir.joinpath(\"req1.txt\"),\n                finder=finder,\n                session=PipSession(),\n                options=options,\n            )\n        )\n\n        assert finder.index_urls == [\"url1\", \"url2\"]\n\n    def test_expand_existing_env_variables(\n        self, tmpdir: Path, finder: PackageFinder\n    ) -> None:\n        template = \"https://{}:x-oauth-basic@github.com/user/{}/archive/master.zip\"\n\n        def make_var(name: str) -> str:\n            return f\"${{{name}}}\"\n\n        env_vars = collections.OrderedDict(\n            [\n                (\"GITHUB_TOKEN\", \"notarealtoken\"),\n                (\"DO_12_FACTOR\", \"awwyeah\"),\n            ]\n        )\n\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(template.format(*map(make_var, env_vars)))\n\n        # Construct the session outside the monkey-patch, since it access the\n        # env\n        session = PipSession()\n        with mock.patch(\"pip._internal.req.req_file.os.getenv\") as getenv:\n            getenv.side_effect = lambda n: env_vars[n]\n\n            reqs = list(\n                parse_reqfile(\n                    tmpdir.joinpath(\"req1.txt\"), finder=finder, session=session\n                )\n            )\n\n        assert len(reqs) == 1, \"parsing requirement file with env variable failed\"\n\n        expected_url = template.format(*env_vars.values())\n        assert reqs[0].link is not None\n        assert reqs[0].link.url == expected_url, \"variable expansion in req file failed\"\n\n    def test_expand_missing_env_variables(\n        self, tmpdir: Path, finder: PackageFinder\n    ) -> None:\n        req_url = (\n            \"https://${NON_EXISTENT_VARIABLE}:$WRONG_FORMAT@\"\n            \"%WINDOWS_FORMAT%github.com/user/repo/archive/master.zip\"\n        )\n\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(req_url)\n\n        # Construct the session outside the monkey-patch, since it access the\n        # env\n        session = PipSession()\n        with mock.patch(\"pip._internal.req.req_file.os.getenv\") as getenv:\n            getenv.return_value = \"\"\n\n            reqs = list(\n                parse_reqfile(\n                    tmpdir.joinpath(\"req1.txt\"), finder=finder, session=session\n                )\n            )\n\n            assert len(reqs) == 1, \"parsing requirement file with env variable failed\"\n            assert reqs[0].link is not None\n            assert (\n                reqs[0].link.url == req_url\n            ), \"ignoring invalid env variable in req file failed\"\n\n    def test_join_lines(self, tmpdir: Path, finder: PackageFinder) -> None:\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"--extra-index-url url1 \\\\\\n--extra-index-url url2\")\n\n        list(\n            parse_reqfile(\n                tmpdir.joinpath(\"req1.txt\"), finder=finder, session=PipSession()\n            )\n        )\n\n        assert finder.index_urls == [\"url1\", \"url2\"]\n\n    def test_req_file_parse_no_only_binary(\n        self, data: TestData, finder: PackageFinder\n    ) -> None:\n        list(\n            parse_reqfile(\n                data.reqfiles.joinpath(\"supported_options2.txt\"),\n                finder=finder,\n                session=PipSession(),\n            )\n        )\n        expected = FormatControl({\"fred\"}, {\"wilma\"})\n        assert finder.format_control == expected\n\n    def test_req_file_parse_comment_start_of_line(\n        self, tmpdir: Path, finder: PackageFinder\n    ) -> None:\n        \"\"\"\n        Test parsing comments in a requirements file\n        \"\"\"\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"# Comment \")\n\n        reqs = list(\n            parse_reqfile(\n                tmpdir.joinpath(\"req1.txt\"), finder=finder, session=PipSession()\n            )\n        )\n\n        assert not reqs\n\n    def test_invalid_options(self, tmpdir: Path, finder: PackageFinder) -> None:\n        \"\"\"\n        Test parsing invalid options such as missing closing quotation\n        \"\"\"\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"--'data\\n\")\n\n        with pytest.raises(RequirementsFileParseError):\n            list(\n                parse_reqfile(\n                    tmpdir.joinpath(\"req1.txt\"), finder=finder, session=PipSession()\n                )\n            )\n\n    def test_req_file_parse_comment_end_of_line_with_url(\n        self, tmpdir: Path, finder: PackageFinder\n    ) -> None:\n        \"\"\"\n        Test parsing comments in a requirements file\n        \"\"\"\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"https://example.com/foo.tar.gz # Comment \")\n\n        reqs = list(\n            parse_reqfile(\n                tmpdir.joinpath(\"req1.txt\"), finder=finder, session=PipSession()\n            )\n        )\n\n        assert len(reqs) == 1\n        assert reqs[0].link is not None\n        assert reqs[0].link.url == \"https://example.com/foo.tar.gz\"\n\n    def test_req_file_parse_egginfo_end_of_line_with_url(\n        self, tmpdir: Path, finder: PackageFinder\n    ) -> None:\n        \"\"\"\n        Test parsing comments in a requirements file\n        \"\"\"\n        with open(tmpdir.joinpath(\"req1.txt\"), \"w\") as fp:\n            fp.write(\"https://example.com/foo.tar.gz#egg=wat\")\n\n        reqs = list(\n            parse_reqfile(\n                tmpdir.joinpath(\"req1.txt\"), finder=finder, session=PipSession()\n            )\n        )\n\n        assert len(reqs) == 1\n        assert reqs[0].name == \"wat\"\n\n    def test_req_file_no_finder(self, tmpdir: Path) -> None:\n        \"\"\"\n        Test parsing a requirements file without a finder\n        \"\"\"\n        with open(tmpdir.joinpath(\"req.txt\"), \"w\") as fp:\n            fp.write(\n                \"\"\"\n    --find-links https://example.com/\n    --index-url https://example.com/\n    --extra-index-url https://two.example.com/\n    --no-use-wheel\n    --no-index\n            \"\"\"\n            )\n\n        parse_reqfile(tmpdir.joinpath(\"req.txt\"), session=PipSession())\n\n    @pytest.mark.parametrize(\n        \"raw_req_file,expected_name,expected_spec\",\n        [\n            pytest.param(\n                b\"Django==1.4.2\",\n                \"Django\",\n                \"==1.4.2\",\n                id=\"defaults to UTF-8\",\n            ),\n            pytest.param(\n                \"# coding=latin1\\nDjango==1.4.2 # Pas trop de café\".encode(\"latin-1\"),\n                \"Django\",\n                \"==1.4.2\",\n                id=\"decodes based on PEP-263 style headers\",\n            ),\n        ],\n    )\n    def test_general_decoding(\n        self,\n        raw_req_file: bytes,\n        expected_name: str,\n        expected_spec: str,\n        tmpdir: Path,\n        session: PipSession,\n    ) -> None:\n        req_file = tmpdir / \"requirements.txt\"\n        req_file.write_bytes(raw_req_file)\n\n        reqs = tuple(parse_reqfile(req_file.resolve(), session=session))\n\n        assert len(reqs) == 1\n        assert reqs[0].name == expected_name\n        assert reqs[0].specifier == expected_spec\n\n    @pytest.mark.parametrize(\n        \"bom,encoding\",\n        [\n            (codecs.BOM_UTF8, \"utf-8\"),\n            (codecs.BOM_UTF16_BE, \"utf-16-be\"),\n            (codecs.BOM_UTF16_LE, \"utf-16-le\"),\n            (codecs.BOM_UTF32_BE, \"utf-32-be\"),\n            (codecs.BOM_UTF32_LE, \"utf-32-le\"),\n            # BOM automatically added when encoding byte-order dependent encodings\n            (b\"\", \"utf-16\"),\n            (b\"\", \"utf-32\"),\n        ],\n    )\n    def test_decoding_with_BOM(\n        self, bom: bytes, encoding: str, tmpdir: Path, session: PipSession\n    ) -> None:\n        req_name = \"Django\"\n        req_specifier = \"==1.4.2\"\n        encoded_contents = bom + f\"{req_name}{req_specifier}\".encode(encoding)\n        req_file = tmpdir / \"requirements.txt\"\n        req_file.write_bytes(encoded_contents)\n\n        reqs = tuple(parse_reqfile(req_file.resolve(), session=session))\n\n        assert len(reqs) == 1\n        assert reqs[0].name == req_name\n        assert reqs[0].specifier == req_specifier\n\n    def test_warns_and_falls_back_to_locale_on_utf8_decode_fail(\n        self,\n        tmpdir: Path,\n        session: PipSession,\n        caplog: pytest.LogCaptureFixture,\n    ) -> None:\n        # \\xff is valid in latin-1 but not UTF-8\n        data = b\"pip<=24.0 # some comment\\xff\\n\"\n        locale_encoding = \"latin-1\"\n        req_file = tmpdir / \"requirements.txt\"\n        req_file.write_bytes(data)\n\n        # it's hard to rely on a locale definitely existing for testing\n        # so patch things out for simplicity\n        with (\n            caplog.at_level(logging.WARNING),\n            mock.patch(\"locale.getpreferredencoding\", return_value=locale_encoding),\n        ):\n            reqs = tuple(parse_reqfile(req_file.resolve(), session=session))\n\n        assert len(caplog.records) == 1\n        assert (\n            caplog.records[0].msg\n            == \"unable to decode data from %s with default encoding %s, \"\n            \"falling back to encoding from locale: %s. \"\n            \"If this is intentional you should specify the encoding with a \"\n            \"PEP-263 style comment, e.g. '# -*- coding: %s -*-'\"\n        )\n        assert caplog.records[0].args == (\n            str(req_file),\n            \"utf-8\",\n            locale_encoding,\n            locale_encoding,\n        )\n\n        assert len(reqs) == 1\n        assert reqs[0].name == \"pip\"\n        assert str(reqs[0].specifier) == \"<=24.0\"\n\n    @pytest.mark.parametrize(\"encoding\", [\"utf-8\", \"gbk\"])\n    def test_errors_on_non_decodable_data(\n        self, encoding: str, tmpdir: Path, session: PipSession\n    ) -> None:\n        data = b\"\\xff\"\n        req_file = tmpdir / \"requirements.txt\"\n        req_file.write_bytes(data)\n\n        with (\n            pytest.raises(UnicodeDecodeError),\n            mock.patch(\"locale.getpreferredencoding\", return_value=encoding),\n        ):\n            next(parse_reqfile(req_file.resolve(), session=session))\n"
  },
  {
    "path": "tests/unit/test_req_install.py",
    "content": "import os\nimport tempfile\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.req.constructors import (\n    install_req_from_line,\n    install_req_from_req_string,\n)\nfrom pip._internal.req.req_install import InstallRequirement\n\n\nclass TestInstallRequirementBuildDirectory:\n    # no need to test symlinks on Windows\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_tmp_build_directory(self) -> None:\n        # when req is None, we can produce a temporary directory\n        # Make sure we're handling it correctly with real path.\n        requirement = InstallRequirement(None, None)\n        tmp_dir = tempfile.mkdtemp(\"-build\", \"pip-\")\n        tmp_build_dir = requirement.ensure_build_location(\n            tmp_dir,\n            autodelete=False,\n            parallel_builds=False,\n        )\n        assert os.path.dirname(tmp_build_dir) == os.path.realpath(\n            os.path.dirname(tmp_dir)\n        )\n        # are we on a system where /tmp is a symlink\n        if os.path.realpath(tmp_dir) != os.path.abspath(tmp_dir):\n            assert os.path.dirname(tmp_build_dir) != os.path.dirname(tmp_dir)\n        else:\n            assert os.path.dirname(tmp_build_dir) == os.path.dirname(tmp_dir)\n        os.rmdir(tmp_dir)\n        assert not os.path.exists(tmp_dir)\n\n    def test_forward_slash_results_in_a_link(self, tmpdir: Path) -> None:\n        install_dir = tmpdir / \"foo\" / \"bar\"\n\n        # Just create a file for letting the logic work\n        setup_py_path = install_dir / \"setup.py\"\n        os.makedirs(str(install_dir))\n        with open(setup_py_path, \"w\") as f:\n            f.write(\"\")\n\n        requirement = install_req_from_line(install_dir.as_posix())\n\n        assert requirement.link is not None\n\n\nclass TestInstallRequirementFrom:\n    def test_install_req_from_string_invalid_requirement(self) -> None:\n        \"\"\"\n        Requirement strings that cannot be parsed by\n        packaging.requirements.Requirement raise an InstallationError.\n        \"\"\"\n        with pytest.raises(InstallationError) as excinfo:\n            install_req_from_req_string(\"http:/this/is/invalid\")\n\n        assert str(excinfo.value) == (\n            \"Invalid requirement: 'http:/this/is/invalid': \"\n            \"Expected semicolon (after name with no version specifier) or end\\n\"\n            \"    http:/this/is/invalid\\n\"\n            \"        ^\"\n        )\n\n    def test_install_req_from_string_without_comes_from(self) -> None:\n        \"\"\"\n        Test to make sure that install_req_from_string succeeds\n        when called with URL (PEP 508) but without comes_from.\n        \"\"\"\n        # Test with a PEP 508 url install string:\n        wheel_url = (\n            \"https://download.pytorch.org/whl/cu90/\"\n            \"torch-1.0.0-cp36-cp36m-win_amd64.whl\"\n        )\n        install_str = \"torch@ \" + wheel_url\n        install_req = install_req_from_req_string(install_str)\n\n        assert isinstance(install_req, InstallRequirement)\n        assert install_req.link is not None\n        assert install_req.link.url == wheel_url\n        assert install_req.req is not None\n        assert install_req.req.url == wheel_url\n        assert install_req.comes_from is None\n        assert install_req.is_wheel\n\n    def test_install_req_from_string_with_comes_from_without_link(self) -> None:\n        \"\"\"\n        Test to make sure that install_req_from_string succeeds\n        when called with URL (PEP 508) and comes_from\n        does not have a link.\n        \"\"\"\n        # Test with a PEP 508 url install string:\n        wheel_url = (\n            \"https://download.pytorch.org/whl/cu90/\"\n            \"torch-1.0.0-cp36-cp36m-win_amd64.whl\"\n        )\n        install_str = \"torch@ \" + wheel_url\n\n        # Dummy numpy \"comes_from\" requirement without link:\n        comes_from = InstallRequirement(Requirement(\"numpy>=1.15.0\"), comes_from=None)\n\n        # Attempt install from install string comes:\n        install_req = install_req_from_req_string(install_str, comes_from=comes_from)\n\n        assert isinstance(install_req, InstallRequirement)\n        assert isinstance(install_req.comes_from, InstallRequirement)\n        assert install_req.comes_from.link is None\n        assert install_req.link is not None\n        assert install_req.link.url == wheel_url\n        assert install_req.req is not None\n        assert install_req.req.url == wheel_url\n        assert install_req.is_wheel\n"
  },
  {
    "path": "tests/unit/test_req_uninstall.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\nfrom collections.abc import Iterator\nfrom pathlib import Path\nfrom unittest.mock import Mock\n\nimport pytest\n\nimport pip._internal.req.req_uninstall\nfrom pip._internal.req.req_uninstall import (\n    StashedUninstallPathSet,\n    UninstallPathSet,\n    UninstallPthEntries,\n    compact,\n    compress_for_output_listing,\n    compress_for_rename,\n    uninstallation_paths,\n)\n\nfrom tests.lib.filesystem import create_file\n\n\n# Pretend all files are local, so UninstallPathSet accepts files in the tmpdir,\n# outside the virtualenv\ndef mock_permitted(ups: UninstallPathSet, path: str) -> bool:\n    return True\n\n\ndef test_uninstallation_paths() -> None:\n    class dist:\n        def iter_declared_entries(self) -> Iterator[str] | None:\n            return iter([\"file.py\", \"file.pyc\", \"file.so\", \"nopyc.py\"])\n\n        location = \"\"\n\n    d = dist()\n\n    paths = list(uninstallation_paths(d))\n\n    expected = [\n        \"file.py\",\n        \"file.pyc\",\n        \"file.pyo\",\n        \"file.so\",\n        \"nopyc.py\",\n        \"nopyc.pyc\",\n        \"nopyc.pyo\",\n    ]\n\n    assert paths == expected\n\n    # Avoid an easy 'unique generator' bug\n    paths2 = list(uninstallation_paths(d))\n\n    assert paths2 == paths\n\n\ndef test_compressed_listing(tmpdir: Path) -> None:\n    def in_tmpdir(paths: list[str]) -> list[str]:\n        return [\n            str(os.path.join(tmpdir, path.replace(\"/\", os.path.sep))) for path in paths\n        ]\n\n    sample = in_tmpdir(\n        [\n            \"lib/mypkg.dist-info/METADATA\",\n            \"lib/mypkg.dist-info/PKG-INFO\",\n            \"lib/mypkg/would_be_removed.txt\",\n            \"lib/mypkg/would_be_skipped.skip.txt\",\n            \"lib/mypkg/__init__.py\",\n            \"lib/mypkg/my_awesome_code.py\",\n            \"lib/mypkg/__pycache__/my_awesome_code-magic.pyc\",\n            \"lib/mypkg/support/support_file.py\",\n            \"lib/mypkg/support/more_support.py\",\n            \"lib/mypkg/support/would_be_skipped.skip.py\",\n            \"lib/mypkg/support/__pycache__/support_file-magic.pyc\",\n            \"lib/random_other_place/file_without_a_dot_pyc\",\n            \"bin/mybin\",\n        ]\n    )\n\n    # Create the required files\n    for fname in sample:\n        create_file(fname, \"random blub\")\n\n    # Remove the files to be skipped from the paths\n    sample = [path for path in sample if \".skip.\" not in path]\n\n    expected_remove = in_tmpdir(\n        [\n            \"bin/mybin\",\n            \"lib/mypkg.dist-info/*\",\n            \"lib/mypkg/*\",\n            \"lib/random_other_place/file_without_a_dot_pyc\",\n        ]\n    )\n\n    expected_skip = in_tmpdir(\n        [\n            \"lib/mypkg/would_be_skipped.skip.txt\",\n            \"lib/mypkg/support/would_be_skipped.skip.py\",\n        ]\n    )\n\n    expected_rename = in_tmpdir(\n        [\n            \"bin/\",\n            \"lib/mypkg.dist-info/\",\n            \"lib/mypkg/would_be_removed.txt\",\n            \"lib/mypkg/__init__.py\",\n            \"lib/mypkg/my_awesome_code.py\",\n            \"lib/mypkg/__pycache__/\",\n            \"lib/mypkg/support/support_file.py\",\n            \"lib/mypkg/support/more_support.py\",\n            \"lib/mypkg/support/__pycache__/\",\n            \"lib/random_other_place/\",\n        ]\n    )\n\n    will_remove, will_skip = compress_for_output_listing(sample)\n    will_rename = compress_for_rename(sample)\n    assert sorted(expected_skip) == sorted(compact(will_skip))\n    assert sorted(expected_remove) == sorted(compact(will_remove))\n    assert sorted(expected_rename) == sorted(compact(will_rename))\n\n\nclass TestUninstallPathSet:\n    def test_add(self, tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(\n            pip._internal.req.req_uninstall.UninstallPathSet,\n            \"_permitted\",\n            mock_permitted,\n        )\n        # Fix case for windows tests\n        file_extant = os.path.normcase(os.path.join(tmpdir, \"foo\"))\n        file_nonexistent = os.path.normcase(os.path.join(tmpdir, \"nonexistent\"))\n        with open(file_extant, \"w\"):\n            pass\n\n        ups = UninstallPathSet(dist=Mock())\n        assert ups._paths == set()\n        ups.add(file_extant)\n        assert ups._paths == {file_extant}\n\n        ups.add(file_nonexistent)\n        assert ups._paths == {file_extant}\n\n    def test_add_pth(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(\n            pip._internal.req.req_uninstall.UninstallPathSet,\n            \"_permitted\",\n            mock_permitted,\n        )\n        # Fix case for windows tests\n        tmpdir = os.path.normcase(tmp_path)\n        on_windows = sys.platform == \"win32\"\n        pth_file = os.path.join(tmpdir, \"foo.pth\")\n        relative = \"../../example\"\n        if on_windows:\n            share = \"\\\\\\\\example\\\\share\\\\\"\n            share_com = \"\\\\\\\\example.com\\\\share\\\\\"\n        # Create a .pth file for testing\n        with open(pth_file, \"w\") as f:\n            f.writelines([tmpdir, \"\\n\", relative, \"\\n\"])\n            if on_windows:\n                f.writelines([share, \"\\n\", share_com, \"\\n\"])\n        # Add paths to be removed\n        pth = UninstallPthEntries(pth_file)\n        pth.add(tmpdir)\n        pth.add(relative)\n        if on_windows:\n            pth.add(share)\n            pth.add(share_com)\n        # Check that the paths were added to entries\n        if on_windows:\n            check = {tmpdir, relative, share, share_com}\n        else:\n            check = {tmpdir, relative}\n        assert pth.entries == check\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_add_symlink(self, tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(\n            pip._internal.req.req_uninstall.UninstallPathSet,\n            \"_permitted\",\n            mock_permitted,\n        )\n        f = os.path.join(tmpdir, \"foo\")\n        with open(f, \"w\"):\n            pass\n        foo_link = os.path.join(tmpdir, \"foo_link\")\n        os.symlink(f, foo_link)\n\n        ups = UninstallPathSet(dist=Mock())\n        ups.add(foo_link)\n        assert ups._paths == {foo_link}\n\n    def test_compact_shorter_path(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(\n            pip._internal.req.req_uninstall.UninstallPathSet,\n            \"_permitted\",\n            mock_permitted,\n        )\n        monkeypatch.setattr(\"os.path.exists\", lambda p: True)\n        # This deals with nt/posix path differences\n        short_path = os.path.normcase(\n            os.path.abspath(os.path.join(os.path.sep, \"path\"))\n        )\n        ups = UninstallPathSet(dist=Mock())\n        ups.add(short_path)\n        ups.add(os.path.join(short_path, \"longer\"))\n        assert compact(ups._paths) == {short_path}\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_detect_symlink_dirs(\n        self, monkeypatch: pytest.MonkeyPatch, tmpdir: Path\n    ) -> None:\n        monkeypatch.setattr(\n            pip._internal.req.req_uninstall.UninstallPathSet,\n            \"_permitted\",\n            mock_permitted,\n        )\n\n        # construct 2 paths:\n        #  tmpdir/dir/file\n        #  tmpdir/dirlink/file (where dirlink is a link to dir)\n        d = tmpdir.joinpath(\"dir\")\n        d.mkdir()\n        dlink = tmpdir.joinpath(\"dirlink\")\n        os.symlink(d, dlink)\n        d.joinpath(\"file\").touch()\n        path1 = str(d.joinpath(\"file\"))\n        path2 = str(dlink.joinpath(\"file\"))\n\n        ups = UninstallPathSet(dist=Mock())\n        ups.add(path1)\n        ups.add(path2)\n        assert ups._paths == {path1}\n\n\nclass TestStashedUninstallPathSet:\n    WALK_RESULT: list[tuple[str, list[str], list[str]]] = [\n        (\"A\", [\"B\", \"C\"], [\"a.py\"]),\n        (\"A/B\", [\"D\"], [\"b.py\"]),\n        (\"A/B/D\", [], [\"c.py\"]),\n        (\"A/C\", [], [\"d.py\", \"e.py\"]),\n        (\"A/E\", [\"F\"], [\"f.py\"]),\n        (\"A/E/F\", [], []),\n        (\"A/G\", [\"H\"], [\"g.py\"]),\n        (\"A/G/H\", [], [\"h.py\"]),\n    ]\n\n    @classmethod\n    def mock_walk(cls, root: str) -> Iterator[tuple[str, list[str], list[str]]]:\n        for dirname, subdirs, files in cls.WALK_RESULT:\n            dirname = os.path.sep.join(dirname.split(\"/\"))\n            if dirname.startswith(root):\n                yield dirname[len(root) + 1 :], subdirs, files\n\n    def test_compress_for_rename(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        paths = [\n            os.path.sep.join(p.split(\"/\"))\n            for p in [\n                \"A/B/b.py\",\n                \"A/B/D/c.py\",\n                \"A/C/d.py\",\n                \"A/E/f.py\",\n                \"A/G/g.py\",\n            ]\n        ]\n\n        expected_paths = [\n            os.path.sep.join(p.split(\"/\"))\n            for p in [\n                \"A/B/\",  # selected everything below A/B\n                \"A/C/d.py\",  # did not select everything below A/C\n                \"A/E/\",  # only empty folders remain under A/E\n                \"A/G/g.py\",  # non-empty folder remains under A/G\n            ]\n        ]\n\n        monkeypatch.setattr(\"os.walk\", self.mock_walk)\n\n        actual_paths = compress_for_rename(paths)\n        assert set(expected_paths) == set(actual_paths)\n\n    @classmethod\n    def make_stash(\n        cls, tmpdir: Path, paths: list[str]\n    ) -> tuple[StashedUninstallPathSet, list[tuple[str, str]]]:\n        for dirname, subdirs, files in cls.WALK_RESULT:\n            root = os.path.join(tmpdir, *dirname.split(\"/\"))\n            if not os.path.exists(root):\n                os.mkdir(root)\n            for d in subdirs:\n                os.mkdir(os.path.join(root, d))\n            for f in files:\n                with open(os.path.join(root, f), \"wb\"):\n                    pass\n\n        pathset = StashedUninstallPathSet()\n\n        paths = [os.path.join(tmpdir, *p.split(\"/\")) for p in paths]\n        stashed_paths = [(p, pathset.stash(p)) for p in paths]\n\n        return pathset, stashed_paths\n\n    def test_stash(self, tmpdir: Path) -> None:\n        pathset, stashed_paths = self.make_stash(\n            tmpdir,\n            [\n                \"A/B/\",\n                \"A/C/d.py\",\n                \"A/E/\",\n                \"A/G/g.py\",\n            ],\n        )\n\n        for old_path, new_path in stashed_paths:\n            assert not os.path.exists(old_path)\n            assert os.path.exists(new_path)\n\n        assert stashed_paths == pathset._moves\n\n    def test_commit(self, tmpdir: Path) -> None:\n        pathset, stashed_paths = self.make_stash(\n            tmpdir,\n            [\n                \"A/B/\",\n                \"A/C/d.py\",\n                \"A/E/\",\n                \"A/G/g.py\",\n            ],\n        )\n\n        pathset.commit()\n\n        for old_path, new_path in stashed_paths:\n            assert not os.path.exists(old_path)\n            assert not os.path.exists(new_path)\n\n    def test_rollback(self, tmpdir: Path) -> None:\n        pathset, stashed_paths = self.make_stash(\n            tmpdir,\n            [\n                \"A/B/\",\n                \"A/C/d.py\",\n                \"A/E/\",\n                \"A/G/g.py\",\n            ],\n        )\n\n        pathset.rollback()\n\n        for old_path, new_path in stashed_paths:\n            assert os.path.exists(old_path)\n            assert not os.path.exists(new_path)\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_commit_symlinks(self, tmpdir: Path) -> None:\n        adir = tmpdir / \"dir\"\n        adir.mkdir()\n        dirlink = tmpdir / \"dirlink\"\n        dirlink.symlink_to(adir)\n        afile = tmpdir / \"file\"\n        afile.write_text(\"...\")\n        filelink = tmpdir / \"filelink\"\n        filelink.symlink_to(afile)\n\n        pathset = StashedUninstallPathSet()\n        stashed_paths = []\n        stashed_paths.append(pathset.stash(os.fspath(dirlink)))\n        stashed_paths.append(pathset.stash(os.fspath(filelink)))\n        for stashed_path in stashed_paths:\n            assert os.path.lexists(stashed_path)\n        assert not os.path.exists(dirlink)\n        assert not os.path.exists(filelink)\n\n        pathset.commit()\n\n        # stash removed, links removed\n        for stashed_path in stashed_paths:\n            assert not os.path.lexists(stashed_path)\n        assert not os.path.lexists(dirlink)\n        assert not os.path.isdir(dirlink)\n        assert not os.path.lexists(filelink)\n        assert not os.path.isfile(filelink)\n\n        # link targets untouched\n        assert os.path.isdir(adir)\n        assert os.path.isfile(afile)\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_rollback_symlinks(self, tmpdir: Path) -> None:\n        adir = tmpdir / \"dir\"\n        adir.mkdir()\n        dirlink = tmpdir / \"dirlink\"\n        dirlink.symlink_to(adir)\n        afile = tmpdir / \"file\"\n        afile.write_text(\"...\")\n        filelink = tmpdir / \"filelink\"\n        filelink.symlink_to(afile)\n\n        pathset = StashedUninstallPathSet()\n        stashed_paths = []\n        stashed_paths.append(pathset.stash(os.fspath(dirlink)))\n        stashed_paths.append(pathset.stash(os.fspath(filelink)))\n        for stashed_path in stashed_paths:\n            assert os.path.lexists(stashed_path)\n        assert not os.path.lexists(dirlink)\n        assert not os.path.lexists(filelink)\n\n        pathset.rollback()\n\n        # stash removed, links restored\n        for stashed_path in stashed_paths:\n            assert not os.path.lexists(stashed_path)\n        assert os.path.lexists(dirlink)\n        assert os.path.isdir(dirlink)\n        assert os.path.lexists(filelink)\n        assert os.path.isfile(filelink)\n\n        # link targets untouched\n        assert os.path.isdir(adir)\n        assert os.path.isfile(afile)\n"
  },
  {
    "path": "tests/unit/test_resolution_legacy_resolver.py",
    "content": "from __future__ import annotations\n\nimport email.message\nimport logging\nimport os\nfrom typing import TypeVar, cast\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName\n\nfrom pip._internal.exceptions import (\n    InstallationError,\n    NoneMetadataError,\n    UnsupportedPythonVersion,\n)\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.req.constructors import install_req_from_line\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.legacy.resolver import (\n    Resolver,\n    _check_dist_requires_python,\n)\n\nfrom tests.lib import TestData, make_test_finder\nfrom tests.lib.index import make_mock_candidate\n\nT = TypeVar(\"T\")\n\n\nclass FakeDist(BaseDistribution):\n    def __init__(self, metadata: email.message.Message) -> None:\n        self._canonical_name = cast(NormalizedName, \"my-project\")\n        self._metadata = metadata\n\n    def __str__(self) -> str:\n        return f\"<distribution {self.canonical_name!r}>\"\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        return self._canonical_name\n\n    @property\n    def metadata(self) -> email.message.Message:\n        return self._metadata\n\n\ndef make_fake_dist(\n    *, klass: type[BaseDistribution] = FakeDist, requires_python: str | None = None\n) -> BaseDistribution:\n    metadata = email.message.Message()\n    metadata[\"Name\"] = \"my-project\"\n    if requires_python is not None:\n        metadata[\"Requires-Python\"] = requires_python\n\n    # Too many arguments for \"BaseDistribution\"\n    return klass(metadata)  # type: ignore[call-arg]\n\n\ndef make_test_resolver(\n    monkeypatch: pytest.MonkeyPatch,\n    mock_candidates: list[InstallationCandidate],\n) -> Resolver:\n    def _find_candidates(project_name: str) -> list[InstallationCandidate]:\n        return mock_candidates\n\n    finder = make_test_finder()\n    monkeypatch.setattr(finder, \"find_all_candidates\", _find_candidates)\n\n    return Resolver(\n        finder=finder,\n        preparer=mock.Mock(),  # Not used.\n        make_install_req=install_req_from_line,\n        wheel_cache=None,\n        use_user_site=False,\n        force_reinstall=False,\n        ignore_dependencies=False,\n        ignore_installed=False,\n        ignore_requires_python=False,\n        upgrade_strategy=\"to-satisfy-only\",\n    )\n\n\nclass TestAddRequirement:\n    \"\"\"\n    Test _add_requirement_to_set().\n    \"\"\"\n\n    def test_unsupported_wheel_link_requirement_raises(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # GIVEN\n        resolver = make_test_resolver(monkeypatch, [])\n        requirement_set = RequirementSet(check_supported_wheels=True)\n\n        install_req = install_req_from_line(\n            \"https://whatever.com/peppercorn-0.4-py2.py3-bogus-any.whl\",\n        )\n        assert install_req.link is not None\n        assert install_req.link.is_wheel\n        assert install_req.link.scheme == \"https\"\n\n        # WHEN / THEN\n        with pytest.raises(InstallationError):\n            resolver._add_requirement_to_set(requirement_set, install_req)\n\n    def test_unsupported_wheel_local_file_requirement_raises(\n        self, data: TestData, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # GIVEN\n        resolver = make_test_resolver(monkeypatch, [])\n        requirement_set = RequirementSet(check_supported_wheels=True)\n\n        install_req = install_req_from_line(\n            os.fspath(data.packages.joinpath(\"simple.dist-0.1-py1-none-invalid.whl\")),\n        )\n        assert install_req.link is not None\n        assert install_req.link.is_wheel\n        assert install_req.link.scheme == \"file\"\n\n        # WHEN / THEN\n        with pytest.raises(InstallationError):\n            resolver._add_requirement_to_set(requirement_set, install_req)\n\n    def test_exclusive_environment_markers(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"Make sure excluding environment markers are handled correctly.\"\"\"\n        # GIVEN\n        resolver = make_test_resolver(monkeypatch, [])\n        requirement_set = RequirementSet(check_supported_wheels=True)\n\n        eq36 = install_req_from_line(\"Django>=1.6.10,<1.7 ; python_version == '3.6'\")\n        eq36.user_supplied = True\n        ne36 = install_req_from_line(\"Django>=1.6.10,<1.8 ; python_version != '3.6'\")\n        ne36.user_supplied = True\n\n        # WHEN\n        resolver._add_requirement_to_set(requirement_set, eq36)\n        resolver._add_requirement_to_set(requirement_set, ne36)\n\n        # THEN\n        assert requirement_set.has_requirement(\"Django\")\n        assert len(requirement_set.all_requirements) == 1\n\n\nclass TestCheckDistRequiresPython:\n    \"\"\"\n    Test _check_dist_requires_python().\n    \"\"\"\n\n    def test_compatible(self, caplog: pytest.LogCaptureFixture) -> None:\n        \"\"\"\n        Test a Python version compatible with the dist's Requires-Python.\n        \"\"\"\n        caplog.set_level(logging.DEBUG)\n        dist = make_fake_dist(requires_python=\"== 3.6.5\")\n\n        _check_dist_requires_python(\n            dist,\n            version_info=(3, 6, 5),\n            ignore_requires_python=False,\n        )\n        assert not len(caplog.records)\n\n    def test_incompatible(self) -> None:\n        \"\"\"\n        Test a Python version incompatible with the dist's Requires-Python.\n        \"\"\"\n        dist = make_fake_dist(requires_python=\"== 3.6.4\")\n        with pytest.raises(UnsupportedPythonVersion) as exc:\n            _check_dist_requires_python(\n                dist,\n                version_info=(3, 6, 5),\n                ignore_requires_python=False,\n            )\n        assert str(exc.value) == (\n            \"Package 'my-project' requires a different Python: \"\n            \"3.6.5 not in '==3.6.4'\"\n        )\n\n    def test_incompatible_with_ignore_requires(\n        self, caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"\n        Test a Python version incompatible with the dist's Requires-Python\n        while passing ignore_requires_python=True.\n        \"\"\"\n        caplog.set_level(logging.DEBUG)\n        dist = make_fake_dist(requires_python=\"== 3.6.4\")\n        _check_dist_requires_python(\n            dist,\n            version_info=(3, 6, 5),\n            ignore_requires_python=True,\n        )\n        assert len(caplog.records) == 1\n        record = caplog.records[0]\n        assert record.levelname == \"DEBUG\"\n        assert record.message == (\n            \"Ignoring failed Requires-Python check for package 'my-project': \"\n            \"3.6.5 not in '==3.6.4'\"\n        )\n\n    def test_none_requires_python(self, caplog: pytest.LogCaptureFixture) -> None:\n        \"\"\"\n        Test a dist with Requires-Python None.\n        \"\"\"\n        caplog.set_level(logging.DEBUG)\n        dist = make_fake_dist()\n        # Make sure our test setup is correct.\n        assert dist.requires_python == SpecifierSet()\n        assert len(caplog.records) == 0\n\n        # Then there is no exception and no log message.\n        _check_dist_requires_python(\n            dist,\n            version_info=(3, 6, 5),\n            ignore_requires_python=False,\n        )\n        assert len(caplog.records) == 0\n\n    def test_invalid_requires_python(self, caplog: pytest.LogCaptureFixture) -> None:\n        \"\"\"\n        Test a dist with an invalid Requires-Python.\n        \"\"\"\n        caplog.set_level(logging.DEBUG)\n        dist = make_fake_dist(requires_python=\"invalid\")\n        _check_dist_requires_python(\n            dist,\n            version_info=(3, 6, 5),\n            ignore_requires_python=False,\n        )\n        assert len(caplog.records) == 1\n        record = caplog.records[0]\n        assert record.levelname == \"WARNING\"\n        assert record.message == (\n            \"Package 'my-project' has an invalid Requires-Python: \"\n            \"Invalid specifier: 'invalid'\"\n        )\n\n    @pytest.mark.parametrize(\n        \"metadata_name\",\n        [\n            \"METADATA\",\n            \"PKG-INFO\",\n        ],\n    )\n    def test_empty_metadata_error(self, metadata_name: str) -> None:\n        \"\"\"Test dist.metadata raises FileNotFoundError.\"\"\"\n\n        class NotWorkingFakeDist(FakeDist):\n            @property\n            def metadata(self) -> email.message.Message:\n                raise FileNotFoundError(metadata_name)\n\n        dist = make_fake_dist(klass=NotWorkingFakeDist)  # type: ignore\n\n        with pytest.raises(NoneMetadataError) as exc:\n            _check_dist_requires_python(\n                dist,\n                version_info=(3, 6, 5),\n                ignore_requires_python=False,\n            )\n        assert str(exc.value) == (\n            f\"None {metadata_name} metadata found for distribution: \"\n            \"<distribution 'my-project'>\"\n        )\n\n\nclass TestYankedWarning:\n    \"\"\"\n    Test _populate_link() emits warning if one or more candidates are yanked.\n    \"\"\"\n\n    def test_sort_best_candidate__has_non_yanked(\n        self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test unyanked candidate preferred over yanked.\n        \"\"\"\n        # Ignore spurious DEBUG level messages\n        # TODO: Probably better to work out why they are occurring, but IMO the\n        #       tests are at fault here for being to dependent on exact output.\n        caplog.set_level(logging.WARNING)\n        candidates = [\n            make_mock_candidate(\"1.0\"),\n            make_mock_candidate(\"2.0\", yanked_reason=\"bad metadata #2\"),\n        ]\n        ireq = install_req_from_line(\"pkg\")\n\n        resolver = make_test_resolver(monkeypatch, candidates)\n        resolver._populate_link(ireq)\n\n        assert ireq.link == candidates[0].link\n        assert len(caplog.records) == 0\n\n    def test_sort_best_candidate__all_yanked(\n        self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test all candidates yanked.\n        \"\"\"\n        # Ignore spurious DEBUG level messages\n        # TODO: Probably better to work out why they are occurring, but IMO the\n        #       tests are at fault here for being to dependent on exact output.\n        caplog.set_level(logging.WARNING)\n        candidates = [\n            make_mock_candidate(\"1.0\", yanked_reason=\"bad metadata #1\"),\n            # Put the best candidate in the middle, to test sorting.\n            make_mock_candidate(\"3.0\", yanked_reason=\"bad metadata #3\"),\n            make_mock_candidate(\"2.0\", yanked_reason=\"bad metadata #2\"),\n        ]\n        ireq = install_req_from_line(\"pkg\")\n\n        resolver = make_test_resolver(monkeypatch, candidates)\n        resolver._populate_link(ireq)\n\n        assert ireq.link == candidates[1].link\n\n        # Check the log messages.\n        assert len(caplog.records) == 1\n        record = caplog.records[0]\n        assert record.levelname == \"WARNING\"\n        assert record.message == (\n            \"The candidate selected for download or install is a yanked \"\n            \"version: 'mypackage' candidate \"\n            \"(version 3.0 at https://example.com/pkg-3.0.tar.gz)\\n\"\n            \"Reason for being yanked: bad metadata #3\"\n        )\n\n    @pytest.mark.parametrize(\n        \"yanked_reason, expected_reason\",\n        [\n            # Test no reason given.\n            (\"\", \"<none given>\"),\n            # Test a unicode string with a non-ascii character.\n            (\"curly quote: \\u2018\", \"curly quote: \\u2018\"),\n        ],\n    )\n    def test_sort_best_candidate__yanked_reason(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        monkeypatch: pytest.MonkeyPatch,\n        yanked_reason: str,\n        expected_reason: str,\n    ) -> None:\n        \"\"\"\n        Test the log message with various reason strings.\n        \"\"\"\n        # Ignore spurious DEBUG level messages\n        # TODO: Probably better to work out why they are occurring, but IMO the\n        #       tests are at fault here for being to dependent on exact output.\n        caplog.set_level(logging.WARNING)\n        candidates = [\n            make_mock_candidate(\"1.0\", yanked_reason=yanked_reason),\n        ]\n        ireq = install_req_from_line(\"pkg\")\n\n        resolver = make_test_resolver(monkeypatch, candidates)\n        resolver._populate_link(ireq)\n\n        assert ireq.link == candidates[0].link\n\n        assert len(caplog.records) == 1\n        record = caplog.records[0]\n        assert record.levelname == \"WARNING\"\n        expected_message = (\n            \"The candidate selected for download or install is a yanked \"\n            \"version: 'mypackage' candidate \"\n            \"(version 1.0 at https://example.com/pkg-1.0.tar.gz)\\n\"\n            \"Reason for being yanked: \"\n        ) + expected_reason\n        assert record.message == expected_message\n"
  },
  {
    "path": "tests/unit/test_search_scope.py",
    "content": "from pip._internal.models.search_scope import SearchScope\nfrom pip._internal.req.constructors import install_req_from_line\n\n\nclass TestSearchScope:\n    def test_get_formatted_locations_basic_auth(self) -> None:\n        \"\"\"\n        Test that basic authentication credentials defined in URL\n        is not included in formatted output.\n        \"\"\"\n        index_urls = [\n            \"https://pypi.org/simple\",\n            \"https://repo-user:repo-pass@repo.domain.com\",\n        ]\n        find_links = [\"https://links-user:links-pass@page.domain.com\"]\n        search_scope = SearchScope(\n            find_links=find_links,\n            index_urls=index_urls,\n            no_index=False,\n        )\n\n        result = search_scope.get_formatted_locations()\n        assert \"repo-user:****@repo.domain.com\" in result\n        assert \"repo-pass\" not in result\n        assert \"links-user:****@page.domain.com\" in result\n        assert \"links-pass\" not in result\n\n    def test_get_index_urls_locations(self) -> None:\n        \"\"\"Check that the canonical name is on all indexes\"\"\"\n        search_scope = SearchScope(\n            find_links=[],\n            index_urls=[\"file://index1/\", \"file://index2\"],\n            no_index=False,\n        )\n        req = install_req_from_line(\"Complex_Name\")\n        assert req.name is not None\n        actual = search_scope.get_index_urls_locations(req.name)\n        assert actual == [\n            \"file://index1/complex-name/\",\n            \"file://index2/complex-name/\",\n        ]\n"
  },
  {
    "path": "tests/unit/test_self_check_outdated.py",
    "content": "from __future__ import annotations\n\nimport datetime\nimport json\nimport logging\nimport os\nimport sys\nfrom optparse import Values\nfrom pathlib import Path\nfrom unittest.mock import ANY, Mock, patch\n\nimport pytest\nfrom freezegun import freeze_time\n\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal import self_outdated_check\nfrom pip._internal.self_outdated_check import UpgradePrompt, pip_self_version_check\nfrom pip._internal.utils.misc import ExternallyManagedEnvironment\n\n\n@pytest.mark.parametrize(\n    \"key, expected\",\n    [\n        (\n            \"/hello/world/venv\",\n            \"fcd2d5175dd33d5df759ee7b045264230205ef837bf9f582f7c3ada7\",\n        ),\n        (\n            \"C:\\\\Users\\\\User\\\\Desktop\\\\venv\",\n            \"902cecc0745b8ecf2509ba473f3556f0ba222fedc6df433acda24aa5\",\n        ),\n    ],\n)\ndef test_get_statefile_name_known_values(key: str, expected: str) -> None:\n    assert expected == self_outdated_check._get_statefile_name(key)\n\n\n@freeze_time(\"1970-01-02T11:00:00Z\")\n@patch(\"pip._internal.self_outdated_check._self_version_check_logic\")\n@patch(\"pip._internal.self_outdated_check.SelfCheckState\")\n@patch(\"pip._internal.self_outdated_check.check_externally_managed\", new=lambda: None)\ndef test_pip_self_version_check_calls_underlying_implementation(\n    mocked_state: Mock, mocked_function: Mock, tmpdir: Path\n) -> None:\n    # GIVEN\n    mock_session = Mock()\n    fake_options = Values({\"cache_dir\": str(tmpdir)})\n    mocked_function.return_value = None\n\n    # WHEN\n    self_outdated_check.pip_self_version_check(mock_session, fake_options)\n\n    # THEN\n    mocked_state.assert_called_once_with(cache_dir=str(tmpdir))\n    mocked_function.assert_called_once_with(\n        state=mocked_state(cache_dir=str(tmpdir)),\n        current_time=datetime.datetime(\n            1970, 1, 2, 11, 0, 0, tzinfo=datetime.timezone.utc\n        ),\n        local_version=ANY,\n        get_remote_version=ANY,\n    )\n\n\n@pytest.mark.parametrize(\n    [  # noqa: PT006 - String representation is too long\n        \"installed_version\",\n        \"remote_version\",\n        \"stored_version\",\n        \"installed_by_pip\",\n        \"should_show_prompt\",\n    ],\n    [\n        # A newer version available!\n        (\"1.0\", \"2.0\", None, True, True),\n        # A newer version available, and cached value is new too!\n        (\"1.0\", \"2.0\", \"2.0\", True, True),\n        # A newer version available, but was not installed by pip.\n        (\"1.0\", \"2.0\", None, False, False),\n        # On the latest version already.\n        (\"2.0\", \"2.0\", None, True, False),\n        # On the latest version already, and cached value matches.\n        (\"2.0\", \"2.0\", \"2.0\", True, False),\n        # A newer version available, but cached value is older.\n        (\"1.0\", \"2.0\", \"1.0\", True, False),\n    ],\n)\ndef test_core_logic(\n    installed_version: str,\n    remote_version: str,\n    stored_version: str | None,\n    installed_by_pip: bool,\n    should_show_prompt: bool,\n    caplog: pytest.LogCaptureFixture,\n    monkeypatch: pytest.MonkeyPatch,\n) -> None:\n    # GIVEN\n    monkeypatch.setattr(\n        self_outdated_check, \"was_installed_by_pip\", lambda _: installed_by_pip\n    )\n    mock_state = Mock()\n    mock_state.get.return_value = stored_version\n    fake_time = datetime.datetime(2000, 1, 1, 0, 0, 0)\n    version_that_should_be_checked = stored_version or remote_version\n\n    # WHEN\n    with caplog.at_level(logging.DEBUG):\n        return_value = self_outdated_check._self_version_check_logic(\n            state=mock_state,\n            current_time=fake_time,\n            local_version=Version(installed_version),\n            get_remote_version=lambda: remote_version,\n        )\n\n    # THEN\n    mock_state.get.assert_called_once_with(fake_time)\n    assert caplog.messages == [\n        f\"Remote version of pip: {version_that_should_be_checked}\",\n        f\"Local version of pip:  {installed_version}\",\n        f\"Was pip installed by pip? {installed_by_pip}\",\n    ]\n\n    if stored_version:\n        mock_state.set.assert_not_called()\n    else:\n        mock_state.set.assert_called_once_with(\n            version_that_should_be_checked, fake_time\n        )\n\n    if not should_show_prompt:\n        assert return_value is None\n        return  # the remaining assertions are for the other case.\n\n    assert return_value is not None\n    assert return_value.old == installed_version\n    assert return_value.new == remote_version\n\n\nclass TestSelfCheckState:\n    def test_no_cache(self) -> None:\n        # GIVEN / WHEN\n        state = self_outdated_check.SelfCheckState(cache_dir=\"\")\n        assert state._statefile_path is None\n\n    def test_reads_expected_statefile(self, tmpdir: Path) -> None:\n        # GIVEN\n        cache_dir = tmpdir / \"cache_dir\"\n        expected_path = (\n            cache_dir\n            / \"selfcheck\"\n            / self_outdated_check._get_statefile_name(sys.prefix)\n        )\n\n        cache_dir.mkdir()\n        (cache_dir / \"selfcheck\").mkdir()\n        expected_path.write_text('{\"foo\": \"bar\"}')\n\n        # WHEN\n        state = self_outdated_check.SelfCheckState(cache_dir=str(cache_dir))\n\n        # THEN\n        assert state._statefile_path == os.fspath(expected_path)\n        assert state._state == {\"foo\": \"bar\"}\n\n    def test_writes_expected_statefile(self, tmpdir: Path) -> None:\n        # GIVEN\n        cache_dir = tmpdir / \"cache_dir\"\n        cache_dir.mkdir()\n        expected_path = (\n            cache_dir\n            / \"selfcheck\"\n            / self_outdated_check._get_statefile_name(sys.prefix)\n        )\n\n        # WHEN\n        state = self_outdated_check.SelfCheckState(cache_dir=str(cache_dir))\n        state.set(\n            \"1.0.0\",\n            datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),\n        )\n\n        # THEN\n        assert state._statefile_path == os.fspath(expected_path)\n\n        contents = expected_path.read_text()\n        assert json.loads(contents) == {\n            \"key\": sys.prefix,\n            \"last_check\": \"2000-01-01T00:00:00+00:00\",\n            \"pypi_version\": \"1.0.0\",\n        }\n        # Check that the self-check cache entries inherit the root cache permissions.\n        statefile_permissions = os.stat(expected_path).st_mode & 0o666\n        selfcheckdir_permissions = os.stat(cache_dir / \"selfcheck\").st_mode & 0o666\n        cache_permissions = os.stat(cache_dir).st_mode & 0o666\n        assert statefile_permissions == selfcheckdir_permissions == cache_permissions\n\n\n@patch(\"pip._internal.self_outdated_check._self_version_check_logic\")\ndef test_suppressed_by_externally_managed(mocked_function: Mock, tmpdir: Path) -> None:\n    mocked_function.return_value = UpgradePrompt(old=\"1.0\", new=\"2.0\")\n    fake_options = Values({\"cache_dir\": str(tmpdir)})\n    with patch(\n        \"pip._internal.self_outdated_check.check_externally_managed\",\n        side_effect=ExternallyManagedEnvironment(\"nope\"),\n    ):\n        pip_self_version_check(session=Mock(), options=fake_options)\n    mocked_function.assert_not_called()\n"
  },
  {
    "path": "tests/unit/test_target_python.py",
    "content": "from __future__ import annotations\n\nfrom typing import Any\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._vendor.packaging.tags import Tag\n\nfrom pip._internal.models.target_python import TargetPython\n\nfrom tests.lib import CURRENT_PY_VERSION_INFO, pyversion\n\n\nclass TestTargetPython:\n    @pytest.mark.parametrize(\n        \"py_version_info, expected\",\n        [\n            ((), ((0, 0, 0), \"0.0\")),\n            ((2,), ((2, 0, 0), \"2.0\")),\n            ((3,), ((3, 0, 0), \"3.0\")),\n            ((3, 7), ((3, 7, 0), \"3.7\")),\n            ((3, 7, 3), ((3, 7, 3), \"3.7\")),\n            # Check a minor version with two digits.\n            ((3, 10, 1), ((3, 10, 1), \"3.10\")),\n        ],\n    )\n    def test_init__py_version_info(\n        self,\n        py_version_info: tuple[int, ...],\n        expected: tuple[tuple[int, int, int], str],\n    ) -> None:\n        \"\"\"\n        Test passing the py_version_info argument.\n        \"\"\"\n        expected_py_version_info, expected_py_version = expected\n\n        target_python = TargetPython(py_version_info=py_version_info)\n\n        # The _given_py_version_info attribute should be set as is.\n        assert target_python._given_py_version_info == py_version_info\n\n        assert target_python.py_version_info == expected_py_version_info\n        assert target_python.py_version == expected_py_version\n\n    def test_init__py_version_info_none(self) -> None:\n        \"\"\"\n        Test passing py_version_info=None.\n        \"\"\"\n        target_python = TargetPython(py_version_info=None)\n\n        assert target_python._given_py_version_info is None\n\n        assert target_python.py_version_info == CURRENT_PY_VERSION_INFO\n        assert target_python.py_version == pyversion\n\n    @pytest.mark.parametrize(\n        \"kwargs, expected\",\n        [\n            ({}, \"\"),\n            ({\"py_version_info\": (3, 6)}, \"version_info='3.6'\"),\n            (\n                {\"platforms\": [\"darwin\"], \"py_version_info\": (3, 6)},\n                \"platforms=['darwin'] version_info='3.6'\",\n            ),\n            (\n                {\n                    \"platforms\": [\"darwin\"],\n                    \"py_version_info\": (3, 6),\n                    \"abis\": [\"cp36m\"],\n                    \"implementation\": \"cp\",\n                },\n                (\n                    \"platforms=['darwin'] version_info='3.6' abis=['cp36m'] \"\n                    \"implementation='cp'\"\n                ),\n            ),\n        ],\n    )\n    def test_format_given(self, kwargs: dict[str, Any], expected: str) -> None:\n        target_python = TargetPython(**kwargs)\n        actual = target_python.format_given()\n        assert actual == expected\n\n    @pytest.mark.parametrize(\n        \"py_version_info, expected_version\",\n        [\n            ((), \"\"),\n            ((2,), \"2\"),\n            ((3,), \"3\"),\n            ((3, 7), \"37\"),\n            ((3, 7, 3), \"37\"),\n            # Check a minor version with two digits.\n            ((3, 10, 1), \"310\"),\n            # Check that versions=None is passed to get_sorted_tags().\n            (None, None),\n        ],\n    )\n    @mock.patch(\"pip._internal.models.target_python.get_supported\")\n    def test_get_sorted_tags(\n        self,\n        mock_get_supported: mock.Mock,\n        py_version_info: tuple[int, ...] | None,\n        expected_version: str | None,\n    ) -> None:\n        dummy_tags = [Tag(\"py4\", \"none\", \"any\"), Tag(\"py5\", \"none\", \"any\")]\n        mock_get_supported.return_value = dummy_tags\n\n        target_python = TargetPython(py_version_info=py_version_info)\n        actual = target_python.get_sorted_tags()\n        assert actual == dummy_tags\n\n        assert mock_get_supported.call_args[1][\"version\"] == expected_version\n\n        # Check that the value was cached.\n        assert target_python._valid_tags == dummy_tags\n\n    def test_get_unsorted_tags__uses_cached_value(self) -> None:\n        \"\"\"\n        Test that get_unsorted_tags() uses the cached value.\n        \"\"\"\n        target_python = TargetPython(py_version_info=None)\n        target_python._valid_tags_set = {\n            Tag(\"py2\", \"none\", \"any\"),\n            Tag(\"py3\", \"none\", \"any\"),\n        }\n        actual = target_python.get_unsorted_tags()\n        assert actual == {Tag(\"py2\", \"none\", \"any\"), Tag(\"py3\", \"none\", \"any\")}\n"
  },
  {
    "path": "tests/unit/test_urls.py",
    "content": "import os\nimport sys\nimport urllib.parse\n\nimport pytest\n\nfrom pip._internal.utils.urls import path_to_url, url_to_path\n\n\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_path_to_url_unix() -> None:\n    assert path_to_url(\"/tmp/file\") == \"file:///tmp/file\"\n    path = os.path.join(os.getcwd(), \"file\")\n    assert path_to_url(\"file\") == \"file://\" + urllib.parse.quote(path)\n\n\n@pytest.mark.skipif(\"sys.platform != 'win32'\")\n@pytest.mark.parametrize(\n    \"path, url\",\n    [\n        pytest.param(\"C:/tmp/file\", \"file:///C:/tmp/file\", id=\"posix-path\"),\n        pytest.param(\"C:\\\\tmp\\\\file\", \"file:///C:/tmp/file\", id=\"nt-path\"),\n    ],\n)\ndef test_path_to_url_win(path: str, url: str) -> None:\n    assert path_to_url(path) == url\n\n\n@pytest.mark.skipif(\"sys.platform != 'win32'\")\ndef test_unc_path_to_url_win() -> None:\n    # The two and four slash forms are both acceptable for our purposes. CPython's\n    # behaviour has changed several times here, so blindly accept either.\n    # - https://github.com/python/cpython/issues/78457\n    # - https://github.com/python/cpython/issues/126205\n    url = path_to_url(r\"\\\\unc\\as\\path\")\n    assert url in [\"file://unc/as/path\", \"file:////unc/as/path\"]\n\n\n@pytest.mark.skipif(\"sys.platform != 'win32'\")\ndef test_relative_path_to_url_win() -> None:\n    path = os.path.join(os.getcwd(), \"file\").replace(\"\\\\\", \"/\")\n    assert path_to_url(\"file\") == \"file:///\" + urllib.parse.quote(path, safe=\"/:\")\n\n\n@pytest.mark.parametrize(\n    \"url,win_expected,non_win_expected\",\n    [\n        (\"file:tmp\", \"tmp\", \"tmp\"),\n        (\"file:C:/path/to/file\", r\"C:\\path\\to\\file\", \"C:/path/to/file\"),\n        (\"file:/path/to/file\", r\"\\path\\to\\file\", \"/path/to/file\"),\n        (\"file://localhost/tmp/file\", r\"\\tmp\\file\", \"/tmp/file\"),\n        (\"file://localhost/C:/tmp/file\", r\"C:\\tmp\\file\", \"/C:/tmp/file\"),\n        (\"file://somehost/tmp/file\", r\"\\\\somehost\\tmp\\file\", None),\n        (\"file:///tmp/file\", r\"\\tmp\\file\", \"/tmp/file\"),\n        (\"file:///C:/tmp/file\", r\"C:\\tmp\\file\", \"/C:/tmp/file\"),\n    ],\n)\ndef test_url_to_path(url: str, win_expected: str, non_win_expected: str) -> None:\n    if sys.platform == \"win32\":\n        expected_path = win_expected\n    else:\n        expected_path = non_win_expected\n\n    if expected_path is None:\n        with pytest.raises(ValueError):\n            url_to_path(url)\n    else:\n        assert url_to_path(url) == expected_path\n\n\n@pytest.mark.skipif(\"sys.platform != 'win32'\")\ndef test_url_to_path_path_to_url_symmetry_win() -> None:\n    path = r\"C:\\tmp\\file\"\n    assert url_to_path(path_to_url(path)) == path\n\n    unc_path = r\"\\\\unc\\share\\path\"\n    assert url_to_path(path_to_url(unc_path)) == unc_path\n"
  },
  {
    "path": "tests/unit/test_utils.py",
    "content": "\"\"\"\nutil tests\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport shutil\nimport stat\nimport sys\nimport time\nfrom collections.abc import Iterator\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Any, Callable, NoReturn\nfrom unittest.mock import Mock, patch\n\nimport pytest\n\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.exceptions import HashMismatch, HashMissing, InstallationError\nfrom pip._internal.utils.deprecation import PipDeprecationWarning, deprecated\nfrom pip._internal.utils.egg_link import egg_link_path_from_location\nfrom pip._internal.utils.glibc import (\n    glibc_version_string,\n    glibc_version_string_confstr,\n    glibc_version_string_ctypes,\n)\nfrom pip._internal.utils.hashes import Hashes, MissingHashes\nfrom pip._internal.utils.misc import (\n    HiddenText,\n    build_netloc,\n    build_url_from_netloc,\n    display_path,\n    format_size,\n    get_prog,\n    hide_url,\n    hide_value,\n    is_console_interactive,\n    normalize_path,\n    normalize_version_info,\n    parse_netloc,\n    redact_auth_from_requirement,\n    redact_auth_from_url,\n    redact_netloc,\n    remove_auth_from_url,\n    rmtree,\n    rmtree_errorhandler,\n    split_auth_from_netloc,\n    split_auth_netloc_from_url,\n    tabulate,\n)\n\n\nclass Tests_EgglinkPath:\n    \"util.egg_link_path_from_location() tests\"\n\n    def setup_method(self) -> None:\n        project = \"foo\"\n\n        self.mock_dist = Mock(project_name=project)\n        self.site_packages = \"SITE_PACKAGES\"\n        self.user_site = \"USER_SITE\"\n        self.user_site_egglink = os.path.join(self.user_site, f\"{project}.egg-link\")\n        self.site_packages_egglink = os.path.join(\n            self.site_packages,\n            f\"{project}.egg-link\",\n        )\n\n        # patches\n        from pip._internal.utils import egg_link as utils\n\n        self.old_site_packages = utils.site_packages\n        self.mock_site_packages = utils.site_packages = \"SITE_PACKAGES\"\n        self.old_running_under_virtualenv = utils.running_under_virtualenv\n        self.mock_running_under_virtualenv = utils.running_under_virtualenv = Mock()\n        self.old_virtualenv_no_global = utils.virtualenv_no_global\n        self.mock_virtualenv_no_global = utils.virtualenv_no_global = Mock()\n        self.old_user_site = utils.user_site\n        self.mock_user_site = utils.user_site = self.user_site\n        from os import path\n\n        self.old_isfile = path.isfile\n        self.mock_isfile = path.isfile = Mock()\n\n    def teardown_method(self) -> None:\n        from pip._internal.utils import egg_link as utils\n\n        utils.site_packages = self.old_site_packages\n        utils.running_under_virtualenv = self.old_running_under_virtualenv\n        utils.virtualenv_no_global = self.old_virtualenv_no_global\n        utils.user_site = self.old_user_site\n        from os import path\n\n        path.isfile = self.old_isfile\n\n    def eggLinkInUserSite(self, egglink: str) -> bool:\n        return egglink == self.user_site_egglink\n\n    def eggLinkInSitePackages(self, egglink: str) -> bool:\n        return egglink == self.site_packages_egglink\n\n    # ####################### #\n    # # egglink in usersite # #\n    # ####################### #\n    def test_egglink_in_usersite_notvenv(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = False\n        self.mock_isfile.side_effect = self.eggLinkInUserSite\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.user_site_egglink\n        )\n\n    def test_egglink_in_usersite_venv_noglobal(self) -> None:\n        self.mock_virtualenv_no_global.return_value = True\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.side_effect = self.eggLinkInUserSite\n        assert egg_link_path_from_location(self.mock_dist.project_name) is None\n\n    def test_egglink_in_usersite_venv_global(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.side_effect = self.eggLinkInUserSite\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.user_site_egglink\n        )\n\n    # ####################### #\n    # # egglink in sitepkgs # #\n    # ####################### #\n    def test_egglink_in_sitepkgs_notvenv(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = False\n        self.mock_isfile.side_effect = self.eggLinkInSitePackages\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.site_packages_egglink\n        )\n\n    def test_egglink_in_sitepkgs_venv_noglobal(self) -> None:\n        self.mock_virtualenv_no_global.return_value = True\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.side_effect = self.eggLinkInSitePackages\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.site_packages_egglink\n        )\n\n    def test_egglink_in_sitepkgs_venv_global(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.side_effect = self.eggLinkInSitePackages\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.site_packages_egglink\n        )\n\n    # ################################## #\n    # # egglink in usersite & sitepkgs # #\n    # ################################## #\n    def test_egglink_in_both_notvenv(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = False\n        self.mock_isfile.return_value = True\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.user_site_egglink\n        )\n\n    def test_egglink_in_both_venv_noglobal(self) -> None:\n        self.mock_virtualenv_no_global.return_value = True\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.return_value = True\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.site_packages_egglink\n        )\n\n    def test_egglink_in_both_venv_global(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.return_value = True\n        assert (\n            egg_link_path_from_location(self.mock_dist.project_name)\n            == self.site_packages_egglink\n        )\n\n    # ############## #\n    # # no egglink # #\n    # ############## #\n    def test_noegglink_in_sitepkgs_notvenv(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = False\n        self.mock_isfile.return_value = False\n        assert egg_link_path_from_location(self.mock_dist.project_name) is None\n\n    def test_noegglink_in_sitepkgs_venv_noglobal(self) -> None:\n        self.mock_virtualenv_no_global.return_value = True\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.return_value = False\n        assert egg_link_path_from_location(self.mock_dist.project_name) is None\n\n    def test_noegglink_in_sitepkgs_venv_global(self) -> None:\n        self.mock_virtualenv_no_global.return_value = False\n        self.mock_running_under_virtualenv.return_value = True\n        self.mock_isfile.return_value = False\n        assert egg_link_path_from_location(self.mock_dist.project_name) is None\n\n\ndef test_rmtree_errorhandler_nonexistent_directory(tmpdir: Path) -> None:\n    \"\"\"\n    Test rmtree_errorhandler ignores the given non-existing directory.\n    \"\"\"\n    nonexistent_path = str(tmpdir / \"foo\")\n    mock_func = Mock()\n    # Argument 3 to \"rmtree_errorhandler\" has incompatible type \"None\"; expected\n    # \"Tuple[Type[BaseException], BaseException, TracebackType]\"\n    rmtree_errorhandler(mock_func, nonexistent_path, None)  # type: ignore[arg-type]\n    mock_func.assert_not_called()\n\n\ndef test_rmtree_errorhandler_readonly_directory(tmpdir: Path) -> None:\n    \"\"\"\n    Test rmtree_errorhandler makes the given read-only directory writable.\n    \"\"\"\n    # Create read only directory\n    subdir_path = tmpdir / \"subdir\"\n    subdir_path.mkdir()\n    path = str(subdir_path)\n    os.chmod(path, stat.S_IREAD)\n\n    # Make sure mock_func is called with the given path\n    mock_func = Mock()\n    # Argument 3 to \"rmtree_errorhandler\" has incompatible type \"None\"; expected\n    # \"Tuple[Type[BaseException], BaseException, TracebackType]\"\n    rmtree_errorhandler(mock_func, path, None)  # type: ignore[arg-type]\n    mock_func.assert_called_with(path)\n\n    # Make sure the path is now writable\n    assert os.stat(path).st_mode & stat.S_IWRITE\n\n\ndef test_rmtree_errorhandler_reraises_error(tmpdir: Path) -> None:\n    \"\"\"\n    Test rmtree_errorhandler reraises an exception\n    by the given unreadable directory.\n    \"\"\"\n    # Create directory without read permission\n    path = tmpdir / \"subdir\"\n    path.mkdir()\n    old_mode = path.stat().st_mode\n    path.chmod(stat.S_IWRITE)\n\n    mock_func = Mock()\n\n    try:\n        raise RuntimeError(\"test message\")\n    except RuntimeError:\n        # Make sure the handler reraises an exception\n        with pytest.raises(RuntimeError, match=\"test message\"):\n            # Argument 3 to \"rmtree_errorhandler\" has incompatible type\n            # \"Union[Tuple[Type[BaseException], BaseException, TracebackType],\n            # Tuple[None, None, None]]\"; expected \"Tuple[Type[BaseException],\n            # BaseException, TracebackType]\"\n            rmtree_errorhandler(\n                mock_func, path, sys.exc_info()  # type: ignore[arg-type]\n            )\n    finally:\n        # Restore permissions to let pytest to clean up temp dirs\n        path.chmod(old_mode)\n\n    mock_func.assert_not_called()\n\n\ndef test_rmtree_skips_nonexistent_directory() -> None:\n    \"\"\"\n    Test wrapped rmtree doesn't raise an error\n    by the given nonexistent directory.\n    \"\"\"\n    rmtree.__wrapped__(\"nonexistent-subdir\")  # type: ignore[attr-defined]\n\n\nclass Failer:\n    def __init__(self, duration: int = 1) -> None:\n        self.succeed_after = time.time() + duration\n\n    def call(self, *args: Any, **kw: Any) -> None:\n        \"\"\"Fail with OSError self.max_fails times\"\"\"\n        if time.time() < self.succeed_after:\n            raise OSError(\"Failed\")\n\n\ndef test_rmtree_retries(monkeypatch: pytest.MonkeyPatch) -> None:\n    \"\"\"\n    Test pip._internal.utils.rmtree will retry failures\n    \"\"\"\n    monkeypatch.setattr(shutil, \"rmtree\", Failer(duration=1).call)\n    rmtree(\"foo\")\n\n\ndef test_rmtree_retries_for_3sec(monkeypatch: pytest.MonkeyPatch) -> None:\n    \"\"\"\n    Test pip._internal.utils.rmtree will retry failures for no more than 3 sec\n    \"\"\"\n    monkeypatch.setattr(shutil, \"rmtree\", Failer(duration=5).call)\n    with pytest.raises(OSError):\n        rmtree(\"foo\")\n\n\nif sys.byteorder == \"little\":\n    expected_byte_string = (\n        \"b'\\\\xff\\\\xfe/\\\\x00p\\\\x00a\\\\x00t\\\\x00h\\\\x00/\\\\x00d\\\\x00\\\\xe9\\\\x00f\\\\x00'\"\n    )\nelif sys.byteorder == \"big\":\n    expected_byte_string = (\n        \"b'\\\\xfe\\\\xff\\\\x00/\\\\x00p\\\\x00a\\\\x00t\\\\x00h\\\\x00/\\\\x00d\\\\x00\\\\xe9\\\\x00f'\"\n    )\n\n\nclass Test_display_path:\n    on_unix = pytest.mark.skipif(\"sys.platform == 'win32'\")\n    on_win32 = pytest.mark.skipif(\"sys.platform != 'win32'\")\n\n    @pytest.mark.parametrize(\n        \"path, fake_cwd, expected\",\n        [\n            pytest.param(\n                *(\"/home/name/project\", Path(\"/home/name\"), \"./project\"),\n                marks=on_unix,\n            ),\n            pytest.param(\n                *(\"/home\", Path(\"/home/name\"), \"/home\"),\n                marks=on_unix,\n                id=\"not-go-up\",\n            ),\n            pytest.param(\n                *(\"C:\\\\Name\\\\Project\", Path(\"C:\\\\Name\"), \".\\\\Project\"),\n                marks=on_win32,\n            ),\n            pytest.param(\n                *(\"D:\\\\Data\", Path(\"C:\\\\Name\"), \"D:\\\\Data\"),\n                marks=on_win32,\n            ),\n        ],\n    )\n    def test_display(self, path: str, fake_cwd: Path, expected: str) -> None:\n        with patch(\"pathlib.Path.cwd\") as cwd_func:\n            cwd_func.return_value = fake_cwd\n            got = display_path(path)\n            assert got == expected\n\n\nclass Test_normalize_path:\n    # Technically, symlinks are possible on Windows, but you need a special\n    # permission bit to create them, and Python 2 doesn't support it anyway, so\n    # it's easiest just to skip this test on Windows altogether.\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_resolve_symlinks(self, tmpdir: Path) -> None:\n        print(type(tmpdir))\n        print(dir(tmpdir))\n        orig_working_dir = os.getcwd()\n        os.chdir(tmpdir)\n        try:\n            d = os.path.join(\"foo\", \"bar\")\n            f = os.path.join(d, \"file1\")\n            os.makedirs(d)\n            with open(f, \"w\"):  # Create the file\n                pass\n\n            os.symlink(d, \"dir_link\")\n            os.symlink(f, \"file_link\")\n\n            assert normalize_path(\n                \"dir_link/file1\", resolve_symlinks=True\n            ) == os.path.join(tmpdir, f)\n            assert normalize_path(\n                \"dir_link/file1\", resolve_symlinks=False\n            ) == os.path.join(tmpdir, \"dir_link\", \"file1\")\n\n            assert normalize_path(\"file_link\", resolve_symlinks=True) == os.path.join(\n                tmpdir, f\n            )\n            assert normalize_path(\"file_link\", resolve_symlinks=False) == os.path.join(\n                tmpdir, \"file_link\"\n            )\n        finally:\n            os.chdir(orig_working_dir)\n\n\nclass TestHashes:\n    \"\"\"Tests for pip._internal.utils.hashes\"\"\"\n\n    @pytest.mark.parametrize(\n        \"hash_name, hex_digest, expected\",\n        [\n            # Test a value that matches but with the wrong hash_name.\n            (\"sha384\", 128 * \"a\", False),\n            # Test matching values, including values other than the first.\n            (\"sha512\", 128 * \"a\", True),\n            (\"sha512\", 128 * \"b\", True),\n            # Test a matching hash_name with a value that doesn't match.\n            (\"sha512\", 128 * \"c\", False),\n        ],\n    )\n    def test_is_hash_allowed(\n        self, hash_name: str, hex_digest: str, expected: bool\n    ) -> None:\n        hashes_data = {\n            \"sha512\": [128 * \"a\", 128 * \"b\"],\n        }\n        hashes = Hashes(hashes_data)\n        assert hashes.is_hash_allowed(hash_name, hex_digest) == expected\n\n    def test_success(self, tmpdir: Path) -> None:\n        \"\"\"Make sure no error is raised when at least one hash matches.\n\n        Test check_against_path because it calls everything else.\n\n        \"\"\"\n        file = tmpdir / \"to_hash\"\n        file.write_text(\"hello\")\n        hashes = Hashes(\n            {\n                \"sha256\": [\n                    \"2cf24dba5fb0a30e26e83b2ac5b9e29e\"\n                    \"1b161e5c1fa7425e73043362938b9824\"\n                ],\n                \"sha224\": [\"wrongwrong\"],\n                \"md5\": [\"5d41402abc4b2a76b9719d911017c592\"],\n            }\n        )\n        hashes.check_against_path(os.fspath(file))\n\n    def test_failure(self) -> None:\n        \"\"\"Hashes should raise HashMismatch when no hashes match.\"\"\"\n        hashes = Hashes({\"sha256\": [\"wrongwrong\"]})\n        with pytest.raises(HashMismatch):\n            hashes.check_against_file(BytesIO(b\"hello\"))\n\n    def test_missing_hashes(self) -> None:\n        \"\"\"MissingHashes should raise HashMissing when any check is done.\"\"\"\n        with pytest.raises(HashMissing):\n            MissingHashes().check_against_file(BytesIO(b\"hello\"))\n\n    def test_unknown_hash(self) -> None:\n        \"\"\"Hashes should raise InstallationError when it encounters an unknown\n        hash.\"\"\"\n        hashes = Hashes({\"badbad\": [\"dummy\"]})\n        with pytest.raises(InstallationError):\n            hashes.check_against_file(BytesIO(b\"hello\"))\n\n    def test_non_zero(self) -> None:\n        \"\"\"Test that truthiness tests tell whether any known-good hashes\n        exist.\"\"\"\n        assert Hashes({\"sha256\": [\"dummy\"]})\n        assert not Hashes()\n        assert not Hashes({})\n\n    def test_equality(self) -> None:\n        assert Hashes() == Hashes()\n        assert Hashes({\"sha256\": [\"abcd\"]}) == Hashes({\"sha256\": [\"abcd\"]})\n        assert Hashes({\"sha256\": [\"ab\", \"cd\"]}) == Hashes({\"sha256\": [\"cd\", \"ab\"]})\n\n    def test_hash(self) -> None:\n        cache = {}\n        cache[Hashes({\"sha256\": [\"ab\", \"cd\"]})] = 42\n        assert cache[Hashes({\"sha256\": [\"ab\", \"cd\"]})] == 42\n\n    def test_has_one_of(self) -> None:\n        hashes = Hashes({\"sha256\": [\"abcd\", \"efgh\"], \"sha384\": [\"ijkl\"]})\n        assert hashes.has_one_of({\"sha256\": \"abcd\"})\n        assert hashes.has_one_of({\"sha256\": \"efgh\"})\n        assert not hashes.has_one_of({\"sha256\": \"xyzt\"})\n        empty_hashes = Hashes()\n        assert not empty_hashes.has_one_of({\"sha256\": \"xyzt\"})\n\n\ndef raises(error: type[Exception]) -> NoReturn:\n    raise error\n\n\nclass TestGlibc:\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_glibc_version_string(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(\n            os,\n            \"confstr\",\n            lambda x: \"glibc 2.20\",\n            raising=False,\n        )\n        assert glibc_version_string() == \"2.20\"\n\n    @pytest.mark.skipif(\"sys.platform == 'win32'\")\n    def test_glibc_version_string_confstr(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(\n            os,\n            \"confstr\",\n            lambda x: \"glibc 2.20\",\n            raising=False,\n        )\n        assert glibc_version_string_confstr() == \"2.20\"\n\n    @pytest.mark.parametrize(\n        \"failure\",\n        [\n            lambda x: raises(ValueError),\n            lambda x: raises(OSError),\n            lambda x: \"XXX\",\n        ],\n    )\n    def test_glibc_version_string_confstr_fail(\n        self, monkeypatch: pytest.MonkeyPatch, failure: Callable[[Any], Any]\n    ) -> None:\n        monkeypatch.setattr(os, \"confstr\", failure, raising=False)\n        assert glibc_version_string_confstr() is None\n\n    def test_glibc_version_string_confstr_missing(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.delattr(os, \"confstr\", raising=False)\n        assert glibc_version_string_confstr() is None\n\n    def test_glibc_version_string_ctypes_missing(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setitem(sys.modules, \"ctypes\", None)\n        assert glibc_version_string_ctypes() is None\n\n\n@pytest.mark.parametrize(\n    \"version_info, expected\",\n    [\n        ((), (0, 0, 0)),\n        ((3,), (3, 0, 0)),\n        ((3, 6), (3, 6, 0)),\n        ((3, 6, 2), (3, 6, 2)),\n        ((3, 6, 2, 4), (3, 6, 2)),\n    ],\n)\ndef test_normalize_version_info(\n    version_info: tuple[int, ...], expected: tuple[int, int, int]\n) -> None:\n    actual = normalize_version_info(version_info)\n    assert actual == expected\n\n\nclass TestGetProg:\n    @pytest.mark.parametrize(\n        \"argv, executable, expected\",\n        [\n            (\"/usr/bin/pip\", \"\", \"pip\"),\n            (\"-c\", \"/usr/bin/python\", \"/usr/bin/python -m pip\"),\n            (\"__main__.py\", \"/usr/bin/python\", \"/usr/bin/python -m pip\"),\n            (\"/usr/bin/pip3\", \"\", \"pip3\"),\n        ],\n    )\n    def test_get_prog(\n        self, monkeypatch: pytest.MonkeyPatch, argv: str, executable: str, expected: str\n    ) -> None:\n        monkeypatch.setattr(\"pip._internal.utils.misc.sys.argv\", [argv])\n        monkeypatch.setattr(\"pip._internal.utils.misc.sys.executable\", executable)\n        assert get_prog() == expected\n\n\n@pytest.mark.parametrize(\n    \"host_port, expected_netloc\",\n    [\n        # Test domain name.\n        ((\"example.com\", None), \"example.com\"),\n        ((\"example.com\", 5000), \"example.com:5000\"),\n        # Test IPv4 address.\n        ((\"127.0.0.1\", None), \"127.0.0.1\"),\n        ((\"127.0.0.1\", 5000), \"127.0.0.1:5000\"),\n        # Test bare IPv6 address.\n        ((\"2001:db6::1\", None), \"2001:db6::1\"),\n        # Test IPv6 with port.\n        ((\"2001:db6::1\", 5000), \"[2001:db6::1]:5000\"),\n    ],\n)\ndef test_build_netloc(host_port: tuple[str, int | None], expected_netloc: str) -> None:\n    assert build_netloc(*host_port) == expected_netloc\n\n\n@pytest.mark.parametrize(\n    \"netloc, expected_url, expected_host_port\",\n    [\n        # Test domain name.\n        (\"example.com\", \"https://example.com\", (\"example.com\", None)),\n        (\"example.com:5000\", \"https://example.com:5000\", (\"example.com\", 5000)),\n        # Test IPv4 address.\n        (\"127.0.0.1\", \"https://127.0.0.1\", (\"127.0.0.1\", None)),\n        (\"127.0.0.1:5000\", \"https://127.0.0.1:5000\", (\"127.0.0.1\", 5000)),\n        # Test bare IPv6 address.\n        (\"2001:db6::1\", \"https://[2001:db6::1]\", (\"2001:db6::1\", None)),\n        # Test IPv6 with port.\n        (\"[2001:db6::1]:5000\", \"https://[2001:db6::1]:5000\", (\"2001:db6::1\", 5000)),\n        # Test netloc with auth.\n        (\n            \"user:password@localhost:5000\",\n            \"https://user:password@localhost:5000\",\n            (\"localhost\", 5000),\n        ),\n    ],\n)\ndef test_build_url_from_netloc_and_parse_netloc(\n    netloc: str,\n    expected_url: str,\n    expected_host_port: tuple[str, int | None],\n) -> None:\n    assert build_url_from_netloc(netloc) == expected_url\n    assert parse_netloc(netloc) == expected_host_port\n\n\n@pytest.mark.parametrize(\n    \"netloc, expected\",\n    [\n        # Test a basic case.\n        (\"example.com\", (\"example.com\", (None, None))),\n        # Test with username and no password.\n        (\"user@example.com\", (\"example.com\", (\"user\", None))),\n        # Test with username and password.\n        (\"user:pass@example.com\", (\"example.com\", (\"user\", \"pass\"))),\n        # Test with username and empty password.\n        (\"user:@example.com\", (\"example.com\", (\"user\", \"\"))),\n        # Test the password containing an @ symbol.\n        (\"user:pass@word@example.com\", (\"example.com\", (\"user\", \"pass@word\"))),\n        # Test the password containing a : symbol.\n        (\"user:pass:word@example.com\", (\"example.com\", (\"user\", \"pass:word\"))),\n        # Test URL-encoded reserved characters.\n        (\"user%3Aname:%23%40%5E@example.com\", (\"example.com\", (\"user:name\", \"#@^\"))),\n    ],\n)\ndef test_split_auth_from_netloc(\n    netloc: str, expected: tuple[str, tuple[str | None, str | None]]\n) -> None:\n    actual = split_auth_from_netloc(netloc)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"url, expected\",\n    [\n        # Test a basic case.\n        (\n            \"http://example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (None, None)),\n        ),\n        # Test with username and no password.\n        (\n            \"http://user@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user\", None)),\n        ),\n        # Test with username and password.\n        (\n            \"http://user:pass@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user\", \"pass\")),\n        ),\n        # Test with username and empty password.\n        (\n            \"http://user:@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user\", \"\")),\n        ),\n        # Test the password containing an @ symbol.\n        (\n            \"http://user:pass@word@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user\", \"pass@word\")),\n        ),\n        # Test the password containing a : symbol.\n        (\n            \"http://user:pass:word@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user\", \"pass:word\")),\n        ),\n        # Test URL-encoded reserved characters.\n        (\n            \"http://user%3Aname:%23%40%5E@example.com/path#anchor\",\n            (\"http://example.com/path#anchor\", \"example.com\", (\"user:name\", \"#@^\")),\n        ),\n    ],\n)\ndef test_split_auth_netloc_from_url(\n    url: str, expected: tuple[str, str, tuple[str | None, str | None]]\n) -> None:\n    actual = split_auth_netloc_from_url(url)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"netloc, expected\",\n    [\n        # Test a basic case.\n        (\"example.com\", \"example.com\"),\n        # Test with username and no password.\n        (\"accesstoken@example.com\", \"****@example.com\"),\n        # Test with username and password.\n        (\"user:pass@example.com\", \"user:****@example.com\"),\n        # Test with username and empty password.\n        (\"user:@example.com\", \"user:****@example.com\"),\n        # Test the password containing an @ symbol.\n        (\"user:pass@word@example.com\", \"user:****@example.com\"),\n        # Test the password containing a : symbol.\n        (\"user:pass:word@example.com\", \"user:****@example.com\"),\n        # Test URL-encoded reserved characters.\n        (\"user%3Aname:%23%40%5E@example.com\", \"user%3Aname:****@example.com\"),\n    ],\n)\ndef test_redact_netloc(netloc: str, expected: str) -> None:\n    actual = redact_netloc(netloc)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"auth_url, expected_url\",\n    [\n        (\n            \"https://user:pass@domain.tld/project/tags/v0.2\",\n            \"https://domain.tld/project/tags/v0.2\",\n        ),\n        (\n            \"https://domain.tld/project/tags/v0.2\",\n            \"https://domain.tld/project/tags/v0.2\",\n        ),\n        (\n            \"https://user:pass@domain.tld/svn/project/trunk@8181\",\n            \"https://domain.tld/svn/project/trunk@8181\",\n        ),\n        (\n            \"https://domain.tld/project/trunk@8181\",\n            \"https://domain.tld/project/trunk@8181\",\n        ),\n        (\"git+https://pypi.org/something\", \"git+https://pypi.org/something\"),\n        (\"git+https://user:pass@pypi.org/something\", \"git+https://pypi.org/something\"),\n        (\"git+ssh://git@pypi.org/something\", \"git+ssh://pypi.org/something\"),\n    ],\n)\ndef test_remove_auth_from_url(auth_url: str, expected_url: str) -> None:\n    url = remove_auth_from_url(auth_url)\n    assert url == expected_url\n\n\n@pytest.mark.parametrize(\n    \"auth_url, expected_url\",\n    [\n        (\"https://accesstoken@example.com/abc\", \"https://****@example.com/abc\"),\n        (\"https://user:password@example.com\", \"https://user:****@example.com\"),\n        (\"https://user:@example.com\", \"https://user:****@example.com\"),\n        (\"https://example.com\", \"https://example.com\"),\n        # Test URL-encoded reserved characters.\n        (\n            \"https://user%3Aname:%23%40%5E@example.com\",\n            \"https://user%3Aname:****@example.com\",\n        ),\n    ],\n)\ndef test_redact_auth_from_url(auth_url: str, expected_url: str) -> None:\n    url = redact_auth_from_url(auth_url)\n    assert url == expected_url\n\n\n@pytest.mark.parametrize(\n    \"req, expected\",\n    [\n        (\"pkga\", \"pkga\"),\n        (\n            \"resolvelib@ \"\n            \" git+https://test-user:test-pass@github.com/sarugaku/resolvelib@1.0.1\",\n            \"resolvelib @ \"\n            \"git+https://test-user:****@github.com/sarugaku/resolvelib@1.0.1\",\n        ),\n        (\n            \"resolvelib@\"\n            \" git+https://test-user:test-pass@github.com/sarugaku/resolvelib@1.0.1\"\n            \" ; python_version>='3.6'\",\n            \"resolvelib @ \"\n            \"git+https://test-user:****@github.com/sarugaku/resolvelib@1.0.1\"\n            ' ; python_version >= \"3.6\"',\n        ),\n    ],\n)\ndef test_redact_auth_from_requirement(req: str, expected: str) -> None:\n    assert redact_auth_from_requirement(Requirement(req)) == expected\n\n\nclass TestHiddenText:\n    def test_basic(self) -> None:\n        \"\"\"\n        Test str(), repr(), and attribute access.\n        \"\"\"\n        hidden = HiddenText(\"my-secret\", redacted=\"######\")\n        assert repr(hidden) == \"<HiddenText '######'>\"\n        assert str(hidden) == \"######\"\n        assert hidden.redacted == \"######\"\n        assert hidden.secret == \"my-secret\"\n\n    def test_equality_with_str(self) -> None:\n        \"\"\"\n        Test equality (and inequality) with str objects.\n        \"\"\"\n        hidden = HiddenText(\"secret\", redacted=\"****\")\n\n        # Test that the object doesn't compare equal to either its original\n        # or redacted forms.\n        assert hidden != hidden.secret\n        assert hidden.secret != hidden\n\n        assert hidden != hidden.redacted\n        assert hidden.redacted != hidden\n\n    def test_equality_same_secret(self) -> None:\n        \"\"\"\n        Test equality with an object having the same secret.\n        \"\"\"\n        # Choose different redactions for the two objects.\n        hidden1 = HiddenText(\"secret\", redacted=\"****\")\n        hidden2 = HiddenText(\"secret\", redacted=\"####\")\n\n        assert hidden1 == hidden2\n        # Also test __ne__.\n        assert not hidden1 != hidden2\n\n    def test_equality_different_secret(self) -> None:\n        \"\"\"\n        Test equality with an object having a different secret.\n        \"\"\"\n        hidden1 = HiddenText(\"secret-1\", redacted=\"****\")\n        hidden2 = HiddenText(\"secret-2\", redacted=\"****\")\n\n        assert hidden1 != hidden2\n        # Also test __eq__.\n        assert not hidden1 == hidden2\n\n\ndef test_hide_value() -> None:\n    hidden = hide_value(\"my-secret\")\n    assert repr(hidden) == \"<HiddenText '****'>\"\n    assert str(hidden) == \"****\"\n    assert hidden.redacted == \"****\"\n    assert hidden.secret == \"my-secret\"\n\n\ndef test_hide_url() -> None:\n    hidden_url = hide_url(\"https://user:password@example.com\")\n    assert repr(hidden_url) == \"<HiddenText 'https://user:****@example.com'>\"\n    assert str(hidden_url) == \"https://user:****@example.com\"\n    assert hidden_url.redacted == \"https://user:****@example.com\"\n    assert hidden_url.secret == \"https://user:password@example.com\"\n\n\n@pytest.fixture\ndef patch_deprecation_check_version() -> Iterator[None]:\n    # We do this, so that the deprecation tests are easier to write.\n    import pip._internal.utils.deprecation as d\n\n    old_version = d.current_version\n    d.current_version = \"1.0\"\n    yield\n    d.current_version = old_version\n\n\n@pytest.mark.usefixtures(\"patch_deprecation_check_version\")\n@pytest.mark.parametrize(\"replacement\", [None, \"a magic 8 ball\"])\n@pytest.mark.parametrize(\"gone_in\", [None, \"2.0\"])\n@pytest.mark.parametrize(\"issue\", [None, 988])\n@pytest.mark.parametrize(\"feature_flag\", [None, \"magic-8-ball\"])\ndef test_deprecated_message_contains_information(\n    gone_in: str | None,\n    replacement: str | None,\n    issue: int | None,\n    feature_flag: str | None,\n) -> None:\n    with pytest.warns(PipDeprecationWarning) as record:\n        deprecated(\n            reason=\"Stop doing this!\",\n            replacement=replacement,\n            gone_in=gone_in,\n            feature_flag=feature_flag,\n            issue=issue,\n        )\n\n    assert len(record) == 1\n    assert isinstance(record[0].message, PipDeprecationWarning)\n    message = record[0].message.args[0]\n\n    assert \"DEPRECATION: Stop doing this!\" in message\n    # Ensure non-None values are mentioned.\n    for item in [gone_in, replacement, issue, feature_flag]:\n        if item is not None:\n            assert str(item) in message\n\n\n@pytest.mark.usefixtures(\"patch_deprecation_check_version\")\n@pytest.mark.parametrize(\"replacement\", [None, \"a magic 8 ball\"])\n@pytest.mark.parametrize(\"issue\", [None, 988])\n@pytest.mark.parametrize(\"feature_flag\", [None, \"magic-8-ball\"])\ndef test_deprecated_raises_error_if_too_old(\n    replacement: str | None, issue: int | None, feature_flag: str | None\n) -> None:\n    with pytest.raises(PipDeprecationWarning) as exception:\n        deprecated(\n            reason=\"Stop doing this!\",\n            gone_in=\"1.0\",  # this matches the patched version.\n            replacement=replacement,\n            feature_flag=feature_flag,\n            issue=issue,\n        )\n\n    message = exception.value.args[0]\n\n    assert \"DEPRECATION: Stop doing this!\" in message\n    assert \"1.0\" in message\n    assert str(feature_flag) not in message\n    # Ensure non-None values are mentioned.\n    for item in [replacement, issue]:\n        if item is not None:\n            assert str(item) in message\n\n\n@pytest.mark.usefixtures(\"patch_deprecation_check_version\")\ndef test_deprecated_message_reads_well_past() -> None:\n    with pytest.raises(PipDeprecationWarning) as exception:\n        deprecated(\n            reason=\"Stop doing this!\",\n            gone_in=\"1.0\",  # this matches the patched version.\n            replacement=\"to be nicer\",\n            feature_flag=\"magic-8-ball\",\n            issue=100000,\n        )\n\n    message = exception.value.args[0]\n\n    assert message == (\n        \"DEPRECATION: Stop doing this! \"\n        \"Since pip 1.0, this is no longer supported. \"\n        \"A possible replacement is to be nicer. \"\n        \"Discussion can be found at https://github.com/pypa/pip/issues/100000\"\n    )\n\n\n@pytest.mark.usefixtures(\"patch_deprecation_check_version\")\ndef test_deprecated_message_reads_well_future() -> None:\n    with pytest.warns(PipDeprecationWarning) as record:\n        deprecated(\n            reason=\"Stop doing this!\",\n            gone_in=\"2.0\",  # this is greater than the patched version.\n            replacement=\"to be nicer\",\n            feature_flag=\"crisis\",\n            issue=100000,\n        )\n\n    assert len(record) == 1\n    assert isinstance(record[0].message, PipDeprecationWarning)\n    message = record[0].message.args[0]\n\n    assert message == (\n        \"DEPRECATION: Stop doing this! \"\n        \"pip 2.0 will enforce this behaviour change. \"\n        \"A possible replacement is to be nicer. \"\n        \"You can use the flag --use-feature=crisis to test the upcoming behaviour. \"\n        \"Discussion can be found at https://github.com/pypa/pip/issues/100000\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"isatty,no_stdin,expected\",\n    [\n        (True, False, True),\n        (False, False, False),\n        (True, True, False),\n        (False, True, False),\n    ],\n)\ndef test_is_console_interactive(\n    monkeypatch: pytest.MonkeyPatch, isatty: bool, no_stdin: bool, expected: bool\n) -> None:\n    monkeypatch.setattr(sys.stdin, \"isatty\", Mock(return_value=isatty))\n\n    if no_stdin:\n        monkeypatch.setattr(sys, \"stdin\", None)\n\n    assert is_console_interactive() is expected\n\n\n@pytest.mark.parametrize(\n    \"size,expected\",\n    [\n        (123, \"123 bytes\"),\n        (1234, \"1.2 kB\"),\n        (123456, \"123 kB\"),\n        (1234567890, \"1234.6 MB\"),\n    ],\n)\ndef test_format_size(size: int, expected: str) -> None:\n    assert format_size(size) == expected\n\n\n@pytest.mark.parametrize(\n    \"rows, table, sizes\",\n    [\n        ([], [], []),\n        (\n            [\n                (\"I?\", \"version\", \"sdist\", \"wheel\"),\n                (\"\", \"1.18.2\", \"zip\", \"cp38-cp38m-win_amd64\"),\n                (\"v\", 1.18, \"zip\"),\n            ],\n            [\n                \"I? version sdist wheel\",\n                \"   1.18.2  zip   cp38-cp38m-win_amd64\",\n                \"v  1.18    zip\",\n            ],\n            [2, 7, 5, 20],\n        ),\n        (\n            [(\"I?\", \"version\", \"sdist\", \"wheel\"), (), (\"v\", \"1.18.1\", \"zip\")],\n            [\"I? version sdist wheel\", \"\", \"v  1.18.1  zip\"],\n            [2, 7, 5, 5],\n        ),\n    ],\n)\ndef test_tabulate(rows: list[tuple[str]], table: list[str], sizes: list[int]) -> None:\n    assert tabulate(rows) == (table, sizes)\n"
  },
  {
    "path": "tests/unit/test_utils_compatibility_tags.py",
    "content": "import sysconfig\nfrom typing import Any, Callable\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom pip._internal.utils import compatibility_tags\n\n\n@pytest.mark.parametrize(\n    \"version_info, expected\",\n    [\n        ((2,), \"2\"),\n        ((2, 8), \"28\"),\n        ((3,), \"3\"),\n        ((3, 6), \"36\"),\n        # Test a tuple of length 3.\n        ((3, 6, 5), \"36\"),\n        # Test a 2-digit minor version.\n        ((3, 10), \"310\"),\n    ],\n)\ndef test_version_info_to_nodot(version_info: tuple[int], expected: str) -> None:\n    actual = compatibility_tags.version_info_to_nodot(version_info)\n    assert actual == expected\n\n\nclass Testcompatibility_tags:\n    def mock_get_config_var(self, **kwd: str) -> Callable[[str], Any]:\n        \"\"\"\n        Patch sysconfig.get_config_var for arbitrary keys.\n        \"\"\"\n        get_config_var = sysconfig.get_config_var\n\n        def _mock_get_config_var(var: str) -> Any:\n            if var in kwd:\n                return kwd[var]\n            return get_config_var(var)\n\n        return _mock_get_config_var\n\n    def test_no_hyphen_tag(self) -> None:\n        \"\"\"\n        Test that no tag contains a hyphen.\n        \"\"\"\n        import pip._internal.utils.compatibility_tags\n\n        mock_gcf = self.mock_get_config_var(SOABI=\"cpython-35m-darwin\")\n\n        with patch(\"sysconfig.get_config_var\", mock_gcf):\n            supported = pip._internal.utils.compatibility_tags.get_supported()\n\n        for tag in supported:\n            assert \"-\" not in tag.interpreter\n            assert \"-\" not in tag.abi\n            assert \"-\" not in tag.platform\n\n\nclass TestManylinux2010Tags:\n    @pytest.mark.parametrize(\n        \"manylinux2010,manylinux1\",\n        [\n            (\"manylinux2010_x86_64\", \"manylinux1_x86_64\"),\n            (\"manylinux2010_i686\", \"manylinux1_i686\"),\n        ],\n    )\n    def test_manylinux2010_implies_manylinux1(\n        self, manylinux2010: str, manylinux1: str\n    ) -> None:\n        \"\"\"\n        Specifying manylinux2010 implies manylinux1.\n        \"\"\"\n        groups: dict[tuple[str, str], list[str]] = {}\n        supported = compatibility_tags.get_supported(platforms=[manylinux2010])\n        for tag in supported:\n            groups.setdefault((tag.interpreter, tag.abi), []).append(tag.platform)\n\n        for arches in groups.values():\n            if arches == [\"any\"]:\n                continue\n            assert arches[:2] == [manylinux2010, manylinux1]\n\n\nclass TestManylinux2014Tags:\n    @pytest.mark.parametrize(\n        \"manylinuxA,manylinuxB\",\n        [\n            (\"manylinux2014_x86_64\", [\"manylinux2010_x86_64\", \"manylinux1_x86_64\"]),\n            (\"manylinux2014_i686\", [\"manylinux2010_i686\", \"manylinux1_i686\"]),\n        ],\n    )\n    def test_manylinuxA_implies_manylinuxB(\n        self, manylinuxA: str, manylinuxB: list[str]\n    ) -> None:\n        \"\"\"\n        Specifying manylinux2014 implies manylinux2010/manylinux1.\n        \"\"\"\n        groups: dict[tuple[str, str], list[str]] = {}\n        supported = compatibility_tags.get_supported(platforms=[manylinuxA])\n        for tag in supported:\n            groups.setdefault((tag.interpreter, tag.abi), []).append(tag.platform)\n\n        expected_arches = [manylinuxA]\n        expected_arches.extend(manylinuxB)\n        for arches in groups.values():\n            if arches == [\"any\"]:\n                continue\n            assert arches[:3] == expected_arches\n"
  },
  {
    "path": "tests/unit/test_utils_datetime.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pip._internal.utils.datetime import parse_iso_datetime\n\n\n@pytest.mark.parametrize(\n    \"isodate\",\n    [\n        \"2020-01-22\",\n        \"2020-01-22+00:00\",\n        \"2020-01-22+05:00\",\n        \"2020-01-22T14:24:01\",\n        \"2020-01-22 14:24:01\",\n        \"2020-01-22T14:24:01Z\",\n        \"2020-01-22 14:24:01Z\",\n        \"2020-01-22T14:24:01+00:00\",\n        \"2020-01-22 14:24:01+00:00\",\n        \"2020-01-22T14:24:01-05:00\",\n        \"2020-01-22 14:24:01-05:00\",\n        \"2020-01-22T14:24:01.123456Z\",\n        \"2020-01-22 14:24:01.123456Z\",\n        \"2020-01-22T14:24:01.123456+00:00\",\n        \"2020-01-22 14:24:01.123456+00:00\",\n        \"2020-01-22T14:24:01.123456-05:00\",\n        \"2020-01-22 14:24:01.123456-05:00\",\n    ],\n)\ndef test_parse_iso_datetime_valid(isodate: str) -> None:\n    parse_iso_datetime(isodate)\n\n\n@pytest.mark.parametrize(\n    \"isodate\",\n    [\n        \"\",\n        \"not-a-date\",\n        \"2020-13-01\",\n        \"2020-01-32\",\n        \"20220101Z\",\n        \"2022-01-01Z\",\n        \"2020/01/22\",\n        \"2020-01-22 \",\n        \"2020-01-22T\",\n        \"2020-01-22 Z\",\n        \"2020-01-22TZ\",\n    ],\n)\ndef test_parse_iso_datetime_invalid(isodate: str) -> None:\n    with pytest.raises(ValueError):\n        parse_iso_datetime(isodate)\n"
  },
  {
    "path": "tests/unit/test_utils_filesystem.py",
    "content": "import os\nfrom pathlib import Path\n\nfrom pip._internal.utils.filesystem import (\n    _subdirs_without_generic,\n    subdirs_without_files,\n    subdirs_without_wheels,\n)\n\n\ndef make_file(path: str) -> None:\n    Path(path).touch()\n\n\ndef make_valid_symlink(path: str) -> None:\n    target = path + \"1\"\n    make_file(target)\n    os.symlink(target, path)\n\n\ndef make_broken_symlink(path: str) -> None:\n    os.symlink(\"foo\", path)\n\n\ndef make_dir(path: str) -> None:\n    os.mkdir(path)\n\n\nclass TestSubdirsWithoutGeneric:\n    \"\"\"Tests for _subdirs_without_generic.\"\"\"\n\n    def test_yieled_in_reverse_order(self, tmp_path: Path) -> None:\n        test_dir = tmp_path / \"empty\"\n        deepest_dir = test_dir / \"a\" / \"b\" / \"c\" / \"d\"\n        deepest_dir.mkdir(parents=True)\n\n        result = list(\n            _subdirs_without_generic(str(test_dir), lambda root, filenames: False)\n        )\n        assert [\n            deepest_dir,\n            deepest_dir.parent,\n            deepest_dir.parent.parent,\n            deepest_dir.parent.parent.parent,\n            test_dir,\n        ] == result\n\n\nclass TestSubdirsWithoutFiles:\n    \"\"\"Tests for subdirs_without_files function.\"\"\"\n\n    def test_empty_directory_tree(self, tmp_path: Path) -> None:\n        \"\"\"An empty directory should yield itself.\"\"\"\n        test_dir = tmp_path / \"empty\"\n        test_dir.mkdir()\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        assert result == [test_dir]\n\n    def test_directory_with_file(self, tmp_path: Path) -> None:\n        \"\"\"A directory with a file should not be yielded.\"\"\"\n        test_dir = tmp_path / \"with_file\"\n        test_dir.mkdir()\n        (test_dir / \"file.txt\").touch()\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        assert result == []\n\n    def test_nested_empty_directories(self, tmp_path: Path) -> None:\n        \"\"\"Nested empty directories should all be yielded.\"\"\"\n        test_dir = tmp_path / \"root\"\n        (test_dir / \"a\" / \"b\" / \"c\").mkdir(parents=True)\n        (test_dir / \"d\" / \"e\").mkdir(parents=True)\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        # Should yield all directories since none have files\n        assert len(result) == 6  # root, a, a/b, a/b/c, d, d/e\n        assert test_dir in result\n\n    def test_mixed_empty_and_non_empty(self, tmp_path: Path) -> None:\n        \"\"\"Only empty subdirectories should be yielded.\"\"\"\n        test_dir = tmp_path / \"mixed\"\n        empty1 = test_dir / \"empty1\"\n        empty2 = test_dir / \"empty2\"\n        with_file = test_dir / \"with_file\"\n\n        empty1.mkdir(parents=True)\n        empty2.mkdir(parents=True)\n        with_file.mkdir(parents=True)\n        (with_file / \"file.txt\").touch()\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        assert empty1 in result\n        assert empty2 in result\n        assert with_file not in result\n        assert test_dir not in result  # root has subdirs with files\n\n    def test_deeply_nested_file_marks_parents(self, tmp_path: Path) -> None:\n        \"\"\"A file deep in the tree marks all parent directories as non-empty.\"\"\"\n        test_dir = tmp_path / \"deep\"\n        deep_dir = test_dir / \"a\" / \"b\" / \"c\"\n        deep_dir.mkdir(parents=True)\n        (deep_dir / \"file.txt\").touch()\n\n        # Create another branch that's empty\n        empty_branch = test_dir / \"empty\"\n        empty_branch.mkdir()\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        # Only the empty branch should be yielded\n        assert result == [empty_branch]\n\n    def test_multiple_files_at_various_levels(self, tmp_path: Path) -> None:\n        \"\"\"Files at various levels should be handled correctly.\"\"\"\n        test_dir = tmp_path / \"various\"\n        (test_dir / \"a\" / \"b\").mkdir(parents=True)\n        (test_dir / \"c\" / \"d\").mkdir(parents=True)\n        (test_dir / \"e\").mkdir(parents=True)\n\n        # File in a/b\n        (test_dir / \"a\" / \"b\" / \"file1.txt\").touch()\n        # File in c (not in c/d)\n        (test_dir / \"c\" / \"file2.txt\").touch()\n        # e is empty\n\n        result = list(subdirs_without_files(str(test_dir)))\n\n        # Only c/d and e should be yielded (c/d has no files, e is empty)\n        assert test_dir / \"c\" / \"d\" in result\n        assert test_dir / \"e\" in result\n        assert len(result) == 2\n\n\nclass TestSubdirsWithoutWheels:\n    \"\"\"Tests for subdirs_without_wheels function.\"\"\"\n\n    def test_directory_with_wheel_file(self, tmp_path: Path) -> None:\n        \"\"\"A directory with a .whl file should not be yielded.\"\"\"\n        test_dir = tmp_path / \"with_wheel\"\n        test_dir.mkdir()\n        (test_dir / \"package-1.0-py3-none-any.whl\").touch()\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        assert result == []\n\n    def test_directory_with_non_wheel_files(self, tmp_path: Path) -> None:\n        \"\"\"A directory with non-wheel files should be yielded.\"\"\"\n        test_dir = tmp_path / \"no_wheels\"\n        test_dir.mkdir()\n        (test_dir / \"metadata.json\").touch()\n        (test_dir / \"readme.txt\").touch()\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        assert result == [test_dir]\n\n    def test_mixed_wheel_and_non_wheel_dirs(self, tmp_path: Path) -> None:\n        \"\"\"Only directories without wheels should be yielded.\"\"\"\n        test_dir = tmp_path / \"mixed_wheels\"\n        has_wheel = test_dir / \"has_wheel\"\n        no_wheel = test_dir / \"no_wheel\"\n\n        has_wheel.mkdir(parents=True)\n        no_wheel.mkdir(parents=True)\n\n        (has_wheel / \"package-1.0-py3-none-any.whl\").touch()\n        (no_wheel / \"metadata.json\").touch()\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        assert no_wheel in result\n        assert has_wheel not in result\n        assert test_dir not in result  # root has subdir with wheel\n\n    def test_nested_wheel_marks_parents(self, tmp_path: Path) -> None:\n        \"\"\"A wheel file deep in the tree marks all parent directories.\"\"\"\n        test_dir = tmp_path / \"nested_wheel\"\n        deep_dir = test_dir / \"a\" / \"b\" / \"c\"\n        deep_dir.mkdir(parents=True)\n        (deep_dir / \"package-1.0-py3-none-any.whl\").touch()\n\n        empty_branch = test_dir / \"empty\"\n        empty_branch.mkdir()\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        # Only the empty branch should be yielded\n        assert result == [empty_branch]\n\n    def test_wheel_file_extension_matching(self, tmp_path: Path) -> None:\n        \"\"\"Only files ending with .whl should be considered wheels.\"\"\"\n        test_dir = tmp_path / \"extensions\"\n        (test_dir / \"subdir1\").mkdir(parents=True)\n        (test_dir / \"subdir2\").mkdir(parents=True)\n\n        # Not a wheel (missing extension)\n        (test_dir / \"subdir1\" / \"package-1.0-py3-none-any\").touch()\n        # Not a wheel (.whl in middle of name)\n        (test_dir / \"subdir1\" / \"package.whl.backup\").touch()\n\n        # This is a wheel\n        (test_dir / \"subdir2\" / \"real-1.0-py3-none-any.whl\").touch()\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        assert test_dir / \"subdir1\" in result\n        assert test_dir / \"subdir2\" not in result\n\n    def test_empty_directory_tree_no_wheels(self, tmp_path: Path) -> None:\n        \"\"\"Empty directories should be yielded as having no wheels.\"\"\"\n        test_dir = tmp_path / \"empty_tree\"\n        (test_dir / \"a\" / \"b\").mkdir(parents=True)\n        (test_dir / \"c\").mkdir(parents=True)\n\n        result = list(subdirs_without_wheels(str(test_dir)))\n\n        # All directories should be yielded since none have wheels\n        assert len(result) == 4  # test_dir, a, a/b, c\n        assert test_dir in result\n"
  },
  {
    "path": "tests/unit/test_utils_retry.py",
    "content": "import random\nimport sys\nfrom time import perf_counter, sleep\nfrom typing import NoReturn\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom pip._internal.utils.retry import retry\n\n\ndef test_retry_no_error() -> None:\n    function = Mock(return_value=\"daylily\")\n    wrapped = retry(wait=0, stop_after_delay=0.01)(function)\n    assert wrapped(\"eggs\", alternative=\"spam\") == \"daylily\"\n    function.assert_called_once_with(\"eggs\", alternative=\"spam\")\n\n\ndef test_retry_no_error_after_retry() -> None:\n    raised = False\n\n    def _raise_once() -> str:\n        nonlocal raised\n        if not raised:\n            raised = True\n            raise RuntimeError(\"ham\")\n        return \"daylily\"\n\n    function = Mock(wraps=_raise_once)\n    wrapped = retry(wait=0, stop_after_delay=0.01)(function)\n    assert wrapped() == \"daylily\"\n    assert function.call_count == 2\n\n\ndef test_retry_last_error_is_reraised() -> None:\n    errors = []\n\n    def _raise_error() -> NoReturn:\n        error = RuntimeError(random.random())\n        errors.append(error)\n        raise error\n\n    function = Mock(wraps=_raise_error)\n    wrapped = retry(wait=0, stop_after_delay=0.01)(function)\n    with pytest.raises(RuntimeError) as exc_info:\n        wrapped()\n    assert exc_info.value is errors[-1]\n\n    assert function.call_count > 1, \"expected at least one retry\"\n\n\n@pytest.mark.parametrize(\"exc\", [KeyboardInterrupt, SystemExit])\ndef test_retry_ignores_base_exception(exc: type[BaseException]) -> None:\n    function = Mock(side_effect=exc())\n    wrapped = retry(wait=0, stop_after_delay=0.01)(function)\n    with pytest.raises(exc):\n        wrapped()\n    function.assert_called_once()\n\n\ndef create_timestamped_callable(sleep_per_call: float = 0) -> tuple[Mock, list[float]]:\n    timestamps = []\n\n    def _raise_error() -> NoReturn:\n        timestamps.append(perf_counter())\n        if sleep_per_call:\n            sleep(sleep_per_call)\n        raise RuntimeError\n\n    return Mock(wraps=_raise_error), timestamps\n\n\n@pytest.mark.skipif(\n    sys.platform == \"win32\", reason=\"Too flaky on Windows due to poor timer resolution\"\n)\n@pytest.mark.flaky(reruns=3, reruns_delay=1)\n@pytest.mark.parametrize(\"wait_duration\", [0.015, 0.045, 0.15])\ndef test_retry_wait(wait_duration: float) -> None:\n    function, timestamps = create_timestamped_callable()\n    wrapped = retry(wait=wait_duration, stop_after_delay=0.1)(function)\n    start_time = perf_counter()\n    with pytest.raises(RuntimeError):\n        wrapped()\n    assert len(timestamps) >= 2\n    # Just check the first retry, with a margin of 10% to permit for\n    # unavoidable variation.\n    assert timestamps[1] - start_time >= (wait_duration * 0.9)\n\n\n@pytest.mark.skipif(\n    sys.platform == \"win32\", reason=\"Too flaky on Windows due to poor timer resolution\"\n)\n@pytest.mark.flaky(reruns=3, reruns_delay=1)\n@pytest.mark.parametrize(\n    \"call_duration, max_allowed_calls\", [(0.01, 11), (0.04, 3), (0.15, 1)]\n)\ndef test_retry_time_limit(call_duration: float, max_allowed_calls: int) -> None:\n    function, timestamps = create_timestamped_callable(sleep_per_call=call_duration)\n    wrapped = retry(wait=0, stop_after_delay=0.1)(function)\n\n    start_time = perf_counter()\n    with pytest.raises(RuntimeError):\n        wrapped()\n    assert len(timestamps) <= max_allowed_calls\n    # Add a margin of 10% to permit for unavoidable variation.\n    assert all(t - start_time <= (0.1 * 1.1) for t in timestamps)\n\n\ndef test_retry_method() -> None:\n    class MyClass:\n        def __init__(self) -> None:\n            self.calls = 0\n\n        @retry(wait=0, stop_after_delay=3)\n        def method(self, string: str) -> str:\n            self.calls += 1\n            if self.calls >= 5:\n                return string\n            raise RuntimeError\n\n    o = MyClass()\n    assert o.method(\"orange\") == \"orange\"\n    assert o.calls == 5\n"
  },
  {
    "path": "tests/unit/test_utils_subprocess.py",
    "content": "from __future__ import annotations\n\nimport locale\nimport sys\nfrom logging import DEBUG, ERROR, INFO, WARNING\n\nimport pytest\n\nfrom pip._internal.cli.spinners import SpinnerInterface\nfrom pip._internal.exceptions import InstallationSubprocessError\nfrom pip._internal.utils.logging import VERBOSE\nfrom pip._internal.utils.misc import hide_value\nfrom pip._internal.utils.subprocess import (\n    CommandArgs,\n    call_subprocess,\n    format_command_args,\n    make_command,\n    subprocess_logger,\n)\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        ([\"pip\", \"list\"], \"pip list\"),\n        (\n            [\"foo\", \"space space\", \"new\\nline\", 'double\"quote', \"single'quote\"],\n            \"\"\"foo 'space space' 'new\\nline' 'double\"quote' 'single'\"'\"'quote'\"\"\",\n        ),\n        # Test HiddenText arguments.\n        (\n            make_command(hide_value(\"secret1\"), \"foo\", hide_value(\"secret2\")),\n            \"'****' foo '****'\",\n        ),\n    ],\n)\ndef test_format_command_args(args: CommandArgs, expected: str) -> None:\n    actual = format_command_args(args)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"stdout_only, expected\",\n    [\n        (True, (\"out\\n\", \"out\\r\\n\")),\n        (False, (\"out\\nerr\\n\", \"out\\r\\nerr\\r\\n\", \"err\\nout\\n\", \"err\\r\\nout\\r\\n\")),\n    ],\n)\ndef test_call_subprocess_stdout_only(\n    capfd: pytest.CaptureFixture[str],\n    monkeypatch: pytest.MonkeyPatch,\n    stdout_only: bool,\n    expected: tuple[str, ...],\n) -> None:\n    log = []\n    monkeypatch.setattr(\n        subprocess_logger,\n        \"log\",\n        lambda level, *args: log.append(args[0]),\n    )\n    out = call_subprocess(\n        [\n            sys.executable,\n            \"-c\",\n            \"import sys; sys.stdout.write('out\\\\n'); sys.stderr.write('err\\\\n')\",\n        ],\n        command_desc=\"test stdout_only\",\n        stdout_only=stdout_only,\n    )\n    assert out in expected\n    captured = capfd.readouterr()\n    assert captured.err == \"\"\n    assert log == [\"Running command %s\", \"out\", \"err\"] or log == [\n        \"Running command %s\",\n        \"err\",\n        \"out\",\n    ]\n\n\nclass FakeSpinner(SpinnerInterface):\n    def __init__(self) -> None:\n        self.spin_count = 0\n        self.final_status: str | None = None\n\n    def spin(self) -> None:\n        self.spin_count += 1\n\n    def finish(self, final_status: str) -> None:\n        self.final_status = final_status\n\n\nclass TestCallSubprocess:\n    \"\"\"\n    Test call_subprocess().\n    \"\"\"\n\n    def check_result(\n        self,\n        capfd: pytest.CaptureFixture[str],\n        caplog: pytest.LogCaptureFixture,\n        log_level: int,\n        spinner: FakeSpinner,\n        result: str | None,\n        expected: tuple[list[str] | None, list[tuple[str, int, str]]],\n        expected_spinner: tuple[int, str | None],\n    ) -> None:\n        \"\"\"\n        Check the result of calling call_subprocess().\n\n        :param log_level: the logging level that caplog was set to.\n        :param spinner: the FakeSpinner object passed to call_subprocess()\n            to be checked.\n        :param result: the call_subprocess() return value to be checked.\n        :param expected: a pair (expected_proc, expected_records), where\n            1) `expected_proc` is the expected return value of\n              call_subprocess() as a list of lines, or None if the return\n              value is expected to be None;\n            2) `expected_records` is the expected value of\n              caplog.record_tuples.\n        :param expected_spinner: a 2-tuple of the spinner's expected\n            (spin_count, final_status).\n        \"\"\"\n        expected_proc, expected_records = expected\n\n        if expected_proc is None:\n            assert result is None\n        else:\n            assert result is not None\n            assert result.splitlines() == expected_proc\n\n        # Confirm that stdout and stderr haven't been written to.\n        captured = capfd.readouterr()\n        assert (captured.out, captured.err) == (\"\", \"\")\n\n        records = caplog.record_tuples\n        if len(records) != len(expected_records):\n            raise RuntimeError(f\"{records} != {expected_records}\")\n\n        for record, expected_record in zip(records, expected_records):\n            # Check the logger_name and log level parts exactly.\n            assert record[:2] == expected_record[:2]\n            # For the message portion, check only a substring.  Also, we\n            # can't use startswith() since the order of stdout and stderr\n            # isn't guaranteed in cases where stderr is also present.\n            # For example, we observed the stderr lines coming before stdout\n            # in CI for PyPy 2.7 even though stdout happens first\n            # chronologically.\n            assert expected_record[2] in record[2]\n\n        assert (spinner.spin_count, spinner.final_status) == expected_spinner\n\n    def prepare_call(\n        self,\n        caplog: pytest.LogCaptureFixture,\n        log_level: int,\n        command: str | None = None,\n    ) -> tuple[list[str], FakeSpinner]:\n        if command is None:\n            command = 'print(\"Hello\"); print(\"world\")'\n\n        caplog.set_level(log_level)\n        spinner = FakeSpinner()\n        args = [sys.executable, \"-c\", command]\n\n        return (args, spinner)\n\n    def test_debug_logging(\n        self, capfd: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"\n        Test DEBUG logging (and without passing show_stdout=True).\n        \"\"\"\n        log_level = DEBUG\n        args, spinner = self.prepare_call(caplog, log_level)\n        result = call_subprocess(\n            args,\n            command_desc=\"test debug logging\",\n            spinner=spinner,\n        )\n\n        expected = (\n            [\"Hello\", \"world\"],\n            [\n                (\"pip.subprocessor\", VERBOSE, \"Running \"),\n                (\"pip.subprocessor\", VERBOSE, \"Hello\"),\n                (\"pip.subprocessor\", VERBOSE, \"world\"),\n            ],\n        )\n        # The spinner shouldn't spin in this case since the subprocess\n        # output is already being logged to the console.\n        self.check_result(\n            capfd,\n            caplog,\n            log_level,\n            spinner,\n            result,\n            expected,\n            expected_spinner=(0, None),\n        )\n\n    def test_info_logging(\n        self, capfd: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"\n        Test INFO logging (and without passing show_stdout=True).\n        \"\"\"\n        log_level = INFO\n        args, spinner = self.prepare_call(caplog, log_level)\n        result = call_subprocess(\n            args,\n            command_desc=\"test info logging\",\n            spinner=spinner,\n        )\n\n        expected: tuple[list[str], list[tuple[str, int, str]]] = (\n            [\"Hello\", \"world\"],\n            [],\n        )\n        # The spinner should spin twice in this case since the subprocess\n        # output isn't being written to the console.\n        self.check_result(\n            capfd,\n            caplog,\n            log_level,\n            spinner,\n            result,\n            expected,\n            expected_spinner=(2, \"done\"),\n        )\n\n    def test_info_logging__subprocess_error(\n        self, capfd: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"\n        Test INFO logging of a subprocess with an error (and without passing\n        show_stdout=True).\n        \"\"\"\n        log_level = INFO\n        command = 'print(\"Hello\"); print(\"world\"); exit(\"fail\")'\n        args, spinner = self.prepare_call(caplog, log_level, command=command)\n\n        with pytest.raises(InstallationSubprocessError) as exc:\n            call_subprocess(\n                args,\n                command_desc=\"test info logging with subprocess error\",\n                spinner=spinner,\n            )\n        result = None\n        exception = exc.value\n        assert exception.reference == \"subprocess-exited-with-error\"\n        assert \"exit code: 1\" in exception.message\n        assert exception.note_stmt\n        assert \"not a problem with pip\" in exception.note_stmt\n        # Check that the process output is captured, and would be shown.\n        assert exception.context\n        assert \"Hello\\n\" in exception.context\n        assert \"fail\\n\" in exception.context\n        assert \"world\\n\" in exception.context\n\n        expected = (\n            None,\n            [\n                # pytest's caplog overrides the formatter, which means that we\n                # won't see the message formatted through our formatters.\n                (\"pip.subprocessor\", ERROR, \"subprocess error exited with 1\"),\n            ],\n        )\n        # The spinner should spin three times in this case since the\n        # subprocess output isn't being written to the console.\n        self.check_result(\n            capfd,\n            caplog,\n            log_level,\n            spinner,\n            result,\n            expected,\n            expected_spinner=(3, \"error\"),\n        )\n\n    def test_info_logging_with_show_stdout_true(\n        self, capfd: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture\n    ) -> None:\n        \"\"\"\n        Test INFO logging with show_stdout=True.\n        \"\"\"\n        log_level = INFO\n        args, spinner = self.prepare_call(caplog, log_level)\n        result = call_subprocess(\n            args,\n            command_desc=\"test info logging with show_stdout\",\n            spinner=spinner,\n            show_stdout=True,\n        )\n\n        expected = (\n            [\"Hello\", \"world\"],\n            [\n                (\"pip.subprocessor\", INFO, \"Running \"),\n                (\"pip.subprocessor\", INFO, \"Hello\"),\n                (\"pip.subprocessor\", INFO, \"world\"),\n            ],\n        )\n        # The spinner shouldn't spin in this case since the subprocess\n        # output is already being written to the console.\n        self.check_result(\n            capfd,\n            caplog,\n            log_level,\n            spinner,\n            result,\n            expected,\n            expected_spinner=(0, None),\n        )\n\n    @pytest.mark.parametrize(\n        \"exit_status, show_stdout, extra_ok_returncodes, log_level, expected\",\n        [\n            # The spinner should show here because show_stdout=False means\n            # the subprocess should get logged at DEBUG level, but the passed\n            # log level is only INFO.\n            (0, False, None, INFO, (None, \"done\", 2)),\n            # Test some cases where the spinner should not be shown.\n            (0, False, None, DEBUG, (None, None, 0)),\n            # Test show_stdout=True.\n            (0, True, None, DEBUG, (None, None, 0)),\n            (0, True, None, INFO, (None, None, 0)),\n            # The spinner should show here because show_stdout=True means\n            # the subprocess should get logged at INFO level, but the passed\n            # log level is only WARNING.\n            (0, True, None, WARNING, (None, \"done\", 2)),\n            # Test a non-zero exit status.\n            (3, False, None, INFO, (InstallationSubprocessError, \"error\", 2)),\n            # Test a non-zero exit status also in extra_ok_returncodes.\n            (3, False, (3,), INFO, (None, \"done\", 2)),\n        ],\n    )\n    def test_spinner_finish(\n        self,\n        exit_status: int,\n        show_stdout: bool,\n        extra_ok_returncodes: tuple[int, ...] | None,\n        log_level: int,\n        caplog: pytest.LogCaptureFixture,\n        expected: tuple[type[Exception] | None, str | None, int],\n    ) -> None:\n        \"\"\"\n        Test that the spinner finishes correctly.\n        \"\"\"\n        expected_exc_type = expected[0]\n        expected_final_status = expected[1]\n        expected_spin_count = expected[2]\n\n        command = f'print(\"Hello\"); print(\"world\"); exit({exit_status})'\n        args, spinner = self.prepare_call(caplog, log_level, command=command)\n        exc_type: type[Exception] | None\n        try:\n            call_subprocess(\n                args,\n                command_desc=\"spinner go spinny\",\n                show_stdout=show_stdout,\n                extra_ok_returncodes=extra_ok_returncodes,\n                spinner=spinner,\n            )\n        except Exception as exc:\n            exc_type = type(exc)\n        else:\n            exc_type = None\n\n        assert exc_type == expected_exc_type\n        assert spinner.final_status == expected_final_status\n        assert spinner.spin_count == expected_spin_count\n\n    def test_closes_stdin(self) -> None:\n        with pytest.raises(InstallationSubprocessError):\n            call_subprocess(\n                [sys.executable, \"-c\", \"input()\"],\n                show_stdout=True,\n                command_desc=\"stdin reader\",\n            )\n\n\ndef test_unicode_decode_error(caplog: pytest.LogCaptureFixture) -> None:\n    if locale.getpreferredencoding() != \"UTF-8\":\n        pytest.skip(\"locale.getpreferredencoding() is not UTF-8\")\n    caplog.set_level(INFO)\n    call_subprocess(\n        [\n            sys.executable,\n            \"-c\",\n            \"import sys; sys.stdout.buffer.write(b'\\\\xff')\",\n        ],\n        command_desc=\"invalid decode output\",\n        show_stdout=True,\n    )\n\n    assert len(caplog.records) == 2\n    # First log record is \"Running ...\"\n    assert caplog.record_tuples[1] == (\"pip.subprocessor\", INFO, \"\\\\xff\")\n"
  },
  {
    "path": "tests/unit/test_utils_temp_dir.py",
    "content": "from __future__ import annotations\n\nimport itertools\nimport os\nimport stat\nimport tempfile\nfrom collections.abc import Iterator\nfrom pathlib import Path\nfrom typing import Any\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.utils import temp_dir\nfrom pip._internal.utils.misc import ensure_dir\nfrom pip._internal.utils.temp_dir import (\n    AdjacentTempDirectory,\n    TempDirectory,\n    _Default,\n    _default,\n    global_tempdir_manager,\n    tempdir_registry,\n)\n\n\n# No need to test symlinked directories on Windows\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_symlinked_path() -> None:\n    with TempDirectory() as tmp_dir:\n        assert os.path.exists(tmp_dir.path)\n\n        alt_tmp_dir = tempfile.mkdtemp(prefix=\"pip-test-\")\n        assert os.path.dirname(tmp_dir.path) == os.path.dirname(\n            os.path.realpath(alt_tmp_dir)\n        )\n        # are we on a system where /tmp is a symlink\n        if os.path.realpath(alt_tmp_dir) != os.path.abspath(alt_tmp_dir):\n            assert os.path.dirname(tmp_dir.path) != os.path.dirname(alt_tmp_dir)\n        else:\n            assert os.path.dirname(tmp_dir.path) == os.path.dirname(alt_tmp_dir)\n        os.rmdir(tmp_dir.path)\n        assert not os.path.exists(tmp_dir.path)\n\n\ndef test_deletes_readonly_files() -> None:\n    def create_file(*args: str) -> None:\n        fpath = os.path.join(*args)\n        ensure_dir(os.path.dirname(fpath))\n        with open(fpath, \"w\") as f:\n            f.write(\"Holla!\")\n\n    def readonly_file(*args: str) -> None:\n        fpath = os.path.join(*args)\n        os.chmod(fpath, stat.S_IREAD)\n\n    with TempDirectory() as tmp_dir:\n        create_file(tmp_dir.path, \"normal-file\")\n        create_file(tmp_dir.path, \"readonly-file\")\n        readonly_file(tmp_dir.path, \"readonly-file\")\n\n        create_file(tmp_dir.path, \"subfolder\", \"normal-file\")\n        create_file(tmp_dir.path, \"subfolder\", \"readonly-file\")\n        readonly_file(tmp_dir.path, \"subfolder\", \"readonly-file\")\n\n\ndef test_path_access_after_context_raises() -> None:\n    with TempDirectory() as tmp_dir:\n        path = tmp_dir.path\n\n    with pytest.raises(AssertionError) as e:\n        _ = tmp_dir.path\n\n    assert path in str(e.value)\n\n\ndef test_path_access_after_clean_raises() -> None:\n    tmp_dir = TempDirectory()\n    path = tmp_dir.path\n    tmp_dir.cleanup()\n\n    with pytest.raises(AssertionError) as e:\n        _ = tmp_dir.path\n\n    assert path in str(e.value)\n\n\ndef test_create_and_cleanup_work() -> None:\n    tmp_dir = TempDirectory()\n    created_path = tmp_dir.path\n\n    assert tmp_dir.path is not None\n    assert os.path.exists(created_path)\n\n    tmp_dir.cleanup()\n    assert not os.path.exists(created_path)\n\n\n@pytest.mark.parametrize(\n    \"name\",\n    [\n        \"ABC\",\n        \"ABC.dist-info\",\n        \"_+-\",\n        \"_package\",\n        \"A......B\",\n        \"AB\",\n        \"A\",\n        \"2\",\n    ],\n)\ndef test_adjacent_directory_names(name: str) -> None:\n    def names() -> Iterator[str]:\n        return AdjacentTempDirectory._generate_names(name)\n\n    chars = AdjacentTempDirectory.LEADING_CHARS\n\n    # Ensure many names are unique\n    # (For long *name*, this sequence can be extremely long.\n    # However, since we're only ever going to take the first\n    # result that works, provided there are many of those\n    # and that shorter names result in totally unique sets,\n    # it's okay to skip part of the test.)\n    some_names = list(itertools.islice(names(), 1000))\n    # We should always get at least 1000 names\n    assert len(some_names) == 1000\n\n    # Ensure original name does not appear early in the set\n    assert name not in some_names\n\n    if len(name) > 2:\n        # Names should be at least 90% unique (given the infinite\n        # range of inputs, and the possibility that generated names\n        # may already exist on disk anyway, this is a much cheaper\n        # criteria to enforce than complete uniqueness).\n        assert len(some_names) > 0.9 * len(set(some_names))\n\n        # Ensure the first few names are the same length as the original\n        same_len = list(itertools.takewhile(lambda x: len(x) == len(name), some_names))\n        assert len(same_len) > 10\n\n        # Check the first group are correct\n        expected_names = [\"~\" + name[1:]]\n        expected_names.extend(\"~\" + c + name[2:] for c in chars)\n        for x, y in zip(some_names, expected_names):\n            assert x == y\n\n    else:\n        # All names are going to be longer than our original\n        assert min(len(x) for x in some_names) > 1\n\n        # All names are going to be unique\n        assert len(some_names) == len(set(some_names))\n\n        if len(name) == 2:\n            # All but the first name are going to end with our original\n            assert all(x.endswith(name) for x in some_names[1:])\n        else:\n            # All names are going to end with our original\n            assert all(x.endswith(name) for x in some_names)\n\n\n@pytest.mark.parametrize(\n    \"name\",\n    [\n        \"A\",\n        \"ABC\",\n        \"ABC.dist-info\",\n        \"_+-\",\n        \"_package\",\n    ],\n)\ndef test_adjacent_directory_exists(name: str, tmpdir: Path) -> None:\n    block_name, expect_name = itertools.islice(\n        AdjacentTempDirectory._generate_names(name), 2\n    )\n\n    original = os.path.join(tmpdir, name)\n    blocker = os.path.join(tmpdir, block_name)\n\n    ensure_dir(original)\n    ensure_dir(blocker)\n\n    with AdjacentTempDirectory(original) as atmp_dir:\n        assert expect_name == os.path.split(atmp_dir.path)[1]\n\n\ndef test_adjacent_directory_permission_error(monkeypatch: pytest.MonkeyPatch) -> None:\n    name = \"ABC\"\n\n    def raising_mkdir(*args: Any, **kwargs: Any) -> None:\n        raise OSError(\"Unknown OSError\")\n\n    with TempDirectory() as tmp_dir:\n        original = os.path.join(tmp_dir.path, name)\n\n        ensure_dir(original)\n        monkeypatch.setattr(\"os.mkdir\", raising_mkdir)\n\n        with pytest.raises(OSError):\n            with AdjacentTempDirectory(original):\n                pass\n\n\ndef test_global_tempdir_manager() -> None:\n    with global_tempdir_manager():\n        d = TempDirectory(globally_managed=True)\n        path = d.path\n        assert os.path.exists(path)\n    assert not os.path.exists(path)\n\n\ndef test_tempdirectory_asserts_global_tempdir(monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setattr(temp_dir, \"_tempdir_manager\", None)\n    with pytest.raises(AssertionError):\n        TempDirectory(globally_managed=True)\n\n\ndeleted_kind = \"deleted\"\nnot_deleted_kind = \"not-deleted\"\n\n\n@pytest.mark.parametrize(\n    \"delete,kind,exists\",\n    [\n        (None, deleted_kind, False),\n        (_default, deleted_kind, False),\n        (True, deleted_kind, False),\n        (False, deleted_kind, True),\n        (None, not_deleted_kind, True),\n        (_default, not_deleted_kind, True),\n        (True, not_deleted_kind, False),\n        (False, not_deleted_kind, True),\n        (None, \"unspecified\", False),\n        (_default, \"unspecified\", False),\n        (True, \"unspecified\", False),\n        (False, \"unspecified\", True),\n    ],\n)\ndef test_tempdir_registry(delete: bool | _Default, kind: str, exists: bool) -> None:\n    with tempdir_registry() as registry:\n        registry.set_delete(deleted_kind, True)\n        registry.set_delete(not_deleted_kind, False)\n\n        with TempDirectory(delete=delete, kind=kind) as d:\n            path = d.path\n            assert os.path.exists(path)\n        assert os.path.exists(path) == exists\n\n\n@pytest.mark.parametrize(\"delete,exists\", [(_default, True), (None, False)])\ndef test_temp_dir_does_not_delete_explicit_paths_by_default(\n    tmpdir: Path, delete: _Default | None, exists: bool\n) -> None:\n    p = tmpdir / \"example\"\n    p.mkdir()\n    path = os.fspath(p)\n\n    with tempdir_registry() as registry:\n        registry.set_delete(deleted_kind, True)\n\n        with TempDirectory(path=path, delete=delete, kind=deleted_kind) as d:\n            assert str(d.path) == path\n            assert os.path.exists(path)\n        assert os.path.exists(path) == exists\n\n\n@pytest.mark.parametrize(\"should_delete\", [True, False])\ndef test_tempdir_registry_lazy(should_delete: bool) -> None:\n    \"\"\"\n    Test the registry entry can be updated after a temp dir is created,\n    to change whether a kind should be deleted or not.\n    \"\"\"\n    with tempdir_registry() as registry:\n        with TempDirectory(delete=None, kind=\"test-for-lazy\") as d:\n            path = d.path\n            registry.set_delete(\"test-for-lazy\", should_delete)\n            assert os.path.exists(path)\n        assert os.path.exists(path) == (not should_delete)\n\n\ndef test_tempdir_cleanup_ignore_errors() -> None:\n    os_unlink = os.unlink\n\n    # mock os.unlink to fail with EACCES for a specific filename to simulate\n    # how removing a loaded exe/dll behaves.\n    def unlink(name: str, *args: Any, **kwargs: Any) -> None:\n        if \"bomb\" in name:\n            raise PermissionError(name)\n        else:\n            os_unlink(name)\n\n    with mock.patch(\"os.unlink\", unlink):\n        with TempDirectory(ignore_cleanup_errors=True) as tmp_dir:\n            path = tmp_dir.path\n            with open(os.path.join(path, \"bomb\"), \"a\"):\n                pass\n\n    filename = os.path.join(path, \"bomb\")\n    assert os.path.isfile(filename)\n    os.unlink(filename)\n"
  },
  {
    "path": "tests/unit/test_utils_unpacking.py",
    "content": "import io\nimport os\nimport shutil\nimport stat\nimport sys\nimport tarfile\nimport tempfile\nimport time\nimport zipfile\nfrom pathlib import Path\n\nimport pytest\nfrom _pytest.monkeypatch import MonkeyPatch\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils.unpacking import (\n    _get_default_mode_plus_executable,\n    is_within_directory,\n    untar_file,\n    unzip_file,\n)\n\nfrom tests.lib import TestData\n\n\nclass TestUnpackArchives:\n    \"\"\"\n    test_tar.tgz/test_tar.zip have content as follows engineered to confirm 3\n    things:\n     1) confirm that reg files, dirs, and symlinks get unpacked\n     2) permissions are not preserved (and go by the 022 umask)\n     3) reg files with *any* execute perms, get chmod +x\n\n       file.txt         600 regular file\n       symlink.txt      777 symlink to file.txt\n       script_owner.sh  700 script where owner can execute\n       script_group.sh  610 script where group can execute\n       script_world.sh  601 script where world can execute\n       dir              744 directory\n       dir/dirfile      622 regular file\n     4) the file contents are extracted correctly (though the content of\n        each file isn't currently unique)\n\n    \"\"\"\n\n    def setup_method(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n        self.old_mask = os.umask(0o022)\n        self.symlink_expected_mode = None\n        self.default_file_mode = self._probe_created_file_mode()\n        self.default_dir_mode = self._probe_created_dir_mode()\n        self.executable_mode = _get_default_mode_plus_executable()\n\n    def teardown_method(self) -> None:\n        os.umask(self.old_mask)\n        shutil.rmtree(self.tempdir, ignore_errors=True)\n\n    def mode(self, path: str) -> int:\n        return stat.S_IMODE(os.stat(path).st_mode)\n\n    def _probe_created_file_mode(self) -> int:\n        path = os.path.join(self.tempdir, \"probe_file_mode\")\n        with open(path, \"wb\"):\n            pass\n        mode = self.mode(path)\n        os.remove(path)\n        return mode\n\n    def _probe_created_dir_mode(self) -> int:\n        path = os.path.join(self.tempdir, \"probe_dir_mode\")\n        os.mkdir(path)\n        mode = self.mode(path)\n        os.rmdir(path)\n        return mode\n\n    def confirm_files(self) -> None:\n        # expectations based on the unpack logic that writes non-executable\n        # files/dirs with local defaults and sets executables to chmod +x.\n        # Some environments (e.g. with default ACLs) can alter the effective\n        # default mode even with a fixed umask, so probe defaults in tempdir.\n        for fname, expected_mode, test, expected_contents in [\n            (\"file.txt\", self.default_file_mode, os.path.isfile, b\"file\\n\"),\n            # We don't test the \"symlink.txt\" contents for now.\n            (\"symlink.txt\", self.default_file_mode, os.path.isfile, None),\n            (\"script_owner.sh\", self.executable_mode, os.path.isfile, b\"file\\n\"),\n            (\"script_group.sh\", self.executable_mode, os.path.isfile, b\"file\\n\"),\n            (\"script_world.sh\", self.executable_mode, os.path.isfile, b\"file\\n\"),\n            (\"dir\", self.default_dir_mode, os.path.isdir, None),\n            (\n                os.path.join(\"dir\", \"dirfile\"),\n                self.default_file_mode,\n                os.path.isfile,\n                b\"\",\n            ),\n        ]:\n            path = os.path.join(self.tempdir, fname)\n            if path.endswith(\"symlink.txt\") and sys.platform == \"win32\":\n                # no symlinks created on windows\n                continue\n            assert test(path), path\n            if expected_contents is not None:\n                with open(path, mode=\"rb\") as f:\n                    contents = f.read()\n                assert contents == expected_contents, f\"fname: {fname}\"\n            if sys.platform == \"win32\":\n                # the permissions tests below don't apply in windows\n                # because os.chmod() ignores the execute bit\n                continue\n            mode = self.mode(path)\n            assert (\n                mode == expected_mode\n            ), f\"mode: {mode}, expected mode: {expected_mode}\"\n\n    def make_zip_file(self, filename: str, file_list: list[str]) -> str:\n        \"\"\"\n        Create a zip file for test case\n        \"\"\"\n        test_zip = os.path.join(self.tempdir, filename)\n        with zipfile.ZipFile(test_zip, \"w\") as myzip:\n            for item in file_list:\n                myzip.writestr(item, \"file content\")\n        return test_zip\n\n    def make_tar_file(self, filename: str, file_list: list[str]) -> str:\n        \"\"\"\n        Create a tar file for test case\n        \"\"\"\n        test_tar = os.path.join(self.tempdir, filename)\n        with tarfile.open(test_tar, \"w\") as mytar:\n            for item in file_list:\n                file_tarinfo = tarfile.TarInfo(item)\n                mytar.addfile(file_tarinfo, io.BytesIO(b\"file content\"))\n        return test_tar\n\n    @pytest.mark.skipif(\n        sys.platform == \"win32\", reason=\"os.chmod() ignores execute bit on Windows\"\n    )\n    def test_confirm_files_mode_preconditions(self) -> None:\n        assert self.executable_mode == 0o755\n        assert not (self.default_file_mode & 0o111), (\n            f\"default_file_mode {self.default_file_mode:#o} has execute bits set; \"\n            \"the permission tests in confirm_files() would be meaningless\"\n        )\n\n    def test_unpack_tgz(self, data: TestData) -> None:\n        \"\"\"\n        Test unpacking a *.tgz, and setting execute permissions\n        \"\"\"\n        test_file = data.packages.joinpath(\"test_tar.tgz\")\n        untar_file(os.fspath(test_file), self.tempdir)\n        self.confirm_files()\n        # Check the timestamp of an extracted file\n        file_txt_path = os.path.join(self.tempdir, \"file.txt\")\n        mtime = time.gmtime(os.stat(file_txt_path).st_mtime)\n        assert mtime[0:6] == (2013, 8, 16, 5, 13, 37), mtime\n\n    def test_unpack_zip(self, data: TestData) -> None:\n        \"\"\"\n        Test unpacking a *.zip, and setting execute permissions\n        \"\"\"\n        test_file = data.packages.joinpath(\"test_zip.zip\")\n        unzip_file(os.fspath(test_file), self.tempdir)\n        self.confirm_files()\n\n    def test_unpack_zip_failure(self) -> None:\n        \"\"\"\n        Test unpacking a *.zip with file containing .. path\n        and expect exception\n        \"\"\"\n        files = [\"regular_file.txt\", os.path.join(\"..\", \"outside_file.txt\")]\n        test_zip = self.make_zip_file(\"test_zip.zip\", files)\n        with pytest.raises(InstallationError) as e:\n            unzip_file(test_zip, self.tempdir)\n        assert \"trying to install outside target directory\" in str(e.value)\n\n    def test_unpack_zip_success(self) -> None:\n        \"\"\"\n        Test unpacking a *.zip with regular files,\n        no file will be installed outside target directory after unpack\n        so no exception raised\n        \"\"\"\n        files = [\n            \"regular_file1.txt\",\n            os.path.join(\"dir\", \"dir_file1.txt\"),\n            os.path.join(\"dir\", \"..\", \"dir_file2.txt\"),\n        ]\n        test_zip = self.make_zip_file(\"test_zip.zip\", files)\n        unzip_file(test_zip, self.tempdir)\n\n    def test_unpack_tar_failure(self) -> None:\n        \"\"\"\n        Test unpacking a *.tar with file containing .. path\n        and expect exception\n        \"\"\"\n        files = [\"regular_file.txt\", os.path.join(\"..\", \"outside_file.txt\")]\n        test_tar = self.make_tar_file(\"test_tar.tar\", files)\n        with pytest.raises(InstallationError) as e:\n            untar_file(test_tar, self.tempdir)\n\n        # The error message comes from tarfile.data_filter when it is available,\n        # otherwise from pip's own check.\n        if hasattr(tarfile, \"data_filter\"):\n            assert \"is outside the destination\" in str(e.value)\n        else:\n            assert \"trying to install outside target directory\" in str(e.value)\n\n    def test_unpack_tar_success(self) -> None:\n        \"\"\"\n        Test unpacking a *.tar with regular files,\n        no file will be installed outside target directory after unpack\n        so no exception raised\n        \"\"\"\n        files = [\n            \"regular_file1.txt\",\n            os.path.join(\"dir\", \"dir_file1.txt\"),\n            os.path.join(\"dir\", \"..\", \"dir_file2.txt\"),\n        ]\n        test_tar = self.make_tar_file(\"test_tar.tar\", files)\n        untar_file(test_tar, self.tempdir)\n\n    @pytest.mark.skipif(\n        not hasattr(tarfile, \"data_filter\"),\n        reason=\"tarfile filters (PEP-721) not available\",\n    )\n    def test_unpack_tar_filter(self) -> None:\n        \"\"\"\n        Test that the tarfile.data_filter is used to disallow dangerous\n        behaviour (PEP-721)\n        \"\"\"\n        test_tar = os.path.join(self.tempdir, \"test_tar_filter.tar\")\n        with tarfile.open(test_tar, \"w\") as mytar:\n            file_tarinfo = tarfile.TarInfo(\"bad-link\")\n            file_tarinfo.type = tarfile.SYMTYPE\n            file_tarinfo.linkname = \"../../../../pwn\"\n            mytar.addfile(file_tarinfo, io.BytesIO(b\"\"))\n        with pytest.raises(InstallationError) as e:\n            untar_file(test_tar, self.tempdir)\n\n        assert \"is outside the destination\" in str(e.value)\n\n    @pytest.mark.parametrize(\n        \"input_prefix, unpack_prefix\",\n        [\n            (\"\", \"\"),\n            (\"dir/\", \"\"),  # pip ignores a common leading directory\n            (\"dir/sub/\", \"sub/\"),  # pip ignores *one* common leading directory\n        ],\n    )\n    def test_unpack_tar_links(self, input_prefix: str, unpack_prefix: str) -> None:\n        \"\"\"\n        Test unpacking a *.tar with file containing hard & soft links\n        \"\"\"\n        test_tar = os.path.join(self.tempdir, \"test_tar_links.tar\")\n        content = b\"file content\"\n        with tarfile.open(test_tar, \"w\") as mytar:\n            file_tarinfo = tarfile.TarInfo(input_prefix + \"regular_file.txt\")\n            file_tarinfo.size = len(content)\n            mytar.addfile(file_tarinfo, io.BytesIO(content))\n\n            hardlink_tarinfo = tarfile.TarInfo(input_prefix + \"hardlink.txt\")\n            hardlink_tarinfo.type = tarfile.LNKTYPE\n            hardlink_tarinfo.linkname = input_prefix + \"regular_file.txt\"\n            mytar.addfile(hardlink_tarinfo)\n\n            symlink_tarinfo = tarfile.TarInfo(input_prefix + \"symlink.txt\")\n            symlink_tarinfo.type = tarfile.SYMTYPE\n            symlink_tarinfo.linkname = \"regular_file.txt\"\n            mytar.addfile(symlink_tarinfo)\n\n        untar_file(test_tar, self.tempdir)\n\n        unpack_dir = os.path.join(self.tempdir, unpack_prefix)\n        with open(os.path.join(unpack_dir, \"regular_file.txt\"), \"rb\") as f:\n            assert f.read() == content\n\n        with open(os.path.join(unpack_dir, \"hardlink.txt\"), \"rb\") as f:\n            assert f.read() == content\n\n        with open(os.path.join(unpack_dir, \"symlink.txt\"), \"rb\") as f:\n            assert f.read() == content\n\n    def test_unpack_normal_tar_link1_no_data_filter(\n        self, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test unpacking a normal tar with file containing soft links, but no data_filter\n        \"\"\"\n        if hasattr(tarfile, \"data_filter\"):\n            monkeypatch.delattr(\"tarfile.data_filter\")\n\n        tar_filename = \"test_tar_links_no_data_filter.tar\"\n        tar_filepath = os.path.join(self.tempdir, tar_filename)\n\n        extract_path = os.path.join(self.tempdir, \"extract_path\")\n\n        with tarfile.open(tar_filepath, \"w\") as tar:\n            file_data = io.BytesIO(b\"normal\\n\")\n            normal_file_tarinfo = tarfile.TarInfo(name=\"normal_file\")\n            normal_file_tarinfo.size = len(file_data.getbuffer())\n            tar.addfile(normal_file_tarinfo, fileobj=file_data)\n\n            info = tarfile.TarInfo(\"normal_symlink\")\n            info.type = tarfile.SYMTYPE\n            info.linkpath = \"normal_file\"\n            tar.addfile(info)\n\n        untar_file(tar_filepath, extract_path)\n\n        assert os.path.islink(os.path.join(extract_path, \"normal_symlink\"))\n\n        link_path = os.readlink(os.path.join(extract_path, \"normal_symlink\"))\n        assert link_path == \"normal_file\"\n\n        with open(os.path.join(extract_path, \"normal_symlink\"), \"rb\") as f:\n            assert f.read() == b\"normal\\n\"\n\n    def test_unpack_normal_tar_link2_no_data_filter(\n        self, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test unpacking a normal tar with file containing soft links, but no data_filter\n        \"\"\"\n        if hasattr(tarfile, \"data_filter\"):\n            monkeypatch.delattr(\"tarfile.data_filter\")\n\n        tar_filename = \"test_tar_links_no_data_filter.tar\"\n        tar_filepath = os.path.join(self.tempdir, tar_filename)\n\n        extract_path = os.path.join(self.tempdir, \"extract_path\")\n\n        with tarfile.open(tar_filepath, \"w\") as tar:\n            file_data = io.BytesIO(b\"normal\\n\")\n            normal_file_tarinfo = tarfile.TarInfo(name=\"normal_file\")\n            normal_file_tarinfo.size = len(file_data.getbuffer())\n            tar.addfile(normal_file_tarinfo, fileobj=file_data)\n\n            info = tarfile.TarInfo(\"sub/normal_symlink\")\n            info.type = tarfile.SYMTYPE\n            info.linkpath = \"..\" + os.path.sep + \"normal_file\"\n            tar.addfile(info)\n\n        untar_file(tar_filepath, extract_path)\n\n        assert os.path.islink(os.path.join(extract_path, \"sub\", \"normal_symlink\"))\n\n        link_path = os.readlink(os.path.join(extract_path, \"sub\", \"normal_symlink\"))\n        assert link_path == \"..\" + os.path.sep + \"normal_file\"\n\n        with open(os.path.join(extract_path, \"sub\", \"normal_symlink\"), \"rb\") as f:\n            assert f.read() == b\"normal\\n\"\n\n    def test_unpack_evil_tar_link1_no_data_filter(\n        self, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test unpacking a evil tar with file containing soft links, but no data_filter\n        \"\"\"\n        if hasattr(tarfile, \"data_filter\"):\n            monkeypatch.delattr(\"tarfile.data_filter\")\n\n        tar_filename = \"test_tar_links_no_data_filter.tar\"\n        tar_filepath = os.path.join(self.tempdir, tar_filename)\n\n        import_filename = \"import_file\"\n        import_filepath = os.path.join(self.tempdir, import_filename)\n        open(import_filepath, \"w\").close()\n\n        extract_path = os.path.join(self.tempdir, \"extract_path\")\n\n        with tarfile.open(tar_filepath, \"w\") as tar:\n            info = tarfile.TarInfo(\"evil_symlink\")\n            info.type = tarfile.SYMTYPE\n            info.linkpath = import_filepath\n            tar.addfile(info)\n\n        with pytest.raises(InstallationError) as e:\n            untar_file(tar_filepath, extract_path)\n\n        msg = (\n            \"The tar file ({}) has a file ({}) trying to install outside \"\n            \"target directory ({})\"\n        )\n        assert msg.format(tar_filepath, \"evil_symlink\", import_filepath) in str(e.value)\n\n        assert not os.path.exists(os.path.join(extract_path, \"evil_symlink\"))\n\n    def test_unpack_evil_tar_link2_no_data_filter(\n        self, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"\n        Test unpacking a evil tar with file containing soft links, but no data_filter\n        \"\"\"\n        if hasattr(tarfile, \"data_filter\"):\n            monkeypatch.delattr(\"tarfile.data_filter\")\n\n        tar_filename = \"test_tar_links_no_data_filter.tar\"\n        tar_filepath = os.path.join(self.tempdir, tar_filename)\n\n        import_filename = \"import_file\"\n        import_filepath = os.path.join(self.tempdir, import_filename)\n        open(import_filepath, \"w\").close()\n\n        extract_path = os.path.join(self.tempdir, \"extract_path\")\n\n        link_path = \"..\" + os.sep + import_filename\n\n        with tarfile.open(tar_filepath, \"w\") as tar:\n            info = tarfile.TarInfo(\"evil_symlink\")\n            info.type = tarfile.SYMTYPE\n            info.linkpath = link_path\n            tar.addfile(info)\n\n        with pytest.raises(InstallationError) as e:\n            untar_file(tar_filepath, extract_path)\n\n        msg = (\n            \"The tar file ({}) has a file ({}) trying to install outside \"\n            \"target directory ({})\"\n        )\n        assert msg.format(tar_filepath, \"evil_symlink\", link_path) in str(e.value)\n\n        assert not os.path.exists(os.path.join(extract_path, \"evil_symlink\"))\n\n\ndef test_unpack_tar_unicode(tmpdir: Path) -> None:\n    test_tar = tmpdir / \"test.tar\"\n    # tarfile tries to decode incoming\n    with tarfile.open(test_tar, \"w\", format=tarfile.PAX_FORMAT, encoding=\"utf-8\") as f:\n        metadata = tarfile.TarInfo(\"dir/åäö_日本語.py\")\n        f.addfile(metadata, io.BytesIO(b\"hello world\"))\n\n    output_dir = tmpdir / \"output\"\n    output_dir.mkdir()\n\n    untar_file(os.fspath(test_tar), str(output_dir))\n\n    output_dir_name = str(output_dir)\n    contents = os.listdir(output_dir_name)\n    assert \"åäö_日本語.py\" in contents\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test the second containing the first.\n        ((\"parent/sub\", \"parent/\"), False),\n        # Test the first not ending in a trailing slash.\n        ((\"parent\", \"parent/foo\"), True),\n        # Test target containing `..` but still inside the parent.\n        ((\"parent/\", \"parent/foo/../bar\"), True),\n        # Test target within the parent\n        ((\"parent/\", \"parent/sub\"), True),\n        # Test target outside parent\n        ((\"parent/\", \"parent/../sub\"), False),\n        # Test target sub-string of parent\n        ((\"parent/child\", \"parent/childfoo\"), False),\n    ],\n)\ndef test_is_within_directory(args: tuple[str, str], expected: bool) -> None:\n    result = is_within_directory(*args)\n    assert result == expected\n"
  },
  {
    "path": "tests/unit/test_utils_virtualenv.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport site\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nfrom pip._internal.utils import virtualenv\n\n\n@pytest.mark.parametrize(\n    \"real_prefix, base_prefix, expected\",\n    [\n        (None, None, False),  # Python 2 base interpreter\n        (None, sys.prefix, False),  # Python 3 base interpreter\n        (None, \"not_sys_prefix\", True),  # PEP405 venv\n        (sys.prefix, None, True),  # Unknown case\n        (sys.prefix, sys.prefix, True),  # Unknown case\n        (sys.prefix, \"not_sys_prefix\", True),  # Unknown case\n        (\"not_sys_prefix\", None, True),  # Python 2 virtualenv\n        (\"not_sys_prefix\", sys.prefix, True),  # Python 3 virtualenv\n        (\"not_sys_prefix\", \"not_sys_prefix\", True),  # Unknown case\n    ],\n)\ndef test_running_under_virtualenv(\n    monkeypatch: pytest.MonkeyPatch,\n    real_prefix: str | None,\n    base_prefix: str | None,\n    expected: bool,\n) -> None:\n    # Use raising=False to prevent AttributeError on missing attribute\n    if real_prefix is None:\n        monkeypatch.delattr(sys, \"real_prefix\", raising=False)\n    else:\n        monkeypatch.setattr(sys, \"real_prefix\", real_prefix, raising=False)\n    if base_prefix is None:\n        monkeypatch.delattr(sys, \"base_prefix\", raising=False)\n    else:\n        monkeypatch.setattr(sys, \"base_prefix\", base_prefix, raising=False)\n    assert virtualenv.running_under_virtualenv() == expected\n\n\n@pytest.mark.parametrize(\n    \"under_virtualenv, no_global_file, expected\",\n    [\n        (False, False, False),\n        (False, True, False),\n        (True, False, False),\n        (True, True, True),\n    ],\n)\ndef test_virtualenv_no_global_with_regular_virtualenv(\n    monkeypatch: pytest.MonkeyPatch,\n    tmpdir: Path,\n    under_virtualenv: bool,\n    no_global_file: bool,\n    expected: bool,\n) -> None:\n    monkeypatch.setattr(virtualenv, \"_running_under_venv\", lambda: False)\n\n    monkeypatch.setattr(site, \"__file__\", os.fspath(tmpdir / \"site.py\"))\n    monkeypatch.setattr(\n        virtualenv,\n        \"_running_under_legacy_virtualenv\",\n        lambda: under_virtualenv,\n    )\n    if no_global_file:\n        (tmpdir / \"no-global-site-packages.txt\").touch()\n\n    assert virtualenv.virtualenv_no_global() == expected\n\n\n@pytest.mark.parametrize(\n    \"pyvenv_cfg_lines, under_venv, expect_no_global, expect_warning\",\n    [\n        (None, False, False, False),\n        (None, True, True, True),  # this has a warning.\n        (\n            [\n                \"home = <we do not care>\",\n                \"include-system-site-packages = true\",\n                \"version = <we do not care>\",\n            ],\n            True,\n            False,\n            False,\n        ),\n        (\n            [\n                \"home = <we do not care>\",\n                \"include-system-site-packages = false\",\n                \"version = <we do not care>\",\n            ],\n            True,\n            True,\n            False,\n        ),\n    ],\n)\ndef test_virtualenv_no_global_with_pep_405_virtual_environment(\n    monkeypatch: pytest.MonkeyPatch,\n    caplog: pytest.LogCaptureFixture,\n    pyvenv_cfg_lines: list[str] | None,\n    under_venv: bool,\n    expect_no_global: bool,\n    expect_warning: bool,\n) -> None:\n    monkeypatch.setattr(virtualenv, \"_running_under_legacy_virtualenv\", lambda: False)\n    monkeypatch.setattr(virtualenv, \"_get_pyvenv_cfg_lines\", lambda: pyvenv_cfg_lines)\n    monkeypatch.setattr(virtualenv, \"_running_under_venv\", lambda: under_venv)\n\n    with caplog.at_level(logging.WARNING):\n        assert virtualenv.virtualenv_no_global() == expect_no_global\n\n    if expect_warning:\n        assert caplog.records\n\n        # Check for basic information\n        message = caplog.records[-1].getMessage().lower()\n        assert \"could not access 'pyvenv.cfg'\" in message\n        assert \"assuming global site-packages is not accessible\" in message\n\n\n@pytest.mark.parametrize(\n    \"contents, expected\",\n    [\n        (None, None),\n        (\"\", []),\n        (\"a = b\\nc = d\\n\", [\"a = b\", \"c = d\"]),\n        (\"a = b\\nc = d\", [\"a = b\", \"c = d\"]),  # no trailing newlines\n    ],\n)\ndef test_get_pyvenv_cfg_lines_for_pep_405_virtual_environment(\n    monkeypatch: pytest.MonkeyPatch,\n    tmpdir: Path,\n    contents: str | None,\n    expected: list[str] | None,\n) -> None:\n    monkeypatch.setattr(sys, \"prefix\", str(tmpdir))\n    if contents is not None:\n        tmpdir.joinpath(\"pyvenv.cfg\").write_text(contents)\n\n    assert virtualenv._get_pyvenv_cfg_lines() == expected\n"
  },
  {
    "path": "tests/unit/test_utils_wheel.py",
    "content": "import os\nfrom collections.abc import Iterator\nfrom contextlib import ExitStack\nfrom email import message_from_string\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Callable\nfrom zipfile import ZipFile\n\nimport pytest\n\nfrom pip._internal.exceptions import UnsupportedWheel\nfrom pip._internal.utils import wheel\n\nfrom tests.lib import TestData\n\n_ZipDir = Callable[[Path], ZipFile]\n\n\n@pytest.fixture\ndef zip_dir() -> Iterator[_ZipDir]:\n    def make_zip(path: Path) -> ZipFile:\n        buf = BytesIO()\n        with ZipFile(buf, \"w\", allowZip64=True) as z:\n            for dirpath, _, filenames in os.walk(path):\n                for filename in filenames:\n                    file_path = os.path.join(path, dirpath, filename)\n                    # Zip files must always have / as path separator\n                    archive_path = os.path.relpath(file_path, path).replace(\n                        os.pathsep, \"/\"\n                    )\n                    z.write(file_path, archive_path)\n\n        return stack.enter_context(ZipFile(buf, \"r\", allowZip64=True))\n\n    stack = ExitStack()\n    with stack:\n        yield make_zip\n\n\ndef test_wheel_dist_info_dir_found(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    expected = \"simple-0.1.dist-info\"\n    dist_info_dir = tmpdir / expected\n    dist_info_dir.mkdir()\n    dist_info_dir.joinpath(\"WHEEL\").touch()\n    assert wheel.wheel_dist_info_dir(zip_dir(tmpdir), \"simple\") == expected\n\n\ndef test_wheel_dist_info_dir_multiple(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    dist_info_dir_1 = tmpdir / \"simple-0.1.dist-info\"\n    dist_info_dir_1.mkdir()\n    dist_info_dir_1.joinpath(\"WHEEL\").touch()\n    dist_info_dir_2 = tmpdir / \"unrelated-0.1.dist-info\"\n    dist_info_dir_2.mkdir()\n    dist_info_dir_2.joinpath(\"WHEEL\").touch()\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_dist_info_dir(zip_dir(tmpdir), \"simple\")\n    assert \"multiple .dist-info directories found\" in str(e.value)\n\n\ndef test_wheel_dist_info_dir_none(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_dist_info_dir(zip_dir(tmpdir), \"simple\")\n    assert \"directory not found\" in str(e.value)\n\n\ndef test_wheel_dist_info_dir_wrong_name(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    dist_info_dir = tmpdir / \"unrelated-0.1.dist-info\"\n    dist_info_dir.mkdir()\n    dist_info_dir.joinpath(\"WHEEL\").touch()\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_dist_info_dir(zip_dir(tmpdir), \"simple\")\n    assert \"does not start with 'simple'\" in str(e.value)\n\n\ndef test_wheel_version_ok(data: TestData) -> None:\n    assert wheel.wheel_version(message_from_string(\"Wheel-Version: 1.9\")) == (1, 9)\n\n\ndef test_wheel_metadata_fails_missing_wheel(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    dist_info_dir = tmpdir / \"simple-0.1.0.dist-info\"\n    dist_info_dir.mkdir()\n    dist_info_dir.joinpath(\"METADATA\").touch()\n\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_metadata(zip_dir(tmpdir), dist_info_dir.name)\n    assert \"could not read\" in str(e.value)\n\n\ndef test_wheel_metadata_fails_on_bad_encoding(tmpdir: Path, zip_dir: _ZipDir) -> None:\n    dist_info_dir = tmpdir / \"simple-0.1.0.dist-info\"\n    dist_info_dir.mkdir()\n    dist_info_dir.joinpath(\"METADATA\").touch()\n    dist_info_dir.joinpath(\"WHEEL\").write_bytes(b\"\\xff\")\n\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_metadata(zip_dir(tmpdir), dist_info_dir.name)\n    assert \"error decoding\" in str(e.value)\n\n\ndef test_wheel_version_fails_on_no_wheel_version() -> None:\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_version(message_from_string(\"\"))\n    assert \"missing Wheel-Version\" in str(e.value)\n\n\n@pytest.mark.parametrize(\n    \"version\",\n    [\n        (\"\",),\n        (\"1.b\",),\n        (\"1.\",),\n    ],\n)\ndef test_wheel_version_fails_on_bad_wheel_version(version: str) -> None:\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.wheel_version(message_from_string(f\"Wheel-Version: {version}\"))\n    assert \"invalid Wheel-Version\" in str(e.value)\n\n\ndef test_check_compatibility() -> None:\n    name = \"test\"\n    vc = wheel.VERSION_COMPATIBLE\n\n    # Major version is higher - should be incompatible\n    higher_v = (vc[0] + 1, vc[1])\n\n    # test raises with correct error\n    with pytest.raises(UnsupportedWheel) as e:\n        wheel.check_compatibility(higher_v, name)\n    assert \"is not compatible\" in str(e)\n\n    # Should only log.warning - minor version is greater\n    higher_v = (vc[0], vc[1] + 1)\n    wheel.check_compatibility(higher_v, name)\n\n    # These should work fine\n    wheel.check_compatibility(wheel.VERSION_COMPATIBLE, name)\n\n    # E.g if wheel to install is 1.0 and we support up to 1.2\n    lower_v = (vc[0], max(0, vc[1] - 1))\n    wheel.check_compatibility(lower_v, name)\n"
  },
  {
    "path": "tests/unit/test_vcs.py",
    "content": "from __future__ import annotations\n\nimport logging\nimport os\nimport pathlib\nfrom typing import Any\nfrom unittest import mock\n\nimport pytest\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import HiddenText, hide_url, hide_value\nfrom pip._internal.utils.subprocess import CommandArgs\nfrom pip._internal.vcs import make_vcs_requirement_url\nfrom pip._internal.vcs.bazaar import Bazaar\nfrom pip._internal.vcs.git import Git, RemoteNotValidError, looks_like_hash\nfrom pip._internal.vcs.mercurial import Mercurial\nfrom pip._internal.vcs.subversion import Subversion\nfrom pip._internal.vcs.versioncontrol import RevOptions, VersionControl\n\nfrom tests.lib import is_svn_installed, need_svn\n\n\n@pytest.mark.skipif(\n    \"CI\" not in os.environ, reason=\"Subversion is only required under CI\"\n)\ndef test_ensure_svn_available() -> None:\n    \"\"\"Make sure that svn is available when running in CI.\"\"\"\n    assert is_svn_installed()\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test without subdir.\n        (\n            (\"git+https://example.com/pkg\", \"dev\", \"myproj\"),\n            \"git+https://example.com/pkg@dev#egg=myproj\",\n        ),\n        # Test with subdir.\n        (\n            (\"git+https://example.com/pkg\", \"dev\", \"myproj\", \"sub/dir\"),\n            \"git+https://example.com/pkg@dev#egg=myproj&subdirectory=sub/dir\",\n        ),\n        # Test with None subdir.\n        (\n            (\"git+https://example.com/pkg\", \"dev\", \"myproj\", None),\n            \"git+https://example.com/pkg@dev#egg=myproj\",\n        ),\n        # Test an unescaped project name.\n        (\n            (\"git+https://example.com/pkg\", \"dev\", \"zope-interface\"),\n            \"git+https://example.com/pkg@dev#egg=zope_interface\",\n        ),\n        # Test a revision with special characters.\n        (\n            (\"git+https://example.com/pkg\", \"dev@1#2\", \"myproj\"),\n            \"git+https://example.com/pkg@dev%401%232#egg=myproj\",\n        ),\n    ],\n)\ndef test_make_vcs_requirement_url(args: tuple[Any, ...], expected: str) -> None:\n    actual = make_vcs_requirement_url(*args)\n    assert actual == expected\n\n\ndef test_rev_options_repr() -> None:\n    rev_options = RevOptions(Git, \"develop\")\n    assert repr(rev_options) == \"<RevOptions git: rev='develop'>\"\n\n\n@pytest.mark.parametrize(\n    \"vc_class, expected1, expected2, kwargs\",\n    [\n        # First check VCS-specific RevOptions behavior.\n        (Bazaar, [], [\"-r\", \"123\"], {}),\n        (Git, [\"HEAD\"], [\"123\"], {}),\n        (Mercurial, [], [\"--rev=123\"], {}),\n        (Subversion, [], [\"-r\", \"123\"], {}),\n        # Test extra_args.  For this, test using a single VersionControl class.\n        (\n            Git,\n            [\"HEAD\", \"opt1\", \"opt2\"],\n            [\"123\", \"opt1\", \"opt2\"],\n            {\"extra_args\": [\"opt1\", \"opt2\"]},\n        ),\n    ],\n)\ndef test_rev_options_to_args(\n    vc_class: type[VersionControl],\n    expected1: list[str],\n    expected2: list[str],\n    kwargs: dict[str, Any],\n) -> None:\n    \"\"\"\n    Test RevOptions.to_args().\n    \"\"\"\n    assert RevOptions(vc_class, **kwargs).to_args() == expected1\n    assert RevOptions(vc_class, \"123\", **kwargs).to_args() == expected2\n\n\ndef test_rev_options_to_display() -> None:\n    \"\"\"\n    Test RevOptions.to_display().\n    \"\"\"\n    # The choice of VersionControl class doesn't matter here since\n    # the implementation is the same for all of them.\n    rev_options = RevOptions(Git)\n    assert rev_options.to_display() == \"\"\n\n    rev_options = RevOptions(Git, \"master\")\n    assert rev_options.to_display() == \" (to revision master)\"\n\n\ndef test_rev_options_make_new() -> None:\n    \"\"\"\n    Test RevOptions.make_new().\n    \"\"\"\n    # The choice of VersionControl class doesn't matter here since\n    # the implementation is the same for all of them.\n    rev_options = RevOptions(Git, \"master\", extra_args=[\"foo\", \"bar\"])\n    new_options = rev_options.make_new(\"develop\")\n\n    assert new_options is not rev_options\n    assert new_options.extra_args == [\"foo\", \"bar\"]\n    assert new_options.rev == \"develop\"\n    assert new_options.vc_class is Git\n\n\n@pytest.mark.parametrize(\n    \"sha, expected\",\n    [\n        ((40 * \"a\"), True),\n        ((40 * \"A\"), True),\n        # Test a string containing all valid characters.\n        ((18 * \"a\" + \"0123456789abcdefABCDEF\"), True),\n        ((40 * \"g\"), False),\n        ((39 * \"a\"), False),\n        ((41 * \"a\"), False),\n    ],\n)\ndef test_looks_like_hash(sha: str, expected: bool) -> None:\n    assert looks_like_hash(sha) == expected\n\n\n@pytest.mark.parametrize(\n    \"vcs_cls, remote_url, expected\",\n    [\n        # Mercurial is one of the subclasses using the base class implementation.\n        # `hg://` isn't a real prefix but it tests the default behaviour.\n        (Mercurial, \"hg://user@example.com/MyProject\", False),\n        (Mercurial, \"http://example.com/MyProject\", True),\n        # The Git subclasses should return true in all cases.\n        (Git, \"git://example.com/MyProject\", True),\n        (Git, \"http://example.com/MyProject\", True),\n        # Subversion also overrides the base class implementation.\n        (Subversion, \"svn://example.com/MyProject\", True),\n    ],\n)\ndef test_should_add_vcs_url_prefix(\n    vcs_cls: type[VersionControl], remote_url: str, expected: bool\n) -> None:\n    actual = vcs_cls.should_add_vcs_url_prefix(remote_url)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"url, target\",\n    [\n        # A fully qualified remote url. No changes needed.\n        (\"ssh://bob@server/foo/bar.git\", \"ssh://bob@server/foo/bar.git\"),\n        (\"git://bob@server/foo/bar.git\", \"git://bob@server/foo/bar.git\"),\n        # User is optional and does not need a default.\n        (\"ssh://server/foo/bar.git\", \"ssh://server/foo/bar.git\"),\n        # The common scp shorthand for ssh remotes. Pip won't recognise these as\n        # git remotes until they have a 'ssh://' prefix and the ':' in the middle\n        # is gone.\n        (\"git@example.com:foo/bar.git\", \"ssh://git@example.com/foo/bar.git\"),\n        (\"example.com:foo.git\", \"ssh://example.com/foo.git\"),\n        # Http(s) remote names are already complete and should remain unchanged.\n        (\"https://example.com/foo\", \"https://example.com/foo\"),\n        (\"http://example.com/foo/bar.git\", \"http://example.com/foo/bar.git\"),\n        (\"https://bob@example.com/foo\", \"https://bob@example.com/foo\"),\n    ],\n)\ndef test_git_remote_url_to_pip(url: str, target: str) -> None:\n    assert Git._git_remote_to_pip_url(url) == target\n\n\n@pytest.mark.parametrize(\n    \"url, platform\",\n    [\n        # Windows paths with the ':' drive prefix look dangerously close to SCP.\n        (\"c:/piffle/wiffle/waffle/poffle.git\", \"nt\"),\n        (r\"c:\\faffle\\waffle\\woffle\\piffle.git\", \"nt\"),\n        # Unix paths less so but test them anyway.\n        (\"/muffle/fuffle/pufffle/fluffle.git\", \"posix\"),\n    ],\n)\ndef test_paths_are_not_mistaken_for_scp_shorthand(url: str, platform: str) -> None:\n    # File paths should not be mistaken for SCP shorthand. If they do then\n    # 'c:/piffle/wiffle' would end up as 'ssh://c/piffle/wiffle'.\n    from pip._internal.vcs.git import SCP_REGEX\n\n    assert not SCP_REGEX.match(url)\n\n    if platform == os.name:\n        with pytest.raises(RemoteNotValidError):\n            Git._git_remote_to_pip_url(url)\n\n\ndef test_git_remote_local_path(tmpdir: pathlib.Path) -> None:\n    path = pathlib.Path(tmpdir, \"project.git\")\n    path.mkdir()\n    # Path must exist to be recognised as a local git remote.\n    assert Git._git_remote_to_pip_url(str(path)) == path.as_uri()\n\n\n@mock.patch(\"pip._internal.vcs.git.Git.get_remote_url\")\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision\")\n@mock.patch(\"pip._internal.vcs.git.Git.get_subdirectory\")\n@pytest.mark.parametrize(\n    \"git_url, target_url_prefix\",\n    [\n        (\n            \"https://github.com/pypa/pip-test-package\",\n            \"git+https://github.com/pypa/pip-test-package\",\n        ),\n        (\n            \"git@github.com:pypa/pip-test-package\",\n            \"git+ssh://git@github.com/pypa/pip-test-package\",\n        ),\n    ],\n    ids=[\"https\", \"ssh\"],\n)\n@pytest.mark.network\ndef test_git_get_src_requirements(\n    mock_get_subdirectory: mock.Mock,\n    mock_get_revision: mock.Mock,\n    mock_get_remote_url: mock.Mock,\n    git_url: str,\n    target_url_prefix: str,\n) -> None:\n    sha = \"5547fa909e83df8bd743d3978d6667497983a4b7\"\n\n    mock_get_remote_url.return_value = Git._git_remote_to_pip_url(git_url)\n    mock_get_revision.return_value = sha\n    mock_get_subdirectory.return_value = None\n\n    ret = Git.get_src_requirement(\".\", \"pip-test-package\")\n\n    target = f\"{target_url_prefix}@{sha}#egg=pip_test_package\"\n    assert ret == target\n\n\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision_sha\")\ndef test_git_resolve_revision_rev_exists(get_sha_mock: mock.Mock) -> None:\n    get_sha_mock.return_value = (\"123456\", False)\n    url = HiddenText(\"git+https://git.example.com\", redacted=\"*\")\n    rev_options = Git.make_rev_options(\"develop\")\n\n    new_options = Git.resolve_revision(\".\", url, rev_options)\n    assert new_options.rev == \"123456\"\n\n\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision_sha\")\ndef test_git_resolve_revision_rev_not_found(get_sha_mock: mock.Mock) -> None:\n    get_sha_mock.return_value = (None, False)\n    url = HiddenText(\"git+https://git.example.com\", redacted=\"*\")\n    rev_options = Git.make_rev_options(\"develop\")\n\n    new_options = Git.resolve_revision(\".\", url, rev_options)\n    assert new_options.rev == \"develop\"\n\n\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision_sha\")\ndef test_git_resolve_revision_not_found_warning(\n    get_sha_mock: mock.Mock, caplog: pytest.LogCaptureFixture\n) -> None:\n    caplog.set_level(logging.INFO)\n    get_sha_mock.return_value = (None, False)\n    url = HiddenText(\"git+https://git.example.com\", redacted=\"*\")\n    sha = 40 * \"a\"\n    rev_options = Git.make_rev_options(sha)\n\n    # resolve_revision with a full sha would fail here because\n    # it attempts a git fetch. This case is now covered by\n    # test_resolve_commit_not_on_branch.\n\n    rev_options = Git.make_rev_options(sha[:6])\n    new_options = Git.resolve_revision(\".\", url, rev_options)\n    assert new_options.rev == \"aaaaaa\"\n\n    # Check that a warning got logged only for the abbreviated hash.\n    messages = [r.getMessage() for r in caplog.records]\n    messages = [msg for msg in messages if msg.startswith(\"Did not find \")]\n    assert messages == [\n        \"Did not find branch or tag 'aaaaaa', assuming revision or ref.\"\n    ]\n\n\n@pytest.mark.parametrize(\n    \"rev_name,result\",\n    [\n        (\"5547fa909e83df8bd743d3978d6667497983a4b7\", True),\n        (\"5547fa909\", False),\n        (\"5678\", False),\n        (\"abc123\", False),\n        (\"foo\", False),\n        (None, False),\n    ],\n)\n@mock.patch(\"pip._internal.vcs.git.Git.get_revision\")\ndef test_git_is_commit_id_equal(\n    mock_get_revision: mock.Mock, rev_name: str | None, result: bool\n) -> None:\n    \"\"\"\n    Test Git.is_commit_id_equal().\n    \"\"\"\n    mock_get_revision.return_value = \"5547fa909e83df8bd743d3978d6667497983a4b7\"\n    assert Git.is_commit_id_equal(\"/path\", rev_name) is result\n\n\n# The non-SVN backends all use the same get_netloc_and_auth(), so only test\n# Git as a representative.\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test a basic case.\n        ((\"example.com\", \"https\"), (\"example.com\", (None, None))),\n        # Test with username and password.\n        ((\"user:pass@example.com\", \"https\"), (\"user:pass@example.com\", (None, None))),\n    ],\n)\ndef test_git__get_netloc_and_auth(\n    args: tuple[str, str], expected: tuple[str, tuple[None, None]]\n) -> None:\n    \"\"\"\n    Test VersionControl.get_netloc_and_auth().\n    \"\"\"\n    netloc, scheme = args\n    actual = Git.get_netloc_and_auth(netloc, scheme)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"args, expected\",\n    [\n        # Test https.\n        ((\"example.com\", \"https\"), (\"example.com\", (None, None))),\n        # Test https with username and no password.\n        ((\"user@example.com\", \"https\"), (\"example.com\", (\"user\", None))),\n        # Test https with username and password.\n        ((\"user:pass@example.com\", \"https\"), (\"example.com\", (\"user\", \"pass\"))),\n        # Test https with URL-encoded reserved characters.\n        (\n            (\"user%3Aname:%23%40%5E@example.com\", \"https\"),\n            (\"example.com\", (\"user:name\", \"#@^\")),\n        ),\n        # Test ssh with username and password.\n        ((\"user:pass@example.com\", \"ssh\"), (\"user:pass@example.com\", (None, None))),\n    ],\n)\ndef test_subversion__get_netloc_and_auth(\n    args: tuple[str, str], expected: tuple[str, tuple[str | None, str | None]]\n) -> None:\n    \"\"\"\n    Test Subversion.get_netloc_and_auth().\n    \"\"\"\n    netloc, scheme = args\n    actual = Subversion.get_netloc_and_auth(netloc, scheme)\n    assert actual == expected\n\n\ndef test_git__get_url_rev__idempotent() -> None:\n    \"\"\"\n    Check that Git.get_url_rev_and_auth() is idempotent for what the code calls\n    \"stub URLs\" (i.e. URLs that don't contain \"://\").\n\n    Also check that it doesn't change self.url.\n    \"\"\"\n    url = \"git+git@git.example.com:MyProject#egg=MyProject\"\n    result1 = Git.get_url_rev_and_auth(url)\n    result2 = Git.get_url_rev_and_auth(url)\n    expected = (\"git@git.example.com:MyProject\", None, (None, None))\n    assert result1 == expected\n    assert result2 == expected\n\n\n@pytest.mark.parametrize(\n    \"url, expected\",\n    [\n        (\n            \"svn+https://svn.example.com/MyProject\",\n            (\"https://svn.example.com/MyProject\", None, (None, None)),\n        ),\n        # Test a \"+\" in the path portion.\n        (\n            \"svn+https://svn.example.com/My+Project\",\n            (\"https://svn.example.com/My+Project\", None, (None, None)),\n        ),\n        # Test percent-encoded characters in revision.\n        (\n            \"svn+https://svn.example.com/MyProject@dev%401%232\",\n            (\"https://svn.example.com/MyProject\", \"dev@1#2\", (None, None)),\n        ),\n    ],\n)\ndef test_version_control__get_url_rev_and_auth(\n    url: str, expected: tuple[str, None, tuple[None, None]]\n) -> None:\n    \"\"\"\n    Test the basic case of VersionControl.get_url_rev_and_auth().\n    \"\"\"\n    actual = VersionControl.get_url_rev_and_auth(url)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        \"https://svn.example.com/MyProject\",\n        # Test a URL containing a \"+\" (but not in the scheme).\n        \"https://svn.example.com/My+Project\",\n    ],\n)\ndef test_version_control__get_url_rev_and_auth__missing_plus(url: str) -> None:\n    \"\"\"\n    Test passing a URL to VersionControl.get_url_rev_and_auth() with a \"+\"\n    missing from the scheme.\n    \"\"\"\n    with pytest.raises(ValueError) as excinfo:\n        VersionControl.get_url_rev_and_auth(url)\n\n    assert \"malformed VCS url\" in str(excinfo.value)\n\n\n@pytest.mark.parametrize(\n    \"url\",\n    [\n        # Test a URL with revision part as empty.\n        \"git+https://github.com/MyUser/myProject.git@#egg=py_pkg\",\n    ],\n)\ndef test_version_control__get_url_rev_and_auth__no_revision(url: str) -> None:\n    \"\"\"\n    Test passing a URL to VersionControl.get_url_rev_and_auth() with\n    empty revision\n    \"\"\"\n    with pytest.raises(InstallationError) as excinfo:\n        VersionControl.get_url_rev_and_auth(url)\n\n    assert \"an empty revision (after @)\" in str(excinfo.value)\n\n\n@pytest.mark.parametrize(\"vcs_cls\", [Bazaar, Git, Mercurial, Subversion])\n@pytest.mark.parametrize(\n    \"exc_cls, msg_re\",\n    [\n        (FileNotFoundError, r\"Cannot find command '{name}'\"),\n        (PermissionError, r\"No permission to execute '{name}'\"),\n        (NotADirectoryError, \"Cannot find command '{name}' - invalid PATH\"),\n    ],\n    ids=[\"FileNotFoundError\", \"PermissionError\", \"NotADirectoryError\"],\n)\ndef test_version_control__run_command__fails(\n    vcs_cls: type[VersionControl], exc_cls: type[Exception], msg_re: str\n) -> None:\n    \"\"\"\n    Test that ``VersionControl.run_command()`` raises ``BadCommand``\n    when the command is not found or when the user have no permission\n    to execute it. The error message must contains the command name.\n    \"\"\"\n    with mock.patch(\"pip._internal.vcs.versioncontrol.call_subprocess\") as call:\n        call.side_effect = exc_cls\n        with pytest.raises(BadCommand, match=msg_re.format(name=vcs_cls.name)):\n            vcs_cls.run_command([])\n\n\n@pytest.mark.parametrize(\n    \"url, expected\",\n    [\n        # Test http.\n        (\n            \"bzr+http://bzr.myproject.org/MyProject/trunk/#egg=MyProject\",\n            \"http://bzr.myproject.org/MyProject/trunk/\",\n        ),\n        # Test https.\n        (\n            \"bzr+https://bzr.myproject.org/MyProject/trunk/#egg=MyProject\",\n            \"https://bzr.myproject.org/MyProject/trunk/\",\n        ),\n        # Test ftp.\n        (\n            \"bzr+ftp://bzr.myproject.org/MyProject/trunk/#egg=MyProject\",\n            \"ftp://bzr.myproject.org/MyProject/trunk/\",\n        ),\n        # Test sftp.\n        (\n            \"bzr+sftp://bzr.myproject.org/MyProject/trunk/#egg=MyProject\",\n            \"sftp://bzr.myproject.org/MyProject/trunk/\",\n        ),\n        # Test launchpad.\n        (\"bzr+lp:MyLaunchpadProject#egg=MyLaunchpadProject\", \"lp:MyLaunchpadProject\"),\n        # Test ssh (special handling).\n        (\n            \"bzr+ssh://bzr.myproject.org/MyProject/trunk/#egg=MyProject\",\n            \"bzr+ssh://bzr.myproject.org/MyProject/trunk/\",\n        ),\n    ],\n)\ndef test_bazaar__get_url_rev_and_auth(url: str, expected: str) -> None:\n    \"\"\"\n    Test Bazaar.get_url_rev_and_auth().\n    \"\"\"\n    actual = Bazaar.get_url_rev_and_auth(url)\n    assert actual == (expected, None, (None, None))\n\n\n@pytest.mark.parametrize(\n    \"url, expected\",\n    [\n        # Test an https URL.\n        (\n            \"svn+https://svn.example.com/MyProject#egg=MyProject\",\n            (\"https://svn.example.com/MyProject\", None, (None, None)),\n        ),\n        # Test an https URL with a username and password.\n        (\n            \"svn+https://user:pass@svn.example.com/MyProject#egg=MyProject\",\n            (\"https://svn.example.com/MyProject\", None, (\"user\", \"pass\")),\n        ),\n        # Test an ssh URL.\n        (\n            \"svn+ssh://svn.example.com/MyProject#egg=MyProject\",\n            (\"svn+ssh://svn.example.com/MyProject\", None, (None, None)),\n        ),\n        # Test an ssh URL with a username.\n        (\n            \"svn+ssh://user@svn.example.com/MyProject#egg=MyProject\",\n            (\"svn+ssh://user@svn.example.com/MyProject\", None, (None, None)),\n        ),\n    ],\n)\ndef test_subversion__get_url_rev_and_auth(\n    url: str, expected: tuple[str, None, tuple[str | None, str | None]]\n) -> None:\n    \"\"\"\n    Test Subversion.get_url_rev_and_auth().\n    \"\"\"\n    actual = Subversion.get_url_rev_and_auth(url)\n    assert actual == expected\n\n\n# The non-SVN backends all use the same make_rev_args(), so only test\n# Git as a representative.\n@pytest.mark.parametrize(\n    \"username, password, expected\",\n    [\n        (None, None, []),\n        (\"user\", None, []),\n        (\"user\", hide_value(\"pass\"), []),\n    ],\n)\ndef test_git__make_rev_args(\n    username: str | None, password: HiddenText | None, expected: CommandArgs\n) -> None:\n    \"\"\"\n    Test VersionControl.make_rev_args().\n    \"\"\"\n    actual = Git.make_rev_args(username, password)\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\n    \"username, password, expected\",\n    [\n        (None, None, []),\n        (\"user\", None, [\"--username\", \"user\"]),\n        (\n            \"user\",\n            hide_value(\"pass\"),\n            [\"--username\", \"user\", \"--password\", hide_value(\"pass\")],\n        ),\n    ],\n)\ndef test_subversion__make_rev_args(\n    username: str | None, password: HiddenText | None, expected: CommandArgs\n) -> None:\n    \"\"\"\n    Test Subversion.make_rev_args().\n    \"\"\"\n    actual = Subversion.make_rev_args(username, password)\n    assert actual == expected\n\n\ndef test_subversion__get_url_rev_options() -> None:\n    \"\"\"\n    Test Subversion.get_url_rev_options().\n    \"\"\"\n    secret_url = \"svn+https://user:pass@svn.example.com/MyProject@v1.0#egg=MyProject\"\n    hidden_url = hide_url(secret_url)\n    url, rev_options = Subversion().get_url_rev_options(hidden_url)\n    assert url == hide_url(\"https://svn.example.com/MyProject\")\n    assert rev_options.rev == \"v1.0\"\n    assert rev_options.extra_args == (\n        [\"--username\", \"user\", \"--password\", hide_value(\"pass\")]\n    )\n\n\ndef test_get_git_version() -> None:\n    git_version = Git().get_git_version()\n    assert git_version >= (1, 0, 0)\n\n\n@pytest.mark.parametrize(\n    \"version, expected\",\n    [\n        (\"git version 2.17\", (2, 17)),\n        (\"git version 2.18.1\", (2, 18)),\n        (\"git version 2.35.GIT\", (2, 35)),  # gh:12280\n        (\"oh my git version 2.37.GIT\", ()),  #  invalid version\n        (\"git version 2.GIT\", ()),  # invalid version\n    ],\n)\ndef test_get_git_version_parser(version: str, expected: tuple[int, int]) -> None:\n    with mock.patch(\"pip._internal.vcs.git.Git.run_command\", return_value=version):\n        assert Git().get_git_version() == expected\n\n\n@pytest.mark.parametrize(\n    \"use_interactive,is_atty,expected\",\n    [\n        (None, False, False),\n        (None, True, True),\n        (False, False, False),\n        (False, True, False),\n        (True, False, True),\n        (True, True, True),\n    ],\n)\n@mock.patch(\"sys.stdin.isatty\")\ndef test_subversion__init_use_interactive(\n    mock_isatty: mock.Mock, use_interactive: bool, is_atty: bool, expected: bool\n) -> None:\n    \"\"\"\n    Test Subversion.__init__() with mocked sys.stdin.isatty() output.\n    \"\"\"\n    mock_isatty.return_value = is_atty\n    svn = Subversion(use_interactive=use_interactive)\n    assert svn.use_interactive == expected\n\n\n@need_svn\ndef test_subversion__call_vcs_version() -> None:\n    \"\"\"\n    Test Subversion.call_vcs_version() against local ``svn``.\n    \"\"\"\n    version = Subversion().call_vcs_version()\n    # All Subversion releases since 1.0.0 have used three parts.\n    assert len(version) == 3\n    for part in version:\n        assert isinstance(part, int)\n    assert version[0] >= 1\n\n\n@pytest.mark.parametrize(\n    \"svn_output, expected_version\",\n    [\n        (\n            \"svn, version 1.10.3 (r1842928)\\n\"\n            \"   compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0\",\n            (1, 10, 3),\n        ),\n        (\n            \"svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)\\n\"\n            \"   compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2\",\n            (1, 12, 0),\n        ),\n        (\"svn, version 1.9.7 (r1800392)\", (1, 9, 7)),\n        (\"svn, version 1.9.7a1 (r1800392)\", ()),\n        (\"svn, version 1.9 (r1800392)\", (1, 9)),\n        (\"svn, version .9.7 (r1800392)\", ()),\n        (\"svn version 1.9.7 (r1800392)\", ()),\n        (\"svn 1.9.7\", ()),\n        (\"svn, version . .\", ()),\n        (\"\", ()),\n    ],\n)\n@mock.patch(\"pip._internal.vcs.subversion.Subversion.run_command\")\ndef test_subversion__call_vcs_version_patched(\n    mock_run_command: mock.Mock, svn_output: str, expected_version: tuple[int, ...]\n) -> None:\n    \"\"\"\n    Test Subversion.call_vcs_version() against patched output.\n    \"\"\"\n    mock_run_command.return_value = svn_output\n    version = Subversion().call_vcs_version()\n    assert version == expected_version\n\n\n@mock.patch(\"pip._internal.vcs.subversion.Subversion.run_command\")\ndef test_subversion__call_vcs_version_svn_not_installed(\n    mock_run_command: mock.Mock,\n) -> None:\n    \"\"\"\n    Test Subversion.call_vcs_version() when svn is not installed.\n    \"\"\"\n    mock_run_command.side_effect = BadCommand\n    with pytest.raises(BadCommand):\n        Subversion().call_vcs_version()\n\n\n@pytest.mark.parametrize(\n    \"version\",\n    [\n        (),\n        (1,),\n        (1, 8),\n        (1, 8, 0),\n    ],\n)\ndef test_subversion__get_vcs_version_cached(version: tuple[int, ...]) -> None:\n    \"\"\"\n    Test Subversion.get_vcs_version() with previously cached result.\n    \"\"\"\n    svn = Subversion()\n    svn._vcs_version = version\n    assert svn.get_vcs_version() == version\n\n\n@pytest.mark.parametrize(\n    \"vcs_version\",\n    [\n        (),\n        (1, 7),\n        (1, 8, 0),\n    ],\n)\n@mock.patch(\"pip._internal.vcs.subversion.Subversion.call_vcs_version\")\ndef test_subversion__get_vcs_version_call_vcs(\n    mock_call_vcs: mock.Mock, vcs_version: tuple[int, ...]\n) -> None:\n    \"\"\"\n    Test Subversion.get_vcs_version() with mocked output from\n    call_vcs_version().\n    \"\"\"\n    mock_call_vcs.return_value = vcs_version\n    svn = Subversion()\n    assert svn.get_vcs_version() == vcs_version\n\n    # Check that the version information is cached.\n    assert svn._vcs_version == vcs_version\n\n\n@pytest.mark.parametrize(\n    \"use_interactive,vcs_version,expected_options\",\n    [\n        (False, (), [\"--non-interactive\"]),\n        (False, (1, 7, 0), [\"--non-interactive\"]),\n        (False, (1, 8, 0), [\"--non-interactive\"]),\n        (True, (), []),\n        (True, (1, 7, 0), []),\n        (True, (1, 8, 0), [\"--force-interactive\"]),\n    ],\n)\ndef test_subversion__get_remote_call_options(\n    use_interactive: bool, vcs_version: tuple[int, ...], expected_options: list[str]\n) -> None:\n    \"\"\"\n    Test Subversion.get_remote_call_options().\n    \"\"\"\n    svn = Subversion(use_interactive=use_interactive)\n    svn._vcs_version = vcs_version\n    assert svn.get_remote_call_options() == expected_options\n\n\nclass _TestVcsArgs:\n    @pytest.fixture(autouse=True)\n    def setup_base(\n        self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path\n    ) -> None:\n        self.dest = os.fspath(tmp_path / \"dest\")\n        self.call_subprocess_mock = mock.MagicMock()\n        monkeypatch.setattr(\n            \"pip._internal.vcs.versioncontrol.call_subprocess\",\n            self.call_subprocess_mock,\n        )\n\n    def assert_call_args(self, args: CommandArgs) -> None:\n        assert self.call_subprocess_mock.call_args[0][0] == args\n\n\nclass TestBazaarArgs(_TestVcsArgs):\n    def setup_method(self) -> None:\n        # Test Data.\n        self.url = \"bzr+http://username:password@bzr.example.com/\"\n        # use_interactive is set to False to test that remote call options are\n        # properly added.\n        self.svn = Bazaar()\n        self.rev_options = RevOptions(Bazaar)\n\n    def test_fetch_new(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=1)\n        self.assert_call_args(\n            [\n                \"bzr\",\n                \"checkout\",\n                \"--lightweight\",\n                hide_url(\"bzr+http://username:password@bzr.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new_quiet(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=0)\n        self.assert_call_args(\n            [\n                \"bzr\",\n                \"checkout\",\n                \"--lightweight\",\n                \"--quiet\",\n                hide_url(\"bzr+http://username:password@bzr.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new_very_verbose(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=2)\n        self.assert_call_args(\n            [\n                \"bzr\",\n                \"checkout\",\n                \"--lightweight\",\n                \"-vv\",\n                hide_url(\"bzr+http://username:password@bzr.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_update(self) -> None:\n        self.svn.update(self.dest, hide_url(self.url), self.rev_options, verbosity=1)\n        self.assert_call_args(\n            [\n                \"bzr\",\n                \"update\",\n            ]\n        )\n\n    def test_update_quiet(self) -> None:\n        self.svn.update(self.dest, hide_url(self.url), self.rev_options, verbosity=0)\n        self.assert_call_args(\n            [\n                \"bzr\",\n                \"update\",\n                \"-q\",\n            ]\n        )\n\n\nclass TestGitArgs(_TestVcsArgs):\n    def setup_method(self) -> None:\n        # Test Data.\n        self.url = \"git+http://username:password@git.example.com/\"\n        self.svn = Git()\n        self.rev_options = RevOptions(Git)\n\n    def test_fetch_new(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(2, 17)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.fetch_new(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=1\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"clone\",\n            \"--filter=blob:none\",\n            hide_url(\"git+http://username:password@git.example.com/\"),\n            self.dest,\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=1)\n\n    def test_fetch_new_legacy(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 0)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.fetch_new(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=1\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"clone\",\n            hide_url(\"git+http://username:password@git.example.com/\"),\n            self.dest,\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=1)\n\n    def test_fetch_new_legacy_quiet(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 0)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.fetch_new(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=0\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"clone\",\n            \"--quiet\",\n            hide_url(\"git+http://username:password@git.example.com/\"),\n            self.dest,\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=0)\n\n    def test_fetch_new_quiet(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(2, 17)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.fetch_new(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=0\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"clone\",\n            \"--filter=blob:none\",\n            \"--quiet\",\n            hide_url(\"git+http://username:password@git.example.com/\"),\n            self.dest,\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=0)\n\n    def test_switch(self) -> None:\n        with mock.patch.object(self.svn, \"update_submodules\") as update_submodules_mock:\n            self.svn.switch(\n                self.dest, hide_url(self.url), self.rev_options, verbosity=1\n            )\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"git\",\n            \"checkout\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=1)\n\n    def test_switch_quiet(self) -> None:\n        with mock.patch.object(self.svn, \"update_submodules\") as update_submodules_mock:\n            self.svn.switch(\n                self.dest, hide_url(self.url), self.rev_options, verbosity=0\n            )\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"git\",\n            \"checkout\",\n            \"-q\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=0)\n\n    def test_update(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 9)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.update(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=1\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"fetch\",\n            \"--tags\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[2][0][0] == [\n            \"git\",\n            \"reset\",\n            \"--hard\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=1)\n\n    def test_update_legacy(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 8)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.update(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=1\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"fetch\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[2][0][0] == [\n            \"git\",\n            \"reset\",\n            \"--hard\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=1)\n\n    def test_update_legacy_quiet(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 9)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.update(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=0\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"fetch\",\n            \"--tags\",\n            \"-q\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[2][0][0] == [\n            \"git\",\n            \"reset\",\n            \"--hard\",\n            \"-q\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=0)\n\n    def test_update_quiet(self) -> None:\n        with mock.patch.object(self.svn, \"get_git_version\", return_value=(1, 8)):\n            with mock.patch.object(\n                self.svn, \"update_submodules\"\n            ) as update_submodules_mock:\n                self.svn.update(\n                    self.dest, hide_url(self.url), self.rev_options, verbosity=0\n                )\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"git\",\n            \"fetch\",\n            \"-q\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[2][0][0] == [\n            \"git\",\n            \"reset\",\n            \"--hard\",\n            \"-q\",\n            \"HEAD\",\n        ]\n\n        update_submodules_mock.assert_called_with(self.dest, verbosity=0)\n\n\nclass TestMercurialArgs(_TestVcsArgs):\n    def setup_method(self) -> None:\n        # Test Data.\n        self.url = \"hg+http://username:password@hg.example.com/\"\n        self.svn = Mercurial()\n        self.rev_options = RevOptions(Mercurial)\n\n    def test_fetch_new(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=1)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"clone\",\n            \"--noupdate\",\n            hide_url(\"hg+http://username:password@hg.example.com/\"),\n            self.dest,\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n        ]\n\n    def test_fetch_new_quiet(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=0)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"clone\",\n            \"--noupdate\",\n            \"--quiet\",\n            hide_url(\"hg+http://username:password@hg.example.com/\"),\n            self.dest,\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n            \"--quiet\",\n        ]\n\n    def test_fetch_new_very_verbose(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=2)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"clone\",\n            \"--noupdate\",\n            \"--verbose\",\n            hide_url(\"hg+http://username:password@hg.example.com/\"),\n            self.dest,\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n            \"--verbose\",\n        ]\n\n    def test_fetch_new_debug(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=3)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"clone\",\n            \"--noupdate\",\n            \"--verbose\",\n            \"--debug\",\n            hide_url(\"hg+http://username:password@hg.example.com/\"),\n            self.dest,\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n            \"--verbose\",\n            \"--debug\",\n        ]\n\n    def test_update(self) -> None:\n        self.svn.update(self.dest, hide_url(self.url), self.rev_options, verbosity=1)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"pull\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n        ]\n\n    def test_update_quiet(self) -> None:\n        self.svn.update(self.dest, hide_url(self.url), self.rev_options, verbosity=0)\n\n        assert self.call_subprocess_mock.call_args_list[0][0][0] == [\n            \"hg\",\n            \"pull\",\n            \"-q\",\n        ]\n\n        assert self.call_subprocess_mock.call_args_list[1][0][0] == [\n            \"hg\",\n            \"update\",\n            \"-q\",\n        ]\n\n\nclass TestSubversionArgs(_TestVcsArgs):\n    def setup_method(self) -> None:\n        # Test Data.\n        self.url = \"svn+http://username:password@svn.example.com/\"\n        # use_interactive is set to False to test that remote call options are\n        # properly added.\n        self.svn = Subversion(use_interactive=False)\n        self.rev_options = RevOptions(Subversion)\n\n    def test_obtain(self) -> None:\n        self.svn.obtain(self.dest, hide_url(self.url), verbosity=1)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--non-interactive\",\n                \"--username\",\n                \"username\",\n                \"--password\",\n                hide_value(\"password\"),\n                hide_url(\"http://svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_obtain_quiet(self) -> None:\n        self.svn.obtain(self.dest, hide_url(self.url), verbosity=0)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--quiet\",\n                \"--non-interactive\",\n                \"--username\",\n                \"username\",\n                \"--password\",\n                hide_value(\"password\"),\n                hide_url(\"http://svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=1)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--non-interactive\",\n                hide_url(\"svn+http://username:password@svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new_quiet(self) -> None:\n        self.svn.fetch_new(self.dest, hide_url(self.url), self.rev_options, verbosity=0)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--quiet\",\n                \"--non-interactive\",\n                hide_url(\"svn+http://username:password@svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new_revision(self) -> None:\n        rev_options = RevOptions(Subversion, \"123\")\n        self.svn.fetch_new(self.dest, hide_url(self.url), rev_options, verbosity=1)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--non-interactive\",\n                \"-r\",\n                \"123\",\n                hide_url(\"svn+http://username:password@svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_fetch_new_revision_quiet(self) -> None:\n        rev_options = RevOptions(Subversion, \"123\")\n        self.svn.fetch_new(self.dest, hide_url(self.url), rev_options, verbosity=0)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"checkout\",\n                \"--quiet\",\n                \"--non-interactive\",\n                \"-r\",\n                \"123\",\n                hide_url(\"svn+http://username:password@svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_switch(self) -> None:\n        self.svn.switch(self.dest, hide_url(self.url), self.rev_options)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"switch\",\n                \"--non-interactive\",\n                hide_url(\"svn+http://username:password@svn.example.com/\"),\n                self.dest,\n            ]\n        )\n\n    def test_update(self) -> None:\n        self.svn.update(self.dest, hide_url(self.url), self.rev_options)\n        self.assert_call_args(\n            [\n                \"svn\",\n                \"update\",\n                \"--non-interactive\",\n                self.dest,\n            ]\n        )\n"
  },
  {
    "path": "tests/unit/test_vcs_mercurial.py",
    "content": "\"\"\"\nContains functional tests of the Mercurial class.\n\"\"\"\n\nimport configparser\nimport os\nfrom pathlib import Path\n\nfrom pip._internal.utils.misc import hide_url\nfrom pip._internal.vcs.mercurial import Mercurial\n\nfrom tests.lib import need_mercurial\n\n\n@need_mercurial\ndef test_mercurial_switch_updates_config_file_when_found(tmpdir: Path) -> None:\n    hg = Mercurial()\n    options = hg.make_rev_options()\n    hg_dir = os.path.join(tmpdir, \".hg\")\n    os.mkdir(hg_dir)\n\n    config = configparser.RawConfigParser()\n    config.add_section(\"paths\")\n    config.set(\"paths\", \"default\", \"old_url\")\n\n    hgrc_path = os.path.join(hg_dir, \"hgrc\")\n    with open(hgrc_path, \"w\") as f:\n        config.write(f)\n    hg.switch(os.fspath(tmpdir), hide_url(\"new_url\"), options)\n\n    config.read(hgrc_path)\n\n    default_path = config.get(\"paths\", \"default\")\n    assert default_path == \"new_url\"\n"
  },
  {
    "path": "tests/unit/test_wheel.py",
    "content": "\"\"\"Tests for wheel binary packages and .dist-info.\"\"\"\n\nfrom __future__ import annotations\n\nimport csv\nimport os\nimport pathlib\nimport sys\nimport textwrap\nfrom email import message_from_string\nfrom pathlib import Path\nfrom typing import cast\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.locations import get_scheme\nfrom pip._internal.models.direct_url import (\n    DIRECT_URL_METADATA_NAME,\n    ArchiveInfo,\n    DirectUrl,\n)\nfrom pip._internal.models.scheme import Scheme\nfrom pip._internal.operations.install import wheel\nfrom pip._internal.operations.install.wheel import (\n    InstalledCSVRow,\n    RecordPath,\n    get_console_script_specs,\n)\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.misc import hash_file\nfrom pip._internal.utils.unpacking import unpack_file\n\nfrom tests.lib import DATA_DIR, TestData\nfrom tests.lib.wheel import make_wheel\n\n\n@pytest.mark.parametrize(\n    \"console_scripts\",\n    [\n        \"pip = pip._internal.main:pip\",\n        \"pip:pip = pip._internal.main:pip\",\n        \"進入點 = 套件.模組:函式\",\n    ],\n)\ndef test_get_entrypoints(tmp_path: pathlib.Path, console_scripts: str) -> None:\n    entry_points_text = f\"\"\"\n        [console_scripts]\n        {console_scripts}\n        [section]\n        common:one = module:func\n        common:two = module:other_func\n    \"\"\"\n\n    distribution = make_wheel(\n        \"simple\",\n        \"0.1.0\",\n        extra_metadata_files={\n            \"entry_points.txt\": entry_points_text,\n        },\n    ).as_distribution(\"simple\")\n\n    entry_point, entry_point_value = console_scripts.split(\" = \")\n    assert wheel.get_entrypoints(distribution) == ({entry_point: entry_point_value}, {})\n\n\ndef test_get_entrypoints_no_entrypoints(tmp_path: pathlib.Path) -> None:\n    distribution = make_wheel(\"simple\", \"0.1.0\").as_distribution(\"simple\")\n\n    console, gui = wheel.get_entrypoints(distribution)\n    assert console == {}\n    assert gui == {}\n\n\n@pytest.mark.parametrize(\n    \"outrows, expected\",\n    [\n        (\n            [\n                (\"\", \"\", \"a\"),\n                (\"\", \"\", \"\"),\n            ],\n            [\n                (\"\", \"\", \"\"),\n                (\"\", \"\", \"a\"),\n            ],\n        ),\n        (\n            [\n                # Include an int to check avoiding the following error:\n                # > TypeError: '<' not supported between instances of 'str' and 'int'\n                (\"\", \"\", 1),\n                (\"\", \"\", \"\"),\n            ],\n            [\n                (\"\", \"\", \"\"),\n                (\"\", \"\", \"1\"),\n            ],\n        ),\n        (\n            [\n                # Test the normalization correctly encode everything for csv.writer().\n                (\"😉\", \"\", 1),\n                (\"\", \"\", \"\"),\n            ],\n            [\n                (\"\", \"\", \"\"),\n                (\"😉\", \"\", \"1\"),\n            ],\n        ),\n    ],\n)\ndef test_normalized_outrows(\n    outrows: list[tuple[RecordPath, str, str]], expected: list[tuple[str, str, str]]\n) -> None:\n    actual = wheel._normalized_outrows(outrows)\n    assert actual == expected\n\n\ndef call_get_csv_rows_for_installed(tmpdir: Path, text: str) -> list[InstalledCSVRow]:\n    path = tmpdir.joinpath(\"temp.txt\")\n    path.write_text(text)\n\n    # Test that an installed file appearing in RECORD has its filename\n    # updated in the new RECORD file.\n    installed = cast(dict[RecordPath, RecordPath], {\"a\": \"z\"})\n    lib_dir = \"/lib/dir\"\n\n    with open(path, **wheel.csv_io_kwargs(\"r\")) as f:\n        record_rows = list(csv.reader(f))\n    outrows = wheel.get_csv_rows_for_installed(\n        record_rows,\n        installed=installed,\n        changed=set(),\n        generated=[],\n        lib_dir=lib_dir,\n    )\n    return outrows\n\n\ndef test_get_csv_rows_for_installed(\n    tmpdir: Path, caplog: pytest.LogCaptureFixture\n) -> None:\n    text = textwrap.dedent(\n        \"\"\"\\\n    a,b,c\n    d,e,f\n    \"\"\"\n    )\n    outrows = call_get_csv_rows_for_installed(tmpdir, text)\n\n    expected = [\n        (\"z\", \"b\", \"c\"),\n        (\"d\", \"e\", \"f\"),\n    ]\n    assert outrows == expected\n    # Check there were no warnings.\n    assert len(caplog.records) == 0\n\n\ndef test_get_csv_rows_for_installed__long_lines(\n    tmpdir: Path, caplog: pytest.LogCaptureFixture\n) -> None:\n    text = textwrap.dedent(\n        \"\"\"\\\n    a,b,c,d\n    e,f,g\n    h,i,j,k\n    \"\"\"\n    )\n    outrows = call_get_csv_rows_for_installed(tmpdir, text)\n    assert outrows == [\n        (\"z\", \"b\", \"c\"),\n        (\"e\", \"f\", \"g\"),\n        (\"h\", \"i\", \"j\"),\n    ]\n\n    messages = [rec.message for rec in caplog.records]\n    assert messages == [\n        \"RECORD line has more than three elements: ['a', 'b', 'c', 'd']\",\n        \"RECORD line has more than three elements: ['h', 'i', 'j', 'k']\",\n    ]\n\n\n@pytest.mark.parametrize(\n    \"text,expected\",\n    [\n        (\"Root-Is-Purelib: true\", True),\n        (\"Root-Is-Purelib: false\", False),\n        (\"Root-Is-Purelib: hello\", False),\n        (\"\", False),\n        (\"root-is-purelib: true\", True),\n        (\"root-is-purelib: True\", True),\n    ],\n)\ndef test_wheel_root_is_purelib(text: str, expected: bool) -> None:\n    assert wheel.wheel_root_is_purelib(message_from_string(text)) == expected\n\n\ndef test_dist_from_broken_wheel_fails(data: TestData) -> None:\n    from pip._internal.exceptions import InvalidWheel\n    from pip._internal.metadata import FilesystemWheel, get_wheel_distribution\n\n    package = data.packages.joinpath(\"corruptwheel-1.0-py2.py3-none-any.whl\")\n    with pytest.raises(InvalidWheel):\n        get_wheel_distribution(\n            FilesystemWheel(os.fspath(package)), canonicalize_name(\"brokenwheel\")\n        )\n\n\nclass TestWheelFile:\n    def test_unpack_wheel_no_flatten(self, tmpdir: Path) -> None:\n        filepath = os.path.join(DATA_DIR, \"packages\", \"meta-1.0-py2.py3-none-any.whl\")\n        unpack_file(filepath, os.fspath(tmpdir))\n        assert os.path.isdir(os.path.join(tmpdir, \"meta-1.0.dist-info\"))\n\n\nclass TestInstallUnpackedWheel:\n    \"\"\"\n    Tests for moving files from wheel src to scheme paths\n    \"\"\"\n\n    def prep(self, data: TestData, tmp_path: Path) -> None:\n        # Since Path implements __add__, os.path.join returns a Path object.\n        # Passing Path objects to interfaces expecting str (like\n        # `compileall.compile_file`) can cause failures, so we normalize it\n        # to a string here.\n        tmpdir = str(tmp_path)\n        self.name = \"sample\"\n        self.wheelpath = make_wheel(\n            \"sample\",\n            \"1.2.0\",\n            metadata_body=textwrap.dedent(\n                \"\"\"\n                A sample Python project\n                =======================\n\n                ...\n                \"\"\"\n            ),\n            metadata_updates={\n                \"Requires-Dist\": [\"peppercorn\"],\n            },\n            extra_files={\n                \"sample/__init__.py\": textwrap.dedent(\n                    '''\n                    __version__ = '1.2.0'\n\n                    def main():\n                        \"\"\"Entry point for the application script\"\"\"\n                        print(\"Call your main application code here\")\n                    '''\n                ),\n                \"sample/package_data.dat\": \"some data\",\n            },\n            extra_metadata_files={\n                \"DESCRIPTION.rst\": textwrap.dedent(\n                    \"\"\"\n                    A sample Python project\n                    =======================\n\n                    ...\n                    \"\"\"\n                ),\n                \"top_level.txt\": \"sample\\n\",\n                \"empty_dir/empty_dir/\": \"\",\n            },\n            extra_data_files={\n                \"data/my_data/data_file\": \"some data\",\n            },\n            entry_points={\n                \"console_scripts\": [\"sample = sample:main\"],\n                \"gui_scripts\": [\"sample2 = sample:main\"],\n            },\n        ).save_to_dir(tmpdir)\n        self.req = Requirement(\"sample\")\n        self.src = os.path.join(tmpdir, \"src\")\n        self.dest = os.path.join(tmpdir, \"dest\")\n        self.scheme = Scheme(\n            purelib=os.path.join(self.dest, \"lib\"),\n            platlib=os.path.join(self.dest, \"lib\"),\n            headers=os.path.join(self.dest, \"headers\"),\n            scripts=os.path.join(self.dest, \"bin\"),\n            data=os.path.join(self.dest, \"data\"),\n        )\n        self.src_dist_info = os.path.join(self.src, \"sample-1.2.0.dist-info\")\n        self.dest_dist_info = os.path.join(\n            self.scheme.purelib, \"sample-1.2.0.dist-info\"\n        )\n\n    def assert_permission(self, path: str, mode: int) -> None:\n        target_mode = os.stat(path).st_mode & 0o777\n        assert (target_mode & mode) == mode, oct(target_mode)\n\n    def assert_installed(self, expected_permission: int) -> None:\n        # lib\n        assert os.path.isdir(os.path.join(self.scheme.purelib, \"sample\"))\n        # dist-info\n        metadata = os.path.join(self.dest_dist_info, \"METADATA\")\n        self.assert_permission(metadata, expected_permission)\n        record = os.path.join(self.dest_dist_info, \"RECORD\")\n        self.assert_permission(record, expected_permission)\n        # data files\n        data_file = os.path.join(self.scheme.data, \"my_data\", \"data_file\")\n        assert os.path.isfile(data_file)\n        # package data\n        pkg_data = os.path.join(self.scheme.purelib, \"sample\", \"package_data.dat\")\n        assert os.path.isfile(pkg_data)\n\n    def test_std_install(self, data: TestData, tmpdir: Path) -> None:\n        self.prep(data, tmpdir)\n        wheel.install_wheel(\n            self.name,\n            self.wheelpath,\n            scheme=self.scheme,\n            req_description=str(self.req),\n        )\n        self.assert_installed(0o644)\n\n    @pytest.mark.parametrize(\"user_mask, expected_permission\", [(0o27, 0o640)])\n    def test_std_install_with_custom_umask(\n        self, data: TestData, tmpdir: Path, user_mask: int, expected_permission: int\n    ) -> None:\n        \"\"\"Test that the files created after install honor the permissions\n        set when the user sets a custom umask\"\"\"\n\n        prev_umask = os.umask(user_mask)\n        try:\n            self.prep(data, tmpdir)\n            wheel.install_wheel(\n                self.name,\n                self.wheelpath,\n                scheme=self.scheme,\n                req_description=str(self.req),\n            )\n            self.assert_installed(expected_permission)\n        finally:\n            os.umask(prev_umask)\n\n    def test_std_install_requested(self, data: TestData, tmpdir: Path) -> None:\n        self.prep(data, tmpdir)\n        wheel.install_wheel(\n            self.name,\n            self.wheelpath,\n            scheme=self.scheme,\n            req_description=str(self.req),\n            requested=True,\n        )\n        self.assert_installed(0o644)\n        requested_path = os.path.join(self.dest_dist_info, \"REQUESTED\")\n        assert os.path.isfile(requested_path)\n\n    def test_std_install_with_direct_url(self, data: TestData, tmpdir: Path) -> None:\n        \"\"\"Test that install_wheel creates direct_url.json metadata when\n        provided with a direct_url argument. Also test that the RECORDS\n        file contains an entry for direct_url.json in that case.\n        Note direct_url.url is intentionally different from wheelpath,\n        because wheelpath is typically the result of a local build.\n        \"\"\"\n        self.prep(data, tmpdir)\n        direct_url = DirectUrl(\n            url=\"file:///home/user/archive.tgz\",\n            info=ArchiveInfo(),\n        )\n        wheel.install_wheel(\n            self.name,\n            self.wheelpath,\n            scheme=self.scheme,\n            req_description=str(self.req),\n            direct_url=direct_url,\n        )\n        direct_url_path = os.path.join(self.dest_dist_info, DIRECT_URL_METADATA_NAME)\n        self.assert_permission(direct_url_path, 0o644)\n        with open(direct_url_path, \"rb\") as f1:\n            expected_direct_url_json = direct_url.to_json()\n            direct_url_json = f1.read().decode(\"utf-8\")\n            assert direct_url_json == expected_direct_url_json\n        # check that the direc_url file is part of RECORDS\n        with open(os.path.join(self.dest_dist_info, \"RECORD\")) as f2:\n            assert DIRECT_URL_METADATA_NAME in f2.read()\n\n    def test_install_prefix(self, data: TestData, tmpdir: Path) -> None:\n        prefix = os.path.join(os.path.sep, \"some\", \"path\")\n        self.prep(data, tmpdir)\n        scheme = get_scheme(\n            self.name,\n            user=False,\n            home=None,\n            root=str(tmpdir),  # Casting needed for CPython 3.10+. See GH-10358.\n            isolated=False,\n            prefix=prefix,\n        )\n        wheel.install_wheel(\n            self.name,\n            self.wheelpath,\n            scheme=scheme,\n            req_description=str(self.req),\n        )\n\n        bin_dir = \"Scripts\" if WINDOWS else \"bin\"\n        assert os.path.exists(os.path.join(tmpdir, \"some\", \"path\", bin_dir))\n        assert os.path.exists(os.path.join(tmpdir, \"some\", \"path\", \"my_data\"))\n\n    def test_dist_info_contains_empty_dir(self, data: TestData, tmpdir: Path) -> None:\n        \"\"\"\n        Test that empty dirs are not installed\n        \"\"\"\n        # e.g. https://github.com/pypa/pip/issues/1632#issuecomment-38027275\n        self.prep(data, tmpdir)\n        wheel.install_wheel(\n            self.name,\n            self.wheelpath,\n            scheme=self.scheme,\n            req_description=str(self.req),\n        )\n        self.assert_installed(0o644)\n        assert not os.path.isdir(os.path.join(self.dest_dist_info, \"empty_dir\"))\n\n    @pytest.mark.parametrize(\"path\", [\"/tmp/example\", \"../example\", \"./../example\"])\n    def test_wheel_install_rejects_bad_paths(\n        self, data: TestData, tmpdir: Path, path: str\n    ) -> None:\n        self.prep(data, tmpdir)\n        wheel_path = make_wheel(\n            \"simple\", \"0.1.0\", extra_files={path: \"example contents\\n\"}\n        ).save_to_dir(tmpdir)\n        with pytest.raises(InstallationError) as e:\n            wheel.install_wheel(\n                \"simple\",\n                str(wheel_path),\n                scheme=self.scheme,\n                req_description=\"simple\",\n            )\n\n        exc_text = str(e.value)\n        assert os.path.basename(wheel_path) in exc_text\n        assert \"example\" in exc_text\n\n    @pytest.mark.xfail(strict=True)\n    @pytest.mark.parametrize(\"entrypoint\", [\"hello = hello\", \"hello = hello:\"])\n    @pytest.mark.parametrize(\"entrypoint_type\", [\"console_scripts\", \"gui_scripts\"])\n    def test_invalid_entrypoints_fail(\n        self, data: TestData, tmpdir: Path, entrypoint: str, entrypoint_type: str\n    ) -> None:\n        self.prep(data, tmpdir)\n        wheel_path = make_wheel(\n            \"simple\", \"0.1.0\", entry_points={entrypoint_type: [entrypoint]}\n        ).save_to_dir(tmpdir)\n        with pytest.raises(InstallationError) as e:\n            wheel.install_wheel(\n                \"simple\",\n                str(wheel_path),\n                scheme=self.scheme,\n                req_description=\"simple\",\n            )\n\n        exc_text = str(e.value)\n        assert os.path.basename(wheel_path) in exc_text\n        assert entrypoint in exc_text\n\n\nclass TestMessageAboutScriptsNotOnPATH:\n    tilde_warning_msg = (\n        \"NOTE: The current PATH contains path(s) starting with `~`, \"\n        \"which may not be expanded by all applications.\"\n    )\n\n    def _template(self, paths: list[str], scripts: list[str]) -> str | None:\n        with patch.dict(\"os.environ\", {\"PATH\": os.pathsep.join(paths)}):\n            return wheel.message_about_scripts_not_on_PATH(scripts)\n\n    def test_no_script(self) -> None:\n        retval = self._template(paths=[\"/a/b\", \"/c/d/bin\"], scripts=[])\n        assert retval is None\n\n    def test_single_script__single_dir_not_on_PATH(self) -> None:\n        retval = self._template(paths=[\"/a/b\", \"/c/d/bin\"], scripts=[\"/c/d/foo\"])\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"foo is installed in '/c/d'\" in retval\n        assert self.tilde_warning_msg not in retval\n\n    def test_two_script__single_dir_not_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"], scripts=[\"/c/d/foo\", \"/c/d/baz\"]\n        )\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"baz and foo are installed in '/c/d'\" in retval\n        assert self.tilde_warning_msg not in retval\n\n    def test_multi_script__multi_dir_not_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"],\n            scripts=[\"/c/d/foo\", \"/c/d/bar\", \"/c/d/baz\", \"/a/b/c/spam\"],\n        )\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"bar, baz and foo are installed in '/c/d'\" in retval\n        assert \"spam is installed in '/a/b/c'\" in retval\n        assert self.tilde_warning_msg not in retval\n\n    def test_multi_script_all__multi_dir_not_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"],\n            scripts=[\"/c/d/foo\", \"/c/d/bar\", \"/c/d/baz\", \"/a/b/c/spam\", \"/a/b/c/eggs\"],\n        )\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"bar, baz and foo are installed in '/c/d'\" in retval\n        assert \"eggs and spam are installed in '/a/b/c'\" in retval\n        assert self.tilde_warning_msg not in retval\n\n    def test_two_script__single_dir_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"], scripts=[\"/a/b/foo\", \"/a/b/baz\"]\n        )\n        assert retval is None\n\n    def test_multi_script__multi_dir_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"],\n            scripts=[\"/a/b/foo\", \"/a/b/bar\", \"/a/b/baz\", \"/c/d/bin/spam\"],\n        )\n        assert retval is None\n\n    def test_multi_script__single_dir_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\"], scripts=[\"/a/b/foo\", \"/a/b/bar\", \"/a/b/baz\"]\n        )\n        assert retval is None\n\n    def test_PATH_check_path_normalization(self) -> None:\n        retval = self._template(\n            paths=[\"/a/./b/../b//c/\", \"/d/e/bin\"], scripts=[\"/a/b/c/foo\"]\n        )\n        assert retval is None\n\n    def test_single_script__single_dir_on_PATH(self) -> None:\n        retval = self._template(paths=[\"/a/b\", \"/c/d/bin\"], scripts=[\"/a/b/foo\"])\n        assert retval is None\n\n    def test_PATH_check_case_insensitive_on_windows(self) -> None:\n        retval = self._template(paths=[\"C:\\\\A\\\\b\"], scripts=[\"c:\\\\a\\\\b\\\\c\", \"C:/A/b/d\"])\n        if WINDOWS:\n            assert retval is None\n        else:\n            assert retval is not None\n            assert self.tilde_warning_msg not in retval\n\n    def test_trailing_ossep_removal(self) -> None:\n        retval = self._template(\n            paths=[os.path.join(\"a\", \"b\", \"\")], scripts=[os.path.join(\"a\", \"b\", \"c\")]\n        )\n        assert retval is None\n\n    def test_missing_PATH_env_treated_as_empty_PATH_env(\n        self, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        scripts = [\"a/b/foo\"]\n\n        monkeypatch.delenv(\"PATH\")\n        retval_missing = wheel.message_about_scripts_not_on_PATH(scripts)\n\n        monkeypatch.setenv(\"PATH\", \"\")\n        retval_empty = wheel.message_about_scripts_not_on_PATH(scripts)\n\n        assert retval_missing == retval_empty\n\n    def test_no_script_tilde_in_path(self) -> None:\n        retval = self._template(paths=[\"/a/b\", \"/c/d/bin\", \"~/e\", \"/f/g~g\"], scripts=[])\n        assert retval is None\n\n    def test_multi_script_all_tilde__multi_dir_not_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/a/b\", \"/c/d/bin\", \"~e/f\"],\n            scripts=[\n                \"/c/d/foo\",\n                \"/c/d/bar\",\n                \"/c/d/baz\",\n                \"/a/b/c/spam\",\n                \"/a/b/c/eggs\",\n                \"/e/f/tilde\",\n            ],\n        )\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"bar, baz and foo are installed in '/c/d'\" in retval\n        assert \"eggs and spam are installed in '/a/b/c'\" in retval\n        assert \"tilde is installed in '/e/f'\" in retval\n        assert self.tilde_warning_msg in retval\n\n    def test_multi_script_all_tilde_not_at_start__multi_dir_not_on_PATH(self) -> None:\n        retval = self._template(\n            paths=[\"/e/f~f\", \"/c/d/bin\"],\n            scripts=[\n                \"/c/d/foo\",\n                \"/c/d/bar\",\n                \"/c/d/baz\",\n                \"/e/f~f/c/spam\",\n                \"/e/f~f/c/eggs\",\n            ],\n        )\n        assert retval is not None\n        assert \"--no-warn-script-location\" in retval\n        assert \"bar, baz and foo are installed in '/c/d'\" in retval\n        assert \"eggs and spam are installed in '/e/f~f/c'\" in retval\n        assert self.tilde_warning_msg not in retval\n\n\nclass TestWheelHashCalculators:\n    def prep(self, tmpdir: Path) -> None:\n        self.test_file = tmpdir.joinpath(\"hash.file\")\n        # Want this big enough to trigger the internal read loops.\n        self.test_file_len = 2 * 1024 * 1024\n        with open(str(self.test_file), \"w\") as fp:\n            fp.truncate(self.test_file_len)\n        self.test_file_hash = (\n            \"5647f05ec18958947d32874eeb788fa396a05d0bab7c1b71f112ceb7e9b31eee\"\n        )\n        self.test_file_hash_encoded = (\n            \"sha256=VkfwXsGJWJR9ModO63iPo5agXQurfBtx8RLOt-mzHu4\"\n        )\n\n    def test_hash_file(self, tmpdir: Path) -> None:\n        self.prep(tmpdir)\n        h, length = hash_file(os.fspath(self.test_file))\n        assert length == self.test_file_len\n        assert h.hexdigest() == self.test_file_hash\n\n    def test_rehash(self, tmpdir: Path) -> None:\n        self.prep(tmpdir)\n        h, length = wheel.rehash(os.fspath(self.test_file))\n        assert length == str(self.test_file_len)\n        assert h == self.test_file_hash_encoded\n\n\ndef test_get_console_script_specs_replaces_python_version(\n    monkeypatch: pytest.MonkeyPatch,\n) -> None:\n    # Fake Python version.\n    monkeypatch.setattr(sys, \"version_info\", (10, 11))\n\n    entry_points = {\n        \"pip\": \"real_pip\",\n        \"pip99\": \"whatever\",\n        \"pip99.88\": \"whatever\",\n        \"easy_install\": \"real_easy_install\",\n        \"easy_install-99.88\": \"whatever\",\n        # The following shouldn't be replaced.\n        \"not_pip_or_easy_install-99\": \"whatever\",\n        \"not_pip_or_easy_install-99.88\": \"whatever\",\n    }\n    specs = get_console_script_specs(entry_points)\n    assert specs == [\n        \"pip = real_pip\",\n        \"pip10 = real_pip\",\n        \"pip10.11 = real_pip\",\n        \"easy_install = real_easy_install\",\n        \"easy_install-10.11 = real_easy_install\",\n        \"not_pip_or_easy_install-99 = whatever\",\n        \"not_pip_or_easy_install-99.88 = whatever\",\n    ]\n"
  },
  {
    "path": "tests/unit/test_wheel_builder.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import cast\n\nimport pytest\n\nfrom pip._internal import wheel_builder\nfrom pip._internal.models.link import Link\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.vcs.git import Git\n\nfrom tests.lib import _create_test_package\n\n\n@pytest.mark.parametrize(\n    \"s, expected\",\n    [\n        # Trivial.\n        (\"pip-18.0\", True),\n        # Ambiguous.\n        (\"foo-2-2\", True),\n        (\"im-valid\", True),\n        # Invalid.\n        (\"invalid\", False),\n        (\"im_invalid\", False),\n    ],\n)\ndef test_contains_egg_info(s: str, expected: bool) -> None:\n    result = wheel_builder._contains_egg_info(s)\n    assert result == expected\n\n\n@dataclass\nclass ReqMock:\n    name: str = \"pendulum\"\n    is_wheel: bool = False\n    editable: bool = False\n    link: Link | None = None\n    constraint: bool = False\n    source_dir: str | None = \"/tmp/pip-install-123/pendulum\"\n    supports_pyproject_editable: bool = False\n\n\n@pytest.mark.parametrize(\n    \"req, expected\",\n    [\n        (ReqMock(editable=True), False),\n        (ReqMock(source_dir=None), False),\n        (ReqMock(link=Link(\"git+https://g.c/org/repo\")), False),\n        (ReqMock(link=Link(\"https://g.c/dist.tgz\")), False),\n        (ReqMock(link=Link(\"https://g.c/dist-2.0.4.tgz\")), True),\n    ],\n)\ndef test_should_cache(req: ReqMock, expected: bool) -> None:\n    assert wheel_builder._should_cache(cast(InstallRequirement, req)) is expected\n\n\ndef test_should_cache_git_sha(tmpdir: Path) -> None:\n    repo_path = os.fspath(_create_test_package(tmpdir, name=\"mypkg\"))\n    commit = Git.get_revision(repo_path)\n\n    # a link referencing a sha should be cached\n    url = \"git+https://g.c/o/r@\" + commit + \"#egg=mypkg\"\n    req = ReqMock(link=Link(url), source_dir=repo_path)\n    assert wheel_builder._should_cache(cast(InstallRequirement, req))\n\n    # a link not referencing a sha should not be cached\n    url = \"git+https://g.c/o/r@master#egg=mypkg\"\n    req = ReqMock(link=Link(url), source_dir=repo_path)\n    assert not wheel_builder._should_cache(cast(InstallRequirement, req))\n"
  },
  {
    "path": "tools/__init__.py",
    "content": ""
  },
  {
    "path": "tools/codespell-ignore.txt",
    "content": "# An actual English word\nlousily\nfollowings\n# A contributor first name\nwil\nWhit\n# Codebase variable or class names\nuptodate\nafile\nfailer\n"
  },
  {
    "path": "tools/news/template.rst",
    "content": "{# This is a heavily customised version of towncrier's default template. #}\n\n{#-\n  Only render if there's any changes to show.\n\n  This serves as a compatibility \"hack\" since we render unreleased news entries\n  in our changelog with ``sphinxcontrib.towncrier``; which triggers a render even\n  when there's no entries to be rendered.\n#}\n{% if sections[''] %}\n\n{#- Heading for individual version #}\n{{ versiondata.version }} ({{ versiondata.date }})\n{{ top_underline * ((versiondata.version + versiondata.date)|length + 3) }}\n{#\n\n  The following loop will run exactly once, with ``section_name == \"\"``.\n\n  This is due to the undocumented \"sections\" feature in towncrier.\n  See https://github.com/twisted/towncrier/issues/61.\n\n  We don't use this feature, and this template doesn't render the section\n  heading for that reason.\n#}\n{% for section_name, entries_by_type in sections.items() -%}\n{# Only show types with entries and ``showcontent = true``, using the order from pyproject.toml #}\n{% for type_ in definitions if (sections[section_name][type_] and definitions[type_]['showcontent']) %}\n\n{# Heading for individual types #}\n{{ definitions[type_]['name'] }}\n{{ underlines[0] * definitions[type_]['name']|length }}\n{# This is the loop that generates individual entries #}\n{% for message, issue_reference in sections[section_name][type_]|dictsort(by='value') %}\n\n- {{ message }}\n  {%- if type_ not in [\"vendor\", \"process\"] %} ({{ issue_reference|sort|join(', ') }}){% endif %}\n{% endfor %}\n\n{% else %}\n{# We only have entries where the type has ``showcontent = true``. #}\nNo significant changes.\n\n{% endfor -%}\n{% endfor -%}\n{% endif -%}\n"
  },
  {
    "path": "tools/protected_pip.py",
    "content": "from __future__ import annotations\n\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\nfrom collections.abc import Iterable\nfrom glob import glob\n\nVIRTUAL_ENV = os.environ[\"VIRTUAL_ENV\"]\nTOX_PIP_DIR = os.path.join(VIRTUAL_ENV, \"pip\")\n\n\ndef pip(args: Iterable[str | pathlib.Path]) -> None:\n    # First things first, get a recent (stable) version of pip.\n    if not os.path.exists(TOX_PIP_DIR):\n        subprocess.check_call(\n            [\n                sys.executable,\n                \"-m\",\n                \"pip\",\n                \"--disable-pip-version-check\",\n                \"install\",\n                \"-t\",\n                TOX_PIP_DIR,\n                \"pip\",\n            ]\n        )\n        shutil.rmtree(glob(os.path.join(TOX_PIP_DIR, \"pip-*.dist-info\"))[0])\n    # And use that version.\n    pypath_env = os.environ.get(\"PYTHONPATH\")\n    pypath = pypath_env.split(os.pathsep) if pypath_env is not None else []\n    pypath.insert(0, TOX_PIP_DIR)\n    os.environ[\"PYTHONPATH\"] = os.pathsep.join(pypath)\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", *(os.fspath(a) for a in args)])\n\n\nif __name__ == \"__main__\":\n    pip(sys.argv[1:])\n"
  },
  {
    "path": "tools/release/__init__.py",
    "content": "\"\"\"Helpers for release automation.\n\nThese are written according to the order they are called in.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport pathlib\nimport subprocess\nimport tempfile\nimport unicodedata\nfrom collections.abc import Iterator\n\nfrom nox.sessions import Session\n\n\ndef get_version_from_arguments(session: Session) -> str | None:\n    \"\"\"Checks the arguments passed to `nox -s release`.\n\n    If there is only 1 argument that looks like a pip version, returns that.\n    Otherwise, returns None.\n    \"\"\"\n    if len(session.posargs) != 1:\n        return None\n    version = session.posargs[0]\n\n    # We delegate to a script here, so that it can depend on packaging.\n    session.install(\"packaging\")\n    cmd = [\n        os.path.join(session.bin, \"python\"),\n        \"tools/release/check_version.py\",\n        version,\n    ]\n    not_ok = subprocess.run(cmd).returncode\n    if not_ok:\n        return None\n\n    # All is good.\n    return version\n\n\ndef modified_files_in_git(*args: str) -> int:\n    return subprocess.run(\n        [\"git\", \"diff\", \"--no-patch\", \"--exit-code\", *args],\n        capture_output=True,\n    ).returncode\n\n\ndef strip_rtl_ltr_overrides(a: str) -> str:\n    \"\"\"Strip RIGHT-TO-LEFT OVERRIDE and LEFT-TO-RIGHT OVERRIDE characters\n    from author names.\n    Reorder the characters in between them to preserve the perception.\n    See https://github.com/pypa/pip/issues/12467 for more info.\"\"\"\n    rtl = \"\\N{RIGHT-TO-LEFT OVERRIDE}\"\n    ltr = \"\\N{LEFT-TO-RIGHT OVERRIDE}\"\n\n    # If there are no overrides to RIGHT-TO-LEFT,\n    # only strip useless LEFT-TO-RIGHT overrides.\n    # This returns the original for most of the authors.\n    # It also serves as a termination condition for recursive calls.\n    if rtl not in a:\n        return a.replace(ltr, \"\")\n\n    prefix = a[: a.index(rtl)].replace(ltr, \"\")\n    rest = a[: a.index(rtl) : -1]\n    if ltr not in rest:\n        rest = rest.replace(rtl, \"\")\n    else:\n        rest = a[a.index(ltr) - 1 : a.index(rtl) : -1].replace(rtl, \"\")\n        rest += a[a.index(ltr) + 1 :]\n    combined = prefix + strip_rtl_ltr_overrides(rest)\n    assert rtl not in combined, f\"RIGHT-TO-LEFT OVERRIDE in {combined!r}\"\n    assert ltr not in combined, f\"LEFT-TO-RIGHT OVERRIDE in {combined!r}\"\n    return combined\n\n\ndef get_author_list() -> list[str]:\n    \"\"\"Get the list of authors from Git commits.\"\"\"\n    # subprocess because session.run doesn't give us stdout\n    # only use names in list of Authors\n    result = subprocess.run(\n        [\"git\", \"log\", \"--use-mailmap\", \"--format=%aN\"],\n        capture_output=True,\n        encoding=\"utf-8\",\n    )\n\n    # Create a unique list.\n    authors = []\n    seen_authors: set[str] = set()\n    for author in result.stdout.splitlines():\n        author = author.strip()\n        author = strip_rtl_ltr_overrides(author)\n        author = unicodedata.normalize(\"NFC\", author)\n        if author.lower() not in seen_authors:\n            seen_authors.add(author.lower())\n            authors.append(author)\n\n    # Sort our list of Authors by their case insensitive name\n    return sorted(authors, key=lambda x: x.lower())\n\n\ndef generate_authors(filename: str) -> None:\n    # Get our list of authors\n    authors = get_author_list()\n\n    # Write our authors to the AUTHORS file\n    with open(filename, \"w\", encoding=\"utf-8\") as fp:\n        fp.write(\"\\n\".join(authors))\n        fp.write(\"\\n\")\n\n\ndef commit_file(session: Session, filename: str, *, message: str) -> None:\n    session.run(\"git\", \"add\", filename, external=True, silent=True)\n    session.run(\"git\", \"commit\", \"-m\", message, external=True, silent=True)\n\n\ndef generate_news(session: Session, version: str) -> None:\n    session.install(\"towncrier\")\n    session.run(\"towncrier\", \"build\", \"--yes\", \"--version\", version, silent=True)\n\n\ndef update_version_file(version: str, filepath: str) -> None:\n    with open(filepath, encoding=\"utf-8\") as f:\n        content = list(f)\n\n    file_modified = False\n    with open(filepath, \"w\", encoding=\"utf-8\") as f:\n        for line in content:\n            if line.startswith(\"__version__ =\"):\n                f.write(f'__version__ = \"{version}\"\\n')\n                file_modified = True\n            else:\n                f.write(line)\n\n    assert file_modified, f\"Version file {filepath} did not get modified\"\n\n\ndef create_git_tag(session: Session, tag_name: str, *, message: str) -> None:\n    session.run(\n        # fmt: off\n        \"git\", \"tag\", \"-m\", message, tag_name,\n        # fmt: on\n        external=True,\n        silent=True,\n    )\n\n\ndef get_next_development_version(version: str) -> str:\n    is_beta = \"b\" in version.lower()\n\n    parts = version.split(\".\")\n    s_major, s_minor, *_ = parts\n\n    # We only permit betas.\n    if is_beta:\n        s_minor, _, s_dev_number = s_minor.partition(\"b\")\n    else:\n        s_dev_number = \"0\"\n\n    major, minor = map(int, [s_major, s_minor])\n\n    # Increase minor version number if we're not releasing a beta.\n    if not is_beta:\n        # We have at most 4 releases, starting with 0. Once we reach 3, we'd\n        # want to roll-over to the next year's release numbers.\n        if minor == 3:\n            major += 1\n            minor = 0\n        else:\n            minor += 1\n\n    return f\"{major}.{minor}.dev\" + s_dev_number\n\n\ndef have_files_in_folder(folder_name: str) -> bool:\n    if not os.path.exists(folder_name):\n        return False\n    return bool(os.listdir(folder_name))\n\n\n@contextlib.contextmanager\ndef workdir(\n    nox_session: Session,\n    dir_path: pathlib.Path,\n) -> Iterator[pathlib.Path]:\n    \"\"\"Temporarily chdir when entering CM and chdir back on exit.\"\"\"\n    orig_dir = pathlib.Path.cwd()\n\n    nox_session.chdir(dir_path)\n    try:\n        yield dir_path\n    finally:\n        nox_session.chdir(orig_dir)\n\n\n@contextlib.contextmanager\ndef isolated_temporary_checkout(\n    nox_session: Session,\n    target_ref: str,\n) -> Iterator[pathlib.Path]:\n    \"\"\"Make a clean checkout of a given version in tmp dir.\"\"\"\n    with tempfile.TemporaryDirectory() as tmp_dir_path:\n        tmp_dir = pathlib.Path(tmp_dir_path)\n        git_checkout_dir = tmp_dir / f\"pip-build-{target_ref}\"\n        nox_session.run(\n            # fmt: off\n            \"git\", \"clone\",\n            \"--depth\", \"1\",\n            \"--config\", \"core.autocrlf=false\",\n            \"--branch\", str(target_ref),\n            \"--\",\n            \".\", str(git_checkout_dir),\n            # fmt: on\n            external=True,\n            silent=True,\n        )\n\n        yield git_checkout_dir\n\n\ndef get_git_untracked_files() -> Iterator[str]:\n    \"\"\"List all local file paths that aren't tracked by Git.\"\"\"\n    git_ls_files_cmd = (\n        # fmt: off\n        \"git\", \"ls-files\",\n        \"--ignored\", \"--exclude-standard\",\n        \"--others\", \"--\", \".\",\n        # fmt: on\n    )\n    # session.run doesn't seem to return any output:\n    ls_files_out = subprocess.check_output(git_ls_files_cmd, text=True)\n    for file_name in ls_files_out.splitlines():\n        if file_name.strip():  # it's useless if empty\n            continue\n\n        yield file_name\n"
  },
  {
    "path": "tools/release/check_version.py",
    "content": "\"\"\"Checks if the version is acceptable, as per this project's release process.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom datetime import datetime\n\nfrom packaging.version import InvalidVersion, Version\n\n\ndef is_this_a_good_version_number(string: str) -> str | None:\n    try:\n        v = Version(string)\n    except InvalidVersion as e:\n        return str(e)\n\n    if v.local:\n        return \"Nope. PyPI refuses local release versions.\"\n\n    if v.dev:\n        return \"No development releases on PyPI. What are you even thinking?\"\n\n    if v.pre and v.pre[0] != \"b\":\n        return \"Only beta releases are allowed. No alphas.\"\n\n    release = v.release\n    expected_major = datetime.now().year % 100\n\n    if len(release) not in [2, 3]:\n        return f\"Not of the form: {expected_major}.N or {expected_major}.N.P\"\n\n    return None\n\n\ndef main() -> None:\n    problem = is_this_a_good_version_number(sys.argv[1])\n    if problem is not None:\n        print(\"ERROR:\", problem)\n        sys.exit(1)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "tools/update-rtd-redirects.py",
    "content": "\"\"\"Update the 'exact' redirects on Read the Docs to match an in-tree file's contents.\n\nRelevant API reference: https://docs.readthedocs.io/en/stable/api/v3.html#redirects\n\"\"\"\n\n# /// script\n# requires-python = \">=3.11\"\n# dependencies = [\"httpx\", \"rich\", \"pyyaml\"]\n# ///\n\nimport operator\nimport os\nimport sys\nfrom pathlib import Path\n\nimport httpx\nimport rich\nimport yaml\n\ntry:\n    _TOKEN = os.environ[\"RTD_API_TOKEN\"]\nexcept KeyError:\n    rich.print(\n        \"[bold]error[/]: [red]No API token provided. Please set `RTD_API_TOKEN`.[/]\",\n        file=sys.stderr,\n    )\n    sys.exit(1)\n\nRTD_API_HEADERS = {\"Authorization\": f\"token {_TOKEN}\"}\nRTD_API_BASE_URL = \"https://readthedocs.org/api/v3/projects/pip/\"\nREPO_ROOT = Path(__file__).resolve().parent.parent\n\n\n# --------------------------------------------------------------------------------------\n# Helpers\n# --------------------------------------------------------------------------------------\ndef next_step(msg: str) -> None:\n    rich.print(f\"> [blue]{msg}[/]\")\n\n\ndef log_response(response: httpx.Response) -> None:\n    request = response.request\n    rich.print(f\"[bold magenta]{request.method}[/] {request.url} -> {response}\")\n\n\ndef get_rtd_api() -> httpx.Client:\n    return httpx.Client(\n        headers=RTD_API_HEADERS,\n        base_url=RTD_API_BASE_URL,\n        event_hooks={\"response\": [log_response]},\n    )\n\n\n# --------------------------------------------------------------------------------------\n# Actual logic\n# --------------------------------------------------------------------------------------\nnext_step(\"Loading local redirects from the yaml file.\")\n\nwith open(REPO_ROOT / \".readthedocs-custom-redirects.yml\") as f:\n    local_redirects = yaml.safe_load(f)\n\nrich.print(\"Loaded local redirects!\")\nfor src, dst in sorted(local_redirects.items()):\n    rich.print(f\"  [yellow]{src}[/] --> {dst}\")\nrich.print(f\"{len(local_redirects)} entries.\")\n\n\nnext_step(\"Fetch redirects configured on RTD.\")\n\nwith get_rtd_api() as rtd_api:\n    response = rtd_api.get(\"redirects/\")\n    response.raise_for_status()\n\n    rtd_redirects = response.json()\n\nfor redirect in sorted(\n    rtd_redirects[\"results\"], key=operator.itemgetter(\"type\", \"from_url\", \"to_url\")\n):\n    if redirect[\"type\"] != \"exact\":\n        rich.print(f\"  [magenta]{redirect['type']}[/]\")\n        continue\n\n    pk = redirect[\"pk\"]\n    src = redirect[\"from_url\"]\n    dst = redirect[\"to_url\"]\n    rich.print(f\"  [yellow]{src}[/] -({pk:^5})-> {dst}\")\n\nrich.print(f\"{rtd_redirects['count']} entries.\")\n\n\nnext_step(\"Compare and determine modifications.\")\n\nredirects_to_remove: list[int] = []\nredirects_to_add: dict[str, str] = {}\n\nfor redirect in rtd_redirects[\"results\"]:\n    if redirect[\"type\"] != \"exact\":\n        continue\n\n    rtd_src = redirect[\"from_url\"]\n    rtd_dst = redirect[\"to_url\"]\n    redirect_id = redirect[\"pk\"]\n\n    if rtd_src not in local_redirects:\n        redirects_to_remove.append(redirect_id)\n        continue\n\n    local_dst = local_redirects[rtd_src]\n    if local_dst != rtd_dst:\n        redirects_to_remove.append(redirect_id)\n        redirects_to_add[rtd_src] = local_dst\n\n    del local_redirects[rtd_src]\n\nfor src, dst in sorted(local_redirects.items()):\n    redirects_to_add[src] = dst\n    del local_redirects[src]\n\nassert not local_redirects\n\nif not redirects_to_remove:\n    rich.print(\"Nothing to remove.\")\nelse:\n    rich.print(f\"To remove: ({len(redirects_to_remove)} entries)\")\n    for redirect_id in redirects_to_remove:\n        rich.print(\" \", redirect_id)\n\nif not redirects_to_add:\n    rich.print(\"Nothing to add.\")\nelse:\n    rich.print(f\"To add: ({len(redirects_to_add)} entries)\")\n    for src, dst in redirects_to_add.items():\n        rich.print(f\"  {src} --> {dst}\")\n\n\nnext_step(\"Update the RTD redirects.\")\n\nif not (redirects_to_add or redirects_to_remove):\n    rich.print(\"[green]Nothing to do![/]\")\n    sys.exit(0)\n\nexit_code = 0\nwith get_rtd_api() as rtd_api:\n    for redirect_id in redirects_to_remove:\n        response = rtd_api.delete(f\"redirects/{redirect_id}/\")\n        response.raise_for_status()\n        if response.status_code != 204:\n            rich.print(\"[red]This might not have been removed correctly.[/]\")\n            exit_code = 1\n\n    for src, dst in redirects_to_add.items():\n        response = rtd_api.post(\n            \"redirects/\",\n            json={\"from_url\": src, \"to_url\": dst, \"type\": \"exact\"},\n        )\n        response.raise_for_status()\n        if response.status_code != 201:\n            rich.print(\"[red]This might not have been added correctly.[/]\")\n            exit_code = 1\n\nsys.exit(exit_code)\n"
  },
  {
    "path": "tools/vendoring/patches/cachecontrol.patch",
    "content": "diff --git a/src/pip/_vendor/cachecontrol/__init__.py b/src/pip/_vendor/cachecontrol/__init__.py\nindex 2a63377e0..3f8c36f67 100644\n--- a/src/pip/_vendor/cachecontrol/__init__.py\n+++ b/src/pip/_vendor/cachecontrol/__init__.py\n@@ -15,7 +15,8 @@ from pip._vendor.cachecontrol.wrapper import CacheControl\n \n __author__ = \"Eric Larson\"\n __email__ = \"eric@ionrock.org\"\n-__version__ = importlib.metadata.version(\"cachecontrol\")\n+# pip patch: this won't work when vendored, so just patch it out as it's unused\n+# __version__ = importlib.metadata.version(\"cachecontrol\")\n \n __all__ = [\n     \"__author__\",\n"
  },
  {
    "path": "tools/vendoring/patches/certifi.patch",
    "content": "diff --git a/src/pip/_vendor/certifi/core.py b/src/pip/_vendor/certifi/core.py\nindex 1c9661cc7..2f2f7e088 100644\n--- a/src/pip/_vendor/certifi/core.py\n+++ b/src/pip/_vendor/certifi/core.py\n@@ -37,14 +37,14 @@ if sys.version_info >= (3, 11):\n             # We also have to hold onto the actual context manager, because\n             # it will do the cleanup whenever it gets garbage collected, so\n             # we will also store that at the global level as well.\n-            _CACERT_CTX = as_file(files(\"certifi\").joinpath(\"cacert.pem\"))\n+            _CACERT_CTX = as_file(files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\"))\n             _CACERT_PATH = str(_CACERT_CTX.__enter__())\n             atexit.register(exit_cacert_ctx)\n \n         return _CACERT_PATH\n \n     def contents() -> str:\n-        return files(\"certifi\").joinpath(\"cacert.pem\").read_text(encoding=\"ascii\")\n+        return files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\").read_text(encoding=\"ascii\")\n \n else:\n \n@@ -73,11 +73,11 @@ else:\n             # We also have to hold onto the actual context manager, because\n             # it will do the cleanup whenever it gets garbage collected, so\n             # we will also store that at the global level as well.\n-            _CACERT_CTX = get_path(\"certifi\", \"cacert.pem\")\n+            _CACERT_CTX = get_path(\"pip._vendor.certifi\", \"cacert.pem\")\n             _CACERT_PATH = str(_CACERT_CTX.__enter__())\n             atexit.register(exit_cacert_ctx)\n \n         return _CACERT_PATH\n \n     def contents() -> str:\n-        return read_text(\"certifi\", \"cacert.pem\", encoding=\"ascii\")\n+        return read_text(\"pip._vendor.certifi\", \"cacert.pem\", encoding=\"ascii\")\n"
  },
  {
    "path": "tools/vendoring/patches/pkg_resources.patch",
    "content": "diff --git a/src/pip/_vendor/pkg_resources/__init__.py b/src/pip/_vendor/pkg_resources/__init__.py\nindex d47df3f3c..415c0c432 100644\n--- a/src/pip/_vendor/pkg_resources/__init__.py\n+++ b/src/pip/_vendor/pkg_resources/__init__.py\n@@ -87,7 +87,7 @@ except ImportError:\n     # no write support, probably under GAE\n     WRITE_SUPPORT = False\n \n-from pkg_resources.extern.jaraco.text import (\n+from pip._internal.utils._jaraco_text import (\n     yield_lines,\n     drop_comment,\n     join_continuation,\n@@ -102,12 +102,11 @@ if TYPE_CHECKING:\n     from _typeshed import BytesPath, StrPath, StrOrBytesPath\n     from typing_extensions import Self\n \n-warnings.warn(\n-    \"pkg_resources is deprecated as an API. \"\n-    \"See https://setuptools.pypa.io/en/latest/pkg_resources.html\",\n-    DeprecationWarning,\n-    stacklevel=2,\n-)\n+\n+# Patch: Remove deprecation warning from vendored pkg_resources.\n+# Setting PYTHONWARNINGS=error to verify builds produce no warnings\n+# causes immediate exceptions.\n+# See https://github.com/pypa/pip/issues/12243\n \n \n _T = TypeVar(\"_T\")\n"
  },
  {
    "path": "tools/vendoring/patches/pygments.patch",
    "content": "This patch mainly handles tweaking imports into a form that can be transformed\nto import from the vendored namespace.\n\ndiff --git a/src/pip/_vendor/pygments/__main__.py b/src/pip/_vendor/pygments/__main__.py\nindex 5eb2c747..04997f49 100644\n--- a/src/pip/_vendor/pygments/__main__.py\n+++ b/src/pip/_vendor/pygments/__main__.py\n@@ -9,9 +9,9 @@\n \"\"\"\n \n import sys\n-import pygments.cmdline\n+from pygments.cmdline import main\n \n try:\n-    sys.exit(pygments.cmdline.main(sys.argv))\n+    sys.exit(main(sys.argv))\n except KeyboardInterrupt:\n     sys.exit(1)\ndiff --git a/src/pip/_vendor/pygments/lexer.py b/src/pip/_vendor/pygments/lexer.py\nindex eb5403e7..837ada12 100644\n--- a/src/pip/_vendor/pygments/lexer.py\n+++ b/src/pip/_vendor/pygments/lexer.py\n@@ -207,7 +207,9 @@ class Lexer(metaclass=LexerMeta):\n                 text, _ = guess_decode(text)\n             elif self.encoding == 'chardet':\n                 try:\n-                    import chardet\n+                    # pip vendoring note: this code is not reachable by pip,\n+                    # removed import of chardet to make it clear.\n+                    raise ImportError('chardet is not vendored by pip')\n                 except ImportError as e:\n                     raise ImportError('To enable chardet encoding guessing, '\n                                       'please install the chardet library '\ndiff --git a/src/pip/_vendor/pygments/sphinxext.py b/src/pip/_vendor/pygments/sphinxext.py\nindex f935688f..e2986361 100644\n--- a/src/pip/_vendor/pygments/sphinxext.py\n+++ b/src/pip/_vendor/pygments/sphinxext.py\n@@ -91,7 +91,7 @@ class PygmentsDoc(Directive):\n         The columns are the lexer name, the extensions handled by this lexer\n         (or \"None\"), the aliases and a link to the lexer class.\"\"\"\n         from pygments.lexers._mapping import LEXERS\n-        import pygments.lexers\n+        from pygments.lexers import find_lexer_class\n         out = []\n \n         table = []\n@@ -102,7 +102,7 @@ class PygmentsDoc(Directive):\n             return name\n \n         for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()):\n-            lexer_cls = pygments.lexers.find_lexer_class(data[1])\n+            lexer_cls = find_lexer_class(data[1])\n             extensions = lexer_cls.filenames + lexer_cls.alias_filenames\n \n             table.append({\n"
  },
  {
    "path": "tools/vendoring/patches/requests.patch",
    "content": "diff --git a/src/pip/_vendor/requests/__init__.py b/src/pip/_vendor/requests/__init__.py\nindex 300a16c5..a66f6024 100644\n--- a/src/pip/_vendor/requests/__init__.py\n+++ b/src/pip/_vendor/requests/__init__.py\n@@ -49,10 +49,7 @@ try:\n except ImportError:\n     charset_normalizer_version = None\n \n-try:\n-    from chardet import __version__ as chardet_version\n-except ImportError:\n-    chardet_version = None\n+chardet_version = None\n \n \n def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n@@ -76,11 +76,8 @@ def check_compatibility(urllib3_version, chardet_version, charset_normalizer_ver\n         # charset_normalizer >= 2.0.0 < 4.0.0\n         assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)\n     else:\n-        warnings.warn(\n-            \"Unable to find acceptable character detection dependency \"\n-            \"(chardet or charset_normalizer).\",\n-            RequestsDependencyWarning,\n-        )\n+        # pip does not need or use character detection\n+        pass\n\n\n def _check_cryptography(cryptography_version):\n@@ -118,6 +115,11 @@ except (AssertionError, ValueError):\n # if the standard library doesn't support SNI or the\n # 'ssl' library isn't available.\n try:\n+    # Note: This logic prevents upgrading cryptography on Windows, if imported\n+    #       as part of pip.\n+    from pip._internal.utils.compat import WINDOWS\n+    if not WINDOWS:\n+        raise ImportError(\"pip internals: don't import cryptography on Windows\")\n     try:\n         import ssl\n     except ImportError:\ndiff --git a/src/pip/_vendor/requests/compat.py b/src/pip/_vendor/requests/compat.py\nindex 6776163c..7819bb99 100644\n--- a/src/pip/_vendor/requests/compat.py\n+++ b/src/pip/_vendor/requests/compat.py\n@@ -27,19 +24,10 @@ is_py2 = _ver[0] == 2\n #: Python 3.x?\n is_py3 = _ver[0] == 3\n \n-# json/simplejson module import resolution\n-has_simplejson = False\n-try:\n-    import simplejson as json\n-\n-    has_simplejson = True\n-except ImportError:\n-    import json\n-\n-if has_simplejson:\n-    from simplejson import JSONDecodeError\n-else:\n-    from json import JSONDecodeError\n+# Note: We've patched out simplejson support in pip because it prevents\n+#       upgrading simplejson on Windows.\n+import json\n+from json import JSONDecodeError\n \n # Keep OrderedDict for backwards compatibility.\n from collections import OrderedDict\ndiff --git a/src/pip/_vendor/requests/help.py b/src/pip/_vendor/requests/help.py\nindex 8fbcd656..094e2046 100644\n--- a/src/pip/_vendor/requests/help.py\n+++ b/src/pip/_vendor/requests/help.py\n@@ -15,10 +15,7 @@ try:\n except ImportError:\n     charset_normalizer = None\n \n-try:\n-    import chardet\n-except ImportError:\n-    chardet = None\n+chardet = None\n \n try:\n     from urllib3.contrib import pyopenssl\ndiff --git a/src/pip/_vendor/requests/__init__.py b/src/pip/_vendor/requests/__init__.py\nindex 9d4e72c60..04230fc8d 100644\n--- a/src/pip/_vendor/requests/__init__.py\n+++ b/src/pip/_vendor/requests/__init__.py\n@@ -44,11 +44,7 @@ from pip._vendor import urllib3\n\n from .exceptions import RequestsDependencyWarning\n\n-try:\n-    from charset_normalizer import __version__ as charset_normalizer_version\n-except ImportError:\n-    charset_normalizer_version = None\n-\n+charset_normalizer_version = None\n chardet_version = None\n\n\ndiff --git a/src/pip/_vendor/requests/help.py b/src/pip/_vendor/requests/help.py\nindex 17ca75eda..ddbb6150d 100644\n--- a/src/pip/_vendor/requests/help.py\n+++ b/src/pip/_vendor/requests/help.py\n@@ -10,11 +10,7 @@ from pip._vendor import urllib3\n\n from . import __version__ as requests_version\n\n-try:\n-    import charset_normalizer\n-except ImportError:\n-    charset_normalizer = None\n-\n+charset_normalizer = None\n chardet = None\n\n try:\n--- a/src/pip/_vendor/requests/compat.py\n+++ b/src/pip/_vendor/requests/compat.py\n@@ -7,7 +7,6 @@ between Python 2 and Python 3. It remains for backwards\n compatibility until the next major version.\n \"\"\"\n\n-import importlib\n import sys\n\n # -------\n@@ -30,12 +29,6 @@ import sys\n def _resolve_char_detection():\n     \"\"\"Find supported character detection libraries.\"\"\"\n     chardet = None\n-    for lib in (\"chardet\", \"charset_normalizer\"):\n-        if chardet is None:\n-            try:\n-                chardet = importlib.import_module(lib)\n-            except ImportError:\n-                pass\n     return chardet\n\n\ndiff --git a/src/pip/_vendor/requests/packages.py b/src/pip/_vendor/requests/packages.py\nindex 5ab3d8e25..200c38287 100644\n--- a/src/pip/_vendor/requests/packages.py\n+++ b/src/pip/_vendor/requests/packages.py\n@@ -6,12 +6,14 @@ from .compat import chardet\n # I don't like it either. Just look the other way. :)\n\n for package in (\"urllib3\", \"idna\"):\n-    locals()[package] = __import__(package)\n+    vendored_package = \"pip._vendor.\" + package\n+    locals()[package] = __import__(vendored_package)\n     # This traversal is apparently necessary such that the identities are\n     # preserved (requests.packages.urllib3.* is urllib3.*)\n     for mod in list(sys.modules):\n-        if mod == package or mod.startswith(f\"{package}.\"):\n-            sys.modules[f\"requests.packages.{mod}\"] = sys.modules[mod]\n+        if mod == vendored_package or mod.startswith(vendored_package + '.'):\n+            unprefixed_mod = mod[len(\"pip._vendor.\"):]\n+            sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod]\n\n if chardet is not None:\n     target = chardet.__name__\n"
  },
  {
    "path": "tools/vendoring/patches/truststore.patch",
    "content": "diff --git a/src/pip/_vendor/truststore/_api.py b/src/pip/_vendor/truststore/_api.py\nindex 47b7a63ab..d09d3096f 100644\n--- a/src/pip/_vendor/truststore/_api.py\n+++ b/src/pip/_vendor/truststore/_api.py\n@@ -48,12 +48,12 @@ def inject_into_ssl() -> None:\n     # the truststore patched instance\n     # also see https://github.com/psf/requests/pull/6667\n     try:\n-        import requests.adapters\n+        from pip._vendor.requests import adapters as requests_adapters\n\n-        preloaded_context = getattr(requests.adapters, \"_preloaded_ssl_context\", None)\n+        preloaded_context = getattr(requests_adapters, \"_preloaded_ssl_context\", None)\n         if preloaded_context is not None:\n             setattr(\n-                requests.adapters,\n+                requests_adapters,\n                 \"_preloaded_ssl_context\",\n                 SSLContext(ssl.PROTOCOL_TLS_CLIENT),\n             )\n"
  },
  {
    "path": "tools/vendoring/patches/urllib3-disable-brotli.patch",
    "content": "diff --git a/src/pip/_vendor/urllib3/response.py b/src/pip/_vendor/urllib3/response.py\nindex 01f08eee8..4969b70e3 100644\n--- a/src/pip/_vendor/urllib3/response.py\n+++ b/src/pip/_vendor/urllib3/response.py\n@@ -8,13 +8,7 @@\n from socket import error as SocketError\n from socket import timeout as SocketTimeout\n \n-try:\n-    try:\n-        import brotlicffi as brotli\n-    except ImportError:\n-        import brotli\n-except ImportError:\n-    brotli = None\n+brotli = None\n \n from . import util\n from ._collections import HTTPHeaderDict\ndiff --git a/src/pip/_vendor/urllib3/util/request.py b/src/pip/_vendor/urllib3/util/request.py\nindex b574b081e..330766ef4 100644\n--- a/src/pip/_vendor/urllib3/util/request.py\n+++ b/src/pip/_vendor/urllib3/util/request.py\n@@ -13,15 +13,6 @@\n SKIPPABLE_HEADERS = frozenset([\"accept-encoding\", \"host\", \"user-agent\"])\n \n ACCEPT_ENCODING = \"gzip,deflate\"\n-try:\n-    try:\n-        import brotlicffi as _unused_module_brotli  # noqa: F401\n-    except ImportError:\n-        import brotli as _unused_module_brotli  # noqa: F401\n-except ImportError:\n-    pass\n-else:\n-    ACCEPT_ENCODING += \",br\"\n \n _FAILEDTELL = object()\n \n"
  },
  {
    "path": "tools/vendoring/patches/urllib3.patch",
    "content": "diff --git a/src/pip/_vendor/urllib3/contrib/securetransport.py b/src/pip/_vendor/urllib3/contrib/securetransport.py\nindex b97555454..189132baa 100644\n--- a/src/pip/_vendor/urllib3/contrib/securetransport.py\n+++ b/src/pip/_vendor/urllib3/contrib/securetransport.py\n@@ -19,8 +19,8 @@\n\n To use this module, simply import and inject it::\n\n-    import urllib3.contrib.securetransport\n-    urllib3.contrib.securetransport.inject_into_urllib3()\n+    import urllib3.contrib.securetransport as securetransport\n+    securetransport.inject_into_urllib3()\n\n Happy TLSing!\n\ndiff --git a/src/pip/_vendor/urllib3/contrib/pyopenssl.py b/src/pip/_vendor/urllib3/contrib/pyopenssl.py\nindex c43146279..4cded53f6 100644\n--- a/src/pip/_vendor/urllib3/contrib/pyopenssl.py\n+++ b/src/pip/_vendor/urllib3/contrib/pyopenssl.py\n@@ -28,7 +28,7 @@\n .. code-block:: python\n\n     try:\n-        import urllib3.contrib.pyopenssl\n-        urllib3.contrib.pyopenssl.inject_into_urllib3()\n+        import urllib3.contrib.pyopenssl as pyopenssl\n+        pyopenssl.inject_into_urllib3()\n     except ImportError:\n         pass\n"
  }
]